Import a 3D Model and automatically assign and export animations
TypeScript
Add manual weight painting with mirroring and live weight heatmap (#157)
ReneArmenta-lsc5b2ed0a7b19f
diff --git a/src/Mesh2MotionEngine.ts b/src/Mesh2MotionEngine.tsindex a37e097..d040e67 100644--- a/src/Mesh2MotionEngine.ts+++ b/src/Mesh2MotionEngine.ts@@ -20,6 +20,7 @@ import { ArmExtensionControl } from './lib/processes/animations-listing/ArmExtenimport { DownloadSettings } from './lib/processes/export-to-file/DownloadSettings.ts'import { StepExportToFile } from './lib/processes/export-to-file/StepExportToFile.ts'import { StepWeightSkin } from './lib/processes/weight-skin/StepWeightSkin.ts'+import { StepWeightPainting } from './lib/processes/weight-painting/StepWeightPainting.ts'import { ProcessStep } from './lib/enums/ProcessStep.ts'import { type Bone, Group, Scene, type Skeleton, type Vector3 } from 'three'@@ -62,6 +63,7 @@ export class Mesh2MotionEngine {public load_skeleton_step: StepLoadSkeletonpublic edit_skeleton_step: StepEditSkeletonpublic weight_skin_step: StepWeightSkin+ public weight_painting_step: StepWeightPaintingpublic animations_listing_step: StepAnimationsListingpublic download_settings: DownloadSettingspublic file_export_step: StepExportToFile@@ -107,6 +109,7 @@ export class Mesh2MotionEngine {this.load_skeleton_step = new StepLoadSkeleton(this.scene)this.edit_skeleton_step = new StepEditSkeleton()this.weight_skin_step = new StepWeightSkin()+ this.weight_painting_step = new StepWeightPainting(this)this.animations_listing_step = new StepAnimationsListing(this.theme_manager)this.download_settings = new DownloadSettings()this.file_export_step = new StepExportToFile()@@ -200,6 +203,9 @@ export class Mesh2MotionEngine {if (this.active_skinned_meshes_provider !== null) {return this.active_skinned_meshes_provider()}+ if (this.process_step === ProcessStep.WeightPainting) {+ return this.weight_painting_step.active_skinned_meshes()+ }return this.animations_listing_step.active_skinned_meshes()}@@ -335,6 +341,159 @@ export class Mesh2MotionEngine {}}+ private weight_paint_pointer_id: number | null = null+ private weight_paint_source: 'edit' | 'weight_painting' | null = null++ /**+ * Handles a left-button press in a weight paint mode, painting or picking at+ * the initial raycast hit.+ * @returns true when the press hit the mesh and was claimed for painting or+ * picking. Returning false leaves the press to OrbitControls, so a drag that+ * started on empty space rotates the camera instead of painting.+ */+ public handle_weight_paint_pointer_down (event: PointerEvent): boolean {+ const edit_step_painting = this.process_step === ProcessStep.EditSkeleton &&+ this.edit_skeleton_step.is_weight_painting_enabled()+ const weight_painting_step_painting = this.process_step === ProcessStep.WeightPainting &&+ this.weight_painting_step.is_draw_mode_active()+ const weight_painting_step_picking = this.process_step === ProcessStep.WeightPainting &&+ this.weight_painting_step.is_bone_picking_enabled()++ // the bone picker takes priority over the brush+ if (weight_painting_step_picking) {+ const picked_intersection = this.weight_paint_intersection(event,+ this.weight_painting_step.active_skinned_meshes())+ if (picked_intersection !== null) {+ this.weight_painting_step.pick_bone(picked_intersection)+ }+ return picked_intersection !== null+ }++ // Shift + click switches bones without arming the picker first+ if (weight_painting_step_painting && event.shiftKey) {+ const picked_intersection = this.weight_paint_intersection(event,+ this.weight_painting_step.active_skinned_meshes())+ if (picked_intersection !== null) {+ this.weight_painting_step.pick_bone(picked_intersection)+ }+ return picked_intersection !== null+ }++ let intersection: THREE.Intersection | null+ if (edit_step_painting) {+ const group = this.weight_skin_step.weight_painted_mesh_group()+ if (group === null || !group.visible) { return false }+ this.weight_paint_source = 'edit'+ intersection = this.weight_paint_intersection(event,+ group.children.filter(child => child.userData.weight_painted === true))+ } else if (weight_painting_step_painting) {+ this.weight_paint_source = 'weight_painting'+ intersection = this.weight_paint_intersection(event, this.weight_painting_step.active_skinned_meshes())+ } else {+ return false+ }++ if (intersection === null) {+ this.weight_paint_source = null+ return false+ }++ this.weight_paint_pointer_id = event.pointerId+ if (this.weight_paint_source === 'edit') {+ this.edit_skeleton_step.begin_weight_paint_stroke()+ this.edit_skeleton_step.paint_weights(intersection, this.camera)+ } else {+ this.weight_painting_step.begin_weight_paint_stroke()+ this.weight_painting_step.paint_weights(intersection, this.camera)+ this.weight_painting_step.update_brush_cursor(event, intersection)+ }+ return true+ }++ /** @returns true when the pointer is over a paintable mesh */+ public handle_weight_paint_pointer_move (event: PointerEvent): boolean {+ if (this.weight_paint_pointer_id !== event.pointerId || this.weight_paint_source === null) { return false }++ const targets = this.weight_paint_source === 'edit'+ ? this.weight_skin_step.weight_painted_mesh_group()?.children.filter(child => child.userData.weight_painted === true) ?? []+ : this.weight_painting_step.active_skinned_meshes()++ const intersection = this.weight_paint_intersection(event, targets)+ if (intersection === null) {+ // re-entering the mesh should not sweep a stroke across the gap+ if (this.weight_paint_source === 'edit') {+ this.edit_skeleton_step.reset_weight_paint_dab_path()+ } else {+ this.weight_painting_step.reset_paint_dab_path()+ this.weight_painting_step.update_brush_cursor(event, null)+ }+ return false+ }++ if (this.weight_paint_source === 'edit') {+ this.edit_skeleton_step.paint_weights(intersection, this.camera)+ } else {+ this.weight_painting_step.paint_weights(intersection, this.camera)+ // reuse this raycast for the outline instead of casting again+ this.weight_painting_step.update_brush_cursor(event, intersection)+ }+ return true+ }++ /**+ * Positions the brush outline on the skinned mesh under the pointer.+ * @returns true when the pointer is over a paintable mesh+ */+ public update_weight_paint_brush_cursor (event: PointerEvent): boolean {+ if (this.process_step !== ProcessStep.WeightPainting) { return false }++ const intersection = this.weight_paint_intersection(event,+ this.weight_painting_step.active_skinned_meshes())+ this.weight_painting_step.update_brush_cursor(event, intersection)+ return intersection !== null && intersection.object instanceof THREE.SkinnedMesh+ }++ /** Shows the paint crosshair only while hovering the weight preview mesh. */+ public update_edit_weight_paint_cursor (event: PointerEvent): void {+ if (this.process_step !== ProcessStep.EditSkeleton) { return }++ const group = this.weight_skin_step.weight_painted_mesh_group()+ const targets = group !== null && group.visible+ ? group.children.filter(child => child.userData.weight_painted === true)+ : []+ const over_mesh = this.weight_paint_intersection(event, targets) !== null+ this.renderer.domElement.style.cursor = over_mesh ? 'crosshair' : ''+ }++ /** Shows the bone the picker would select under the pointer. */+ public update_weight_paint_picker_hover (event: PointerEvent): void {+ if (this.process_step !== ProcessStep.WeightPainting) { return }++ const intersection = this.weight_paint_intersection(event,+ this.weight_painting_step.active_skinned_meshes())+ this.weight_painting_step.update_picker_hover(intersection)+ }++ public handle_weight_paint_pointer_up (event: PointerEvent): void {+ if (this.weight_paint_pointer_id !== event.pointerId) { return }+ if (this.weight_paint_source === 'edit') {+ this.edit_skeleton_step.end_weight_paint_stroke()+ } else if (this.weight_paint_source === 'weight_painting') {+ this.weight_painting_step.end_weight_paint_stroke()+ }+ this.weight_paint_pointer_id = null+ this.weight_paint_source = null+ }++ private weight_paint_intersection (event: MouseEvent | PointerEvent,+ targets: THREE.Object3D[]): THREE.Intersection | null {+ if (targets.length === 0) { return null }++ const raycaster = new THREE.Raycaster()+ raycaster.setFromCamera(Utility.normalized_mouse_position(event), this.camera)+ return raycaster.intersectObjects(targets, false)[0] ?? null+ }+public update_edit_bone_interaction_mode (): void {this.mesh_drag_bone_placement.sync_interaction_mode(this.process_step, this.transform_controls)this.is_transform_controls_dragging = false@@ -358,6 +517,9 @@ export class Mesh2MotionEngine {case ProcessStep.BindPose:this.process_step = ProcessStep.BindPosebreak+ case ProcessStep.WeightPainting:+ this.process_step = ProcessStep.WeightPainting+ breakcase ProcessStep.AnimationsListing:this.process_step = ProcessStep.AnimationsListingbreak@@ -388,10 +550,12 @@ export class Mesh2MotionEngine {// clean up things related to steps in since we can navigate back and forththis.edit_skeleton_step.cleanup_on_exit_step()+ this.weight_painting_step.cleanup_on_exit_step()this.load_skeleton_step.dispose()- // only show animation player on the animation listing page- if (process_step === ProcessStep.AnimationsListing) {+ // the weight painting step also gets the timeline to scrub and slow down+ // the test animation+ if (process_step === ProcessStep.AnimationsListing || process_step === ProcessStep.WeightPainting) {this.show_animation_player(true)} else {this.show_animation_player(false)@@ -449,15 +613,34 @@ export class Mesh2MotionEngine {this.changed_model_preview_display(this.mesh_preview_display_type) // show weight painted mesh by default}else if (this.process_step === ProcessStep.BindPose) {- this.transform_controls.enabled = false // shouldn't be editing bones- this.calculate_skin_weighting_for_models()-- this.remove_skinned_meshes_from_scene() // clean up in case we had skinned meshes in scene previously- this.scene.add(...this.weight_skin_step.final_skinned_meshes()) // add final skinned mesh to scene-- this.weight_skin_step.weight_painted_mesh_group().visible = false // hide weight painted mesh+ this.prepare_skinned_meshes_for_preview()this.process_step_changed(ProcessStep.AnimationsListing)}+ else if (this.process_step === ProcessStep.WeightPainting) {+ this.prepare_skinned_meshes_for_preview()+ this.weight_painting_step.begin(+ this.weight_skin_step.final_skinned_meshes(),+ this.load_skeleton_step.skeleton_type(),+ this.load_skeleton_step.skeleton_scale(),+ this.edit_skeleton_step.weight_paint_manager,+ this.animations_listing_step.get_animation_player()+ )++ const weight_skin_skeleton = this.weight_skin_step.skeleton()+ if (weight_skin_skeleton !== undefined) {+ this.regenerate_skeleton_helper(weight_skin_skeleton)+ }+ this.sync_skeleton_helper_joint_visibility()++ // bones are visible by default in this step so picking and spotting+ // deformation problems is easier; the timeline checkbox can hide them+ if (this.ui.dom_show_skeleton_checkbox !== null) {+ this.ui.dom_show_skeleton_checkbox.checked = true+ }+ if (this.skeleton_helper !== undefined) {+ this.skeleton_helper.show()+ }+ }else if (this.process_step === ProcessStep.AnimationsListing) {this.process_step = ProcessStep.AnimationsListing@@ -504,6 +687,8 @@ export class Mesh2MotionEngine {// render/update functions in thatif (this.process_step === ProcessStep.AnimationsListing) {this.animations_listing_step.frame_change(delta_time)+ } else if (this.process_step === ProcessStep.WeightPainting) {+ this.weight_painting_step.frame_change(delta_time)}this.frame_listeners.forEach((listener) => { listener(delta_time) })@@ -530,6 +715,9 @@ export class Mesh2MotionEngine {// show/hide weight painted mesh depending on viewthis.weight_skin_step.weight_painted_mesh_group().visible =this.mesh_preview_display_type === ModelPreviewDisplay.WeightPainted++ this.edit_skeleton_step.set_weight_paint_available(+ this.mesh_preview_display_type === ModelPreviewDisplay.WeightPainted)}public changed_transform_controls_mode (radio_button_selected: string): void {@@ -643,12 +831,46 @@ export class Mesh2MotionEngine {}}+ /** Rebind the model and add the final skinned meshes for a posed preview step. */+ private prepare_skinned_meshes_for_preview (): void {+ this.transform_controls.enabled = false // shouldn't be editing bones+ this.calculate_skin_weighting_for_models()++ this.remove_skinned_meshes_from_scene() // clean up in case we had skinned meshes in scene previously+ this.scene.add(...this.weight_skin_step.final_skinned_meshes()) // add final skinned mesh to scene++ this.weight_skin_step.weight_painted_mesh_group().visible = false // hide weight painted mesh+ }++ /**+ * Discard the manual weight overrides and re-run skinning so the meshes get+ * the automatic solver weights again.+ */+ public reset_weights_to_auto (): void {+ this.edit_skeleton_step.reset_weight_paint_overrides()+ this.process_step_changed(ProcessStep.WeightPainting)+ }++ /** Leave the skinned preview steps and return to positioning the skeleton. */+ public back_to_edit_skeleton (): void {+ this.remove_skinned_meshes_from_scene() // clear any existing skinned meshes+ this.debugging_visual_object = Utility.regenerate_debugging_scene(this.scene)+ this.process_step = this.process_step_changed(ProcessStep.EditSkeleton)++ // reset current bone selection for edit skeleton step+ this.edit_skeleton_step.set_currently_selected_bone(null)++ // reset the undo/redo system+ this.edit_skeleton_step.clear_undo_history()+ }+private calculate_skin_weighting_for_models (): void {// we only need one binding skeleton. All skinned meshes will use this.this.weight_skin_step.reset_all_skin_process_data() // clear out any existing skinned meshes in storage// needed for skinning process if we change modesthis.weight_skin_step.create_bone_formula_object(this.edit_skeleton_step.armature(), this.load_skeleton_step.skeleton_type())+ this.weight_skin_step.set_manual_weight_overrides(this.edit_skeleton_step.manual_weight_overrides())// Pass head weight correction settings to the weight skin stepthis.weight_skin_step.set_head_weight_correction_settings(@@ -692,6 +914,7 @@ export class Mesh2MotionEngine {public setup_weight_skinning_config (): void {this.weight_skin_step.create_bone_formula_object(this.edit_skeleton_step.armature(), this.load_skeleton_step.skeleton_type())+ this.weight_skin_step.set_manual_weight_overrides(this.edit_skeleton_step.manual_weight_overrides())// Pass head weight correction settings to the weight skin stepthis.weight_skin_step.set_head_weight_correction_settings(diff --git a/src/create.html b/src/create.htmlindex 6d089ec..a50d791 100644--- a/src/create.html+++ b/src/create.html@@ -285,7 +285,49 @@</div></div>+ <details id="weight-painting-tools" style="max-width: 280px;" hidden>+ <summary>Weight painting</summary>+ <p><small>Paint weights on the colored mesh. Painted vertices override the automatic weights and are kept when binding and exporting. Use Add to strengthen a bone, Subtract to remove it, and Smooth to blend a vertex with its neighbours and soften steps around joints. Mirror L/R applies the stroke to the matching bone on the opposite side.</small></p>+ <button id="weight-paint-toggle" type="button" aria-pressed="false">Start painting</button>+ <div style="display: flex; flex-direction: column; gap: 0.5rem; margin-top: 0.5rem;">+ <label for="weight-paint-bone">Bone</label>+ <select id="weight-paint-bone"></select>++ <div class="pill-switch-group" aria-label="Weight paint mode" style="margin: 0;">+ <span class="pill-switch-label">Brush</span>+ <div class="pill-switch">+ <input type="radio" id="weight-paint-add" name="weight-paint-mode" value="add" checked />+ <label for="weight-paint-add">Add</label>+ <input type="radio" id="weight-paint-subtract" name="weight-paint-mode" value="subtract" />+ <label for="weight-paint-subtract">Subtract</label>+ <input type="radio" id="weight-paint-smooth" name="weight-paint-mode" value="smooth" />+ <label for="weight-paint-smooth">Smooth</label>+ </div>+ </div>++ <label for="weight-paint-radius">Brush size</label>+ <input id="weight-paint-radius" type="range" min="4" max="160" step="1" value="24" />+ <label for="weight-paint-strength">Strength</label>+ <input id="weight-paint-strength" type="range" min="0.05" max="1" step="0.05" value="0.5" />++ <div style="display: flex; gap: 0.5rem;">+ <button id="weight-paint-undo" type="button" disabled>Undo stroke</button>+ <button id="weight-paint-clear" type="button" disabled>Clear all</button>+ </div>++ <div class="styled-checkbox">+ <input type="checkbox" id="weight-paint-mirror" checked />+ <label for="weight-paint-mirror">Mirror L/R</label>+ </div>+ </div>+ </details>+ <div class="styled-checkbox">+ <input type="checkbox" id="enable-weight-paint-step" />+ <label for="enable-weight-paint-step">Add weight painting step</label>++ <img data-tippy-content="Adds an optional step after posing the bones where you can paint weights while testing a couple of animations." src="images/icons/help.svg" alt="Help" width="20" height="20" />+ </div><div class="styled-checkbox"><input type="checkbox" id="mirror-skeleton" name="mirror-skeleton" value="mirror" checked>@@ -338,6 +380,102 @@<p class="step-instructions">Select animations you want to export by checking them by animation</p></span> -->+ <span id="weight-paint-step-tools" style="display: none; flex-direction: column; max-width: 320px;">+ <div class="pill-switch-group" aria-label="Weight painting mode" style="margin: 0 0 0.75rem;">+ <div class="pill-switch">+ <input type="radio" id="weight-paint-mode-paint" name="weight-paint-step-view-mode" value="paint" checked />+ <label for="weight-paint-mode-paint">Paint</label>++ <input type="radio" id="weight-paint-mode-test" name="weight-paint-step-view-mode" value="test" />+ <label for="weight-paint-mode-test">Test</label>+ </div>+ </div>++ <span id="weight-paint-paint-tools" style="display: flex; flex-direction: column; gap: 0.75rem;">+ <fieldset style="position: fixed; right: 300px; top: 52px;">+ <div style="display: flex; gap: 2px;">+ <button id="weight-paint-step-undo" class="secondary-button" title="Undo (Ctrl+Z)" disabled>+ <img src="images/icons/undo.png" alt="Undo" width="16" height="16" />+ </button>+ <button id="weight-paint-step-redo" class="secondary-button" title="Redo (Ctrl+Y)" disabled>+ <img src="images/icons/redo.png" alt="Redo" width="16" height="16" />+ </button>+ </div>+ </fieldset>++ <div style="display: flex; flex-direction: column; gap: 0.35rem;">+ <span class="weight-paint-tools-heading">Select Bone</span>+ <div style="display: flex; align-items: center; gap: 0.5rem;">+ <button id="weight-paint-step-pick-bone" class="secondary-button" type="button" aria-pressed="false"+ aria-label="Pick a bone by clicking the model"+ title="Pick a bone by clicking the model. Shortcut: Shift + click on the model."+ data-tippy-content="Pick a bone by clicking the model. Shortcut: Shift + click on the model.">+ <img src="images/icons/color-picker.svg" alt="" width="20" height="20" />+ </button>+ <span id="weight-paint-step-bone-name" class="weight-paint-bone-name">—</span>+ </div>+ </div>++ <div class="pill-switch-group" aria-label="Weight brush mode" style="margin: 0;"+ data-tippy-content="Brush mode. Shortcut: X">+ <div class="pill-switch">+ <input type="radio" id="weight-paint-step-add" name="weight-paint-step-mode" value="add" checked />+ <label for="weight-paint-step-add">Add</label>++ <input type="radio" id="weight-paint-step-subtract" name="weight-paint-step-mode" value="subtract" />+ <label for="weight-paint-step-subtract">Remove</label>++ <input type="radio" id="weight-paint-step-smooth" name="weight-paint-step-mode" value="smooth" />+ <label for="weight-paint-step-smooth">Smooth</label>+ </div>+ </div>++ <div class="weight-paint-slider-row">+ <label for="weight-paint-step-radius">Brush size</label>+ <input id="weight-paint-step-radius" type="range" min="4" max="160" step="1" value="24" />+ <span id="weight-paint-step-radius-value">24 px</span>+ </div>++ <div class="weight-paint-slider-row">+ <label for="weight-paint-step-strength">Strength</label>+ <input id="weight-paint-step-strength" type="range" min="0.05" max="1" step="0.05" value="0.5" />+ <span id="weight-paint-step-strength-value">50%</span>+ </div>++ <button id="weight-paint-step-reset" class="secondary-button" type="button" disabled+ data-tippy-content="Restore the automatic weights from skinning and remove all manual painting">+ Reset weights to auto+ </button>++ <div class="styled-checkbox">+ <input type="checkbox" id="weight-paint-step-mirror" checked />+ <label for="weight-paint-step-mirror">Mirror L/R</label>+ </div>+ </span>++ <span id="weight-paint-test-tools" style="display: none; flex-direction: column; gap: 0.75rem;">+ <div id="weight-paint-step-animation-list" class="weight-paint-animation-list"></div>++ <div style="display: flex; align-items: center; gap: 0.5rem;">+ <label for="weight-paint-step-speed">Speed</label>+ <select id="weight-paint-step-speed" style="flex: 1;">+ <option value="0.1">0.1x</option>+ <option value="0.25">0.25x</option>+ <option value="0.5">0.5x</option>+ <option value="1" selected>1x</option>+ <option value="1.5">1.5x</option>+ <option value="2">2x</option>+ </select>+ </div>+ <span id="weight-paint-step-animation-status" style="font-size: 0.85rem;"></span>+ </span>++ <div style="display: flex; gap: 0.5rem; margin-top: 1rem;">+ <button class="no-style-button" id="action_back_to_edit_skeleton_from_weight_paint">‹ Back</button>+ <button id="action_continue_to_animations">Continue ›</button>+ </div>+ </span>+<span id="skinned-step-animation-export-options"><div id="animations-listing"><!-- Filter textbox and tab switcher side by side -->@@ -477,6 +615,9 @@</span></div>+ <!-- fixed-size outline that follows the pointer while painting weights -->+ <div id="weight-paint-brush-cursor" aria-hidden="true"></div>+<!-- build version information--><span id="build-version"></span></body>diff --git a/src/lib/EventListeners.ts b/src/lib/EventListeners.tsindex 048939c..7fe60a2 100644--- a/src/lib/EventListeners.ts+++ b/src/lib/EventListeners.ts@@ -16,6 +16,42 @@ export class EventListeners {constructor (private readonly bootstrap: Mesh2MotionEngine) {}+ private update_weight_painting_cursor (): void {+ if (this.bootstrap.weight_painting_step.is_bone_picking_enabled()) {+ const icon = document.querySelector<HTMLImageElement>('#weight-paint-step-pick-bone img')+ let icon_url = 'images/icons/color-picker-cursor.svg'+ if (icon !== null) {+ const replaced_url = icon.src.replace('color-picker.svg', 'color-picker-cursor.svg')+ if (replaced_url.includes('color-picker-cursor.svg')) {+ icon_url = replaced_url+ }+ }++ // tip of the pipette is the hotspot; crosshair is the fallback+ this.bootstrap.renderer.domElement.style.cursor = `url("${icon_url}") 2 22, crosshair`+ return+ }++ // the crosshair is only shown while hovering a paintable mesh; empty space+ // keeps the normal pointer so rotating the canvas matches the other steps+ this.bootstrap.renderer.domElement.style.cursor = ''+ }++ private is_typing_target (target: EventTarget | null): boolean {+ return target instanceof HTMLInputElement ||+ target instanceof HTMLTextAreaElement ||+ target instanceof HTMLSelectElement ||+ (target instanceof HTMLElement && target.isContentEditable)+ }++ /**+ * True while a press that missed the mesh is dragging the camera. The press+ * is left to OrbitControls, so paint previews should not follow the pointer.+ */+ private is_camera_rotation_drag (event: PointerEvent): boolean {+ return event.buttons !== 0 && this.active_canvas_pointer_id === null+ }+public addEventListeners (): void {// monitor theme changesthis.bootstrap.theme_manager.addEventListener('theme-changed', (event: any) => {@@ -27,6 +63,31 @@ export class EventListeners {this.bootstrap.process_step = this.bootstrap.process_step_changed(ProcessStep.EditSkeleton)})+ this.bootstrap.edit_skeleton_step.addEventListener('weightPaintModeChanged', (event: Event) => {+ const enabled = (event as CustomEvent<{ enabled: boolean }>).detail.enabled+ if (enabled) {+ this.bootstrap.transform_controls.detach()+ this.bootstrap.transform_controls.enabled = false+ this.bootstrap.ui.hide_selected_bone_overlay()+ } else {+ this.bootstrap.update_edit_bone_interaction_mode()+ }+ this.bootstrap.renderer.domElement.style.cursor = ''+ })+ this.bootstrap.edit_skeleton_step.addEventListener('weightPaintChanged', () => {+ if (this.bootstrap.process_step === ProcessStep.EditSkeleton &&+ this.bootstrap.mesh_preview_display_type === ModelPreviewDisplay.WeightPainted) {+ this.bootstrap.regenerate_weight_painted_preview_mesh()+ }+ })+ this.bootstrap.weight_painting_step.addEventListener('weightPaintModeChanged', () => {+ this.bootstrap.ui.hide_selected_bone_overlay()+ this.update_weight_painting_cursor()+ })+ this.bootstrap.weight_painting_step.addEventListener('bonePickModeChanged', () => {+ this.update_weight_painting_cursor()+ })+// Listen for skeleton transformation events to update UI and visuals// this can happen with undo/redo systemthis.bootstrap.edit_skeleton_step.addEventListener('skeletonTransformed', () => {@@ -74,11 +135,97 @@ export class EventListeners {// it will scroll the webpage instead of dragging the transform controls or the camera.this.bootstrap.renderer.domElement.style.touchAction = 'none'+ // Weight paint modes claim left-button presses only when the initial+ // raycast hits the mesh. A press on empty space is left to OrbitControls,+ // so dragging after it rotates the camera instead of painting. Middle/right+ // mouse and the wheel keep orbiting, panning, and zooming either way.+ this.bootstrap.renderer.domElement.addEventListener('pointerdown', (event: PointerEvent) => {+ const edit_step_painting = this.bootstrap.process_step === ProcessStep.EditSkeleton &&+ this.bootstrap.edit_skeleton_step.is_weight_painting_enabled()+ const weight_painting_step_painting = this.bootstrap.process_step === ProcessStep.WeightPainting &&+ this.bootstrap.weight_painting_step.is_draw_mode_active()+ const weight_painting_step_picking = this.bootstrap.process_step === ProcessStep.WeightPainting &&+ this.bootstrap.weight_painting_step.is_bone_picking_enabled()++ // left paints/picks. The right button stays free for panning the camera.+ const should_capture = event.button === 0 &&+ (edit_step_painting || weight_painting_step_painting || weight_painting_step_picking)++ if (!should_capture) {+ // middle/right drags orbit and pan; keep the normal pointer for them+ if (this.bootstrap.process_step === ProcessStep.WeightPainting) {+ this.bootstrap.weight_painting_step.hide_brush_cursor()+ this.bootstrap.renderer.domElement.style.cursor = ''+ }+ return+ }++ // the initial raycast decides whether this press paints or rotates+ if (!this.bootstrap.handle_weight_paint_pointer_down(event)) {+ this.bootstrap.weight_painting_step.hide_brush_cursor()+ this.bootstrap.weight_painting_step.hide_picker_hover()+ this.update_weight_painting_cursor()+ return+ }++ event.preventDefault()+ event.stopImmediatePropagation()+ if (!weight_painting_step_picking) {+ this.bootstrap.renderer.domElement.style.cursor = 'crosshair'+ }+ this.active_canvas_pointer_id = event.pointerId+ this.bootstrap.renderer.domElement.setPointerCapture(event.pointerId)+ }, { capture: true })+this.bootstrap.renderer.domElement.addEventListener('pointermove', (event: PointerEvent) => {if (this.active_canvas_pointer_id !== null && event.pointerId !== this.active_canvas_pointer_id) {return}+ if (this.bootstrap.process_step === ProcessStep.EditSkeleton &&+ this.bootstrap.edit_skeleton_step.is_weight_painting_enabled()) {+ if (this.is_camera_rotation_drag(event)) {+ this.bootstrap.renderer.domElement.style.cursor = ''+ return+ }+ event.preventDefault()+ const over_mesh = this.bootstrap.handle_weight_paint_pointer_move(event)+ if (this.active_canvas_pointer_id !== null) {+ this.bootstrap.renderer.domElement.style.cursor = over_mesh ? 'crosshair' : ''+ } else {+ this.bootstrap.update_edit_weight_paint_cursor(event)+ }+ return+ }++ // while the picker is armed, preview the bone under the pointer before the click+ if (this.bootstrap.process_step === ProcessStep.WeightPainting &&+ this.bootstrap.weight_painting_step.is_bone_picking_enabled()) {+ if (this.is_camera_rotation_drag(event)) {+ this.bootstrap.weight_painting_step.hide_picker_hover()+ this.bootstrap.renderer.domElement.style.cursor = ''+ return+ }+ event.preventDefault()+ this.bootstrap.update_weight_paint_picker_hover(event)+ return+ }++ if (this.bootstrap.process_step === ProcessStep.WeightPainting &&+ this.bootstrap.weight_painting_step.is_draw_mode_active()) {+ if (this.is_camera_rotation_drag(event)) {+ this.bootstrap.weight_painting_step.hide_brush_cursor()+ this.bootstrap.renderer.domElement.style.cursor = ''+ return+ }+ event.preventDefault()+ const over_mesh = this.active_canvas_pointer_id !== null+ ? this.bootstrap.handle_weight_paint_pointer_move(event)+ : this.bootstrap.update_weight_paint_brush_cursor(event)+ this.bootstrap.renderer.domElement.style.cursor = over_mesh ? 'crosshair' : ''+ return+ }+if (this.bootstrap.is_transform_controls_dragging) {this.bootstrap.handle_transform_controls_moving()}@@ -110,6 +257,21 @@ export class EventListeners {}})+ this.bootstrap.renderer.domElement.addEventListener('pointerleave', () => {+ this.bootstrap.weight_painting_step.hide_brush_cursor()+ this.bootstrap.weight_painting_step.hide_picker_hover()+ this.bootstrap.renderer.domElement.style.cursor = ''+ })++ // keep the context menu out of the way while the paint tools are open, so+ // right-drag can still pan the camera+ this.bootstrap.renderer.domElement.addEventListener('contextmenu', (event: MouseEvent) => {+ if (this.bootstrap.process_step === ProcessStep.WeightPainting &&+ this.bootstrap.weight_painting_step.is_paint_mode_active()) {+ event.preventDefault()+ }+ })+this.bootstrap.renderer.domElement.addEventListener('pointerdown', (event: PointerEvent) => {const use_mesh_drag_mode =this.bootstrap.process_step === ProcessStep.EditSkeleton &&@@ -138,6 +300,7 @@ export class EventListeners {return}+ this.bootstrap.handle_weight_paint_pointer_up(event)this.bootstrap.handle_mesh_drag_mode_mouse_up()if (this.active_canvas_pointer_id !== null &&@@ -147,7 +310,7 @@ export class EventListeners {this.active_canvas_pointer_id = nullthis.bootstrap.ui.hide_selected_bone_overlay()- this.bootstrap.renderer.domElement.style.cursor = ''+ this.update_weight_painting_cursor()})document.addEventListener('pointercancel', (event: PointerEvent) => {@@ -155,6 +318,7 @@ export class EventListeners {return}+ this.bootstrap.handle_weight_paint_pointer_up(event)this.bootstrap.handle_mesh_drag_mode_mouse_up()if (this.active_canvas_pointer_id !== null &&@@ -164,7 +328,7 @@ export class EventListeners {this.active_canvas_pointer_id = nullthis.bootstrap.ui.hide_selected_bone_overlay()- this.bootstrap.renderer.domElement.style.cursor = ''+ this.update_weight_painting_cursor()})// custom event listeners for the transform controls.@@ -223,12 +387,26 @@ export class EventListeners {})this.bootstrap.load_model_step.addEventListener('modelLoaded', () => {+ this.bootstrap.edit_skeleton_step.reset_weight_paint_overrides()this.bootstrap.process_step = this.bootstrap.process_step_changed(ProcessStep.LoadSkeleton)})this.bootstrap.ui.dom_bind_pose_button?.addEventListener('click', () => {this.bootstrap.setup_weight_skinning_config()- this.bootstrap.process_step_changed(ProcessStep.BindPose)++ // the weight painting step is optional, so skip it unless the user+ // enabled it while positioning the bones+ const weight_paint_step_enabled = this.bootstrap.ui.dom_enable_weight_paint_step?.checked ?? false+ this.bootstrap.process_step_changed(+ weight_paint_step_enabled ? ProcessStep.WeightPainting : ProcessStep.BindPose)+ })++ this.bootstrap.ui.dom_back_to_edit_skeleton_from_weight_paint_button?.addEventListener('click', () => {+ this.bootstrap.back_to_edit_skeleton()+ })++ this.bootstrap.ui.dom_continue_to_animations_button?.addEventListener('click', () => {+ this.bootstrap.process_step_changed(ProcessStep.AnimationsListing)})// rotate model after loading it in to orient it correctly@@ -307,18 +485,16 @@ export class EventListeners {})})- // going back to edit skeleton step after skinning- // this will do a lot of resetting+ // going back from the animation listing returns to weight painting when+ // that optional step is enabled, otherwise it goes straight back to the bonesthis.bootstrap.ui.dom_back_to_edit_skeleton_button?.addEventListener('click', () => {- this.bootstrap.remove_skinned_meshes_from_scene() // clear any existing skinned meshes- this.bootstrap.debugging_visual_object = Utility.regenerate_debugging_scene(this.bootstrap.scene)- this.bootstrap.process_step = this.bootstrap.process_step_changed(ProcessStep.EditSkeleton)-- // reset current bone selection for edit skeleton step- this.bootstrap.edit_skeleton_step.set_currently_selected_bone(null)+ const weight_paint_step_enabled = this.bootstrap.ui.dom_enable_weight_paint_step?.checked ?? false+ if (weight_paint_step_enabled) {+ this.bootstrap.process_step_changed(ProcessStep.WeightPainting)+ return+ }- // reset the undo/redo system- this.bootstrap.edit_skeleton_step.clear_undo_history()+ this.bootstrap.back_to_edit_skeleton()})// going back to load skeleton step from edit skeleton step@@ -372,8 +548,11 @@ export class EventListeners {// Keyboard shortcuts for undo/redodocument.addEventListener('keydown', (event: KeyboardEvent) => {- // Only handle keyboard shortcuts when in EditSkeleton step- if (this.bootstrap.process_step !== ProcessStep.EditSkeleton) {+ const is_edit_step = this.bootstrap.process_step === ProcessStep.EditSkeleton+ const is_weight_painting_step = this.bootstrap.process_step === ProcessStep.WeightPainting++ // Only handle keyboard shortcuts in these steps+ if (!is_edit_step && !is_weight_painting_step) {return}@@ -385,12 +564,25 @@ export class EventListeners {if (is_undo_shortcut_pressed) {event.preventDefault()- this.bootstrap.edit_skeleton_step.undo_bone_transformation()+ if (is_edit_step) {+ if (this.bootstrap.edit_skeleton_step.is_weight_painting_enabled() &&+ this.bootstrap.edit_skeleton_step.weight_paint_manager.can_undo()) {+ this.bootstrap.edit_skeleton_step.undo_weight_paint_stroke()+ } else {+ this.bootstrap.edit_skeleton_step.undo_bone_transformation()+ }+ } else if (is_weight_painting_step) {+ this.bootstrap.weight_painting_step.undo_weight_paint_stroke()+ }}if (is_redo_shortcut_pressed) {event.preventDefault()- this.bootstrap.edit_skeleton_step.redo_bone_transformation()+ if (is_edit_step) {+ this.bootstrap.edit_skeleton_step.redo_bone_transformation()+ } else if (is_weight_painting_step) {+ this.bootstrap.weight_painting_step.redo_weight_paint_stroke()+ }}})}diff --git a/src/lib/UI.ts b/src/lib/UI.tsindex d2b2978..f74992a 100644--- a/src/lib/UI.ts+++ b/src/lib/UI.ts@@ -70,9 +70,13 @@ export class UI {dom_arm_plane_offset_label: HTMLElement | null = nulldom_arm_plane_setting_container: HTMLElement | null = null+ dom_weight_paint_step_tools: HTMLElement | null = null+ dom_enable_weight_paint_step: HTMLInputElement | null = nulldom_skinned_mesh_tools: HTMLElement | null = nulldom_skinned_mesh_animation_tools: HTMLElement | null = nulldom_back_to_edit_skeleton_button: HTMLButtonElement | null = null+ dom_back_to_edit_skeleton_from_weight_paint_button: HTMLButtonElement | null = null+ dom_continue_to_animations_button: HTMLButtonElement | null = nulldom_back_to_load_skeleton_button: HTMLButtonElement | null = nulldom_back_to_load_model_button: HTMLButtonElement | null = nulldom_enable_skin_debugging: HTMLInputElement | null = null@@ -218,11 +222,17 @@ export class UI {this.dom_scale_skeleton_percentage_display = document.querySelector('#scale-skeleton-percentage-display')this.dom_scale_skeleton_controls = document.querySelector('#scale-skeleton-controls')+ // UI controls for the optional weight painting step+ this.dom_weight_paint_step_tools = document.querySelector('#weight-paint-step-tools')+ this.dom_enable_weight_paint_step = document.querySelector('#enable-weight-paint-step')+// UI controls for working with skinned meshthis.dom_skinned_mesh_tools = document.querySelector('#skinned-step-tools')this.dom_skinned_mesh_animation_tools = document.querySelector('#skinned-step-animation-export-options')this.dom_back_to_edit_skeleton_button = document.querySelector('#action_back_to_edit_skeleton')+ this.dom_back_to_edit_skeleton_from_weight_paint_button = document.querySelector('#action_back_to_edit_skeleton_from_weight_paint')+ this.dom_continue_to_animations_button = document.querySelector('#action_continue_to_animations')this.dom_back_to_load_skeleton_button = document.querySelector('#action_back_to_load_skeleton')this.dom_back_to_load_model_button = document.querySelector('#action_back_to_load_model')@@ -291,6 +301,9 @@ export class UI {if (this.dom_skeleton_edit_tools != null) {this.dom_skeleton_edit_tools.style.display = 'none'}+ if (this.dom_weight_paint_step_tools != null) {+ this.dom_weight_paint_step_tools.style.display = 'none'+ }if (this.dom_skinned_mesh_tools != null) {this.dom_skinned_mesh_tools.style.display = 'none'}diff --git a/src/lib/enums/ProcessStep.ts b/src/lib/enums/ProcessStep.tsindex 92ccb17..3c7cd50 100644--- a/src/lib/enums/ProcessStep.ts+++ b/src/lib/enums/ProcessStep.ts@@ -3,6 +3,7 @@ export enum ProcessStep {LoadSkeleton = 'load-skeleton',EditSkeleton = 'edit-skeleton',WeightSkin = 'weight-skin',+ WeightPainting = 'weight-painting',AnimationsListing = 'animations-export',StepExportToFile = 'export-to-file',BindPose = 'BindPose'diff --git a/src/lib/processes/animations-listing/StepAnimationsListing.ts b/src/lib/processes/animations-listing/StepAnimationsListing.tsindex c14a6aa..b19f2b9 100644--- a/src/lib/processes/animations-listing/StepAnimationsListing.ts+++ b/src/lib/processes/animations-listing/StepAnimationsListing.ts@@ -2,7 +2,8 @@ import { UI } from '../../UI.ts'import { AnimationPlayer } from './AnimationPlayer.ts'import {- type AnimationClip, AnimationMixer, type SkinnedMesh, type AnimationAction, Object3D, type Scene+ type AnimationClip, AnimationMixer, SkinnedMesh,+ type AnimationAction, Object3D, type Scene} from 'three'import { AnimationUtility } from './AnimationUtility.ts'@@ -161,7 +162,7 @@ export class StepAnimationsListing extends EventTarget {this.animation_player.clear_animation()}- // If we change skeleton types, we need to reset some of the state+ // If we change skeleton types, we need to reset some of the state// in the case we selected animations. This clears the UI state associated with that.private reset_ui_elements (): void {if (this.ui.dom_animation_clip_list !== null) {@@ -185,6 +186,11 @@ export class StepAnimationsListing extends EventTarget {return this.animation_mixer}+ /** Shared timeline UI, also used by the optional weight painting step. */+ public get_animation_player (): AnimationPlayer {+ return this.animation_player+ }+// setup in the bootstrap.ts file and only called if we are actively// on this steppublic frame_change (delta_time: number): void {diff --git a/src/lib/processes/edit-skeleton/StepEditSkeleton.ts b/src/lib/processes/edit-skeleton/StepEditSkeleton.tsindex f3e613a..80fb8f3 100644--- a/src/lib/processes/edit-skeleton/StepEditSkeleton.ts+++ b/src/lib/processes/edit-skeleton/StepEditSkeleton.ts@@ -1,3 +1,5 @@+import { type ManualWeightOverrides, type WeightPaintManager } from '../weight-painting/WeightPaintManager.ts'+import { WeightPaintEditTools } from '../weight-painting/WeightPaintEditTools.ts'import { UI } from '../../UI.ts'import { Generators } from '../../Generators.ts'import { Utility } from '../../Utilities.ts'@@ -14,6 +16,7 @@ import {Skeleton,type Scene,type Bone,+ type Intersection,BufferGeometry,PointsMaterial,Points,@@ -46,6 +49,13 @@ export class StepEditSkeleton extends EventTarget {private skinning_algorithm: string | null = nullprivate show_debug: boolean = true+ /** Weight painting tools shown while positioning the joints. */+ public readonly weight_paint_tools = new WeightPaintEditTools()++ public get weight_paint_manager (): WeightPaintManager {+ return this.weight_paint_tools.manager+ }+private currently_selected_bone: Bone | null = nullprivate joint_hover_point: Object3D | null = null@@ -75,6 +85,15 @@ export class StepEditSkeleton extends EventTarget {super()this.ui = UI.getInstance()this.undo_redo_system = new UndoRedoSystem(50) // Store up to 50 undo states++ // the paint tools own their state, but the engine listens on this step+ this.weight_paint_tools.addEventListener('weightPaintModeChanged', (event) => {+ const detail = (event as CustomEvent<{ enabled: boolean }>).detail+ this.dispatchEvent(new CustomEvent('weightPaintModeChanged', { detail }))+ })+ this.weight_paint_tools.addEventListener('weightPaintChanged', () => {+ this.dispatchEvent(new CustomEvent('weightPaintChanged'))+ })}/**@@ -168,6 +187,8 @@ export class StepEditSkeleton extends EventTarget {}public begin (main_scene: Scene, skeleton_type: SkeletonType): void {+ this._current_skeleton_type = skeleton_type+ this.weight_paint_tools.begin(this.threejs_skeleton.bones)this.update_ui_options_on_begin(skeleton_type)// show UI elements for editing mesh@@ -291,14 +312,19 @@ export class StepEditSkeleton extends EventTarget {}private update_bind_button_text (): void {- if (this.show_debug && this.ui.dom_bind_pose_button !== null) {- this.ui.dom_bind_pose_button.innerHTML = 'Test Skinning Algorithm ›'+ if (this.ui.dom_bind_pose_button === null) { return }++ if (this.ui.dom_enable_weight_paint_step?.checked === true) {+ this.ui.dom_bind_pose_button.innerHTML = 'Weight painting ›'return}- if (this.ui.dom_bind_pose_button !== null) {- this.ui.dom_bind_pose_button.innerHTML = 'Finish ›'+ if (this.show_debug) {+ this.ui.dom_bind_pose_button.innerHTML = 'Test Skinning Algorithm ›'+ return}++ this.ui.dom_bind_pose_button.innerHTML = 'Finish ›'}public show_debugging (): boolean {@@ -442,6 +468,57 @@ export class StepEditSkeleton extends EventTarget {return this.arm_plane_offset}+ public manual_weight_overrides (): ManualWeightOverrides {+ return this.weight_paint_tools.overrides_for_skin()+ }++ public set_weight_paint_available (available: boolean): void {+ this.weight_paint_tools.set_available(available)+ }++ public is_weight_painting_enabled (): boolean {+ return this.weight_paint_tools.is_enabled()+ }++ public set_weight_painting_enabled (enabled: boolean): void {+ const was_enabled = this.weight_paint_tools.is_enabled()+ this.weight_paint_tools.set_enabled(enabled)+ if (enabled && !was_enabled && this.weight_paint_tools.is_enabled()) {+ this.set_currently_selected_bone(null)+ }+ }++ public begin_weight_paint_stroke (): void {+ this.weight_paint_tools.begin_stroke()+ }++ public end_weight_paint_stroke (): void {+ this.weight_paint_tools.end_stroke()+ }++ /** Breaks the drag sweep when the pointer leaves the mesh. */+ public reset_weight_paint_dab_path (): void {+ this.weight_paint_tools.reset_dab_path()+ }++ /** Paints (or smooths) the selected bone under the brush. */+ public paint_weights (intersection: Intersection, camera: PerspectiveCamera): void {+ this.weight_paint_tools.paint(intersection, camera)+ }++ public undo_weight_paint_stroke (): void {+ this.weight_paint_tools.undo_stroke()+ }++ public clear_weight_paint (): void {+ this.weight_paint_tools.clear()+ }++ /** Used when a different model is loaded, since vertex indices no longer match. */+ public reset_weight_paint_overrides (): void {+ this.weight_paint_tools.reset()+ }+public add_event_listeners (): void {if (this.ui.dom_move_to_origin_button !== null) {this.ui.dom_move_to_origin_button.addEventListener('click', () => {@@ -490,6 +567,10 @@ export class StepEditSkeleton extends EventTarget {this.update_bind_button_text()})+ this.ui.dom_enable_weight_paint_step?.addEventListener('change', () => {+ this.update_bind_button_text()+ })+// Add undo/redo button event listenersthis.ui.dom_undo_button?.addEventListener('click', () => {this.undo_bone_transformation()@@ -625,6 +706,7 @@ export class StepEditSkeleton extends EventTarget {}public cleanup_on_exit_step (): void {+ this.set_weight_painting_enabled(false)this.remove_event_listeners()this.clear_hover_point_if_exists()this.remove_preview_plane()diff --git a/src/lib/processes/weight-painting/StepWeightPainting.ts b/src/lib/processes/weight-painting/StepWeightPainting.tsnew file mode 100644index 0000000..e4624b1--- /dev/null+++ b/src/lib/processes/weight-painting/StepWeightPainting.ts@@ -0,0 +1,999 @@+import { UI } from '../../UI.ts'+import { AnimationLoader } from '../animations-listing/AnimationLoader.ts'+import { type AnimationPlayer } from '../animations-listing/AnimationPlayer.ts'+import { WeightPaintManager, type WeightPaintMode } from './WeightPaintManager.ts'+import { WeightPaintBrush } from './WeightPaintBrush.ts'+import { RigConfig, type RigAnimation } from '../../RigConfig.ts'+import { Utility } from '../../Utilities.ts'+import {+ AnimationMixer, BufferGeometry, Float32BufferAttribute, LoopRepeat, MeshBasicMaterial,+ Object3D, SkinnedMesh, Vector3,+ type AnimationAction, type AnimationClip, type Bone, type Intersection, type PerspectiveCamera,+ type Quaternion+} from 'three'+import { SkeletonType } from '../../enums/SkeletonType.ts'+import { type Mesh2MotionEngine } from '../../../Mesh2MotionEngine.ts'++type WeightPaintStepMode = 'paint' | 'test'++/**+ * Optional step shown between posing the skeleton and the animation listing.+ *+ * It brings the user straight to the part of skinning that benefits from a+ * posed mesh: a couple of simple animations for testing deformation, plus the+ * weight painting brush and a live heatmap.+ */+export class StepWeightPainting extends EventTarget {+ private static readonly max_animations: number = 4+ private static readonly preferred_animation_names: Partial<Record<SkeletonType, string[]>> = {+ // names match the manifest, falling back to the first animations of the rig+ // when one of these is missing+ human: ['Idle_A', 'Walk', 'Run_Female', 'Crouch_Walk'],+ fox: ['Idle', 'Walk', 'Run', 'Trot'],+ bird: ['Flap', 'Walk', 'Glide', 'Hop'],+ dragon: ['Fly Flap', 'Walk', 'Fly Glide', 'Take_Off'],+ kaiju: ['Idle', 'Walk', 'Roar', 'Attack'],+ spider: ['Idle', 'Walk', 'Jump', 'Attack'],+ snake: ['Idle', 'Coiled', 'Dance', 'Side winding'],+ fish: ['Idle', 'Swim Horizontal', 'Swim Vertical', 'Bite'],+ horse: ['Idle', 'Walk', 'Trot', 'Run']+ }++ private readonly ui: UI = UI.getInstance()+ private readonly animation_loader: AnimationLoader = new AnimationLoader()+ private animation_mixer: AnimationMixer = new AnimationMixer(new Object3D())+ private animations: RigAnimation[] = []+ private selected_animation_index = 0+ private animation_speed = 1.0+ private animation_player: AnimationPlayer | null = null+ private readonly loaded_clips = new Map<string, AnimationClip>()++ private skinned_meshes: SkinnedMesh[] = []+ private skeleton_type: SkeletonType = SkeletonType.None+ private skeleton_scale = 1.0+ private weight_paint_manager: WeightPaintManager | null = null++ private active_mode: WeightPaintStepMode = 'paint'+ private is_active = false+ private alt_rotate_active = false+ private weight_paint_brush: WeightPaintBrush | null = null+ private brush_cursor: HTMLElement | null = null+ private weight_paint_bone_name: string | null = null+ private bone_names: string[] = []+ private bone_picking_enabled = false+ private weight_paint_clear_marker = 0+ private readonly weight_paint_overlays = new Map<SkinnedMesh, SkinnedMesh>()+ private readonly geometry_center_cache = new WeakMap<BufferGeometry, number>()+ private readonly original_materials = new Map<SkinnedMesh, SkinnedMesh['material']>()+ private readonly black_material = new MeshBasicMaterial({ color: 0x000000 })+ private rest_bone_transforms: Array<{+ bone: Bone+ position: Vector3+ quaternion: Quaternion+ scale: Vector3+ }> = []+ private bone_overlay_timeout: number | null = null++ private _added_event_listeners = false++ constructor (private readonly engine: Mesh2MotionEngine) {+ super()+ }++ public begin (+ skinned_meshes: SkinnedMesh[],+ skeleton_type: SkeletonType,+ skeleton_scale: number,+ weight_paint_manager: WeightPaintManager,+ animation_player: AnimationPlayer+ ): void {+ this.skinned_meshes = skinned_meshes+ this.skeleton_type = skeleton_type+ this.skeleton_scale = skeleton_scale+ this.weight_paint_manager = weight_paint_manager+ this.animation_player = animation_player+ this.weight_paint_clear_marker = weight_paint_manager.undo_stack_marker()+ this.animation_player.clear_animation()++ this.is_active = true+ this.alt_rotate_active = false+ if (this.weight_paint_brush === null) {+ this.weight_paint_brush = new WeightPaintBrush(weight_paint_manager)+ }+ this.weight_paint_brush.mode = 'add'+ this.weight_paint_brush.mirror_enabled = true++ this.animation_loader.set_skeleton_type(skeleton_type)+ // the create page serves animation assets from the site root+ this.animation_loader.set_static_root_path('')+ // scale or rig changes make previously loaded clips stale+ this.loaded_clips.clear()++ if (this.ui.dom_current_step_element !== null) {+ this.ui.dom_current_step_element.innerHTML = 'Weight painting'+ }+ if (this.ui.dom_weight_paint_step_tools !== null) {+ this.ui.dom_weight_paint_step_tools.style.display = 'flex'+ }+ if (this.ui.dom_show_skeleton_container !== null) {+ this.ui.dom_show_skeleton_container.style.display = 'inline-flex'+ }++ this.set_bone_picking_enabled(false)+ this.animations = this.skinning_animations(skeleton_type)+ this.capture_rest_pose()+ this.update_weight_paint_bone_options()+ this.populate_animation_options()++ // every vertex starts normalized, and every stroke keeps it that way+ this.weight_paint_manager?.normalize_all_weights(this.skinned_meshes)+ this.set_active_mode('paint', true)++ if (!this._added_event_listeners) {+ this.add_event_listeners()+ this._added_event_listeners = true+ }+ }++ public active_skinned_meshes (): SkinnedMesh[] {+ return this.skinned_meshes+ }++ public frame_change (delta_time: number): void {+ this.animation_mixer.update(delta_time)+ this.animation_player?.update(delta_time)+ }++ /** Called when the app leaves the weight painting step. */+ public cleanup_on_exit_step (): void {+ this.is_active = false+ this.alt_rotate_active = false+ this.set_bone_picking_enabled(false)+ this.clear_bone_overlay()+ this.hide_brush_cursor()+ this.weight_paint_manager?.finish_stroke()+ this.restore_skinned_mesh_materials()+ this.dispose_weight_paint_overlays()+ this.animation_mixer.stopAllAction()+ this.animation_mixer = new AnimationMixer(new Object3D())+ this.animation_player?.clear_animation()+ this.set_animation_player_visible(false)+ this.skinned_meshes = []+ this.rest_bone_transforms = []+ this.set_animation_status('')+ }++ public current_mode (): WeightPaintStepMode {+ return this.active_mode+ }++ public is_paint_mode_active (): boolean {+ return this.is_active && this.active_mode === 'paint'+ }++ public is_view_rotation_active (): boolean {+ return this.alt_rotate_active+ }++ /**+ * Paint mode paints with the left mouse button. Starting the drag on empty+ * space or holding Alt returns the camera to the user.+ */+ public is_draw_mode_active (): boolean {+ return this.is_active && this.active_mode === 'paint' && !this.alt_rotate_active+ }++ public set_active_mode (mode: WeightPaintStepMode, force: boolean = false): void {+ if (!this.is_active) { return }+ if (!force && this.active_mode === mode) { return }++ this.active_mode = mode+ if (mode === 'paint') {+ this.enter_paint_mode()+ } else {+ this.enter_test_mode()+ }++ this.update_mode_radios()+ this.dispatchEvent(new CustomEvent('weightPaintModeChanged', {+ detail: { enabled: this.is_draw_mode_active() }+ }))+ }++ private enter_paint_mode (): void {+ this.set_bone_picking_enabled(false)+ this.set_alt_rotate_active(false)+ this.clear_bone_overlay()+ this.hide_brush_cursor()+ this.restore_rest_pose()+ this.animation_player?.clear_animation()+ this.darken_skinned_meshes()+ this.create_weight_paint_overlays()+ this.show_paint_ui(true)+ this.show_test_ui(false)+ this.set_animation_player_visible(false)+ this.update_weight_paint_ui()+ }++ private enter_test_mode (): void {+ this.set_bone_picking_enabled(false)+ this.set_alt_rotate_active(false)+ this.clear_bone_overlay()+ this.hide_brush_cursor()+ this.restore_rest_pose()+ this.dispose_weight_paint_overlays()+ this.restore_skinned_mesh_materials()+ this.show_paint_ui(false)+ this.show_test_ui(true)+ this.set_animation_player_visible(true)+ this.play_animation_at(this.selected_animation_index)++ if (this.animations.length === 0) {+ this.set_animation_status('No test animations available for this rig')+ }+ }++ private set_alt_rotate_active (enabled: boolean): void {+ if (this.alt_rotate_active === enabled) { return }+ if (enabled && (!this.is_active || this.active_mode !== 'paint')) { return }++ this.alt_rotate_active = enabled+ if (enabled) {+ this.set_bone_picking_enabled(false)+ this.hide_brush_cursor()+ }++ this.dispatchEvent(new CustomEvent('weightPaintModeChanged', {+ detail: { enabled: this.is_draw_mode_active() }+ }))+ }++ public begin_weight_paint_stroke (): void {+ this.weight_paint_brush?.begin_stroke()+ this.update_weight_paint_ui()+ }++ public end_weight_paint_stroke (): void {+ // normalize first so the redo snapshot captures the final weights+ this.weight_paint_brush?.finish_stroke(this.skinned_meshes)+ this.update_weight_paint_overlay_colors(this.weight_paint_bone_name)+ this.update_weight_paint_ui()+ }++ /** Paints (or smooths) the selected bone on the posed skinned mesh under the brush. */+ public paint_weights (intersection: Intersection, camera: PerspectiveCamera): void {+ const bone_name = this.weight_paint_bone_name+ if (this.weight_paint_brush === null || bone_name === null) { return }++ this.weight_paint_brush.paint(intersection, camera, bone_name)+ // Mirroring and smoothing can change any vertex, so refresh the whole heatmap.+ this.update_weight_paint_overlay_colors(bone_name)+ this.update_weight_paint_ui()+ }++ /** Breaks the drag sweep when the pointer leaves the mesh. */+ public reset_paint_dab_path (): void {+ this.weight_paint_brush?.reset_dab_path()+ }++ /** Re-runs skinning without the manual overrides and re-enters this step. */+ public reset_weights_to_auto (): void {+ if (!this.is_active) { return }+ this.engine.reset_weights_to_auto()+ }++ public undo_weight_paint_stroke (): void {+ if (this.weight_paint_manager === null) { return }+ if (!this.weight_paint_manager.can_undo_since(this.weight_paint_clear_marker)) { return }+ this.weight_paint_manager.undo()+ this.update_weight_paint_overlay_colors(this.weight_paint_bone_name)+ this.update_weight_paint_ui()+ }++ public redo_weight_paint_stroke (): void {+ if (this.weight_paint_manager === null) { return }+ if (!this.weight_paint_manager.can_redo_since(this.weight_paint_clear_marker)) { return }+ this.weight_paint_manager.redo()+ this.update_weight_paint_overlay_colors(this.weight_paint_bone_name)+ this.update_weight_paint_ui()+ }++ public is_bone_picking_enabled (): boolean {+ return this.bone_picking_enabled+ }++ public set_bone_picking_enabled (enabled: boolean): void {+ if (this.bone_picking_enabled === enabled) {+ this.update_weight_paint_ui()+ return+ }++ this.bone_picking_enabled = enabled+ if (!enabled) {+ this.hide_picker_hover()+ }+ this.dispatchEvent(new CustomEvent('bonePickModeChanged', { detail: { enabled } }))+ this.update_weight_paint_ui()+ }++ /**+ * While the picker is armed, show which bone is under the pointer before the+ * user clicks. The engine feeds this with the current ray intersection.+ */+ public update_picker_hover (intersection: Intersection | null): void {+ if (!this.is_active || this.active_mode !== 'paint' || !this.bone_picking_enabled) { return }+ if (intersection === null) {+ this.hide_picker_hover()+ return+ }++ const bone_name = this.bone_name_at_intersection(intersection)+ if (bone_name === null) {+ this.hide_picker_hover()+ return+ }++ this.clear_bone_overlay_timeout()+ this.ui.show_selected_bone_overlay(bone_name)+ }++ public hide_picker_hover (): void {+ this.clear_bone_overlay_timeout()+ this.ui.hide_selected_bone_overlay()+ }++ /** Select the bone with the strongest influence at the clicked surface point. */+ public pick_bone (intersection: Intersection): void {+ const best_bone_name = this.bone_name_at_intersection(intersection)+ if (best_bone_name === null) { return }++ this.weight_paint_bone_name = best_bone_name+ this.update_bone_name_display()+ this.update_weight_paint_overlay_colors(best_bone_name)+ this.set_bone_picking_enabled(false)+ this.show_picked_bone_overlay(best_bone_name)+ this.update_weight_paint_ui()+ }++ /** Strongest selectable bone influence at the surface point under the pointer. */+ private bone_name_at_intersection (intersection: Intersection): string | null {+ const object = intersection.object+ const face = intersection.face+ if (!(object instanceof SkinnedMesh) || face === null || face === undefined) { return null }++ const positions = object.geometry.attributes.position+ const skin_indices = object.geometry.attributes.skinIndex+ const skin_weights = object.geometry.attributes.skinWeight+ if (positions === undefined || skin_indices === undefined || skin_weights === undefined) { return null }++ object.updateWorldMatrix(true, false)+ const local_point = object.worldToLocal(intersection.point.clone())++ // use the nearest corner of the hit triangle so small features like+ // fingers can still be picked+ let closest_vertex = face.a+ let closest_distance = Infinity+ for (const vertex_index of [face.a, face.b, face.c]) {+ const dx = positions.getX(vertex_index) - local_point.x+ const dy = positions.getY(vertex_index) - local_point.y+ const dz = positions.getZ(vertex_index) - local_point.z+ const distance = dx * dx + dy * dy + dz * dz+ if (distance < closest_distance) {+ closest_distance = distance+ closest_vertex = vertex_index+ }+ }++ const selectable = new Set(this.bone_names)+ let best_bone_name: string | null = null+ let best_weight = 0+ for (let slot = 0; slot < 4; slot++) {+ const weight = skin_weights.array[closest_vertex * 4 + slot] as number+ if (weight <= best_weight) { continue }++ const bone = object.skeleton.bones[skin_indices.array[closest_vertex * 4 + slot] as number]+ if (bone === undefined || !selectable.has(bone.name)) { continue }++ best_bone_name = bone.name+ best_weight = weight+ }++ return best_bone_name+ }++ /** Replaces the textures with a black material so only weight colors show. */+ private darken_skinned_meshes (): void {+ for (const skinned_mesh of this.skinned_meshes) {+ if (!this.original_materials.has(skinned_mesh)) {+ this.original_materials.set(skinned_mesh, skinned_mesh.material)+ }+ skinned_mesh.material = this.black_material+ }+ }++ private restore_skinned_mesh_materials (): void {+ for (const [skinned_mesh, material] of this.original_materials) {+ skinned_mesh.material = material+ }+ this.original_materials.clear()+ }++ private capture_rest_pose (): void {+ const skeleton = this.skinned_meshes[0]?.skeleton+ this.rest_bone_transforms = skeleton === undefined+ ? []+ : skeleton.bones.map((bone) => ({+ bone,+ position: bone.position.clone(),+ quaternion: bone.quaternion.clone(),+ scale: bone.scale.clone()+ }))+ }++ private restore_rest_pose (): void {+ this.animation_mixer.stopAllAction()+ this.animation_mixer = new AnimationMixer(new Object3D())++ for (const transform of this.rest_bone_transforms) {+ transform.bone.position.copy(transform.position)+ transform.bone.quaternion.copy(transform.quaternion)+ transform.bone.scale.copy(transform.scale)+ transform.bone.updateWorldMatrix(true, true)+ }+ }++ /**+ * Shows the brush outline at the pointer. It is a fixed-size HTML circle+ * rather than a world-space ring, so it stays thin and keeps the same screen+ * size at every zoom level.+ */+ public update_brush_cursor (event: PointerEvent, intersection: Intersection | null): void {+ if (!this.is_draw_mode_active() || intersection === null ||+ !(intersection.object instanceof SkinnedMesh) || this.weight_paint_brush === null) {+ this.hide_brush_cursor()+ return+ }++ const cursor = this.brush_cursor_element()+ if (cursor === null) { return }++ const width = this.weight_paint_brush.width_px()+ cursor.style.width = `${width}px`+ cursor.style.height = `${width}px`+ cursor.style.left = `${event.clientX}px`+ cursor.style.top = `${event.clientY}px`+ cursor.style.display = 'block'+ }++ public hide_brush_cursor (): void {+ const cursor = this.brush_cursor_element()+ if (cursor !== null) {+ cursor.style.display = 'none'+ }+ }++ private brush_cursor_element (): HTMLElement | null {+ if (this.brush_cursor === null) {+ this.brush_cursor = document.getElementById('weight-paint-brush-cursor')+ }+ return this.brush_cursor+ }++ private skinning_animations (skeleton_type: SkeletonType): RigAnimation[] {+ const available = RigConfig.animations_for(skeleton_type)+ .filter(animation => animation.name !== 'Rest Pose')+ const preferred_names = StepWeightPainting.preferred_animation_names[skeleton_type] ?? []+ const selected: RigAnimation[] = []++ for (const name of preferred_names) {+ const animation = available.find(candidate => candidate.name === name)+ if (animation !== undefined && !selected.includes(animation)) {+ selected.push(animation)+ }+ if (selected.length === StepWeightPainting.max_animations) { return selected }+ }++ for (const animation of available) {+ if (selected.length === StepWeightPainting.max_animations) { break }+ if (!selected.includes(animation)) {+ selected.push(animation)+ }+ }+ return selected+ }++ private populate_animation_options (): void {+ const list = document.getElementById('weight-paint-step-animation-list')+ if (list === null) { return }++ list.innerHTML = ''+ this.animations.forEach((animation, index) => {+ const button = document.createElement('button')+ button.type = 'button'+ button.className = 'weight-paint-animation-button'+ button.dataset.animationIndex = String(index)+ button.textContent = animation.name.replace(/_/g, ' ')+ button.addEventListener('click', () => {+ this.play_animation_at(index)+ })+ list.appendChild(button)+ })++ if (this.selected_animation_index >= this.animations.length) {+ this.selected_animation_index = 0+ }+ this.update_animation_buttons()++ if (this.animations.length === 0) {+ this.set_animation_status('No test animations available for this rig')+ }+ }++ private update_animation_buttons (): void {+ document.querySelectorAll<HTMLButtonElement>('.weight-paint-animation-button').forEach((button) => {+ const index = Number(button.dataset.animationIndex)+ button.classList.toggle('active', index === this.selected_animation_index)+ })+ }++ private play_animation_at (index: number): void {+ const animation = this.animations[index]+ if (animation === undefined) { return }++ this.selected_animation_index = index+ this.update_animation_buttons()++ const cached_clip = this.loaded_clips.get(animation.file)+ if (cached_clip !== undefined) {+ this.apply_animation(cached_clip)+ return+ }++ this.set_animation_status(`Loading ${animation.name}...`)+ this.animation_loader.load_animation_file(animation.file, this.skeleton_scale)+ .then((clip_pairs) => {+ const clip = clip_pairs[0]?.display_animation_clip+ if (clip === undefined) { return }+ this.loaded_clips.set(animation.file, clip)+ if (this.animations[this.selected_animation_index]?.file === animation.file) {+ this.apply_animation(clip)+ }+ })+ .catch((error: unknown) => {+ console.error('Failed to load weight painting test animation:', animation.file, error)+ this.set_animation_status(`Could not load ${animation.name}`)+ })+ }++ private apply_animation (clip: AnimationClip): void {+ this.animation_mixer.stopAllAction()+ this.animation_mixer = new AnimationMixer(new Object3D())+ this.animation_mixer.timeScale = this.animation_speed++ const actions: AnimationAction[] = []+ this.skinned_meshes.forEach((skinned_mesh) => {+ const action = this.animation_mixer.clipAction(clip, skinned_mesh)+ action.setLoop(LoopRepeat, Infinity)+ action.reset()+ action.play()+ actions.push(action)+ })++ this.animation_mixer.update(0)+ this.animation_player?.set_animation(clip, actions)+ this.set_animation_status('')+ }++ private set_animation_status (text: string): void {+ const status = document.getElementById('weight-paint-step-animation-status')+ if (status !== null) { status.textContent = text }+ }++ private update_weight_paint_bone_options (): void {+ const skeleton = this.skinned_meshes[0]?.skeleton+ const position_bone_name = RigConfig.by_skeleton_type(this.skeleton_type)?.position_tracking_bone_name++ this.bone_names = skeleton === undefined+ ? []+ : skeleton.bones+ .filter(bone => {+ if (bone.name.toLowerCase() === 'root') { return false }+ if (bone.name === position_bone_name) { return true }+ return !Utility.is_leaf_bone(bone)+ })+ .map(bone => bone.name)++ if (skeleton !== undefined && position_bone_name !== undefined &&+ skeleton.bones.some(bone => bone.name === position_bone_name) &&+ !this.bone_names.includes(position_bone_name)) {+ this.bone_names.unshift(position_bone_name)+ }++ if (this.weight_paint_bone_name === null || !this.bone_names.includes(this.weight_paint_bone_name)) {+ this.weight_paint_bone_name = position_bone_name !== undefined && this.bone_names.includes(position_bone_name)+ ? position_bone_name+ : (this.bone_names[0] ?? null)+ }++ this.update_bone_name_display()+ }++ private update_bone_name_display (): void {+ const element = document.getElementById('weight-paint-step-bone-name')+ if (element !== null) {+ element.textContent = this.weight_paint_bone_name ?? '—'+ }+ }++ private show_picked_bone_overlay (bone_name: string): void {+ this.clear_bone_overlay_timeout()++ // the pick happens on pointerdown and the shared pointerup handler hides the+ // overlay, so show it just after the click completes+ this.bone_overlay_timeout = window.setTimeout(() => {+ if (!this.is_active) {+ this.bone_overlay_timeout = null+ return+ }++ this.ui.show_selected_bone_overlay(bone_name)+ this.bone_overlay_timeout = window.setTimeout(() => {+ this.ui.hide_selected_bone_overlay()+ this.bone_overlay_timeout = null+ }, 2500)+ }, 120)+ }++ private clear_bone_overlay_timeout (): void {+ if (this.bone_overlay_timeout !== null) {+ window.clearTimeout(this.bone_overlay_timeout)+ this.bone_overlay_timeout = null+ }+ }++ private clear_bone_overlay (): void {+ this.clear_bone_overlay_timeout()+ this.ui.hide_selected_bone_overlay()+ }++ private update_weight_paint_ui (): void {+ const pick_button = document.getElementById('weight-paint-step-pick-bone') as HTMLButtonElement | null+ if (pick_button !== null) {+ const pick_label = this.bone_picking_enabled+ ? 'Click a bone on the model'+ : 'Pick a bone by clicking the model (Shift + click for a quick switch)'+ pick_button.setAttribute('aria-pressed', String(this.bone_picking_enabled))+ pick_button.setAttribute('aria-label', pick_label)+ pick_button.title = pick_label+ pick_button.disabled = this.skinned_meshes.length === 0 || this.bone_names.length === 0+ }++ this.update_bone_name_display()++ const brush = this.weight_paint_brush+ const mirror = document.getElementById('weight-paint-step-mirror') as HTMLInputElement | null+ if (mirror !== null) {+ mirror.checked = brush?.mirror_enabled ?? true+ }++ const add = document.getElementById('weight-paint-step-add') as HTMLInputElement | null+ const subtract = document.getElementById('weight-paint-step-subtract') as HTMLInputElement | null+ const smooth = document.getElementById('weight-paint-step-smooth') as HTMLInputElement | null+ if (add !== null) { add.checked = brush?.mode === 'add' }+ if (subtract !== null) { subtract.checked = brush?.mode === 'subtract' }+ if (smooth !== null) { smooth.checked = brush?.mode === 'smooth' }++ const radius_input = document.getElementById('weight-paint-step-radius') as HTMLInputElement | null+ if (radius_input !== null && brush !== null) {+ radius_input.value = String(brush.radius_px)+ }+ const radius_value = document.getElementById('weight-paint-step-radius-value')+ if (radius_value !== null && brush !== null) {+ radius_value.textContent = `${Math.round(brush.radius_px)} px`+ }++ const strength_input = document.getElementById('weight-paint-step-strength') as HTMLInputElement | null+ if (strength_input !== null && brush !== null) {+ strength_input.value = String(brush.strength)+ }+ const strength_value = document.getElementById('weight-paint-step-strength-value')+ if (strength_value !== null && brush !== null) {+ strength_value.textContent = `${Math.round(brush.strength * 100)}%`+ }++ const can_undo = this.weight_paint_manager !== null &&+ this.weight_paint_manager.can_undo_since(this.weight_paint_clear_marker)+ const can_redo = this.weight_paint_manager !== null &&+ this.weight_paint_manager.can_redo_since(this.weight_paint_clear_marker)+ const undo = document.getElementById('weight-paint-step-undo') as HTMLButtonElement | null+ if (undo !== null) { undo.disabled = !can_undo }+ const redo = document.getElementById('weight-paint-step-redo') as HTMLButtonElement | null+ if (redo !== null) { redo.disabled = !can_redo }+ const reset = document.getElementById('weight-paint-step-reset') as HTMLButtonElement | null+ if (reset !== null) {+ reset.disabled = this.weight_paint_manager === null || !this.weight_paint_manager.has_overrides()+ }++ this.update_mode_radios()+ this.update_animation_buttons()+ }++ private update_mode_radios (): void {+ const paint_radio = document.getElementById('weight-paint-mode-paint') as HTMLInputElement | null+ const test_radio = document.getElementById('weight-paint-mode-test') as HTMLInputElement | null+ if (paint_radio !== null) { paint_radio.checked = this.active_mode === 'paint' }+ if (test_radio !== null) { test_radio.checked = this.active_mode === 'test' }+ }++ private show_paint_ui (visible: boolean): void {+ const element = document.getElementById('weight-paint-paint-tools')+ if (element !== null) { element.style.display = visible ? 'flex' : 'none' }+ }++ private show_test_ui (visible: boolean): void {+ const element = document.getElementById('weight-paint-test-tools')+ if (element !== null) { element.style.display = visible ? 'flex' : 'none' }+ }++ private set_animation_player_visible (visible: boolean): void {+ if (this.ui.dom_animation_player !== null) {+ this.ui.dom_animation_player.style.display = visible ? 'flex' : 'none'+ }+ }++ /**+ * Overlay a heatmap of the selected bone's weight on the posed meshes.+ * The overlay shares the source geometry's position/skin attributes, so live+ * weight edits show up without rebuilding any geometry.+ */+ private create_weight_paint_overlays (): void {+ this.dispose_weight_paint_overlays()++ for (const source of this.skinned_meshes) {+ const positions = source.geometry.attributes.position+ const skin_indices = source.geometry.attributes.skinIndex+ const skin_weights = source.geometry.attributes.skinWeight+ if (positions === undefined || skin_indices === undefined || skin_weights === undefined) { continue }++ const geometry = new BufferGeometry()+ geometry.setAttribute('position', positions)+ geometry.setAttribute('skinIndex', skin_indices)+ geometry.setAttribute('skinWeight', skin_weights)+ if (source.geometry.index !== null) {+ geometry.setIndex(source.geometry.index)+ }+ geometry.setAttribute('color', new Float32BufferAttribute(new Float32Array(positions.count * 4), 4))++ const material = new MeshBasicMaterial({+ vertexColors: true,+ transparent: true,+ depthWrite: false+ })+ material.toneMapped = false+ material.polygonOffset = true+ material.polygonOffsetFactor = -1+ material.polygonOffsetUnits = -1++ const overlay = new SkinnedMesh(geometry, material)+ overlay.name = 'Weight Paint Overlay'+ overlay.frustumCulled = false+ overlay.renderOrder = 10+ overlay.position.copy(source.position)+ overlay.quaternion.copy(source.quaternion)+ overlay.scale.copy(source.scale)+ overlay.bindMode = source.bindMode+ overlay.bind(source.skeleton, source.bindMatrix)+ ;(source.parent ?? source).add(overlay)++ this.weight_paint_overlays.set(source, overlay)+ }++ this.update_weight_paint_overlay_colors(this.weight_paint_bone_name)+ this.sync_weight_paint_overlay_visibility()+ }++ private dispose_weight_paint_overlays (): void {+ for (const overlay of this.weight_paint_overlays.values()) {+ overlay.removeFromParent()+ const geometry = overlay.geometry+ // These attributes are shared with the real skinned mesh, so detach them+ // before disposing the overlay's geometry.+ geometry.deleteAttribute('position')+ geometry.deleteAttribute('skinIndex')+ geometry.deleteAttribute('skinWeight')+ geometry.setIndex(null)+ geometry.dispose()+ const materials = Array.isArray(overlay.material) ? overlay.material : [overlay.material]+ for (const material of materials) { material.dispose() }+ }+ this.weight_paint_overlays.clear()+ }++ private sync_weight_paint_overlay_visibility (): void {+ // paint mode always shows the weights; test mode has no overlays at all+ for (const overlay of this.weight_paint_overlays.values()) {+ overlay.visible = true+ }+ }++ private update_weight_paint_overlay_colors (bone_name: string | null): void {+ for (const [source, overlay] of this.weight_paint_overlays) {+ const color = overlay.geometry.attributes.color+ const skin_indices = source.geometry.attributes.skinIndex+ const skin_weights = source.geometry.attributes.skinWeight+ const positions = source.geometry.attributes.position+ if (color === undefined || skin_indices === undefined || skin_weights === undefined || positions === undefined) {+ continue+ }++ const side = bone_name === null ? null : WeightPaintManager.bone_side(bone_name)+ const mirror_bone_name = bone_name === null+ ? null+ : WeightPaintManager.find_mirror_bone_name(bone_name, source.skeleton.bones)+ const selected_index = bone_name === null+ ? -1+ : source.skeleton.bones.findIndex(bone => bone.name === bone_name)+ const mirrored_index = mirror_bone_name === null+ ? selected_index+ : source.skeleton.bones.findIndex(bone => bone.name === mirror_bone_name)+ const center_x = this.geometry_center_x(source.geometry)+ const mirror_enabled = this.weight_paint_brush?.mirror_enabled ?? true++ const vertex_count = positions.count+ for (let i = 0; i < vertex_count; i++) {+ let bone_index = selected_index+ if (mirror_enabled && side !== null) {+ const x = positions.getX(i) - center_x+ if ((side === 'left' && x < 0) || (side === 'right' && x > 0)) {+ bone_index = mirrored_index+ }+ }+ write_weight_color(color, i, this.vertex_weight(skin_indices, skin_weights, i, bone_index))+ }+ color.needsUpdate = true+ }+ }++ private geometry_center_x (geometry: BufferGeometry): number {+ const cached = this.geometry_center_cache.get(geometry)+ if (cached !== undefined) { return cached }++ geometry.computeBoundingBox()+ const box = geometry.boundingBox+ const center_x = box === null ? 0 : (box.min.x + box.max.x) / 2+ this.geometry_center_cache.set(geometry, center_x)+ return center_x+ }++ private vertex_weight (skin_indices: { array: ArrayLike<number> },+ skin_weights: { array: ArrayLike<number> }, vertex_index: number, bone_index: number): number {+ if (bone_index < 0) { return 0 }+ let weight = 0+ for (let slot = 0; slot < 4; slot++) {+ if (skin_indices.array[vertex_index * 4 + slot] === bone_index) {+ weight += skin_weights.array[vertex_index * 4 + slot] as number+ }+ }+ return weight+ }++ private add_event_listeners (): void {+ document.getElementById('weight-paint-mode-paint')?.addEventListener('change', () => {+ this.set_active_mode('paint')+ })+ document.getElementById('weight-paint-mode-test')?.addEventListener('change', () => {+ this.set_active_mode('test')+ })+ document.getElementById('weight-paint-step-pick-bone')?.addEventListener('click', () => {+ this.set_bone_picking_enabled(!this.bone_picking_enabled)+ })+ document.getElementById('weight-paint-step-mirror')?.addEventListener('change', (event) => {+ if (this.weight_paint_brush === null) { return }+ this.weight_paint_brush.mirror_enabled = (event.target as HTMLInputElement).checked+ this.update_weight_paint_overlay_colors(this.weight_paint_bone_name)+ })+ document.getElementById('weight-paint-step-radius')?.addEventListener('input', (event) => {+ if (this.weight_paint_brush === null) { return }+ this.weight_paint_brush.radius_px = Number((event.target as HTMLInputElement).value)+ this.update_weight_paint_ui()+ })+ document.getElementById('weight-paint-step-strength')?.addEventListener('input', (event) => {+ if (this.weight_paint_brush === null) { return }+ this.weight_paint_brush.strength = Number((event.target as HTMLInputElement).value)+ this.update_weight_paint_ui()+ })+ document.querySelectorAll<HTMLInputElement>('input[name="weight-paint-step-mode"]').forEach((input) => {+ input.addEventListener('change', () => {+ if (input.checked && this.weight_paint_brush !== null) {+ this.weight_paint_brush.mode = input.value as WeightPaintMode+ }+ })+ })+ document.getElementById('weight-paint-step-undo')?.addEventListener('click', () => this.undo_weight_paint_stroke())+ document.getElementById('weight-paint-step-redo')?.addEventListener('click', () => this.redo_weight_paint_stroke())+ document.getElementById('weight-paint-step-reset')?.addEventListener('click', () => this.reset_weights_to_auto())+ document.getElementById('weight-paint-step-speed')?.addEventListener('change', (event) => {+ this.animation_speed = Number((event.target as HTMLSelectElement).value)+ this.animation_mixer.timeScale = this.animation_speed+ })++ this.add_keyboard_listeners()+ }++ private add_keyboard_listeners (): void {+ document.addEventListener('keydown', (event: KeyboardEvent) => {+ if (!this.is_active || this.is_typing_target(event.target)) { return }++ if (event.key === 'Alt') {+ this.set_alt_rotate_active(true)+ return+ }++ if (event.key.toLowerCase() === 'x' && this.active_mode === 'paint') {+ event.preventDefault()+ this.toggle_brush_mode()+ }+ })++ document.addEventListener('keyup', (event: KeyboardEvent) => {+ if (event.key === 'Alt') {+ this.set_alt_rotate_active(false)+ }+ })++ window.addEventListener('blur', () => {+ if (!this.is_active) { return }+ this.set_alt_rotate_active(false)+ this.clear_bone_overlay()+ })+ }++ private toggle_brush_mode (): void {+ if (this.weight_paint_brush === null) { return }++ const next_mode: Record<WeightPaintMode, WeightPaintMode> = {+ add: 'subtract',+ subtract: 'smooth',+ smooth: 'add'+ }+ this.weight_paint_brush.mode = next_mode[this.weight_paint_brush.mode]+ this.update_weight_paint_ui()+ }++ private is_typing_target (target: EventTarget | null): boolean {+ return target instanceof HTMLInputElement ||+ target instanceof HTMLTextAreaElement ||+ target instanceof HTMLSelectElement ||+ (target instanceof HTMLElement && target.isContentEditable)+ }+}++/**+ * Heatmap color for the selected bone's weight: blue at 0, yellow at 0.5,+ * red at 1. Alpha ramps up so low weights stay subtle over the texture.+ */+function write_weight_color (+ attribute: { setXYZW: (index: number, x: number, y: number, z: number, w: number) => unknown },+ vertex_index: number,+ weight: number+): void {+ const t = Math.min(1, Math.max(0, weight))++ let red: number+ let green: number+ let blue: number+ if (t < 0.5) {+ const u = t / 0.5+ red = 0.1 + 0.9 * u+ green = 0.35 + 0.55 * u+ blue = 1.0 - 0.9 * u+ } else {+ const u = (t - 0.5) / 0.5+ red = 1.0+ green = 0.9 - 0.8 * u+ blue = 0.1 * (1 - u)+ }++ const alpha = 0.9 * t+ attribute.setXYZW(vertex_index, red, green, blue, alpha)+}diff --git a/src/lib/processes/weight-painting/WeightPaintBrush.ts b/src/lib/processes/weight-painting/WeightPaintBrush.tsnew file mode 100644index 0000000..447eee1--- /dev/null+++ b/src/lib/processes/weight-painting/WeightPaintBrush.ts@@ -0,0 +1,173 @@+import { MathUtils, Matrix3, Mesh, SkinnedMesh, Vector3, type Bone, type Intersection, type PerspectiveCamera } from 'three'+import { WeightPaintManager, type BrushVertex, type WeightPaintMode } from './WeightPaintManager.ts'++/**+ * Shared brush mechanics for the paint tools in the Position Joints step and+ * the optional weight painting step.+ *+ * The brush size is measured in CSS pixels, so both the painted area and the+ * on-screen outline stay the same size no matter how far the camera is zoomed.+ */+export class WeightPaintBrush {+ public radius_px = 24+ public strength = 0.5+ public mode: WeightPaintMode = 'add'+ public mirror_enabled = true++ private active_mode: WeightPaintMode = 'add'+ // highest falloff reached per vertex during this stroke; only the increase+ // is applied so a drag builds up weight without stacking at the same spot+ private readonly stroke_falloffs = new Map<string, number>()+ // where the previous dab landed, so fast pointer moves leave no gaps+ private has_last_dab = false+ private readonly last_dab_center = new Vector3()+ private readonly sweep = new Vector3()+ private readonly sweep_offset = new Vector3()+ private readonly sweep_closest = new Vector3()++ constructor (private readonly manager: WeightPaintManager) {}++ public width_px (): number {+ return this.radius_px * 2+ }++ public begin_stroke (): void {+ this.active_mode = this.mode+ this.stroke_falloffs.clear()+ this.has_last_dab = false+ this.manager.begin_stroke()+ }++ /** @param meshes Finish by normalizing these meshes' influences as well. */+ public finish_stroke (meshes: Mesh[] = []): void {+ if (meshes.length > 0) {+ this.manager.normalize_all_weights(meshes)+ }+ this.manager.finish_stroke()+ this.stroke_falloffs.clear()+ this.has_last_dab = false+ }++ /** Stops the next dab from sweeping across a gap where the pointer left the mesh. */+ public reset_dab_path (): void {+ this.has_last_dab = false+ }++ /**+ * Paints the selected bone (or smooths) on the mesh under the raycast hit.+ * @returns true when at least one vertex changed+ */+ public paint (+ intersection: Intersection,+ camera: PerspectiveCamera,+ bone_name: string,+ fallback_bones?: Bone[]+ ): boolean {+ const object = intersection.object+ if (!(object instanceof Mesh)) { return false }++ const is_skinned = object instanceof SkinnedMesh+ const bones = is_skinned ? object.skeleton.bones : fallback_bones+ if (bones === undefined) { return false }++ let geometry_index: number+ if (typeof object.userData.geometry_index === 'number') {+ geometry_index = object.userData.geometry_index as number+ } else if (is_skinned) {+ geometry_index = -object.id+ } else {+ // preview meshes must map back to the geometry index used for overrides+ return false+ }++ const positions = object.geometry.attributes.position+ if (positions === undefined) { return false }++ object.updateWorldMatrix(true, false)+ const center = intersection.point.clone()+ const radius = this.world_radius(camera, center)+ if (radius <= 0) { return false }++ const normals = object.geometry.attributes.normal+ const normal_matrix = is_skinned ? null : new Matrix3().getNormalMatrix(object.matrixWorld)+ const ray_direction = center.clone().sub(camera.position).normalize()+ const point = new Vector3()+ const normal = new Vector3()+ const vertices: BrushVertex[] = []++ // Sweep from the previous dab's hit point so fast pointer moves paint a+ // continuous stroke instead of leaving gaps between discrete samples.+ const previous_center = this.has_last_dab ? this.last_dab_center : null+ if (previous_center !== null) {+ this.sweep.subVectors(center, previous_center)+ }+ const sweep_length_sq = previous_center === null ? 0 : this.sweep.lengthSq()+ const has_sweep = sweep_length_sq > 1e-12++ for (let i = 0; i < positions.count; i++) {+ const key = `${geometry_index}:${i}`+ object.getVertexPosition(i, point)+ point.applyMatrix4(object.matrixWorld)++ if (has_sweep && previous_center !== null) {+ this.sweep_offset.copy(point).sub(previous_center)+ const t = Math.min(1, Math.max(0, this.sweep_offset.dot(this.sweep) / sweep_length_sq))+ this.sweep_closest.copy(previous_center).addScaledVector(this.sweep, t)+ } else {+ this.sweep_closest.copy(center)+ }++ const distance = point.distanceTo(this.sweep_closest)+ if (distance > radius) { continue }++ if (is_skinned) {+ // Ignore vertices behind the surface the brush is touching, so the+ // brush cannot paint through the mesh to the far side.+ const depth = point.sub(this.sweep_closest).dot(ray_direction)+ if (depth > radius * 0.5) { continue }+ } else if (normals !== undefined && normal_matrix !== null) {+ // The preview meshes are not deformed, so the surface normal is enough+ // to keep the brush from painting the back of the model.+ normal.fromBufferAttribute(normals, i).applyMatrix3(normal_matrix).normalize()+ if (normal.dot(ray_direction) > -0.05) { continue }+ }++ const t = 1 - distance / radius+ const falloff = t * t * (3 - 2 * t)+ // The first dab that reaches a vertex is usually at the brush edge. Only+ // applying the increase lets the stroke keep strengthening that vertex+ // as the brush center passes over it.+ const previous_falloff = this.stroke_falloffs.get(key) ?? 0+ if (falloff <= previous_falloff + 1e-4) { continue }+ this.stroke_falloffs.set(key, falloff)+ vertices.push({ vertex_index: i, falloff: falloff - previous_falloff })+ }++ if (vertices.length === 0) { return false }+ this.has_last_dab = true+ this.last_dab_center.copy(center)++ const painted_count = this.manager.paint_vertices(+ object,+ geometry_index,+ vertices,+ bone_name,+ bones,+ this.strength,+ this.active_mode,+ this.mirror_enabled+ )+ return painted_count > 0+ }++ /** World-space brush radius at a surface point, derived from the pixel size. */+ public world_radius (camera: PerspectiveCamera, point: Vector3): number {+ const forward = camera.getWorldDirection(new Vector3())+ const depth = point.clone().sub(camera.position).dot(forward)+ if (depth <= 0) { return 0 }++ const viewport_height = Math.max(1, window.innerHeight)+ const world_per_pixel = 2 * depth * Math.tan(MathUtils.degToRad(camera.fov) / 2) / viewport_height+ return this.radius_px * world_per_pixel+ }+}diff --git a/src/lib/processes/weight-painting/WeightPaintEditTools.ts b/src/lib/processes/weight-painting/WeightPaintEditTools.tsnew file mode 100644index 0000000..9774b3c--- /dev/null+++ b/src/lib/processes/weight-painting/WeightPaintEditTools.ts@@ -0,0 +1,187 @@+import { type Bone, type Intersection, type PerspectiveCamera } from 'three'+import { Utility } from '../../Utilities.ts'+import { WeightPaintBrush } from './WeightPaintBrush.ts'+import { WeightPaintManager, type ManualWeightOverrides, type WeightPaintMode } from './WeightPaintManager.ts'++/**+ * Weight painting controls shown while positioning the joints.+ *+ * It owns the paint state and the panel in the tool sidebar, so StepEditSkeleton+ * only has to forward engine events and expose the painted overrides.+ */+export class WeightPaintEditTools extends EventTarget {+ public readonly manager = new WeightPaintManager()+ public readonly brush = new WeightPaintBrush(this.manager)++ private bones: Bone[] = []+ private bone_name: string | null = null+ private available = false+ private enabled = false+ private added_event_listeners = false++ public begin (bones: Bone[]): void {+ this.bones = bones+ if (!this.added_event_listeners) {+ this.add_event_listeners()+ this.added_event_listeners = true+ }+ this.update_bone_options()+ this.update_ui()+ }++ public overrides_for_skin (): ManualWeightOverrides {+ return this.manager.overrides_for_skin()+ }++ public set_available (available: boolean): void {+ this.available = available+ if (!available) {+ this.set_enabled(false)+ }+ this.update_ui()+ }++ public is_enabled (): boolean {+ return this.enabled+ }++ public set_enabled (enabled: boolean): void {+ if (enabled && (!this.available || this.bone_name === null)) {+ return+ }+ if (this.enabled === enabled) {+ this.update_ui()+ return+ }++ this.enabled = enabled+ this.dispatchEvent(new CustomEvent('weightPaintModeChanged', { detail: { enabled } }))+ this.update_ui()+ }++ public begin_stroke (): void {+ this.brush.begin_stroke()+ this.update_ui()+ }++ public end_stroke (): void {+ this.brush.finish_stroke()+ this.update_ui()+ }++ /** Breaks the drag sweep when the pointer leaves the mesh. */+ public reset_dab_path (): void {+ this.brush.reset_dab_path()+ }++ public paint (intersection: Intersection, camera: PerspectiveCamera): void {+ if (!this.enabled || this.bone_name === null) { return }++ this.brush.paint(intersection, camera, this.bone_name, this.bones)+ this.update_ui()+ }++ public undo_stroke (): void {+ if (!this.manager.undo()) { return }+ this.dispatchEvent(new CustomEvent('weightPaintChanged'))+ this.update_ui()+ }++ public clear (): void {+ this.manager.clear()+ this.dispatchEvent(new CustomEvent('weightPaintChanged'))+ this.update_ui()+ }++ /** Used when a different model is loaded, since vertex indices no longer match. */+ public reset (): void {+ this.manager.clear()+ this.update_ui()+ }++ private update_bone_options (): void {+ const select = document.getElementById('weight-paint-bone') as HTMLSelectElement | null+ if (select === null) { return }++ const previous = this.bone_name ?? select.value+ select.innerHTML = ''+ for (const bone of this.bones) {+ if (bone.name === 'root' || Utility.is_leaf_bone(bone)) { continue }+ const option = document.createElement('option')+ option.value = bone.name+ option.textContent = bone.name+ select.appendChild(option)+ }++ const previous_still_exists = Array.from(select.options).some(option => option.value === previous)+ select.selectedIndex = previous_still_exists+ ? Array.from(select.options).findIndex(option => option.value === previous)+ : (select.options.length > 0 ? 0 : -1)+ this.bone_name = select.value === '' ? null : select.value+ }++ private update_ui (): void {+ const container = document.getElementById('weight-painting-tools')+ if (container !== null) {+ container.hidden = !this.available+ }++ const toggle = document.getElementById('weight-paint-toggle') as HTMLButtonElement | null+ if (toggle !== null) {+ toggle.textContent = this.enabled ? 'Stop painting' : 'Start painting'+ toggle.setAttribute('aria-pressed', String(this.enabled))+ toggle.disabled = !this.available || this.bone_name === null+ }++ const undo = document.getElementById('weight-paint-undo') as HTMLButtonElement | null+ if (undo !== null) {+ undo.disabled = !this.manager.can_undo()+ }++ const clear = document.getElementById('weight-paint-clear') as HTMLButtonElement | null+ if (clear !== null) {+ clear.disabled = !this.manager.has_overrides()+ }++ const mirror = document.getElementById('weight-paint-mirror') as HTMLInputElement | null+ if (mirror !== null) {+ mirror.checked = this.brush.mirror_enabled+ }++ const add = document.getElementById('weight-paint-add') as HTMLInputElement | null+ const subtract = document.getElementById('weight-paint-subtract') as HTMLInputElement | null+ const smooth = document.getElementById('weight-paint-smooth') as HTMLInputElement | null+ if (add !== null) { add.checked = this.brush.mode === 'add' }+ if (subtract !== null) { subtract.checked = this.brush.mode === 'subtract' }+ if (smooth !== null) { smooth.checked = this.brush.mode === 'smooth' }+ }++ private add_event_listeners (): void {+ document.getElementById('weight-paint-toggle')?.addEventListener('click', () => {+ this.set_enabled(!this.enabled)+ })+ document.getElementById('weight-paint-bone')?.addEventListener('change', (event) => {+ const select = event.target as HTMLSelectElement+ this.bone_name = select.value === '' ? null : select.value+ this.update_ui()+ })+ document.getElementById('weight-paint-radius')?.addEventListener('input', (event) => {+ this.brush.radius_px = Number((event.target as HTMLInputElement).value)+ })+ document.getElementById('weight-paint-strength')?.addEventListener('input', (event) => {+ this.brush.strength = Number((event.target as HTMLInputElement).value)+ })+ document.getElementById('weight-paint-mirror')?.addEventListener('change', (event) => {+ this.brush.mirror_enabled = (event.target as HTMLInputElement).checked+ this.update_ui()+ })+ document.querySelectorAll<HTMLInputElement>('input[name="weight-paint-mode"]').forEach((input) => {+ input.addEventListener('change', () => {+ if (!input.checked) { return }+ this.brush.mode = input.value as WeightPaintMode+ })+ })+ document.getElementById('weight-paint-undo')?.addEventListener('click', () => this.undo_stroke())+ document.getElementById('weight-paint-clear')?.addEventListener('click', () => this.clear())+ }+}diff --git a/src/lib/processes/weight-painting/WeightPaintManager.test.ts b/src/lib/processes/weight-painting/WeightPaintManager.test.tsnew file mode 100644index 0000000..eae3c4a--- /dev/null+++ b/src/lib/processes/weight-painting/WeightPaintManager.test.ts@@ -0,0 +1,308 @@+import { describe, expect, it } from 'vitest'+import { Bone, BufferGeometry, Float32BufferAttribute, Mesh, MeshBasicMaterial, Uint16BufferAttribute } from 'three'+import { WeightPaintManager } from './WeightPaintManager'++function rig (): Bone[] {+ const root = new Bone()+ root.name = 'root'+ const head = new Bone()+ head.name = 'head'+ const jaw = new Bone()+ jaw.name = 'face_jaw'+ root.add(head)+ head.add(jaw)+ return [root, head, jaw]+}++function painted_mesh (jaw_weight = 0.5, head_weight = 0.5): Mesh {+ const geometry = new BufferGeometry()+ geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3))+ geometry.setAttribute('skinIndex', new Uint16BufferAttribute([2, 1, 0, 0, 2, 1, 0, 0], 4))+ geometry.setAttribute('skinWeight', new Float32BufferAttribute([jaw_weight, head_weight, 0, 0, jaw_weight, head_weight, 0, 0], 4))+ geometry.setAttribute('color', new Float32BufferAttribute([1, 1, 1, 1, 1, 1], 3))+ return new Mesh(geometry, new MeshBasicMaterial())+}++function override (manager: WeightPaintManager, vertex: number): Map<string, number> {+ const influences = manager.overrides_for_skin().get(0)?.get(vertex) ?? []+ return new Map(influences.map(influence => [influence.bone_name, influence.weight]))+}++function mirror_rig (): Bone[] {+ const root = new Bone()+ root.name = 'root'+ const head = new Bone()+ head.name = 'head'+ const upperarm_l = new Bone()+ upperarm_l.name = 'upperarm_l'+ const upperarm_r = new Bone()+ upperarm_r.name = 'upperarm_r'+ const spine = new Bone()+ spine.name = 'spine_02'+ return [root, head, upperarm_l, upperarm_r, spine]+}++function mirror_mesh (): Mesh {+ const geometry = new BufferGeometry()+ geometry.setAttribute('position', new Float32BufferAttribute([0.5, 0, 0, -0.5, 0, 0, 0, 0, 0], 3))+ geometry.setAttribute('skinIndex', new Uint16BufferAttribute([1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0], 4))+ geometry.setAttribute('skinWeight', new Float32BufferAttribute([1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0], 4))+ geometry.setAttribute('color', new Float32BufferAttribute([1, 1, 1, 1, 1, 1, 1, 1, 1], 3))+ return new Mesh(geometry, new MeshBasicMaterial())+}++describe('WeightPaintManager', () => {+ it('adds weight to the selected bone and normalises the rest', () => {+ const bones = rig()+ const mesh = painted_mesh(0.25, 0.75)+ const manager = new WeightPaintManager()++ manager.begin_stroke()+ manager.paint_vertices(mesh, 0, [{ vertex_index: 0, falloff: 1 }], 'face_jaw', bones, 0.5, 'add')++ const influences = override(manager, 0)+ expect(influences.get('face_jaw')).toBeCloseTo(0.625)+ expect(influences.get('head')).toBeCloseTo(0.375)+ expect([...influences.values()].reduce((sum, weight) => sum + weight, 0)).toBeCloseTo(1)+ expect(manager.is_vertex_painted(0, 0)).toBe(true)+ expect(manager.is_vertex_painted(0, 1)).toBe(false)+ })++ it('removes weight and hands it to the parent when nothing else is left', () => {+ const bones = rig()+ const mesh = painted_mesh(1, 0)+ const manager = new WeightPaintManager()++ manager.begin_stroke()+ manager.paint_vertices(mesh, 0, [{ vertex_index: 0, falloff: 1 }], 'face_jaw', bones, 1, 'subtract')++ const influences = override(manager, 0)+ expect(influences.get('face_jaw')).toBeUndefined()+ expect(influences.get('head')).toBeCloseTo(1)+ })++ it('undoes a whole stroke', () => {+ const bones = rig()+ const mesh = painted_mesh()+ const manager = new WeightPaintManager()++ manager.begin_stroke()+ manager.paint_vertices(mesh, 0, [{ vertex_index: 0, falloff: 1 }], 'face_jaw', bones, 1, 'add')+ expect(manager.is_vertex_painted(0, 0)).toBe(true)+ expect(manager.can_undo()).toBe(true)++ manager.undo()+ expect(manager.is_vertex_painted(0, 0)).toBe(false)+ expect(manager.can_undo()).toBe(false)+ })++ it('writes the painted weights into the skin attributes', () => {+ const bones = rig()+ const mesh = painted_mesh(0.5, 0.5)+ const manager = new WeightPaintManager()++ manager.begin_stroke()+ manager.paint_vertices(mesh, 0, [{ vertex_index: 0, falloff: 1 }], 'face_jaw', bones, 0.5, 'add')++ const skin_indices = mesh.geometry.attributes.skinIndex.array+ const skin_weights = mesh.geometry.attributes.skinWeight.array+ expect([skin_indices[0], skin_indices[1]]).toEqual([2, 1])+ expect(skin_weights[0]).toBeCloseTo(0.75)+ expect(skin_weights[1]).toBeCloseTo(0.25)+ expect([skin_indices[4], skin_indices[5]]).toEqual([2, 1])+ })++ it('restores skin attributes when a stroke is undone', () => {+ const bones = rig()+ const mesh = painted_mesh(0.5, 0.5)+ const manager = new WeightPaintManager()++ manager.begin_stroke()+ manager.paint_vertices(mesh, 0, [{ vertex_index: 0, falloff: 1 }], 'face_jaw', bones, 1, 'add')+ expect(mesh.geometry.attributes.skinWeight.array[0]).toBeCloseTo(1)++ manager.undo()+ expect(mesh.geometry.attributes.skinWeight.array[0]).toBeCloseTo(0.5)+ expect(mesh.geometry.attributes.skinWeight.array[1]).toBeCloseTo(0.5)+ })++ it('redo restores the whole stroke', () => {+ const bones = rig()+ const mesh = painted_mesh()+ const manager = new WeightPaintManager()++ manager.begin_stroke()+ manager.paint_vertices(mesh, 0, [{ vertex_index: 0, falloff: 1 }], 'face_jaw', bones, 1, 'add')+ manager.finish_stroke()+ const painted_weight = mesh.geometry.attributes.skinWeight.array[0]++ manager.undo()+ expect(mesh.geometry.attributes.skinWeight.array[0]).toBeCloseTo(0.5)+ expect(manager.can_redo()).toBe(true)++ manager.redo()+ expect(mesh.geometry.attributes.skinWeight.array[0]).toBeCloseTo(painted_weight)+ expect(manager.can_redo()).toBe(false)+ })++ it('normalizes every vertex so the weights add up to one', () => {+ const mesh = painted_mesh(0.2, 0.2)+ const manager = new WeightPaintManager()++ expect(manager.normalize_all_weights([mesh])).toBe(true)+ expect(mesh.geometry.attributes.skinWeight.array[0]).toBeCloseTo(0.5)+ expect(mesh.geometry.attributes.skinWeight.array[1]).toBeCloseTo(0.5)++ // a vertex with no influences would collapse; keep one full influence+ const weights = mesh.geometry.attributes.skinWeight+ weights.array[4] = 0+ weights.array[5] = 0+ manager.normalize_all_weights([mesh])+ expect(weights.array[4]).toBeCloseTo(1)+ expect(weights.array[5]).toBeCloseTo(0)+ })++ it('clears only strokes made after a marker', () => {+ const bones = rig()+ const mesh = painted_mesh()+ const manager = new WeightPaintManager()++ manager.begin_stroke()+ manager.paint_vertices(mesh, 0, [{ vertex_index: 0, falloff: 1 }], 'face_jaw', bones, 1, 'add')+ const marker = manager.undo_stack_marker()++ manager.begin_stroke()+ manager.paint_vertices(mesh, 0, [{ vertex_index: 1, falloff: 1 }], 'face_jaw', bones, 1, 'add')+ expect(manager.is_vertex_painted(0, 1)).toBe(true)+ expect(manager.can_undo_since(marker)).toBe(true)++ manager.clear_strokes_since(marker)+ expect(manager.is_vertex_painted(0, 0)).toBe(true)+ expect(manager.is_vertex_painted(0, 1)).toBe(false)+ expect(manager.can_undo_since(marker)).toBe(false)+ expect(mesh.geometry.attributes.skinWeight.array[4]).toBeCloseTo(0.5)+ })++ it('writes overrides into the skin arrays and skips missing bones', () => {+ const bones = rig()+ const mesh = painted_mesh()+ const manager = new WeightPaintManager()+ manager.begin_stroke()+ manager.paint_vertices(mesh, 0, [{ vertex_index: 0, falloff: 1 }], 'face_jaw', bones, 1, 'add')++ // second vertex: one influence no longer exists+ manager.overrides_for_skin().get(0)!.set(1, [+ { bone_name: 'removed_bone', weight: 0.5 },+ { bone_name: 'head', weight: 0.5 }+ ])++ const skin_indices = [2, 1, 0, 0, 0, 0, 0, 0]+ const skin_weights = [0.5, 0.5, 0, 0, 1, 0, 0, 0]+ WeightPaintManager.apply_overrides(manager.overrides_for_skin(), 0, bones, skin_indices, skin_weights)++ expect(skin_indices.slice(0, 4)).toEqual([2, 0, 0, 0])+ expect(skin_weights.slice(0, 4)).toEqual([1, 0, 0, 0])+ expect(skin_indices.slice(4, 8)).toEqual([1, 0, 0, 0])+ expect(skin_weights.slice(4, 8)).toEqual([1, 0, 0, 0])+ })++ it('tracks and clears painted vertices', () => {+ const bones = rig()+ const mesh = painted_mesh()+ const manager = new WeightPaintManager()+ expect(manager.has_overrides()).toBe(false)++ manager.begin_stroke()+ manager.paint_vertices(mesh, 0, [{ vertex_index: 0, falloff: 1 }, { vertex_index: 1, falloff: 0.5 }], 'face_jaw', bones, 1, 'add')+ expect(manager.has_overrides()).toBe(true)+ expect(manager.painted_vertex_count()).toBe(2)++ manager.clear()+ expect(manager.has_overrides()).toBe(false)+ expect(manager.painted_vertex_count()).toBe(0)+ })++ it('mirrors side bones onto the matching counterpart bone', () => {+ const bones = mirror_rig()+ const mesh = mirror_mesh()+ const manager = new WeightPaintManager()++ expect(WeightPaintManager.find_mirror_bone_name('upperarm_l', bones)).toBe('upperarm_r')+ expect(WeightPaintManager.bone_side('face_eye_L')).toBe('left')++ manager.begin_stroke()+ manager.paint_vertices(mesh, 0, [{ vertex_index: 0, falloff: 1 }], 'upperarm_l', bones, 1, 'add', true)++ expect(override(manager, 0).get('upperarm_l')).toBeCloseTo(1)+ expect(override(manager, 1).get('upperarm_r')).toBeCloseTo(1)+ expect(mesh.geometry.attributes.skinIndex.array[4]).toBe(3) // mirrored vertex now uses upperarm_r+ expect(mesh.geometry.attributes.skinWeight.array[4]).toBeCloseTo(1)+ })++ it('smooths a vertex towards the average of its neighbours', () => {+ const bones = rig()+ const geometry = new BufferGeometry()+ // a triangle where vertex 0 is fully jaw and both neighbours are fully head+ geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 1, 0, 0, 0, 1, 0], 3))+ geometry.setAttribute('skinIndex', new Uint16BufferAttribute([+ 2, 0, 0, 0,+ 1, 0, 0, 0,+ 1, 0, 0, 0+ ], 4))+ geometry.setAttribute('skinWeight', new Float32BufferAttribute([+ 1, 0, 0, 0,+ 1, 0, 0, 0,+ 1, 0, 0, 0+ ], 4))+ geometry.setAttribute('color', new Float32BufferAttribute([1, 1, 1, 1, 1, 1, 1, 1, 1], 3))+ geometry.setIndex(new Uint16BufferAttribute([0, 1, 2], 1))+ const mesh = new Mesh(geometry, new MeshBasicMaterial())+ const manager = new WeightPaintManager()++ manager.begin_stroke()+ const painted = manager.paint_vertices(mesh, 0, [{ vertex_index: 0, falloff: 1 }], 'face_jaw', bones, 0.5, 'smooth')++ expect(painted).toBe(1)+ const influences = override(manager, 0)+ expect(influences.get('face_jaw')).toBeCloseTo(0.5)+ expect(influences.get('head')).toBeCloseTo(0.5)+ expect(manager.is_vertex_painted(0, 1)).toBe(false)+ })++ it('does not mirror when the option is off', () => {+ const bones = mirror_rig()+ const mesh = mirror_mesh()+ const manager = new WeightPaintManager()++ manager.begin_stroke()+ manager.paint_vertices(mesh, 0, [{ vertex_index: 0, falloff: 1 }], 'upperarm_l', bones, 1, 'add', false)++ expect(override(manager, 0).get('upperarm_l')).toBeCloseTo(1)+ expect(manager.is_vertex_painted(0, 1)).toBe(false)+ expect(mesh.geometry.attributes.skinIndex.array[4]).toBe(1) // still head+ })++ it('mirrors center bones onto themselves on both sides', () => {+ const bones = mirror_rig()+ const mesh = mirror_mesh()+ const manager = new WeightPaintManager()++ manager.begin_stroke()+ manager.paint_vertices(mesh, 0, [{ vertex_index: 0, falloff: 1 }], 'spine_02', bones, 1, 'add', true)++ expect(override(manager, 0).get('spine_02')).toBeCloseTo(1)+ expect(override(manager, 1).get('spine_02')).toBeCloseTo(1)+ })++ it('only paints the side that matches a sided bone', () => {+ const bones = mirror_rig()+ const mesh = mirror_mesh()+ const manager = new WeightPaintManager()++ manager.begin_stroke()+ const painted = manager.paint_vertices(mesh, 0, [{ vertex_index: 1, falloff: 1 }], 'upperarm_l', bones, 1, 'add', true)++ expect(painted).toBe(0)+ expect(manager.has_overrides()).toBe(false)+ })+})diff --git a/src/lib/processes/weight-painting/WeightPaintManager.ts b/src/lib/processes/weight-painting/WeightPaintManager.tsnew file mode 100644index 0000000..bb4bec5--- /dev/null+++ b/src/lib/processes/weight-painting/WeightPaintManager.ts@@ -0,0 +1,851 @@+import { Vector3, type Bone, type BufferGeometry, type Mesh } from 'three'+import { Generators } from '../../Generators'+import { Utility } from '../../Utilities.js'++export interface PaintedInfluence {+ bone_name: string+ weight: number+}++export type GeometryWeightOverrides = Map<number, PaintedInfluence[]>+export type ManualWeightOverrides = Map<number, GeometryWeightOverrides>+export type WeightPaintMode = 'add' | 'subtract' | 'smooth'++/** One vertex touched by a brush, with the brush falloff at that vertex. */+export interface BrushVertex {+ vertex_index: number+ falloff: number+}++interface SkinBackup {+ indices: number[]+ weights: number[]+}++type BoneSide = 'left' | 'right' | null++interface MirrorData {+ center_x: number+ // vertex index -> mirrored vertex index+ map: Map<number, number>+}++interface UndoRecord {+ stroke_id: number+ before_overrides: ManualWeightOverrides+ after_overrides: ManualWeightOverrides+ // mesh -> vertex -> skin attributes before this stroke touched the vertex+ before_backups: Map<Mesh, Map<number, SkinBackup>>+ // the same vertices after the stroke and normalization, used for redo+ after_backups: Map<Mesh, Map<number, SkinBackup>>+}++/**+ * Stores per-vertex weight overrides made with the weight painting tool.+ *+ * Overrides are saved by geometry index and vertex index, matching the order of+ * StepLoadModel's geometry list. Bone influence is stored by name rather than+ * index, so adding/removing facial bones does not invalidate painted weights.+ *+ * Painted vertices fully replace the automatic weights for that vertex. The+ * rest of the mesh keeps its automatic weights.+ *+ * The same manager is used before binding (on the weight preview mesh) and in+ * the animation stage (on the final skinned meshes). It writes the new weights+ * into the mesh's skin attributes as well as storing the override, so a+ * skinned mesh deforms immediately while an animation is paused.+ */+export class WeightPaintManager {+ private overrides: ManualWeightOverrides = new Map()+ private undo_stack: UndoRecord[] = []+ private redo_stack: UndoRecord[] = []+ private stroke_counter = 0+ private current_stroke: UndoRecord | null = null+ private current_stroke_backups: Map<Mesh, Map<number, SkinBackup>> | null = null+ private readonly bone_colors = Generators.generate_deterministic_bone_colors(120)+ private readonly mirror_cache = new WeakMap<BufferGeometry, MirrorData | null>()+ private readonly adjacency_cache = new WeakMap<BufferGeometry, number[][]>()++ /** Which side of the body a bone belongs to, based on common naming patterns. */+ public static bone_side (bone_name: string): BoneSide {+ const lower = bone_name.toLowerCase()+ if (lower.includes('left')) { return 'left' }+ if (lower.includes('right')) { return 'right' }+ if (/(^|[_.-])l$/.test(lower) || /^l[_.-]/.test(lower)) { return 'left' }+ if (/(^|[_.-])r$/.test(lower) || /^r[_.-]/.test(lower)) { return 'right' }+ return null+ }++ /** The bone on the opposite side with the same base name, e.g. upperarm_l -> upperarm_r. */+ public static find_mirror_bone_name (bone_name: string, bones: Bone[]): string | null {+ const source_side = WeightPaintManager.bone_side(bone_name)+ if (source_side === null) { return null }++ const base_name = Utility.calculate_bone_base_name(bone_name)+ const opposite_side = source_side === 'left' ? 'right' : 'left'+ const match = bones.find(bone =>+ bone.name !== bone_name &&+ Utility.calculate_bone_base_name(bone.name) === base_name &&+ WeightPaintManager.bone_side(bone.name) === opposite_side)+ return match?.name ?? null+ }++ /** Read-only view used by the skinning step when building the final meshes. */+ public overrides_for_skin (): ManualWeightOverrides {+ return this.overrides+ }++ public has_overrides (): boolean {+ for (const geometry_overrides of this.overrides.values()) {+ if (geometry_overrides.size > 0) { return true }+ }+ return false+ }++ public painted_vertex_count (): number {+ let count = 0+ for (const geometry_overrides of this.overrides.values()) {+ count += geometry_overrides.size+ }+ return count+ }++ public is_vertex_painted (geometry_index: number, vertex_index: number): boolean {+ return this.overrides.get(geometry_index)?.has(vertex_index) === true+ }++ public can_undo (): boolean {+ return this.undo_stack.length > 0+ }++ public can_redo (): boolean {+ return this.redo_stack.length > 0+ }++ /** Monotonic marker that survives the undo-history size cap. */+ public undo_stack_marker (): number {+ return this.stroke_counter+ }++ public can_undo_since (marker: number): boolean {+ const latest = this.undo_stack[this.undo_stack.length - 1]+ return latest !== undefined && latest.stroke_id > marker+ }++ public can_redo_since (marker: number): boolean {+ const latest = this.redo_stack[this.redo_stack.length - 1]+ return latest !== undefined && latest.stroke_id > marker+ }++ /** Call once at the start of a brush stroke so undo rolls back the whole stroke. */+ public begin_stroke (): void {+ this.finish_stroke() // in case a stroke was never ended++ const backups = new Map<Mesh, Map<number, SkinBackup>>()+ this.stroke_counter+++ const record: UndoRecord = {+ stroke_id: this.stroke_counter,+ before_overrides: this.clone_overrides(this.overrides),+ after_overrides: this.clone_overrides(this.overrides),+ before_backups: backups,+ after_backups: new Map()+ }+ this.current_stroke = record+ this.current_stroke_backups = backups+ this.undo_stack.push(record)++ if (this.undo_stack.length > 20) {+ this.undo_stack.shift()+ }++ // a new stroke invalidates any redo history+ this.redo_stack = []+ }++ /** Capture the post-stroke skin state so redo can replay the whole stroke. */+ public finish_stroke (): void {+ const record = this.current_stroke+ if (record === null) { return }++ this.current_stroke = null+ this.current_stroke_backups = null++ // nothing was painted, so don't leave a no-op undo step behind+ if (record.before_backups.size === 0) {+ const index = this.undo_stack.indexOf(record)+ if (index >= 0) { this.undo_stack.splice(index, 1) }+ return+ }++ record.after_overrides = this.clone_overrides(this.overrides)+ record.after_backups = this.capture_skin_backups(record.before_backups)+ }++ public undo (): boolean {+ const previous = this.undo_stack.pop()+ if (previous === undefined) { return false }++ this.overrides = this.clone_overrides(previous.before_overrides)+ this.restore_skin_backups(previous.before_backups)+ this.redo_stack.push(previous)+ return true+ }++ public redo (): boolean {+ const next = this.redo_stack.pop()+ if (next === undefined) { return false }++ this.overrides = this.clone_overrides(next.after_overrides)+ this.restore_skin_backups(next.after_backups)+ this.undo_stack.push(next)+ return true+ }++ /**+ * Undoes every stroke made after the marker. Used by the animation stage so+ * clearing only removes paint applied there, not weights painted before bind.+ */+ public clear_strokes_since (marker: number): boolean {+ let changed = false+ while (this.can_undo_since(marker)) {+ if (!this.undo()) { break }+ changed = true+ }++ // clearing should not be undone by a later redo+ if (changed) { this.redo_stack = [] }+ return changed+ }++ public clear (): void {+ this.overrides.clear()+ this.undo_stack = []+ this.redo_stack = []+ this.current_stroke = null+ this.current_stroke_backups = null+ }++ /**+ * Makes every vertex's influences add up to 1.0. Called after each brush+ * stroke so exported weights are always normalized.+ */+ public normalize_all_weights (meshes: Mesh[]): boolean {+ let any_changed = false++ for (const mesh of meshes) {+ const skin_indices = mesh.geometry.attributes.skinIndex+ const skin_weights = mesh.geometry.attributes.skinWeight+ if (skin_indices === undefined || skin_weights === undefined) { continue }++ let mesh_changed = false+ const vertex_count = skin_weights.count+ for (let vertex_index = 0; vertex_index < vertex_count; vertex_index++) {+ const offset = vertex_index * 4+ let total = 0+ for (let slot = 0; slot < 4; slot++) {+ total += skin_weights.array[offset + slot] as number+ }++ if (total > 0) {+ if (Math.abs(total - 1) <= 1e-6) { continue }+ for (let slot = 0; slot < 4; slot++) {+ skin_weights.array[offset + slot] = (skin_weights.array[offset + slot] as number) / total+ }+ mesh_changed = true+ continue+ }++ // A vertex with no influences would collapse; keep its first bone+ // influence so every vertex still sums to 1.0.+ skin_indices.array[offset] = skin_indices.array[offset] ?? 0+ skin_weights.array[offset] = 1+ for (let slot = 1; slot < 4; slot++) {+ skin_weights.array[offset + slot] = 0+ }+ mesh_changed = true+ }++ if (mesh_changed) {+ this.mark_skin_attributes_dirty(mesh)+ any_changed = true+ }+ }++ return any_changed+ }++ /**+ * Applies a brush dab to a set of vertices.+ * @param mirror_enabled when true, the opposite side of the mesh is painted+ * with the matching mirror bone (upperarm_l -> upperarm_r). Center-line bones+ * are mirrored onto themselves so both sides stay symmetric.+ * @returns how many vertices actually changed+ */+ public paint_vertices (+ mesh: Mesh,+ geometry_index: number,+ vertices: BrushVertex[],+ bone_name: string,+ bones: Bone[],+ strength: number,+ mode: WeightPaintMode,+ mirror_enabled: boolean = false+ ): number {+ if (vertices.length === 0) { return 0 }++ let geometry_overrides = this.overrides.get(geometry_index)+ if (geometry_overrides === undefined) {+ geometry_overrides = new Map()+ this.overrides.set(geometry_index, geometry_overrides)+ }++ const mirror_data = mirror_enabled ? this.mirror_data(mesh) : null++ // Smoothing blends each vertex with its neighbours regardless of which bone+ // is selected, and the mirrored brush region is smoothed the same way.+ if (mode === 'smooth') {+ const smooth_vertices = mirror_data === null+ ? vertices+ : this.mirror_brush_vertices(vertices, mirror_data)+ return this.smooth_vertices(mesh, geometry_overrides, smooth_vertices, strength, bones)+ }++ if (mirror_data === null) {+ return this.apply_brush(mesh, geometry_overrides, vertices, bone_name, bones, strength, mode)+ }++ const side = WeightPaintManager.bone_side(bone_name)+ if (side === null) {+ // Center-line bone: paint the union of the brush and its mirror once.+ return this.apply_brush(mesh, geometry_overrides,+ this.mirror_brush_vertices(vertices, mirror_data), bone_name, bones, strength, mode)+ }++ // Side bone: direct-paint only the matching side and mirror the other side+ // with the counterpart bone.+ const positions = mesh.geometry.attributes.position+ const direct_vertices = vertices.filter((vertex) => {+ const x = positions.getX(vertex.vertex_index) - mirror_data.center_x+ return side === 'left' ? x > 0 : x < 0+ })+ if (direct_vertices.length === 0) { return 0 }++ const mirrored_falloffs = new Map<number, number>()+ for (const vertex of direct_vertices) {+ const mirrored_index = mirror_data.map.get(vertex.vertex_index)+ if (mirrored_index !== undefined) {+ mirrored_falloffs.set(mirrored_index,+ Math.max(mirrored_falloffs.get(mirrored_index) ?? 0, vertex.falloff))+ }+ }+ const mirrored_vertices: BrushVertex[] = [...mirrored_falloffs].map(([vertex_index, falloff]) =>+ ({ vertex_index, falloff }))+ const mirror_bone_name = WeightPaintManager.find_mirror_bone_name(bone_name, bones) ?? bone_name++ let painted_count = this.apply_brush(mesh, geometry_overrides, direct_vertices, bone_name, bones, strength, mode)+ if (mirrored_vertices.length > 0) {+ painted_count += this.apply_brush(mesh, geometry_overrides, mirrored_vertices, mirror_bone_name, bones, strength, mode)+ }+ return painted_count+ }++ private apply_brush (+ mesh: Mesh,+ geometry_overrides: GeometryWeightOverrides,+ vertices: BrushVertex[],+ bone_name: string,+ bones: Bone[],+ strength: number,+ mode: WeightPaintMode+ ): number {+ let painted_count = 0+ for (const brush_vertex of vertices) {+ const current = this.current_influences(mesh, geometry_overrides, brush_vertex.vertex_index, bones)+ const current_weight = current.get(bone_name) ?? 0+ const amount = Math.min(1, Math.max(0, strength * brush_vertex.falloff))+ const target_weight = mode === 'add'+ ? current_weight + (1 - current_weight) * amount+ : current_weight * (1 - amount)++ const updated = this.renormalize(current, bone_name, target_weight, bones)+ this.record_stroke_backup(mesh, brush_vertex.vertex_index)+ geometry_overrides.set(brush_vertex.vertex_index, updated)+ this.write_skin_influences(mesh, brush_vertex.vertex_index, updated, bones)+ this.recolor_vertex(mesh, brush_vertex.vertex_index, updated, bones)+ painted_count+++ }++ if (painted_count > 0) {+ this.mark_skin_attributes_dirty(mesh)+ }+ const color_attribute = mesh.geometry.attributes.color+ if (color_attribute !== undefined) {+ color_attribute.needsUpdate = true+ }+ return painted_count+ }++ /** The brush vertices plus their counterparts across the symmetry plane. */+ private mirror_brush_vertices (vertices: BrushVertex[], mirror_data: MirrorData): BrushVertex[] {+ const combined = new Map<number, number>()+ for (const vertex of vertices) {+ combined.set(vertex.vertex_index,+ Math.max(combined.get(vertex.vertex_index) ?? 0, vertex.falloff))+ const mirrored_index = mirror_data.map.get(vertex.vertex_index)+ if (mirrored_index !== undefined) {+ combined.set(mirrored_index, Math.max(combined.get(mirrored_index) ?? 0, vertex.falloff))+ }+ }+ return [...combined].map(([vertex_index, falloff]) => ({ vertex_index, falloff }))+ }++ /**+ * Averages each brushed vertex's influences with its connected neighbours.+ * The brush strength and falloff decide how far the vertex moves towards the+ * average, which softens the stepping that automatic weights leave around+ * elbows, knees and shoulders.+ */+ private smooth_vertices (+ mesh: Mesh,+ geometry_overrides: GeometryWeightOverrides,+ vertices: BrushVertex[],+ strength: number,+ bones: Bone[]+ ): number {+ const adjacency = this.adjacency_for(mesh.geometry)+ const influence_cache = new Map<number, Map<string, number>>()+ const influences_at = (vertex_index: number): Map<string, number> => {+ const cached = influence_cache.get(vertex_index)+ if (cached !== undefined) { return cached }+ const influences = this.current_influences(mesh, geometry_overrides, vertex_index, bones)+ influence_cache.set(vertex_index, influences)+ return influences+ }++ // Compute every target from the same snapshot so the result does not depend+ // on the order the brush vertices are processed in.+ const smoothed = new Map<number, PaintedInfluence[]>()+ for (const vertex of vertices) {+ const amount = Math.min(1, Math.max(0, strength * vertex.falloff))+ if (amount <= 1e-6) { continue }++ const neighbors = adjacency[vertex.vertex_index] ?? []+ if (neighbors.length === 0) { continue }++ const average = new Map<string, number>()+ for (const neighbor of neighbors) {+ for (const [bone_name, weight] of influences_at(neighbor)) {+ average.set(bone_name, (average.get(bone_name) ?? 0) + weight)+ }+ }+ for (const [bone_name, weight] of average) {+ average.set(bone_name, weight / neighbors.length)+ }++ const blended = new Map<string, number>()+ for (const [bone_name, weight] of influences_at(vertex.vertex_index)) {+ blended.set(bone_name, weight * (1 - amount))+ }+ for (const [bone_name, weight] of average) {+ blended.set(bone_name, (blended.get(bone_name) ?? 0) + weight * amount)+ }++ const total = [...blended.values()].reduce((sum, weight) => sum + weight, 0)+ if (total <= 1e-6) { continue }++ const influences = [...blended.entries()]+ .filter(([, weight]) => weight > 1e-6)+ .sort((a, b) => b[1] - a[1])+ .slice(0, 4)+ .map(([bone_name, weight]) => ({ bone_name, weight: weight / total }))+ if (influences.length === 0) { continue }+ smoothed.set(vertex.vertex_index, influences)+ }++ for (const [vertex_index, influences] of smoothed) {+ this.record_stroke_backup(mesh, vertex_index)+ geometry_overrides.set(vertex_index, influences)+ this.write_skin_influences(mesh, vertex_index, influences, bones)+ this.recolor_vertex(mesh, vertex_index, influences, bones)+ }++ if (smoothed.size > 0) {+ this.mark_skin_attributes_dirty(mesh)+ const color_attribute = mesh.geometry.attributes.color+ if (color_attribute !== undefined) { color_attribute.needsUpdate = true }+ }+ return smoothed.size+ }++ /** Connected vertex indices, built lazily from the geometry's triangles. */+ private adjacency_for (geometry: BufferGeometry): number[][] {+ const cached = this.adjacency_cache.get(geometry)+ if (cached !== undefined) { return cached }++ const vertex_count = geometry.attributes.position?.count ?? 0+ const neighbors: Array<Set<number>> = Array.from({ length: vertex_count }, () => new Set<number>())+ const connect = (a: number, b: number): void => {+ if (a === b || a < 0 || b < 0 || a >= vertex_count || b >= vertex_count) { return }+ neighbors[a].add(b)+ neighbors[b].add(a)+ }++ const index = geometry.index+ if (index !== null) {+ for (let i = 0; i + 2 < index.count; i += 3) {+ const a = index.getX(i)+ const b = index.getX(i + 1)+ const c = index.getX(i + 2)+ connect(a, b)+ connect(b, c)+ connect(c, a)+ }+ } else {+ // Non-indexed geometry: vertices in the same triangle are neighbours.+ for (let i = 0; i + 2 < vertex_count; i += 3) {+ connect(i, i + 1)+ connect(i + 1, i + 2)+ connect(i + 2, i)+ }+ }++ const result = neighbors.map(set => [...set])+ this.adjacency_cache.set(geometry, result)+ return result+ }++ /**+ * Finds matching vertices across the model's X symmetry plane. Built lazily+ * and cached per geometry; only used when mirror painting is enabled.+ */+ private mirror_data (mesh: Mesh): MirrorData | null {+ const geometry = mesh.geometry+ if (this.mirror_cache.has(geometry)) {+ return this.mirror_cache.get(geometry) ?? null+ }+ const data = this.build_mirror_data(geometry)+ this.mirror_cache.set(geometry, data)+ return data+ }++ private build_mirror_data (geometry: BufferGeometry): MirrorData | null {+ const positions = geometry.attributes.position+ if (positions === undefined || positions.count === 0) { return null }++ geometry.computeBoundingBox()+ const box = geometry.boundingBox+ if (box === null) { return null }++ const center_x = (box.min.x + box.max.x) / 2+ const size = box.getSize(new Vector3())+ const tolerance = Math.max(size.length() * 0.0015, 1e-6)+ const cell = tolerance+ const key = (x: number, y: number, z: number): string =>+ `${Math.round(x / cell)}|${Math.round(y / cell)}|${Math.round(z / cell)}`++ const buckets = new Map<string, number[]>()+ for (let i = 0; i < positions.count; i++) {+ const bucket_key = key(positions.getX(i), positions.getY(i), positions.getZ(i))+ const bucket = buckets.get(bucket_key)+ if (bucket === undefined) {+ buckets.set(bucket_key, [i])+ } else {+ bucket.push(i)+ }+ }++ const map = new Map<number, number>()+ for (let i = 0; i < positions.count; i++) {+ const x = positions.getX(i)+ if (Math.abs(x - center_x) <= tolerance) { continue } // center line maps to itself+ const y = positions.getY(i)+ const z = positions.getZ(i)+ const mirrored_x = 2 * center_x - x+ const source_side = Math.sign(x - center_x)++ let best_index = -1+ let best_distance = tolerance * tolerance+ for (let dx = -1; dx <= 1; dx++) {+ for (let dy = -1; dy <= 1; dy++) {+ for (let dz = -1; dz <= 1; dz++) {+ const bucket = buckets.get(key(mirrored_x + dx * cell, y + dy * cell, z + dz * cell))+ if (bucket === undefined) { continue }+ for (const candidate of bucket) {+ if (candidate === i) { continue }+ if (Math.sign(positions.getX(candidate) - center_x) === source_side) { continue }+ const ddx = positions.getX(candidate) - mirrored_x+ const ddy = positions.getY(candidate) - y+ const ddz = positions.getZ(candidate) - z+ const distance = ddx * ddx + ddy * ddy + ddz * ddz+ if (distance < best_distance) {+ best_distance = distance+ best_index = candidate+ }+ }+ }+ }+ }+ if (best_index >= 0) {+ map.set(i, best_index)+ }+ }++ return { center_x, map }+ }++ /**+ * Writes painted overrides into a geometry's skin arrays. Vertices that were+ * not painted, or whose bones no longer exist, keep the automatic weights.+ */+ public static apply_overrides (+ overrides: ManualWeightOverrides,+ geometry_index: number,+ bones: Bone[],+ skin_indices: number[],+ skin_weights: number[]+ ): void {+ const geometry_overrides = overrides.get(geometry_index)+ if (geometry_overrides === undefined) { return }++ const bone_index_by_name = new Map<string, number>()+ bones.forEach((bone, index) => bone_index_by_name.set(bone.name, index))++ for (const [vertex_index, influences] of geometry_overrides) {+ const resolved = influences+ .map(influence => ({+ bone_index: bone_index_by_name.get(influence.bone_name),+ weight: influence.weight+ }))+ .filter((influence): influence is { bone_index: number, weight: number } =>+ influence.bone_index !== undefined && influence.weight > 0)+ if (resolved.length === 0) { continue }++ const total = resolved.reduce((sum, influence) => sum + influence.weight, 0)+ const offset = vertex_index * 4+ for (let slot = 0; slot < 4; slot++) {+ const influence = resolved[slot]+ if (influence === undefined) {+ skin_indices[offset + slot] = 0+ skin_weights[offset + slot] = 0+ continue+ }+ skin_indices[offset + slot] = influence.bone_index+ skin_weights[offset + slot] = total > 0 ? influence.weight / total : 0+ }+ }+ }++ private current_influences (+ mesh: Mesh,+ geometry_overrides: GeometryWeightOverrides,+ vertex_index: number,+ bones: Bone[]+ ): Map<string, number> {+ const existing = geometry_overrides.get(vertex_index)+ if (existing !== undefined) {+ return new Map(existing.map(influence => [influence.bone_name, influence.weight]))+ }++ const influences = new Map<string, number>()+ const skin_indices = mesh.geometry.attributes.skinIndex+ const skin_weights = mesh.geometry.attributes.skinWeight+ if (skin_indices === undefined || skin_weights === undefined) {+ return influences+ }++ for (let slot = 0; slot < 4; slot++) {+ const weight = skin_weights.array[vertex_index * 4 + slot] as number+ if (weight <= 0) { continue }+ const bone_index = skin_indices.array[vertex_index * 4 + slot] as number+ const bone_name = bones[bone_index]?.name+ if (bone_name === undefined) { continue }+ influences.set(bone_name, (influences.get(bone_name) ?? 0) + weight)+ }+ return influences+ }++ /** Writes resolved influences back into the mesh's skin attributes. */+ private write_skin_influences (+ mesh: Mesh,+ vertex_index: number,+ influences: PaintedInfluence[],+ bones: Bone[]+ ): void {+ const skin_indices = mesh.geometry.attributes.skinIndex+ const skin_weights = mesh.geometry.attributes.skinWeight+ if (skin_indices === undefined || skin_weights === undefined) { return }++ const bone_index_by_name = new Map<string, number>()+ bones.forEach((bone, index) => bone_index_by_name.set(bone.name, index))++ const resolved = influences+ .map(influence => ({+ bone_index: bone_index_by_name.get(influence.bone_name),+ weight: influence.weight+ }))+ .filter((influence): influence is { bone_index: number, weight: number } =>+ influence.bone_index !== undefined && influence.weight > 0)++ const total = resolved.reduce((sum, influence) => sum + influence.weight, 0)+ const offset = vertex_index * 4+ for (let slot = 0; slot < 4; slot++) {+ const influence = resolved[slot]+ if (influence === undefined) {+ skin_indices.array[offset + slot] = 0+ skin_weights.array[offset + slot] = 0+ continue+ }+ skin_indices.array[offset + slot] = influence.bone_index+ skin_weights.array[offset + slot] = total > 0 ? influence.weight / total : 0+ }+ }++ private record_stroke_backup (mesh: Mesh, vertex_index: number): void {+ if (this.current_stroke_backups === null) { return }++ let mesh_backups = this.current_stroke_backups.get(mesh)+ if (mesh_backups === undefined) {+ mesh_backups = new Map()+ this.current_stroke_backups.set(mesh, mesh_backups)+ }+ if (mesh_backups.has(vertex_index)) { return }++ mesh_backups.set(vertex_index, this.capture_skin_backup(mesh, vertex_index))+ }++ private capture_skin_backups (vertices: Map<Mesh, Map<number, SkinBackup>>): Map<Mesh, Map<number, SkinBackup>> {+ const result = new Map<Mesh, Map<number, SkinBackup>>()++ for (const [mesh, mesh_vertices] of vertices) {+ const backups = new Map<number, SkinBackup>()+ for (const vertex_index of mesh_vertices.keys()) {+ backups.set(vertex_index, this.capture_skin_backup(mesh, vertex_index))+ }+ result.set(mesh, backups)+ }++ return result+ }++ private capture_skin_backup (mesh: Mesh, vertex_index: number): SkinBackup {+ const skin_indices = mesh.geometry.attributes.skinIndex+ const skin_weights = mesh.geometry.attributes.skinWeight+ const backup: SkinBackup = { indices: [0, 0, 0, 0], weights: [0, 0, 0, 0] }+ if (skin_indices !== undefined && skin_weights !== undefined) {+ for (let slot = 0; slot < 4; slot++) {+ backup.indices[slot] = skin_indices.array[vertex_index * 4 + slot] as number+ backup.weights[slot] = skin_weights.array[vertex_index * 4 + slot] as number+ }+ }+ return backup+ }++ private restore_skin_backups (backups: Map<Mesh, Map<number, SkinBackup>>): void {+ for (const [mesh, mesh_backups] of backups) {+ const skin_indices = mesh.geometry.attributes.skinIndex+ const skin_weights = mesh.geometry.attributes.skinWeight+ if (skin_indices === undefined || skin_weights === undefined) { continue }++ for (const [vertex_index, backup] of mesh_backups) {+ for (let slot = 0; slot < 4; slot++) {+ skin_indices.array[vertex_index * 4 + slot] = backup.indices[slot]+ skin_weights.array[vertex_index * 4 + slot] = backup.weights[slot]+ }+ }+ this.mark_skin_attributes_dirty(mesh)+ }+ }++ private mark_skin_attributes_dirty (mesh: Mesh): void {+ const skin_indices = mesh.geometry.attributes.skinIndex+ const skin_weights = mesh.geometry.attributes.skinWeight+ if (skin_indices !== undefined) { skin_indices.needsUpdate = true }+ if (skin_weights !== undefined) { skin_weights.needsUpdate = true }+ }++ /**+ * Gives the painted bone the requested weight and redistributes the rest+ * across its existing influences. If nothing else influences the vertex, the+ * freed weight goes to the bone's parent (e.g. erasing jaw weight on the nose+ * hands it to the head instead of leaving a hole).+ */+ private renormalize (+ current: Map<string, number>,+ bone_name: string,+ target_weight: number,+ bones: Bone[]+ ): PaintedInfluence[] {+ const target = Math.min(1, Math.max(0, target_weight))+ if (target >= 1 - 1e-6) {+ return [{ bone_name, weight: 1 }]+ }++ const others = [...current.entries()]+ .filter(([name, weight]) => name !== bone_name && weight > 0)+ let other_sum = others.reduce((sum, [, weight]) => sum + weight, 0)++ if (other_sum <= 0) {+ const fallback = this.fallback_bone_name(bone_name, bones)+ if (fallback !== null) {+ others.push([fallback, 1])+ other_sum = 1+ } else if (target <= 1e-6) {+ return []+ }+ }++ const influences: PaintedInfluence[] = []+ if (target > 1e-6) {+ influences.push({ bone_name, weight: target })+ }+ const remaining = 1 - target+ if (other_sum > 0) {+ for (const [name, weight] of others) {+ influences.push({ bone_name: name, weight: (weight / other_sum) * remaining })+ }+ }++ return influences+ .filter(influence => influence.weight > 1e-6)+ .sort((a, b) => b.weight - a.weight)+ .slice(0, 4)+ }++ private fallback_bone_name (bone_name: string, bones: Bone[]): string | null {+ const bone = bones.find(candidate => candidate.name === bone_name)+ if (bone !== undefined) {+ const parent = bone.parent+ if (parent !== null && bones.includes(parent as Bone) && parent.name !== 'root') {+ return parent.name+ }+ }++ const head = bones.find(candidate => /^(DEF[-_.])?head$/i.test(candidate.name))+ if (head !== undefined && head.name !== bone_name) { return head.name }++ const fallback = bones.find(candidate => candidate.name !== 'root' && candidate.name !== bone_name)+ return fallback?.name ?? null+ }++ /** Colors a painted vertex by its strongest bone, matching the weight preview colors. */+ private recolor_vertex (mesh: Mesh, vertex_index: number, influences: PaintedInfluence[], bones: Bone[]): void {+ const color_attribute = mesh.geometry.attributes.color+ if (color_attribute === undefined || influences.length === 0) { return }++ const primary_bone_index = bones.findIndex(bone => bone.name === influences[0].bone_name)+ const color = this.bone_colors[primary_bone_index] ?? new Vector3(1, 1, 1)+ color_attribute.setXYZ(vertex_index, color.x, color.y, color.z)+ }++ private clone_overrides (overrides: ManualWeightOverrides): ManualWeightOverrides {+ const copy: ManualWeightOverrides = new Map()+ for (const [geometry_index, geometry_overrides] of overrides) {+ const geometry_copy: GeometryWeightOverrides = new Map()+ for (const [vertex_index, influences] of geometry_overrides) {+ geometry_copy.set(vertex_index, influences.map(influence => ({ ...influence })))+ }+ copy.set(geometry_index, geometry_copy)+ }+ return copy+ }+}diff --git a/src/lib/processes/weight-skin/StepWeightSkin.ts b/src/lib/processes/weight-skin/StepWeightSkin.tsindex 9d598b6..4a339c9 100644--- a/src/lib/processes/weight-skin/StepWeightSkin.ts+++ b/src/lib/processes/weight-skin/StepWeightSkin.ts@@ -1,5 +1,7 @@import { UI } from '../../UI.ts'import SkinningAlgorithm from '../../solvers/SkinningAlgorithm.ts'+import { Utility } from '../../Utilities.ts'+import { WeightPaintManager, type ManualWeightOverrides } from '../weight-painting/WeightPaintManager.ts'import { Generators } from '../../Generators.ts'@@ -13,6 +15,7 @@ export class StepWeightSkin extends EventTarget {private bone_skinning_formula: SkinningAlgorithm | undefinedprivate binding_skeleton: Skeleton | undefinedprivate skinned_meshes: SkinnedMesh[] = []+ private manual_weight_overrides: ManualWeightOverrides | null = null// stores the geometry data for meshes we will skinprivate all_mesh_geometry: BufferGeometry[] = []@@ -122,6 +125,7 @@ export class StepWeightSkin extends EventTarget {const skinned_mesh: SkinnedMesh = new SkinnedMesh(geometry, material)skinned_mesh.name = 'Skinned Mesh ' + idx.toString()+ skinned_mesh.userData.geometry_index = idxskinned_mesh.castShadow = true // skinned mesh won't update right if this is false// do the binding for the mesh to the skeleton@@ -161,6 +165,14 @@ export class StepWeightSkin extends EventTarget {this.bone_skinning_formula.set_arm_plane_offset(offset)}+ /**+ * Manual weights painted in the edit skeleton step. They override the+ * automatic solver result for the vertices that were painted.+ */+ public set_manual_weight_overrides (overrides: ManualWeightOverrides | null): void {+ this.manual_weight_overrides = overrides+ }+public calculate_weights (): number[][] {if (this.bone_skinning_formula === undefined) return [[], []]return this.bone_skinning_formula.calculate_indexes_and_weights()@@ -179,6 +191,13 @@ export class StepWeightSkin extends EventTarget {this.bone_skinning_formula!.set_geometry(geometry_data)const [final_skin_indices, final_skin_weights]: number[][] = this.calculate_weights()+ // Painted weights replace the automatic result for the affected vertices.+ if (this.manual_weight_overrides !== null && this.skinning_armature !== undefined) {+ const bones = Utility.bone_list_from_hierarchy(this.skinning_armature.children[0])+ WeightPaintManager.apply_overrides(this.manual_weight_overrides, idx, bones,+ final_skin_indices, final_skin_weights)+ }+geometry_data.setAttribute('skinIndex', new Uint16BufferAttribute(final_skin_indices, 4))geometry_data.setAttribute('skinWeight', new Float32BufferAttribute(final_skin_weights, 4))@@ -191,6 +210,9 @@ export class StepWeightSkin extends EventTarget {// re-generate the weight painted mesh display if neededif (regenerate_weight_painted_mesh) {const weight_painted_mesh = Generators.create_weight_painted_mesh(final_skin_indices, geometry_data)+ weight_painted_mesh.userData.geometry_index = idx+ weight_painted_mesh.userData.weight_painted = true+ weight_painted_mesh.name = `Weight Painted Mesh ${idx}`const wireframe_mesh = Generators.create_wireframe_mesh_from_geometry(geometry_data)this.weight_painted_mesh_preview?.add(weight_painted_mesh, wireframe_mesh)}diff --git a/src/styles.css b/src/styles.cssindex 7707aca..45254b8 100644--- a/src/styles.css+++ b/src/styles.css@@ -96,7 +96,7 @@ nav .active-nav-item, nav a:hover {/* this was just a star (*) selector, but dark reader extension cannot parse that and crashesIt really just targets text related elements, so just use those instead*/-html, body, li, p, div, span, label, input,+html, body, li, p, div, span, label, input,h1, h2, h3, h4, h5, h6, input, button, select {color: var(--text-primary);font-family: 'Jost', sans-serif;@@ -105,6 +105,11 @@ h1, h2, h3, h4, h5, h6, input, button, select {display: inline-block;}+/* the display rule above otherwise overrides the browser's [hidden] rule */+[hidden] {+ display: none !important;+}+div, p {display: block;}@@ -265,6 +270,95 @@ button.secondary-button.play:hover {transform: scale(1.0);}+/* icon-only bone picker in the weight painting step */+#weight-paint-step-pick-bone {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ padding: 0.35rem 0.75rem;+}++#weight-paint-step-pick-bone[aria-pressed="true"] {+ outline: 2px solid var(--button-primary-bg);+ outline-offset: 1px;+}++/* fixed-size, hairline brush outline shown while painting weights */+#weight-paint-brush-cursor {+ position: fixed;+ left: 0;+ top: 0;+ width: 48px;+ height: 48px;+ border: 2px solid rgba(255, 255, 255, 0.95);+ border-radius: 50%;+ box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.45);+ box-sizing: border-box;+ transform: translate(-50%, -50%);+ pointer-events: none;+ display: none;+ z-index: 20;+}++.weight-paint-tools-heading {+ font-size: 0.8rem;+ font-weight: 600;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--text-secondary);+}++.weight-paint-bone-name {+ font-weight: bold;+ overflow-wrap: anywhere;+}++.weight-paint-slider-row {+ display: flex;+ align-items: center;+ gap: 0.5rem;+}++.weight-paint-slider-row label {+ flex: 0 0 auto;+}++.weight-paint-slider-row input[type="range"] {+ flex: 1;+ min-width: 0;+}++.weight-paint-slider-row span {+ width: 3.5rem;+ text-align: right;+ font-variant-numeric: tabular-nums;+}++.weight-paint-animation-list {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem;+}++.weight-paint-animation-button {+ background: var(--bg-alternate);+ color: var(--text-primary);+ border: 1px solid var(--bg-tertiary);+ border-radius: 0.25rem;+ padding: 0.35rem 0.6rem;+ cursor: pointer;+ font-size: 0.9rem;+}++.weight-paint-animation-button:hover {+ border-color: var(--text-primary);+}++.weight-paint-animation-button.active {+ background: var(--button-primary-bg);+ border-color: var(--button-primary-bg);+}+button.no-style-button {background: none;box-shadow: none;@@ -513,7 +607,7 @@ option {font-size: 20px;}-#load-model-tools, #load-skeleton-tools, #transform-controls, #skeleton-step-actions {+#load-model-tools, #load-skeleton-tools, #transform-controls, #skeleton-step-actions, #weight-paint-step-tools {display: flex;flex-direction: column;row-gap: 0.4rem;diff --git a/static/images/icons/color-picker-cursor.svg b/static/images/icons/color-picker-cursor.svgnew file mode 100644index 0000000..a4fa83b--- /dev/null+++ b/static/images/icons/color-picker-cursor.svg@@ -0,0 +1,13 @@+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round">+ <!-- dark halo keeps the cursor visible on light and dark backgrounds -->+ <g stroke="rgb(0,0,0)" stroke-width="4">+ <path d="m2 22 1-1h3l9-9"/>+ <path d="M3 21v-3l9-9"/>+ <path d="m15 6 3.4-3.4a2.1 2.1 0 1 1 3 3L18 9l.4.4a2.1 2.1 0 1 1-3 3l-3.8-3.8a2.1 2.1 0 1 1 3-3l.4.4Z"/>+ </g>+ <g stroke="rgb(255,255,255)" stroke-width="2">+ <path d="m2 22 1-1h3l9-9"/>+ <path d="M3 21v-3l9-9"/>+ <path d="m15 6 3.4-3.4a2.1 2.1 0 1 1 3 3L18 9l.4.4a2.1 2.1 0 1 1-3 3l-3.8-3.8a2.1 2.1 0 1 1 3-3l.4.4Z"/>+ </g>+</svg>diff --git a/static/images/icons/color-picker.svg b/static/images/icons/color-picker.svgnew file mode 100644index 0000000..5dd771d--- /dev/null+++ b/static/images/icons/color-picker.svg@@ -0,0 +1,5 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="rgb(255,255,255)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <path d="m2 22 1-1h3l9-9"/>+ <path d="M3 21v-3l9-9"/>+ <path d="m15 6 3.4-3.4a2.1 2.1 0 1 1 3 3L18 9l.4.4a2.1 2.1 0 1 1-3 3l-3.8-3.8a2.1 2.1 0 1 1 3-3l.4.4Z"/>+</svg>