Import a 3D Model and automatically assign and export animations
TypeScript
First pass at re-assigning weights with head corrector
Scott Petrovic926dcee54bb7
diff --git a/src/Mesh2MotionEngine.ts b/src/Mesh2MotionEngine.tsindex 90bf66e..6abe84f 100644--- a/src/Mesh2MotionEngine.ts+++ b/src/Mesh2MotionEngine.ts@@ -485,6 +485,12 @@ export class Mesh2MotionEngine {this.weight_skin_step.create_bone_formula_object(this.edit_skeleton_step.armature(), this.edit_skeleton_step.algorithm(),this.load_skeleton_step.skeleton_type())+ // Pass head weight correction settings to the weight skin step+ this.weight_skin_step.set_head_weight_correction_settings(+ this.edit_skeleton_step.use_head_weight_correction(),+ this.edit_skeleton_step.get_preview_plane_height()+ )+this.weight_skin_step.create_binding_skeleton()// add geometry data needed for skinning@@ -525,6 +531,12 @@ export class Mesh2MotionEngine {this.weight_skin_step.set_bone_index_to_test(-1)}+ // Pass head weight correction settings to the weight skin step+ this.weight_skin_step.set_head_weight_correction_settings(+ this.edit_skeleton_step.use_head_weight_correction(),+ this.edit_skeleton_step.get_preview_plane_height()+ )+// Don't do skinning operation if there are bones outside of the mesh// that messes up the bone envelope calculationlet testing_geometry_success = truediff --git a/src/lib/processes/weight-skin/StepWeightSkin.ts b/src/lib/processes/weight-skin/StepWeightSkin.tsindex a926df2..209f72b 100644--- a/src/lib/processes/weight-skin/StepWeightSkin.ts+++ b/src/lib/processes/weight-skin/StepWeightSkin.ts@@ -173,6 +173,19 @@ export class StepWeightSkin extends EventTarget {this.bone_index_to_test = index}+ /**+ * Configure head weight correction settings for the solver+ * @param enabled Whether head weight correction is enabled+ * @param height The preview plane height threshold+ */+ public set_head_weight_correction_settings (enabled: boolean, height: number): void {+ // Only apply to the SolverDistanceChildTargeting solver+ if (this.bone_skinning_formula instanceof SolverDistanceChildTargeting) {+ this.bone_skinning_formula.set_head_weight_correction_enabled(enabled)+ this.bone_skinning_formula.set_preview_plane_height(height)+ }+ }+public calculate_weights (): number[][] {if (this.bone_skinning_formula === undefined) {console.warn('Tried to calculate_weights() but bone_skinning_formula is null for some reason!')diff --git a/src/lib/solvers/HeadWeightCorrector.ts b/src/lib/solvers/HeadWeightCorrector.tsnew file mode 100644index 0000000..e65fb13--- /dev/null+++ b/src/lib/solvers/HeadWeightCorrector.ts@@ -0,0 +1,183 @@+import { Vector3, type Bone, type BufferGeometry } from 'three'+/**+ * HeadWeightCorrector+ * Handles post-processing correction of vertex weights for "chibi" style characters+ * where large heads might incorrectly get weighted to arm bones instead of head bones.+ *+ * This class will reassign vertices that are:+ * 1. Above a specified height threshold (preview plane height)+ * 2. Currently assigned to arm bones+ * 3. Should be assigned to the head bone instead+ */+export class HeadWeightCorrector {+ private readonly geometry: BufferGeometry+ private readonly bones_master_data: Bone[]+ private readonly preview_plane_height: number+ constructor (+ geometry: BufferGeometry,+ bones_master_data: Bone[],+ preview_plane_height: number+ ) {+ this.geometry = geometry+ this.bones_master_data = bones_master_data+ this.preview_plane_height = preview_plane_height+ }++ /**+ * Apply head weight correction to the skin indices and weights+ * @param skin_indices Array of bone indices for each vertex (4 per vertex)+ * @param skin_weights Array of bone weights for each vertex (4 per vertex)+ */+ public apply_head_weight_correction (skin_indices: number[], skin_weights: number[]): void {+ const head_bone_index = this.find_head_bone_index()+ if (head_bone_index === -1) { return } // Head weight correction skipped: DEF-head bone not found++ const arm_bone_indices = this.find_arm_bone_indices()+ if (arm_bone_indices.length === 0) { return } // Head weight correction skipped: No arm bones found++ this.correct_vertex_weights(skin_indices, skin_weights, head_bone_index, arm_bone_indices)+ }++ /**+ * Find the index of the head bone (looking for "DEF-head" or similar)+ */+ private find_head_bone_index (): number {+ // we only have this head corrector for humans right now, but+ // maybe add a more robust way in case it ever expands to other skeleton types+ const head_bone_names = ['DEF-head', 'head', 'Head', 'HEAD']+ for (let i = 0; i < this.bones_master_data.length; i++) {+ const bone_name = this.bones_master_data[i].name+ // Check for exact matches first+ if (head_bone_names.includes(bone_name)) {+ return i+ }++ // Check for partial matches (case-insensitive)+ const lower_bone_name = bone_name.toLowerCase()+ if (+ head_bone_names.some((name) =>+ lower_bone_name.includes(name.toLowerCase())+ )+ ) {+ return i+ }+ }+ return -1 // Head bone not found+ }++ /**+ * Find the indices of arm bones (looking for arm, shoulder, hand bones)+ */+ private find_arm_bone_indices (): number[] {+ const arm_bone_keywords = [+ 'arm',+ 'shoulder',+ 'hand',+ 'finger',+ 'thumb',+ 'elbow',+ 'forearm',+ 'upperarm'+ ]+ const arm_bone_indices: number[] = []+ for (let i = 0; i < this.bones_master_data.length; i++) {+ const bone_name = this.bones_master_data[i].name.toLowerCase()+ // Check if bone name contains any arm-related keywords+ if (arm_bone_keywords.some((keyword) => bone_name.includes(keyword))) {+ arm_bone_indices.push(i)+ }+ }+ return arm_bone_indices+ }++ /**+ * Correct vertex weights for vertices above the height threshold+ */+ private correct_vertex_weights (+ skin_indices: number[],+ skin_weights: number[],+ head_bone_index: number,+ arm_bone_indices: number[]+ ): number {+ const vertex_count = this.geometry.attributes.position.array.length / 3+ let corrected_count = 0+ for (let i = 0; i < vertex_count; i++) {+ const vertex_position = new Vector3().fromBufferAttribute(this.geometry.attributes.position, i)++ // Skip vertices below the height threshold+ if (vertex_position.y <= this.preview_plane_height) { continue }++ const offset = i * 4 // each vertex has 4 slots for skinning weights and indices++ // Check if this vertex is primarily assigned to an arm bone+ const primary_bone_index = skin_indices[offset]+ const primary_weight = skin_weights[offset]++ // If the primary bone is an arm bone and has significant weight, reassign to head+ // Reassign to head bone with 100% weight+ if (arm_bone_indices.includes(primary_bone_index) && primary_weight > 0.5) {+ skin_indices[offset] = head_bone_index+ skin_indices[offset + 1] = 0+ skin_indices[offset + 2] = 0+ skin_indices[offset + 3] = 0+ skin_weights[offset] = 1.0+ skin_weights[offset + 1] = 0.0+ skin_weights[offset + 2] = 0.0+ skin_weights[offset + 3] = 0.0+ corrected_count+++ continue+ }++ // Also check secondary bones for arm assignments+ for (let j = 0; j < 4; j++) {+ const bone_index = skin_indices[offset + j]+ const weight = skin_weights[offset + j]+ // If any arm bone has significant influence, reduce it and increase head influence+ if (arm_bone_indices.includes(bone_index) && weight > 0.3) {+ // Find if head is already in the influences+ let head_slot = -1+ for (let k = 0; k < 4; k++) {+ if (skin_indices[offset + k] === head_bone_index) {+ head_slot = k+ break+ }+ }+ // If head isn't already influencing, replace this arm bone with head+ if (head_slot === -1) {+ skin_indices[offset + j] = head_bone_index+ // Keep the same weight for smooth transition+ } else {+ // Head is already influencing, transfer this arm bone's weight to head+ skin_weights[offset + head_slot] += weight+ skin_weights[offset + j] = 0+ skin_indices[offset + j] = 0+ }+ corrected_count+++ }+ }+ // Normalize weights to ensure they sum to 1.0 since we changed them+ this.normalize_vertex_weights(skin_weights, offset)+ }+ return corrected_count+ }++ /**+ * Normalize weights for a single vertex to ensure they sum to 1.0+ */+ private normalize_vertex_weights (+ skin_weights: number[],+ offset: number+ ): void {+ const total_weight =+ skin_weights[offset] ++ skin_weights[offset + 1] ++ skin_weights[offset + 2] ++ skin_weights[offset + 3]+ if (total_weight > 0) {+ skin_weights[offset] /= total_weight+ skin_weights[offset + 1] /= total_weight+ skin_weights[offset + 2] /= total_weight+ skin_weights[offset + 3] /= total_weight+ }+ }+}diff --git a/src/lib/solvers/SolverDistanceChildTargeting.ts b/src/lib/solvers/SolverDistanceChildTargeting.tsindex 2fc831a..07536ab 100644--- a/src/lib/solvers/SolverDistanceChildTargeting.ts+++ b/src/lib/solvers/SolverDistanceChildTargeting.ts@@ -8,6 +8,7 @@ import { Utility } from '../Utilities.js'import { SkeletonType } from '../enums/SkeletonType.js'import { AbstractAutoSkinSolver } from './AbstractAutoSkinSolver.js'import { Generators } from '../Generators.js'+import { HeadWeightCorrector } from './HeadWeightCorrector.js'/*** SolverDistanceChildTargeting@@ -15,6 +16,24 @@ import { Generators } from '../Generators.js'* This adds extra logic to target ares in the arms and hips to help with assigning weights*/export default class SolverDistanceChildTargeting extends AbstractAutoSkinSolver {+ // Head weight correction properties+ private use_head_weight_correction: boolean = false+ private preview_plane_height: number = 1.4++ /**+ * Enable or disable head weight correction+ */+ public set_head_weight_correction_enabled (enabled: boolean): void {+ this.use_head_weight_correction = enabled+ }++ /**+ * Set the preview plane height for head weight correction+ */+ public set_preview_plane_height (height: number): void {+ this.preview_plane_height = height+ }+/*** Returns an array of vertex indices whose weights do not sum to 1.0 (within a small epsilon).*/@@ -174,6 +193,17 @@ export default class SolverDistanceChildTargeting extends AbstractAutoSkinSolver// all the weights add up to 1.0this.normalize_weights_with_incorrect_vertices(skin_weights)+ // Apply head weight correction if enabled+ if (this.use_head_weight_correction) {+ const head_weight_corrector = new HeadWeightCorrector(+ this.geometry,+ this.get_bone_master_data(),+ this.preview_plane_height+ )+ console.log('applying the head weight correction...')+ head_weight_corrector.apply_head_weight_correction(skin_indices, skin_weights)+ }+console.log('do we have any leftover incorrect weights ', this.find_vertices_with_incorrect_weight_sum(skin_weights))return [skin_indices, skin_weights]