Import a 3D Model and automatically assign and export animations
TypeScript
more lint fixes
Scott Petrovica10b2cf0cf73
diff --git a/.eslintrc.json b/.eslintrc.jsonindex 6c25e69..d89f260 100644--- a/.eslintrc.json+++ b/.eslintrc.json@@ -21,7 +21,6 @@}],"indent": "off",- "keyword-spacing": "off","brace-style": "off","@typescript-eslint/brace-style": "error"}diff --git a/src/lib/Generators.ts b/src/lib/Generators.tsindex 6c25b46..396bb12 100644--- a/src/lib/Generators.ts+++ b/src/lib/Generators.ts@@ -1,50 +1,46 @@-import { PerspectiveCamera, MeshStandardMaterial, DoubleSide, DirectionalLight, GridHelper,- Bone, Skeleton, DirectionalLightHelper, AmbientLight, PlaneGeometry, Mesh,- SphereGeometry, SkeletonHelper, MeshBasicMaterial, MeshPhongMaterial, AxesHelper,- Vector3, PointsMaterial, BufferGeometry, Points, Object3D } from 'three'+import {+ PerspectiveCamera, DoubleSide, DirectionalLight, GridHelper,+ Bone, Skeleton, AmbientLight, PlaneGeometry, Mesh,+ SphereGeometry, SkeletonHelper, type MeshBasicMaterial, MeshPhongMaterial, AxesHelper,+ Vector3, PointsMaterial, BufferGeometry, Points, type Object3D, WebGLRenderer+} from 'three'import { Utility } from './Utilities'--export class Generators-{- static create_material( wireframeValue = true, colorHex = 0x00ff00): MeshPhongMaterial- {- const material = new MeshPhongMaterial({ color: colorHex, wireframe: wireframeValue })+// eslint-disable-next-line @typescript-eslint/no-extraneous-class+export class Generators {+ static create_material (wireframe_value = true, color_hex = 0x00ff00): MeshPhongMaterial {+ const material = new MeshPhongMaterial({ color: color_hex, wireframe: wireframe_value })material.side = DoubleSidereturn material}- static create_grid_helper(color = 0x111155): any[]- {+ static create_grid_helper (color = 0x111155): any[] {// create floor mesh and add to scene to help with shadowsconst floor_geometry = new PlaneGeometry(100, 100, 10, 10)const floor_material = new MeshPhongMaterial({ color: 0x4e4e7a, wireframe: false, opacity: 0.2, transparent: true })floor_material.side = DoubleSide // helps us see that we are below the character-const floor_mesh = new Mesh(floor_geometry, floor_material)floor_mesh.name = 'Floor Mesh'floor_mesh.rotation.x = -Math.PI / 2- floor_mesh.position.y = -.01+ floor_mesh.position.y = -0.01floor_mesh.receiveShadow = true// xyz axes helper display- const axesHelper = new AxesHelper(0.15)- axesHelper.name = 'Axes Helper'- axesHelper.position.copy(new Vector3(0, 0.002, 0)) // offset a bit to avoid z-fighting+ const axes_helper = new AxesHelper(0.15)+ axes_helper.name = 'Axes Helper'+ axes_helper.position.copy(new Vector3(0, 0.002, 0)) // offset a bit to avoid z-fighting// grid display on floorconst size: number = 10const divisions: number = 10- const gridHelper: GridHelper = new GridHelper(size, divisions, color, color)+ const grid_helper: GridHelper = new GridHelper(size, divisions, color, color)-- return [gridHelper, floor_mesh, axesHelper]+ return [grid_helper, floor_mesh, axes_helper]}- static create_bone_hierarchy(): Bone- {+ static create_bone_hierarchy (): Bone {// offset root bone down to move entire bone structureconst bone0 = new Bone()bone0.name = 'rootBone'@@ -72,22 +68,20 @@ export class Generatorsreturn bone0}- static create_skeleton(bone_hierarchy: Object3D): Skeleton- {+ static create_skeleton (bone_hierarchy: Object3D): Skeleton {const bone_list = Utility.bone_list_from_hierarchy(bone_hierarchy)const skeleton = new Skeleton(bone_list)return skeleton}- static create_skeleton_helper(skeleton): SkeletonHelper+ static create_skeleton_helper(skeleton: Skeleton): SkeletonHelper{- const skeletonHelper = new SkeletonHelper(skeleton.bones[0])- return skeletonHelper+ const skeleton_helper = new SkeletonHelper(skeleton.bones[0])+ return skeleton_helper}- static create_spheres_for_points(points, sphere_size = 0.01, color = 0x00ffff, name = '' ): Points- {- let points_material = new PointsMaterial({ size: sphere_size, color: color })+ static create_spheres_for_points (points: Vector3[], sphere_size = 0.01, color = 0x00ffff, name = ''): Points {+ const points_material: PointsMaterial = new PointsMaterial({ size: sphere_size, color })const points_geometry = new BufferGeometry().setFromPoints(points)const point_objects: Points = new Points(points_geometry, points_material)point_objects.name = `Point display: ${name} `@@ -95,83 +89,63 @@ export class Generatorsreturn point_objects}- static create_test_plane_mesh(size: number = 0.08, color: number = 0x0000ff): Mesh- {+ static create_test_plane_mesh (size: number = 0.08, color: number = 0x0000ff): Mesh {const plane_width = sizeconst plane_height = sizeconst plane_width_segments = 2const plane_height_segments = 2- const plane_geometry = new PlaneGeometry( plane_width, plane_height, plane_width_segments, plane_height_segments )+ const plane_geometry = new PlaneGeometry(plane_width, plane_height, plane_width_segments, plane_height_segments)const plane_material: MeshBasicMaterial = Generators.create_material(false, color)const mesh_object = new Mesh(plane_geometry, plane_material)mesh_object.name = 'Plane Intersection Mesh'return mesh_object}- static create_default_lights()- {+ static create_default_lights (): Array<DirectionalLight | AmbientLight> {const light_1 = new DirectionalLight(0x777777, 7)light_1.castShadow = true- // @ts-ignorelight_1.position.set(-2, 2, 2)-- //const light_1_helper = new DirectionalLightHelper(light_1, 1, 0x333333);const light_2 = new AmbientLight(0xffffff, 0.3)// backfill lightconst backfill_light = new DirectionalLight(0x777777, 3)backfill_light.castShadow = false // one shadow is enough-- // @ts-ignorebackfill_light.position.set(2, 2, -2)- return [light_1, light_2, backfill_light]+ const result = [light_1, light_2, backfill_light]+ return result}- static create_camera()- {- const fieldOfView = 10 // in millimeters. Lower makes the camera more isometric- const camera = new PerspectiveCamera(fieldOfView, window.innerWidth / window.innerHeight, 0.1, 1000)-- // @ts-ignore+ static create_camera (): PerspectiveCamera {+ const field_of_view = 10 // in millimeters. Lower makes the camera more isometric+ const camera = new PerspectiveCamera(field_of_view, window.innerWidth / window.innerHeight, 0.1, 1000)camera.position.z = 10-- // @ts-ignorecamera.position.y = 5-- // @ts-ignorecamera.position.x = 5-return camera}- static create_equidistant_spheres_around_circle(sphere_count = 6, color = 0x00ff00, distance = 0.3)- {- const plane_points: Array<Mesh> = []+ static create_equidistant_spheres_around_circle (sphere_count = 6, color = 0x00ff00, distance = 0.3) {+ const plane_points: Mesh[] = []const plane_point_geometry = new SphereGeometry(0.03, 12, 12)const plane_point_material: MeshBasicMaterial = Generators.create_material(true, color)- for (let i = 0; i < sphere_count; i++)- {++ for (let i = 0; i < sphere_count; i++) {// have the points go around the plane in an even circle increments- const angle = (i/sphere_count) * (Math.PI*2)+ const angle = (i / sphere_count) * (Math.PI * 2)const x = Math.cos(angle) * distanceconst y = Math.sin(angle) * distanceconst z = 0const point_mesh: Mesh = new Mesh(plane_point_geometry, plane_point_material)-- // @ts-ignorepoint_mesh.position.set(x, y, z)--plane_points.push(point_mesh)}return plane_points}- static create_window_resize_listener(renderer, camera): void- {+ static create_window_resize_listener (renderer: WebGLRenderer, camera: PerspectiveCamera): void {// there was a bit of horizontal and vertical scrollbars// I tried doing overflow: none, but that wasn't working for some reasonconst contraction_size = 2@@ -183,14 +157,12 @@ export class Generators})}- static create_bone_plane_mesh(bone_start, bone_end, rays_to_cast): Mesh- {+ static create_bone_plane_mesh (bone_start: Bone, bone_end: Bone, rays_to_cast: number): Mesh {// create plane mesh to do the ray casting// we also want to offset it it half the bone distance up the bone// for a better approximation with what countsconst plane_mesh: Mesh = Generators.create_test_plane_mesh(0.02)- // @ts-ignoreplane_mesh.position.copy(Utility.world_position_from_object(bone_start))plane_mesh.lookAt(Utility.world_position_from_object(bone_end))@@ -200,8 +172,7 @@ export class Generatorsconst plane_point_geometry = new SphereGeometry(0.002, 3, 3)const plane_point_material: MeshBasicMaterial = Generators.create_material(true, 0x00ffff)- for (let i = 0; i < rays_to_cast; i++)- {+ for (let i = 0; i < rays_to_cast; i++) {// have the points go around the plane in an even circle incrementsconst distance: number = 0.005 // set radial distance from origin close to help with close verticesconst angle: number = (i/rays_to_cast) * (Math.PI*2)@@ -211,15 +182,10 @@ export class Generatorsconst point_mesh = new Mesh(plane_point_geometry, plane_point_material)point_mesh.name = 'Point mesh PLANE'- // @ts-ignorepoint_mesh.position.set(x, y, z)plane_mesh.add(point_mesh)}return plane_mesh-}-}--diff --git a/src/lib/Utilities.ts b/src/lib/Utilities.tsindex 3d1c2f9..d4a4725 100644--- a/src/lib/Utilities.ts+++ b/src/lib/Utilities.ts@@ -102,7 +102,7 @@ export class Utility {static intersection_points_between_positions_and_mesh(positions, envelope_mesh) {const vertex_positions_inside_bone_envelope: Array<Vector3> = []- const vertex_indexes_inside_bone_evelope: Array<number> = []+ const vertex_indexes_inside_bone_evelope: number[] = []const vertex_count: number = positions.array.length / 3for( let i = 0; i < vertex_count; i++)diff --git a/src/lib/solvers/BoneWeightsByDistance.ts b/src/lib/solvers/BoneWeightsByDistance.tsindex ec3aa28..2c287c1 100644--- a/src/lib/solvers/BoneWeightsByDistance.ts+++ b/src/lib/solvers/BoneWeightsByDistance.ts@@ -1,35 +1,34 @@-import { Bone, BufferGeometry, Scene, Vector3 } from 'three';-import { Utility } from '../Utilities.js';-import BoneCalculationData from '../models/BoneCalculationData.js';+import { Bone, BufferGeometry, Object3D, Scene, Vector3 } from 'three'+import { Utility } from '../Utilities.js'+import BoneCalculationData from '../models/BoneCalculationData.js'--export default class BoneWeightsByDistance+export default class BoneWeightsByDistance{- private bones_master_data: Array<BoneCalculationData> = [];- private geometry: BufferGeometry;- private show_debug: boolean = false;- private bone_idx_test: number = -1;- private debugging_scene_object: Scene;+ private bones_master_data: Array<BoneCalculationData> = []+ private geometry: BufferGeometry+ private show_debug: boolean = false+ private bone_idx_test: number = -1+ private debugging_scene_object: Scene- constructor(bone_hier)+ constructor(bone_hier: Object3D){this.init_bone_weights_data_structure(bone_hier)}- public set_debugging_scene_object(scene_object): void+ public set_debugging_scene_object(scene_object: Scene): void{- this.debugging_scene_object = scene_object;+ this.debugging_scene_object = scene_object}public set_geometry(geom: BufferGeometry): void{- this.geometry = geom;+ this.geometry = geom}private get_vertex_count(): number{if(this.geometry === null) {- return -1;+ return -1}return this.geometry.attributes.position.array.length / 3@@ -37,74 +36,70 @@ export default class BoneWeightsByDistancepublic set_show_debug(debug_value: boolean): void{- this.show_debug = debug_value;+ this.show_debug = debug_value}public set_bone_index_to_test(bone_idx: number): void{- this.bone_idx_test = bone_idx;+ this.bone_idx_test = bone_idx}- private init_bone_weights_data_structure(bone_hier): void+ private init_bone_weights_data_structure(bone_hier: Object3D): void{- const bones_list: Bone[] = Utility.bone_list_from_hierarchy(bone_hier)- bones_list.forEach( (bone) => {- const has_child_bone: boolean = bone.children.length > 0- const supports_envelope: boolean = false- const new_bone_object: BoneCalculationData =+ const bones_list: Bone[] = Utility.bone_list_from_hierarchy(bone_hier)+ bones_list.forEach((bone) => {+ const has_child_bone: boolean = bone.children.length > 0+ const supports_envelope: boolean = false+ const new_bone_object: BoneCalculationData =new BoneCalculationData(bone.name, bone, supports_envelope, has_child_bone)- this.bones_master_data.push( new_bone_object)- });+ this.bones_master_data.push(new_bone_object)+ })}public calculate_indexes_and_weights(): number[][]{- const skinIndices: Array<number> = [];- const skinWeights: Array<number> = [];+ const skinIndices: number[] = []+ const skinWeights: number[] = []// loop through each vertex and find the closest bone// then assign the closest vertices to that bone in the assigned_vertices property- for( let i = 0; i < this.get_vertex_count(); i++)+ for(let i = 0; i < this.get_vertex_count(); i++){- const vertex_position: Vector3 = new Vector3().fromBufferAttribute(this.geometry.attributes.position, i);- let closest_bone: Bone = this.bones_master_data[0].bone_object;- let closest_bone_distance: number = 10000;- let closest_bone_index: number = 0;-- this.bones_master_data.forEach( (bone, idx) => {- const distance: number = Utility.world_position_from_object(bone.bone_object).distanceTo(vertex_position);-- if(distance < closest_bone_distance)- {- closest_bone = bone.bone_object;- closest_bone_distance = distance;- closest_bone_index = idx;- }- })-- this.bones_master_data[closest_bone_index].assigned_vertices.push(i);-- // assign to final weights. closest bone is always 100% weight- skinIndices.push(closest_bone_index, 0, 0, 0);- skinWeights.push(1.0, 0, 0, 0);+ const vertex_position: Vector3 = new Vector3().fromBufferAttribute(this.geometry.attributes.position, i)+ let closest_bone: Bone = this.bones_master_data[0].bone_object+ let closest_bone_distance: number = 10000+ let closest_bone_index: number = 0++ this.bones_master_data.forEach((bone, idx) => {+ const distance: number = Utility.world_position_from_object(bone.bone_object).distanceTo(vertex_position)++ if(distance < closest_bone_distance)+ {+ closest_bone = bone.bone_object+ closest_bone_distance = distance+ closest_bone_index = idx+ }+ })++ this.bones_master_data[closest_bone_index].assigned_vertices.push(i)++ // assign to final weights. closest bone is always 100% weight+ skinIndices.push(closest_bone_index, 0, 0, 0)+ skinWeights.push(1.0, 0, 0, 0)}-+if(this.show_debug){console.log('Assigned all the bones to vertices: ', this.bones_master_data)}return [skinIndices, skinWeights]-}-- public test_bones_outside_in_mesh()+ public test_bones_outside_in_mesh(): never[][]{// don't do test for now and just return success- return [[],[]];+ const return_data = [[], []]+ return return_data}-}--diff --git a/src/lib/solvers/BoneWeightsByEnvelope.ts b/src/lib/solvers/BoneWeightsByEnvelope.tsindex 382b465..77654d0 100644--- a/src/lib/solvers/BoneWeightsByEnvelope.ts+++ b/src/lib/solvers/BoneWeightsByEnvelope.ts@@ -1,481 +1,466 @@-import { BoneEnvelopeGeometry, BoneEnvelopeGeometryUtils } from '../geometry/BoneEnvelopeGeometry.js';-import { Generators } from '../Generators.js';-import { Utility } from '../Utilities.ts';-import BoneCalculationData from '../models/BoneCalculationData.ts';-import { BufferGeometry, Scene, Bone, Object3D, Mesh, Vector3, Raycaster, Intersection } from 'three';+import { BoneEnvelopeGeometry, BoneEnvelopeGeometryUtils } from '../geometry/BoneEnvelopeGeometry.js'+import { Generators } from '../Generators.js'+import { Utility } from '../Utilities.ts'+import BoneCalculationData from '../models/BoneCalculationData.ts'+import { BufferGeometry, Scene, Bone, Object3D, Mesh, Vector3, Raycaster, Intersection } from 'three'-export class BoneWeightsByEnvelope+export class BoneWeightsByEnvelope{- private bones_master_data: Array<BoneCalculationData> = [];- private geometry: BufferGeometry;- private show_debug: boolean = false;- private bone_idx_test: number = -1;-- private debugging_scene_object: Object3D;- private debug_sphere_size = 0.06;- private debug_sphere_color_success = 0x00ff00; // vertices that are part of envelope- private debug_sphere_color_failure = 0xff0000; // vertices that will have to use closest bone-+ private bones_master_data: Array<BoneCalculationData> = []+ private geometry: BufferGeometry+ private show_debug: boolean = false+ private bone_idx_test: number = -1++ private debugging_scene_object: Object3D = new Object3D()+ private debug_sphere_size = 0.06+ private debug_sphere_color_success = 0x00ff00 // vertices that are part of envelope+ private debug_sphere_color_failure = 0xff0000 // vertices that will have to use closest bone++ // two variables used for testing to see if we have an ok bone envelope to bind+ private bone_names_with_errors: string[] = []+ private bone_vertices_with_errors: Vector3[] = []++ constructor(bone_hier: Object3D)+ {+ this.init_bone_weights_data_structure(bone_hier)+ }++ public set_geometry(geom: BufferGeometry): void+ {+ this.geometry = geom+ }++ private init_bone_weights_data_structure(bone_hier: Object3D)+ {+ const bones: Bone[] = Utility.bone_list_from_hierarchy(bone_hier)+ this.bones_master_data = []+ bones.forEach((bone) => {+ const has_child_bone: boolean = bone.children.length > 0+ const supports_envelope: boolean = is_bone_valid_for_envelope_calculation(bone)++ // 4 leg creature has entire word "right", while human has appreviation "R"+ let use_minimum_expand_distance: boolean = false+ if (bone.name === 'Right_Front_Leg_Upper' ||+ bone.name === 'Left_Front_Leg_Upper' ||+ bone.name === 'Right_Back_Leg_Upper' ||+ bone.name === 'L_Toe' ||+ bone.name === 'R_Toe' ||+ bone.name.includes('UpLeg') ||+ bone.name === 'Left_Back_Leg_Upper')+ {+ use_minimum_expand_distance = true+ }- // two variables used for testing to see if we have an ok bone envelope to bind- private bone_names_with_errors: Array<string> = [];- private bone_vertices_with_errors: Array<Vector3> = [];+ const new_bone_object: BoneCalculationData = new BoneCalculationData(bone.name, bone, supports_envelope, has_child_bone, [], use_minimum_expand_distance)++ this.bones_master_data.push(new_bone_object)+ })+ }++ public set_show_debug(debug_value: boolean): void+ {+ this.show_debug = debug_value+ }++ public set_bone_index_to_test(bone_idx: number): void+ {+ this.bone_idx_test = bone_idx+ }++ public set_debugging_scene_object(scene_object: Object3D): void+ {+ this.debugging_scene_object = scene_object+ }++ private geometry_vertex_count(): number+ {+ return this.geometry?.attributes?.position.array.length / 3+ }++ public test_bones_outside_in_mesh(): [string[], Vector3[]]+ {+ this.bones_master_data.forEach((bone: BoneCalculationData, bone_index: number) => {+ if (bone.supports_envelope_calculation)+ {+ const rays_to_cast: number = 4+ const bone_start: Bone = bone.bone_object+ const bone_end: Bone = bone.bone_object.children[0] as Bone+ const intersection_plane_mesh = Generators.create_bone_plane_mesh(bone_start, bone_end, rays_to_cast)+ const [intersection_distances] = this.intersections_for_geometry(rays_to_cast, intersection_plane_mesh)+ const envelope_mesh = this.create_envelope_mesh_for_bone(bone)+ this.expand_envelope_mesh_to_fit_bone(envelope_mesh, intersection_distances, bone)+ }+ })- constructor(bone_hier)+ // there are some errors in bone positions being outside of the mesh.+ // avoid future calculations and eventually exit out+ if (this.bone_names_with_errors.length > 0){- this.init_bone_weights_data_structure(bone_hier)+ return [this.bone_names_with_errors, this.bone_vertices_with_errors]}- public set_geometry(geom: BufferGeometry): void- {- this.geometry = geom;- }+ return [[], []]+ }- private init_bone_weights_data_structure(bone_hier)- {- const bones: Bone[] = Utility.bone_list_from_hierarchy(bone_hier)- this.bones_master_data = [];- bones.forEach( (bone) => {- const has_child_bone: boolean = bone.children.length > 0- const supports_envelope: boolean = is_bone_valid_for_envelope_calculation(bone)-- // 4 leg creature has entire word "right", while human has appreviation "R"- let use_minimum_expand_distance: boolean = false;- if(bone.name === 'Right_Front_Leg_Upper'- || bone.name === 'Left_Front_Leg_Upper'- || bone.name === 'Right_Back_Leg_Upper'- || bone.name === 'L_Toe'- || bone.name === 'R_Toe'- || bone.name.includes('UpLeg')- || bone.name === 'Left_Back_Leg_Upper' )- {- use_minimum_expand_distance = true- }-- const new_bone_object: BoneCalculationData = new BoneCalculationData(bone.name, bone, supports_envelope, has_child_bone, [], use_minimum_expand_distance)-- this.bones_master_data.push( new_bone_object)- });+ public calculate_indexes_and_weights(): number[][]+ {+ // go through each bone, build a bone envelope, see which vertices intersect it,+ // then assign it to the bone+ const vertex_points_that_passed: Vector3[] = []+ const envelope_shapes_to_show: Mesh[] = []+ this.bones_master_data.forEach((bone: BoneCalculationData, bone_index: number) => {+ if (bone.supports_envelope_calculation)+ {+ const rays_to_cast: number = 4+ const bone_start: Bone = bone.bone_object+ const bone_end: Bone = bone.bone_object.children[0] as Bone+ const intersection_plane_mesh = Generators.create_bone_plane_mesh(bone_start, bone_end, rays_to_cast)+ const [intersection_distances] = this.intersections_for_geometry(rays_to_cast, intersection_plane_mesh)+ const envelope_mesh = this.create_envelope_mesh_for_bone(bone)- }+ this.expand_envelope_mesh_to_fit_bone(envelope_mesh, intersection_distances, bone)++ const { vertex_positions_inside_bone_envelope, vertex_indexes_inside_bone_evelope } =+ Utility.intersection_points_between_positions_and_mesh(this.geometry.attributes.position, envelope_mesh)- public set_show_debug(debug_value: boolean): void+ bone.assigned_vertices.push(...vertex_indexes_inside_bone_evelope)++ // show all of these visually when we are done with checks+ vertex_points_that_passed.push(...vertex_positions_inside_bone_envelope)+ envelope_shapes_to_show.push(envelope_mesh)+ }+ })++ // display all the points that passed the bone envelope test+ if (this.show_debug){- this.show_debug = debug_value;+ const debug_assigned_points = Generators.create_spheres_for_points(vertex_points_that_passed,+ this.debug_sphere_size, this.debug_sphere_color_success, 'Vertices assigned to bone')+ this.debugging_scene_object.add(debug_assigned_points)++ envelope_shapes_to_show.forEach((envelope_mesh) => {+ this.debugging_scene_object.add(envelope_mesh)+ // this.debugging_scene_object.add(intersection_plane_mesh)+ })}- public set_bone_index_to_test(bone_idx: number): void+ // There could be some bones that aren't inside the mesh from the last calculation. This will mess up the bone envelope calculations+ // and need to be fixed. We need to abort the calculations+ if (this.bone_names_with_errors.length > 0){- this.bone_idx_test = bone_idx;+ throw new Error(`ERROR: Some bones are outside the mesh. Need to fix this. Bones: ${this.bone_names_with_errors}`)}- public set_debugging_scene_object(scene_object: Object3D): void+ if (this.show_debug){- this.debugging_scene_object = scene_object;+ console.log('Part A: Done finding vertices for bone envelopes', this.bones_master_data)}- private geometry_vertex_count(): number+ // B.+ // find out if there are any vertices that are not assigned to a bone+ // loop through the vertices without bones and find out what their position is... show that in the debugger+ const vertex_indexes_without_bones = vertices_not_assigned_to_bone(this.geometry_vertex_count(), this.bones_master_data)+ const vertex_positions_without_bones: Vector3[] = []+ vertex_indexes_without_bones.forEach((vertex_index) => {+ const vertex_position = new Vector3().fromBufferAttribute(this.geometry.attributes.position, vertex_index)+ vertex_positions_without_bones.push(vertex_position)+ })++ const debug_vertices_without_points = Generators.create_spheres_for_points(vertex_positions_without_bones,+ this.debug_sphere_size, this.debug_sphere_color_failure, 'Vertices unassigned to bone')++ this.debugging_scene_object.add(debug_vertices_without_points)++ console.log('Part B: Finding vertices that are not assigned to any bones', vertex_indexes_without_bones)++ // C. go through each vertex that has no bone and find the closest bone+ // loop through all bones and find out which one is the closest+ const closest_vertex_list: number[] = [] // vertex index linked list+ const closest_bone_list: number[] = [] // bone index linked list++ vertex_indexes_without_bones.forEach((vertex_index, idx) => {+ const closest_bone_index: number = find_closest_bone_index_from_vertex_index(vertex_index, this.geometry, this.bones_master_data)+ closest_vertex_list.push(vertex_indexes_without_bones[idx])+ closest_bone_list.push(closest_bone_index)+ })++ // combine closest vertex bone calculation results with the bone envelope results+ // the bones_vertex_list is the master list+ closest_bone_list.forEach((bone_index, iter_idx) => {+ this.bones_master_data[bone_index].assigned_vertices.push(closest_vertex_list[iter_idx])+ })++ if (this.show_debug){- return this.geometry?.attributes?.position.array.length / 3;+ const left_over_after_all_assigned = vertices_not_assigned_to_bone(this.geometry_vertex_count(), this.bones_master_data)+ console.log('Part C: Seeing if anything is leftover after assignment', left_over_after_all_assigned)}- public test_bones_outside_in_mesh(): [string[], Vector3[]]- {- this.bones_master_data.forEach( (bone: BoneCalculationData, bone_index: number) => {- if (bone.supports_envelope_calculation)- {- const rays_to_cast: number = 4;- let bone_start: Bone = bone.bone_object- let bone_end: Bone = bone.bone_object.children[0] as Bone- const intersection_plane_mesh = Generators.create_bone_plane_mesh(bone_start, bone_end, rays_to_cast)- const [intersection_distances, intersection_vertexes] = this.intersections_for_geometry(rays_to_cast, intersection_plane_mesh);- const envelope_mesh = this.create_envelope_mesh_for_bone(bone)- this.expand_envelope_mesh_to_fit_bone(envelope_mesh, intersection_distances, bone)- }- });-- // there are some errors in bone positions being outside of the mesh.- // avoid future calculations and eventually exit out- if(this.bone_names_with_errors.length > 0)- {- return [this.bone_names_with_errors, this.bone_vertices_with_errors];- }+ // D. Map all weights for each bone to the final skin indices and weights+ // that the buffer attribute needs for the skinning process+ const { final_skin_indices, final_skin_weights } = this.calculate_final_weights(this.bones_master_data, this.geometry_vertex_count())- return [[],[]];+ if (this.show_debug)+ {+ console.log('Assigned all the bones to vertices: ', this.bones_master_data)}- public calculate_indexes_and_weights()+ const final_data = [final_skin_indices, final_skin_weights]+ return final_data+ }++ private create_envelope_mesh_for_bone(bone)+ {+ const envelope_color = 0xaaaaff++ const envelope_geometry: BoneEnvelopeGeometry = new BoneEnvelopeGeometry()+ const envelope_mesh = new Mesh(envelope_geometry as BufferGeometry, Generators.create_material(true, envelope_color))+ envelope_mesh.name = `Envelope Box Mesh: ${bone.name}`+ const padding_multiplier: number = 1.2 // scale the box to help with overlap and points just outside box+ envelope_mesh.scale.set(padding_multiplier, padding_multiplier, padding_multiplier)++ const bone_start: Bone = bone.bone_object+ const bone_end: Bone = bone_start.children[0] as Bone++ // reposition/rotate cylinder to be by the bone+ // to get the right orientation of the cylinder, we need to rotateOnAxis+ // last to make it face the right direction+ const height: number = Utility.distance_between_objects(bone_start, bone_end)+ const bone_direction = Utility.direction_between_points(Utility.world_position_from_object(bone_start), Utility.world_position_from_object(bone_end))+ const facing_direction = Utility.world_position_from_object(bone_end)+ envelope_mesh.position.copy(Utility.world_position_from_object(bone_start))+ envelope_mesh.translateOnAxis(bone_direction, height*0.5)+ envelope_mesh.lookAt(facing_direction)+ envelope_mesh.rotateOnAxis(new Vector3(1,0,0), Math.PI * 0.5)++ return envelope_mesh+ }++ private expand_envelope_mesh_to_fit_bone(envelope_mesh: Mesh, intersections, bone: BoneCalculationData): void+ {+ const bone_start = bone.bone_object+ const bone_end = bone_start.children[0]++ // Grow bone envelope to fix space+ const height = Utility.distance_between_objects(bone_start, bone_end)+ const left_ray_distance: number = intersections[0]+ const back_ray_distance: number = intersections[1]+ const right_ray_distance: number = intersections[2]+ const forward_ray_distance: number = intersections[3]++ if (bone.use_minimum_envelope_expand){- // go through each bone, build a bone envelope, see which vertices intersect it,- // then assign it to the bone- const vertex_points_that_passed: Vector3[] = [];- const envelope_shapes_to_show: Mesh[] = [];-- this.bones_master_data.forEach( (bone: BoneCalculationData, bone_index: number) => {- if (bone.supports_envelope_calculation)- {- const rays_to_cast: number = 4;- let bone_start: Bone = bone.bone_object- let bone_end: Bone = bone.bone_object.children[0] as Bone- const intersection_plane_mesh = Generators.create_bone_plane_mesh(bone_start, bone_end, rays_to_cast)- const [intersection_distances, intersection_vertexes] = this.intersections_for_geometry(rays_to_cast, intersection_plane_mesh);- const envelope_mesh = this.create_envelope_mesh_for_bone(bone)-- this.expand_envelope_mesh_to_fit_bone(envelope_mesh, intersection_distances, bone)-- const { vertex_positions_inside_bone_envelope, vertex_indexes_inside_bone_evelope } =- Utility.intersection_points_between_positions_and_mesh(this.geometry.attributes.position, envelope_mesh);-- bone.assigned_vertices.push(...vertex_indexes_inside_bone_evelope)-- // show all of these visually when we are done with checks- vertex_points_that_passed.push(...vertex_positions_inside_bone_envelope)- envelope_shapes_to_show.push(envelope_mesh)- }- });--- // display all the points that passed the bone envelope test- if(this.show_debug)- {- const debug_assigned_points = Generators.create_spheres_for_points(vertex_points_that_passed,- this.debug_sphere_size, this.debug_sphere_color_success, 'Vertices assigned to bone')- this.debugging_scene_object.add(debug_assigned_points)-- envelope_shapes_to_show.forEach( (envelope_mesh) => {- this.debugging_scene_object.add(envelope_mesh)- //this.debugging_scene_object.add(intersection_plane_mesh)- });- }-- // There could be some bones that aren't inside the mesh from the last calculation. This will mess up the bone envelope calculations- // and need to be fixed. We need to abort the calculations- if(this.bone_names_with_errors.length > 0)- {- throw new Error(`ERROR: Some bones are outside the mesh. Need to fix this. Bones: ${this.bone_names_with_errors}`);- }--- if (this.show_debug)- {- console.log('Part A: Done finding vertices for bone envelopes', this.bones_master_data)- }-- // B.- // find out if there are any vertices that are not assigned to a bone- // loop through the vertices without bones and find out what their position is... show that in the debugger- const vertex_indexes_without_bones = vertices_not_assigned_to_bone(this.geometry_vertex_count(), this.bones_master_data);- const vertex_positions_without_bones: Vector3[] = [];- vertex_indexes_without_bones.forEach( (vertex_index) => {- const vertex_position = new Vector3().fromBufferAttribute(this.geometry.attributes.position, vertex_index);- vertex_positions_without_bones.push(vertex_position)- })--- const debug_vertices_without_points = Generators.create_spheres_for_points(vertex_positions_without_bones,- this.debug_sphere_size, this.debug_sphere_color_failure, 'Vertices unassigned to bone')-- if(this.debugging_scene_object)- {- this.debugging_scene_object.add(debug_vertices_without_points)- }--- console.log('Part B: Finding vertices that are not assigned to any bones', vertex_indexes_without_bones)--- // C. go through each vertex that has no bone and find the closest bone- // loop through all bones and find out which one is the closest- const closest_vertex_list: Array<number> = [] // vertex index linked list- const closest_bone_list: Array<number> = []; // bone index linked list-- vertex_indexes_without_bones.forEach( (vertex_index, idx) => {- let closest_bone_index: number = find_closest_bone_index_from_vertex_index(vertex_index, this.geometry, this.bones_master_data)- closest_vertex_list.push(vertex_indexes_without_bones[idx])- closest_bone_list.push(closest_bone_index)- })-- // combine closest vertex bone calculation results with the bone envelope results- // the bones_vertex_list is the master list- closest_bone_list.forEach( (bone_index, iter_idx) => {- this.bones_master_data[bone_index].assigned_vertices.push(closest_vertex_list[iter_idx])- })-- if (this.show_debug)- {- const left_over_after_all_assigned = vertices_not_assigned_to_bone(this.geometry_vertex_count(), this.bones_master_data);- console.log('Part C: Seeing if anything is leftover after assignment', left_over_after_all_assigned)- }--- // D. Map all weights for each bone to the final skin indices and weights- // that the buffer attribute needs for the skinning process- const { final_skin_indices, final_skin_weights } = this.calculate_final_weights(this.bones_master_data, this.geometry_vertex_count());-- if(this.show_debug)- {- console.log('Assigned all the bones to vertices: ', this.bones_master_data)- }-- return [ final_skin_indices, final_skin_weights ]+ const min_x_side = Math.min(right_ray_distance, left_ray_distance)+ const min_z_side = Math.min(forward_ray_distance, back_ray_distance)++ BoneEnvelopeGeometryUtils.expand_x_positive_face(envelope_mesh.geometry, min_x_side)+ BoneEnvelopeGeometryUtils.expand_x_negative_face(envelope_mesh.geometry, min_x_side)+ BoneEnvelopeGeometryUtils.expand_z_positive_face(envelope_mesh.geometry, min_z_side)+ BoneEnvelopeGeometryUtils.expand_z_negative_face(envelope_mesh.geometry, min_z_side)+ BoneEnvelopeGeometryUtils.expand_y_positive_face(envelope_mesh.geometry, height*0.5)+ BoneEnvelopeGeometryUtils.expand_y_negative_face(envelope_mesh.geometry, height*0.5)}-- private create_envelope_mesh_for_bone(bone)+ else{- let envelope_color = 0xaaaaff-- let envelope_geometry: BoneEnvelopeGeometry = new BoneEnvelopeGeometry()- const envelope_mesh = new Mesh(envelope_geometry as BufferGeometry, Generators.create_material(true, envelope_color));- envelope_mesh.name = `Envelope Box Mesh: ${bone.name}`- const padding_multiplier: number = 1.2 // scale the box to help with overlap and points just outside box- envelope_mesh.scale.set(padding_multiplier, padding_multiplier, padding_multiplier)-- let bone_start: Bone = bone.bone_object- let bone_end: Bone = bone_start.children[0] as Bone-- // reposition/rotate cylinder to be by the bone- // to get the right orientation of the cylinder, we need to rotateOnAxis- // last to make it face the right direction- const height: number = Utility.distance_between_objects(bone_start, bone_end);- const bone_direction = Utility.direction_between_points(Utility.world_position_from_object(bone_start), Utility.world_position_from_object(bone_end));- const facing_direction = Utility.world_position_from_object(bone_end)- envelope_mesh.position.copy(Utility.world_position_from_object(bone_start));- envelope_mesh.translateOnAxis(bone_direction, height*0.5);- envelope_mesh.lookAt(facing_direction)- envelope_mesh.rotateOnAxis(new Vector3(1,0,0), Math.PI * 0.5)-- return envelope_mesh+ BoneEnvelopeGeometryUtils.expand_x_positive_face(envelope_mesh.geometry, right_ray_distance)+ BoneEnvelopeGeometryUtils.expand_x_negative_face(envelope_mesh.geometry, left_ray_distance)+ BoneEnvelopeGeometryUtils.expand_z_positive_face(envelope_mesh.geometry, forward_ray_distance)+ BoneEnvelopeGeometryUtils.expand_z_negative_face(envelope_mesh.geometry, back_ray_distance)+ BoneEnvelopeGeometryUtils.expand_y_positive_face(envelope_mesh.geometry, height*0.5)+ BoneEnvelopeGeometryUtils.expand_y_negative_face(envelope_mesh.geometry, height*0.5)}- private expand_envelope_mesh_to_fit_bone(envelope_mesh: Mesh, intersections, bone: BoneCalculationData)+ // if a bone goes outside a mesh, the intersection will be undefined. keep track of what bones do this and+ if (left_ray_distance === undefined || right_ray_distance === undefined || back_ray_distance === undefined || forward_ray_distance === undefined){- let bone_start = bone.bone_object- let bone_end = bone_start.children[0]-- // Grow bone envelope to fix space- const height = Utility.distance_between_objects(bone_start, bone_end);- const left_ray_distance: number = intersections[0]- const back_ray_distance: number = intersections[1]- const right_ray_distance: number = intersections[2]- const forward_ray_distance: number = intersections[3]-- if(bone.use_minimum_envelope_expand)- {- const min_x_side = Math.min(right_ray_distance, left_ray_distance);- const min_z_side = Math.min(forward_ray_distance, back_ray_distance);-- BoneEnvelopeGeometryUtils.expand_x_positive_face(envelope_mesh.geometry, min_x_side)- BoneEnvelopeGeometryUtils.expand_x_negative_face(envelope_mesh.geometry, min_x_side)- BoneEnvelopeGeometryUtils.expand_z_positive_face(envelope_mesh.geometry, min_z_side)- BoneEnvelopeGeometryUtils.expand_z_negative_face(envelope_mesh.geometry, min_z_side)- BoneEnvelopeGeometryUtils.expand_y_positive_face(envelope_mesh.geometry, height*0.5)- BoneEnvelopeGeometryUtils.expand_y_negative_face(envelope_mesh.geometry, height*0.5)- }- else- {- BoneEnvelopeGeometryUtils.expand_x_positive_face(envelope_mesh.geometry, right_ray_distance)- BoneEnvelopeGeometryUtils.expand_x_negative_face(envelope_mesh.geometry, left_ray_distance)- BoneEnvelopeGeometryUtils.expand_z_positive_face(envelope_mesh.geometry, forward_ray_distance)- BoneEnvelopeGeometryUtils.expand_z_negative_face(envelope_mesh.geometry, back_ray_distance)- BoneEnvelopeGeometryUtils.expand_y_positive_face(envelope_mesh.geometry, height*0.5)- BoneEnvelopeGeometryUtils.expand_y_negative_face(envelope_mesh.geometry, height*0.5)- }---- // if a bone goes outside a mesh, the intersection will be undefined. keep track of what bones do this and- if(left_ray_distance === undefined || right_ray_distance === undefined || back_ray_distance === undefined || forward_ray_distance === undefined)- {- this.bone_names_with_errors.push(bone.name);- this.bone_vertices_with_errors.push( Utility.world_position_from_object(bone_start) )- return;- }-- // updating scene and skeleton allows to correctly calculate the bone envelope positions- envelope_mesh.geometry.computeBoundingBox(); // need to recompute for collision next+ this.bone_names_with_errors.push(bone.name)+ this.bone_vertices_with_errors.push(Utility.world_position_from_object(bone_start))+ return}- private intersections_for_geometry(rays_to_cast, debug_bone_plane_mesh) {- const intersection_distances: Array<number> = []; // ray cast around the object and find how far out the mesh goes- const intersection_vertexes: Array<Vector3> = []; // output for potentially showing in debugger- const normal_mesh: Mesh = new Mesh(this.geometry, Generators.create_material(true));- normal_mesh.name = 'Normal mesh used for intersection';- for (let j = 0; j < rays_to_cast; j++) {- const point_2: Vector3 = Utility.world_position_from_object(debug_bone_plane_mesh.children[j]);- const ray_origin: Vector3 = Utility.world_position_from_object(debug_bone_plane_mesh);- const ray_direction: Vector3 = Utility.direction_between_points(ray_origin, point_2);-- const raycaster: Raycaster = new Raycaster(ray_origin, ray_direction);- //const ray_helper = new THREE.ArrowHelper(ray_direction, ray_origin, 100, 0xffffff,1,1)- //this.debugging_scene_object.add(ray_helper)- // calculate where closest intersection happens- const intersects: Intersection[] = raycaster.intersectObject(normal_mesh);- if (intersects && intersects[0]) {- intersection_distances.push(intersects[0].distance);- intersection_vertexes.push(intersects[0].point)- }-- } // end for loop through rays- return [intersection_distances, intersection_vertexes];- }+ // updating scene and skeleton allows to correctly calculate the bone envelope positions+ envelope_mesh.geometry.computeBoundingBox() // need to recompute for collision next+ }++ private intersections_for_geometry(rays_to_cast: number, debug_bone_plane_mesh)+ {+ const intersection_distances: number[] = [] // ray cast around the object and find how far out the mesh goes+ const intersection_vertexes: Vector3[] = [] // output for potentially showing in debugger+ const normal_mesh: Mesh = new Mesh(this.geometry, Generators.create_material(true))+ normal_mesh.name = 'Normal mesh used for intersection'+ for (let j = 0; j < rays_to_cast; j++) {+ const point_2: Vector3 = Utility.world_position_from_object(debug_bone_plane_mesh.children[j])+ const ray_origin: Vector3 = Utility.world_position_from_object(debug_bone_plane_mesh)+ const ray_direction: Vector3 = Utility.direction_between_points(ray_origin, point_2)++ const raycaster: Raycaster = new Raycaster(ray_origin, ray_direction)+ // const ray_helper = new THREE.ArrowHelper(ray_direction, ray_origin, 100, 0xffffff,1,1)+ // this.debugging_scene_object.add(ray_helper)+ // calculate where closest intersection happens+ const intersects: Intersection[] = raycaster.intersectObject(normal_mesh)+ if (intersects && intersects[0]) {+ intersection_distances.push(intersects[0].distance)+ intersection_vertexes.push(intersects[0].point)+ }+ } // end for loop through rays- /**+ const return_value = [intersection_distances, intersection_vertexes]+ return return_value+ }++ /*** Three.js needs the bone indexes and weights stored as an index and weight pair* Three.js also needs 4 bones per vertex, so we need to manipulate the data to fit that shape- * @param {*} bones_master_data- * @param {*} geometry_vertex_count- * @returns+ * @param {*} bones_master_data+ * @param {*} geometry_vertex_count+ * @returns*/- private calculate_final_weights(bones_master_data, geometry_vertex_count)- {- const final_skin_indices: Array<number> = [];- const final_skin_weights: Array<number> = [];-- // some debug info variables if I want to print with them- let vertices_with_1_bone: number = 0;- let vertices_with_2_bones: number = 0;- let vertices_with_3_bones: number = 0;- let vertices_with_4_bones: number = 0;- let vertices_with_too_many_bones: number = 0;-- for (let i = 0; i < geometry_vertex_count; i++) {- // find out which bones this vertex is assigned to- const bones_for_vertex: Array<number> = [];- const weights_for_vertex: Array<number> = [];- bones_master_data.forEach((bone, bone_index) => {-- // bone includes vertex index- if (bone.assigned_vertices.includes(i)) {- bones_for_vertex.push(bone_index);- weights_for_vertex.push(1);- }- });-- // we might have 1, 2, 3, or 4 bones. Need to morph- // the results to always be an array of length 4- if (bones_for_vertex.length === 1) {- final_skin_indices.push(bones_for_vertex[0], 0, 0, 0);- final_skin_weights.push(1, 0, 0, 0);- vertices_with_1_bone++;- }- else if (bones_for_vertex.length === 2) {- final_skin_indices.push(bones_for_vertex[0], bones_for_vertex[1], 0, 0);- final_skin_weights.push(0.5, 0.5, 0.0, 0);- vertices_with_2_bones++;- }- else if (bones_for_vertex.length === 3) {- final_skin_indices.push(bones_for_vertex[0], bones_for_vertex[1], bones_for_vertex[2], 0);- final_skin_weights.push(0.6, 0.3, 0.1, 0);- vertices_with_3_bones++;- }- else if (bones_for_vertex.length === 4) {- final_skin_indices.push(...bones_for_vertex); // everything- final_skin_weights.push(0.7, 0.2, 0.05, 0.25);- vertices_with_4_bones++;- }- else if (bones_for_vertex.length > 4) {- final_skin_indices.push(bones_for_vertex[0], bones_for_vertex[1], bones_for_vertex[2], bones_for_vertex[3]);- final_skin_weights.push(0.25, 0.25, 0.25, 0.25);-- vertices_with_too_many_bones++;- console.log('ERROR: vertex is assigned to more than 4 bones. need to figure out what to do');- }+ private calculate_final_weights(bones_master_data: BoneCalculationData[], geometry_vertex_count: number)+ {+ const final_skin_indices: number[] = []+ const final_skin_weights: number[] = []++ // some debug info variables if I want to print with them+ let vertices_with_1_bone: number = 0+ let vertices_with_2_bones: number = 0+ let vertices_with_3_bones: number = 0+ let vertices_with_4_bones: number = 0+ let vertices_with_too_many_bones: number = 0++ for (let i = 0; i < geometry_vertex_count; i++) {+ // find out which bones this vertex is assigned to+ const bones_for_vertex: number[] = []+ const weights_for_vertex: number[] = []+ bones_master_data.forEach((bone, bone_index) => {+ // bone includes vertex index+ if (bone.assigned_vertices.includes(i)) {+ bones_for_vertex.push(bone_index)+ weights_for_vertex.push(1)}+ })++ // we might have 1, 2, 3, or 4 bones. Need to morph+ // the results to always be an array of length 4+ if (bones_for_vertex.length === 1) {+ final_skin_indices.push(bones_for_vertex[0], 0, 0, 0)+ final_skin_weights.push(1, 0, 0, 0)+ vertices_with_1_bone+++ }+ else if (bones_for_vertex.length === 2) {+ final_skin_indices.push(bones_for_vertex[0], bones_for_vertex[1], 0, 0)+ final_skin_weights.push(0.5, 0.5, 0.0, 0)+ vertices_with_2_bones+++ }+ else if (bones_for_vertex.length === 3) {+ final_skin_indices.push(bones_for_vertex[0], bones_for_vertex[1], bones_for_vertex[2], 0)+ final_skin_weights.push(0.6, 0.3, 0.1, 0)+ vertices_with_3_bones+++ }+ else if (bones_for_vertex.length === 4) {+ final_skin_indices.push(...bones_for_vertex) // everything+ final_skin_weights.push(0.7, 0.2, 0.05, 0.25)+ vertices_with_4_bones+++ }+ else if (bones_for_vertex.length > 4) {+ final_skin_indices.push(bones_for_vertex[0], bones_for_vertex[1], bones_for_vertex[2], bones_for_vertex[3])+ final_skin_weights.push(0.25, 0.25, 0.25, 0.25)- if (this.show_debug)- {- console.log(`Part D: Finalizing bone weights. How many bones is each vertex assigned to: 1)${vertices_with_1_bone} 2)${vertices_with_2_bones} 3)${vertices_with_3_bones}- 4)${vertices_with_4_bones} 5+)${vertices_with_too_many_bones}`)- }+ vertices_with_too_many_bones+++ console.log('ERROR: vertex is assigned to more than 4 bones. need to figure out what to do')+ }+ }- return { final_skin_indices, final_skin_weights };+ if (this.show_debug)+ {+ console.log(`Part D: Finalizing bone weights. How many bones is each vertex assigned to: 1)${vertices_with_1_bone} 2)${vertices_with_2_bones} 3)${vertices_with_3_bones}+ 4)${vertices_with_4_bones} 5+)${vertices_with_too_many_bones}`)}+ const return_value = { final_skin_indices, final_skin_weights }+ return return_value+ }} // end Class BoneWeightsByEnvelope-function is_bone_valid_for_envelope_calculation(bone: Bone): boolean{- // if our bone doesn't have any children, that means it is the final tip- // and not a bone we want to use for envelope calculations- if(bone.children.length === 0)- {- return false;- }-- // we are going to ignore certain bones for the bone as they- // have odd angles and create bad envelopes- if(- bone.name.includes('Fingers') ||+ // if our bone doesn't have any children, that means it is the final tip+ // and not a bone we want to use for envelope calculations+ if (bone.children.length === 0)+ {+ return false+ }++ // we are going to ignore certain bones for the bone as they+ // have odd angles and create bad envelopes+ if (+ bone.name.includes('Fingers') ||bone.name.includes('HandBase') ||bone.name.includes('Shoulder') ||- bone.name === 'SpineUp' )- {- return false;- }+ bone.name === 'SpineUp')+ {+ return false+ }- return true; // bone is ok to do envelope calculations+ return true // bone is ok to do envelope calculations}-function vertices_not_assigned_to_bone(geometry_vertex_count: number, bones_master_data: Array<BoneCalculationData>)+function vertices_not_assigned_to_bone(geometry_vertex_count: number, bones_master_data: BoneCalculationData[]){- const vertex_indexes_without_bones: Array<number> = [];+ const vertex_indexes_without_bones: number[] = []++ for (let i = 0; i < geometry_vertex_count; i++)+ {+ let does_vertex_exist_in_bones: boolean = false+ bones_master_data.forEach((bone) =>+ {+ if (bone.assigned_vertices.includes(i))+ {+ does_vertex_exist_in_bones = true+ }+ })- for (let i = 0; i < geometry_vertex_count; i++)+ if (!does_vertex_exist_in_bones){- let does_vertex_exist_in_bones: boolean = false;- bones_master_data.forEach((bone) =>- {- if (bone.assigned_vertices.includes(i))- {- does_vertex_exist_in_bones = true;- }- });-- if (does_vertex_exist_in_bones === false)- {- vertex_indexes_without_bones.push(i)- }+ vertex_indexes_without_bones.push(i)}+ }- return vertex_indexes_without_bones;+ return vertex_indexes_without_bones}-function find_closest_bone_index_from_vertex_index(vertex_index, geometry, bones: Array<BoneCalculationData> )+function find_closest_bone_index_from_vertex_index(vertex_index: number, geometry: BufferGeometry, bones: BoneCalculationData[]): number{- const vertex_position: Vector3 = new Vector3().fromBufferAttribute(geometry.attributes.position, vertex_index);- let closest_bone: Bone = bones[0].bone_object;- let closest_bone_distance: number = 10000;- let closest_bone_index: number = 0;+ const vertex_position: Vector3 = new Vector3().fromBufferAttribute(geometry.attributes.position, vertex_index)+ let closest_bone: Bone = bones[0].bone_object+ let closest_bone_distance: number = 10000+ let closest_bone_index: number = 0bones.forEach((bone: BoneCalculationData, idx: number) => {- let distance: number = Utility.world_position_from_object(bone.bone_object).distanceTo(vertex_position);+ let distance: number = Utility.world_position_from_object(bone.bone_object).distanceTo(vertex_position)// if bone has a child, we are going to calculate the distance by getting the half way// point between bone and child bone...to hopefully yield better resultsif (bone.has_child_bone) {- const child_bone: Bone = bone.bone_object.children[0] as Bone;- const child_bone_position: Vector3 = Utility.world_position_from_object(child_bone);- const bone_position: Vector3 = Utility.world_position_from_object(bone.bone_object);- const half_way_point: Vector3 = bone_position.add(child_bone_position).divideScalar(2);- const distance_to_half_way_point: number = half_way_point.distanceTo(vertex_position);+ const child_bone: Bone = bone.bone_object.children[0] as Bone+ const child_bone_position: Vector3 = Utility.world_position_from_object(child_bone)+ const bone_position: Vector3 = Utility.world_position_from_object(bone.bone_object)+ const half_way_point: Vector3 = bone_position.add(child_bone_position).divideScalar(2)+ const distance_to_half_way_point: number = half_way_point.distanceTo(vertex_position)if (distance_to_half_way_point < closest_bone_distance) {- distance = distance_to_half_way_point;+ distance = distance_to_half_way_point}}if (distance < closest_bone_distance) {- closest_bone = bone.bone_object;- closest_bone_distance = distance;- closest_bone_index = idx;+ closest_bone = bone.bone_object+ closest_bone_distance = distance+ closest_bone_index = idx}- });+ })- bones[closest_bone_index].assigned_vertices.push(vertex_index);- return closest_bone_index;+ bones[closest_bone_index].assigned_vertices.push(vertex_index)+ return closest_bone_index}--diff --git a/src/lib/solvers/BoneWeightsByMedianDistance.ts b/src/lib/solvers/BoneWeightsByMedianDistance.tsindex 6a08bd3..52a757d 100644--- a/src/lib/solvers/BoneWeightsByMedianDistance.ts+++ b/src/lib/solvers/BoneWeightsByMedianDistance.ts@@ -11,8 +11,8 @@ import BoneCalculationData from '../models/BoneCalculationData.js';export default class BoneWeightsByMedianDistance{private geometry: BufferGeometry;- private skinIndices: Array<number> = [];- private skinWeights: Array<number> = [];+ private skinIndices: number[] = [];+ private skinWeights: number[] = [];private show_debug: boolean = false;private bone_idx_test: number = -1;private bones_master_data: Array<BoneCalculationData> = [];diff --git a/src/script.js b/src/script.jsindex 8c99b41..1fbbbed 100644--- a/src/script.js+++ b/src/script.js@@ -1,174 +1,155 @@-import * as THREE from 'three';-import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';+import * as THREE from 'three'+import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'-import { Utility } from './lib/Utilities.ts';-import { Generators } from './lib/Generators.ts';+import { Utility } from './lib/Utilities.ts'+import { Generators } from './lib/Generators.ts'-import { TransformControls } from 'three/examples/jsm/controls/TransformControls.js';+import { TransformControls } from 'three/examples/jsm/controls/TransformControls.js'-import { UI } from './lib/UI.js';+import { UI } from './lib/UI.js'-import { StepLoadModel } from './lib/processes/StepLoadModel.js';-import { StepLoadSkeleton } from './lib/processes/StepLoadSkeleton.js';-import { StepEditSkeleton } from './lib/processes/StepEditSkeleton.js';-import { StepAnimationsListing } from './lib/processes/StepAnimationsListing.ts';-import { StepExportToFile } from './lib/processes/StepExportToFile.js';-import { StepWeightSkin } from './lib/processes/StepWeightSkin.js';+import { StepLoadModel } from './lib/processes/StepLoadModel.js'+import { StepLoadSkeleton } from './lib/processes/StepLoadSkeleton.js'+import { StepEditSkeleton } from './lib/processes/StepEditSkeleton.js'+import { StepAnimationsListing } from './lib/processes/StepAnimationsListing.ts'+import { StepExportToFile } from './lib/processes/StepExportToFile.js'+import { StepWeightSkin } from './lib/processes/StepWeightSkin.js'-import { ProcessStep } from './lib/enums/ProcessStep.js';+import { ProcessStep } from './lib/enums/ProcessStep.js'// Initialize basic sene things that are not related to the main work that is being tested-const camera = Generators.create_camera();+const camera = Generators.create_camera()-const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });-renderer.setSize(window.innerWidth, window.innerHeight);-renderer.shadowMap.enabled = true;+const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true })+renderer.setSize(window.innerWidth, window.innerHeight)+renderer.shadowMap.enabled = true-Generators.create_window_resize_listener(renderer, camera);-document.body.appendChild(renderer.domElement);+Generators.create_window_resize_listener(renderer, camera)+document.body.appendChild(renderer.domElement)// center orbit controls around mid-section area with target change-const controls = new OrbitControls(camera, renderer.domElement);-controls.target.set(0, 0.9,0);-controls.update();+const controls = new OrbitControls(camera, renderer.domElement)+controls.target.set(0, 0.9,0)+controls.update()// setup transform controls to eventually test out differnt bone rotations-let transformControls = new TransformControls(camera, renderer.domElement);-let is_transform_controls_dragging = false;+let transformControls = new TransformControls(camera, renderer.domElement)+let is_transform_controls_dragging = false// has UI elements on the HTML page that we will reference/use-let ui = new UI();-let load_model_step = new StepLoadModel()-let load_skeleton_step = new StepLoadSkeleton()-let edit_skeleton_step = new StepEditSkeleton()-let weight_skin_step = new StepWeightSkin()-let animations_listing_step = new StepAnimationsListing()-let file_export_step = new StepExportToFile()+const ui = new UI()+const load_model_step = new StepLoadModel()+const load_skeleton_step = new StepLoadSkeleton()+const edit_skeleton_step = new StepEditSkeleton()+const weight_skin_step = new StepWeightSkin()+const animations_listing_step = new StepAnimationsListing()+const file_export_step = new StepExportToFile()-const scene = new THREE.Scene();-scene.add(transformControls);+const scene = new THREE.Scene()+scene.add(transformControls)// basic things in another group, to better isolate what we are working on-const environment_container = new THREE.Group();-environment_container.name = 'Setup objects';-environment_container.add(...Generators.create_default_lights());+const environment_container = new THREE.Group()+environment_container.name = 'Setup objects'+environment_container.add(...Generators.create_default_lights())environment_container.add(...Generators.create_grid_helper())-scene.add(environment_container);-+scene.add(environment_container)const fog_near = 0const fog_far = 80const fog_color = 0x0d2525-scene.fog = new THREE.Fog(fog_color, fog_near, fog_far);+scene.fog = new THREE.Fog(fog_color, fog_near, fog_far)// for looking at specific bones-let skeleton_helper;-let debugging_visual_object = null;-let process_step = null;+let skeleton_helper+let debugging_visual_object = null+let process_step = null-let clock = new THREE.Clock();+const clock = new THREE.Clock()process_step = process_step_changed(ProcessStep.LoadModel)-function regenerate_skeleton_helper(new_skeleton, helper_name = 'Skeleton Helper')-{+function regenerate_skeleton_helper (new_skeleton, helper_name = 'Skeleton Helper') {// if skeleton helper exists...remove it- if(skeleton_helper)- {- scene.remove(skeleton_helper);+ if (skeleton_helper) {+ scene.remove(skeleton_helper)}- skeleton_helper = new THREE.SkeletonHelper(new_skeleton.bones[0]);- skeleton_helper.name = helper_name;+ skeleton_helper = new THREE.SkeletonHelper(new_skeleton.bones[0])+ skeleton_helper.name = helper_namescene.add(skeleton_helper)}-function handle_transform_controls_moving()-{- if(edit_skeleton_step.is_mirror_mode_enabled())- {+function handle_transform_controls_moving () {+ if (edit_skeleton_step.is_mirror_mode_enabled()) {const selected_bone = transformControls.objectedit_skeleton_step.apply_mirror_mode(selected_bone, transformControls.getMode())}}-function clear_info_panel_message()-{- ui.dom_info_panel.innerHTML = 'Everything ok';-}--function show_skin_failure_message(bones_with_errors)-{+function show_skin_failure_message (bones_with_errors) {// add the bone vertices as sphere to debugging objectconst sphere_failures = Generators.create_spheres_for_points(bones_with_errors, 0.02, 0xff0000)debugging_visual_object.add(sphere_failures)// add information to the info panel- ui.dom_info_panel.innerHTML = 'Some bones are outside the mesh. Fix them up and try to bind again';- ui.dom_info_panel.innerHTML += '<br>';+ ui.dom_info_panel.innerHTML = 'Some bones are outside the mesh. Fix them up and try to bind again'+ ui.dom_info_panel.innerHTML += '<br>'// display the bones names in an HTML listlet bones_error_list = '<ol id="bone-list">'bones_with_errors.forEach((bone) => {bones_error_list += `<li>${ Utility.clean_bone_name_for_messaging(bone) }</li>`- });+ })bones_error_list += '</ol>'ui.dom_info_panel.innerHTML += bones_error_list}-function test_bone_weighting_success()-{- debugging_visual_object = Utility.regenerate_debugging_scene(scene); // clear out the debugging scene+function test_bone_weighting_success () {+ debugging_visual_object = Utility.regenerate_debugging_scene(scene) // clear out the debugging sceneweight_skin_step.create_bone_formula_object(edit_skeleton_step.armature(), edit_skeleton_step.algorithm())-- if(edit_skeleton_step.show_debugging())- {- weight_skin_step.set_show_debug(edit_skeleton_step.show_debugging());- weight_skin_step.set_debug_scene_object(debugging_visual_object);- weight_skin_step.set_bone_index_to_test(-1);++ if (edit_skeleton_step.show_debugging()) {+ weight_skin_step.set_show_debug(edit_skeleton_step.show_debugging())+ weight_skin_step.set_debug_scene_object(debugging_visual_object)+ weight_skin_step.set_bone_index_to_test(-1)}// Don't do skinning operation if there are bones outside of the mesh// that messes up the bone envelope calculation- let testing_geometry_success = true;+ let testing_geometry_success = trueload_model_step.models_geometry_list().forEach((mesh_geometry, index) => {-weight_skin_step.set_mesh_geometry(mesh_geometry)const [bone_names_failing_skin_test, bone_positions_failing_skin_test] = weight_skin_step.test_geometry()- if(bone_names_failing_skin_test.length > 0)- {- let names_with_object_index = bone_names_failing_skin_test.map((bone_name) => bone_name + ` (${mesh_geometry.name})` );+ if (bone_names_failing_skin_test.length > 0) {+ let names_with_object_index = bone_names_failing_skin_test.map((bone_name) => bone_name + ` (${mesh_geometry.name})`)show_skin_failure_message(names_with_object_index)- testing_geometry_success = false;+ testing_geometry_success = false}- });+ })- if(testing_geometry_success === false)- {+ if (!testing_geometry_success) {return false}return true}-function start_skin_weighting_step()-{-+function start_skin_weighting_step () {// we only need one binding skeleton. All skinned meshes will use this.weight_skin_step.create_binding_skeleton()-+weight_skin_step.clear_skinned_meshes() // clear out any existing skinned meshes in storageload_model_step.models_geometry_list().forEach((mesh_geometry, index) => {-// we passed the bone test, so we can do the skinning processweight_skin_step.set_mesh_geometry(mesh_geometry)const [final_skin_indices, final_skin_weights] = weight_skin_step.calculate_weights()- mesh_geometry.setAttribute( 'skinIndex', new THREE.Uint16BufferAttribute( final_skin_indices, 4 ) );- mesh_geometry.setAttribute( 'skinWeight', new THREE.Float32BufferAttribute(final_skin_weights, 4 ) );+ mesh_geometry.setAttribute('skinIndex', new THREE.Uint16BufferAttribute(final_skin_indices, 4))+ mesh_geometry.setAttribute('skinWeight', new THREE.Float32BufferAttribute(final_skin_weights, 4))// create a separate skinned skeleton and helper for the binding pose// having a separate one will help us if we want to go back and edit the original skeleton@@ -176,128 +157,117 @@ function start_skin_weighting_step()weight_skin_step.create_skinned_mesh(mesh_geometry, mesh_material)scene.add(...weight_skin_step.final_skinned_meshes())- });+ })// remember our skeleton position before we do the skinning process// that way if we revert to try again...we will have the original positions/rotations- load_model_step.model_meshes().visible = false; // hide our unskinned mesh after we have done the skinning process+ load_model_step.model_meshes().visible = false // hide our unskinned mesh after we have done the skinning process// re-define skeleton helper to use the skinned mesh)regenerate_skeleton_helper(weight_skin_step.skeleton())// we might want to test out the binding algorithm to see various hitboxes// if we are doing debugging, go to that view, if no debugging, go straight to thd animation listing step- if(edit_skeleton_step.show_debugging())- {+ if (edit_skeleton_step.show_debugging()) {return}process_step_changed(ProcessStep.AnimationsListing)-}-function process_step_changed(process_step)-{+function process_step_changed (process_step) {// we will have the current step turn on the UI elements it needs- ui.hideAllElements();+ ui.hideAllElements()// clean up any event listeners from the previous stepsedit_skeleton_step.removeEventListeners()- switch(process_step)- {+ switch (process_step) {case ProcessStep.LoadModel:process_step = ProcessStep.LoadModelload_model_step.begin()ui.dom_info_panel.innerHTML = load_model_step.instructions_text()- break;+ breakcase ProcessStep.LoadSkeleton:process_step = ProcessStep.LoadSkeletonload_skeleton_step.begin()ui.dom_info_panel.innerHTML = load_skeleton_step.instructions_text()- break;+ breakcase ProcessStep.EditSkeleton:process_step = ProcessStep.EditSkeletonedit_skeleton_step.begin()- transformControls.enabled = true;- transformControls.setMode("translate");- ui.dom_transform_controls_switch.style.display = 'none'; // hide the UI control until we have a bone selected+ transformControls.enabled = true+ transformControls.setMode('translate')+ ui.dom_transform_controls_switch.style.display = 'none' // hide the UI control until we have a bone selectedui.dom_info_panel.innerHTML = edit_skeleton_step.instructions_text()- break;+ breakcase ProcessStep.BindPose:process_step = ProcessStep.BindPoseui.dom_info_panel.innerHTML = weight_skin_step.instructions_text()weight_skin_step.begin()- transformControls.enabled = false; // shouldn't be editing bones+ transformControls.enabled = false // shouldn't be editing bonesstart_skin_weighting_step()- break;+ breakcase ProcessStep.AnimationsListing:process_step = ProcessStep.AnimationsListingui.dom_info_panel.innerHTML = animations_listing_step.instructions_text()animations_listing_step.begin()- transformControls.setMode("rotate");- animations_listing_step.load_and_apply_default_animation_to_skinned_mesh(weight_skin_step.final_skinned_meshes(),- load_skeleton_step.skeleton_type() )- break;+ transformControls.setMode('rotate')+ animations_listing_step.load_and_apply_default_animation_to_skinned_mesh(weight_skin_step.final_skinned_meshes(),+ load_skeleton_step.skeleton_type())+ break}// when we change steps, we are re-creating the skeleeton and helper// so the current transform control reference will be lost/give an error- transformControls.detach();+ transformControls.detach()- return process_step;+ return process_step}const animate = () => {- requestAnimationFrame(animate);+ requestAnimationFrame(animate)- if(animations_listing_step?.mixer())- {- const deltaTime = clock.getDelta();- animations_listing_step.mixer().update(deltaTime);+ if (animations_listing_step?.mixer()) {+ const deltaTime = clock.getDelta()+ animations_listing_step.mixer().update(deltaTime)}- renderer.render(scene, camera);+ renderer.render(scene, camera)};-animate();+animate()//////////////////////////////////// EVENT LISTENERS//////////////////////////////////renderer.domElement.addEventListener('mousemove', (event) => {- if(is_transform_controls_dragging)- {+ if (is_transform_controls_dragging) {handle_transform_controls_moving()}-});+})-renderer.domElement.addEventListener('mousedown', (event) => {-+renderer.domElement.addEventListener('mousedown', (event) => {// primary click is made for rotating around 3d scene- const is_primary_button_click = event.button === 0;-- if(is_primary_button_click) { return; }- if(edit_skeleton_step.skeleton()?.bones === undefined) { return }+ const is_primary_button_click = event.button === 0++ if (is_primary_button_click) { return }+ if (edit_skeleton_step.skeleton()?.bones === undefined) { return }// when we are done with skinned mesh, we shouldn't be editing transforms- if(transformControls.enabled === false)- {+ if (!transformControls.enabled) {return}- // we will change which skeleton we do an intersection test with+ // we will change which skeleton we do an intersection test with// depending on what step we are on. We are either moving the setup skeleton// or moving the bind pose skeletonlet skeleton_to_test = null- if ( process_step === ProcessStep.EditSkeleton)- {+ if (process_step === ProcessStep.EditSkeleton) {skeleton_to_test = edit_skeleton_step.skeleton()- }- else if ( process_step === ProcessStep.AnimationsListing)- {+ } else if (process_step === ProcessStep.AnimationsListing) {skeleton_to_test = weight_skin_step.skeleton()}@@ -305,28 +275,24 @@ renderer.domElement.addEventListener('mousedown', (event) => {// only do selection if we are close// the orbit controls also have panning with alt-click, so we don't want to interfere with that- if(closestDistance > 0.1)- {- return;+ if (closestDistance > 0.1) {+ return}- if (closestBone !== null)- {- transformControls.attach(closestBone);- weight_skin_step.set_bone_index_to_test(closestBoneIndex);- ui.dom_transform_controls_switch.style.display = 'flex';+ if (closestBone !== null) {+ transformControls.attach(closestBone)+ weight_skin_step.set_bone_index_to_test(closestBoneIndex)+ ui.dom_transform_controls_switch.style.display = 'flex'}-+ }, false)- }, false);--transformControls.addEventListener('dragging-changed', function(event) {- is_transform_controls_dragging = event.value; // monitor the dragging state for transform control-});+transformControls.addEventListener('dragging-changed', function (event) {+ is_transform_controls_dragging = event.value // monitor the dragging state for transform control+})transformControls.addEventListener('dragging-changed', function (event) {- controls.enabled = !event.value;-});+ controls.enabled = !event.value+})load_model_step.addEventListener('modelLoaded', (event) => {scene.add(load_model_step.model_meshes())@@ -334,13 +300,12 @@ load_model_step.addEventListener('modelLoaded', (event) => {})load_skeleton_step.addEventListener('skeletonLoaded', (event) => {-// pass in our loaded armature to the edit skeleton for further editing// keep a reference to our initial skeleton data in case we want to revertedit_skeleton_step.set_armature(load_skeleton_step.armature())regenerate_skeleton_helper(edit_skeleton_step.skeleton())-+process_step = process_step_changed(ProcessStep.EditSkeleton)})@@ -350,68 +315,56 @@ load_skeleton_step.addEventListener('skeletonLoaded', (event) => {//////////////////////////////////ui.dom_bind_pose_button.addEventListener('click', () => {-// make sure we have a valid bone position before we try to do any weighting// this test validates that bones are inside the meshconst passed_bone_skinning_test = test_bone_weighting_success()- if(passed_bone_skinning_test)- {+ if (passed_bone_skinning_test) {process_step_changed(ProcessStep.BindPose)- }--});+ }+})ui.dom_back_to_edit_skeleton_button.addEventListener('click', () => {-// clear existing skinned mesh if it exists- const existing_skinned_meshes = scene.children.filter((child) => child.name === 'Skinned Mesh');-+ const existing_skinned_meshes = scene.children.filter((child) => child.name === 'Skinned Mesh')+existing_skinned_meshes.forEach((existing_skinned_mesh) => {- Utility.remove_object_with_children(existing_skinned_mesh);+ Utility.remove_object_with_children(existing_skinned_mesh)})-- debugging_visual_object = Utility.regenerate_debugging_scene(scene); // clear out the debugging scene++ debugging_visual_object = Utility.regenerate_debugging_scene(scene) // clear out the debugging sceneprocess_step = process_step_changed(ProcessStep.EditSkeleton)regenerate_skeleton_helper(edit_skeleton_step.skeleton())- load_model_step.model_meshes().visible = true; // show the unskinned mesh again+ load_model_step.model_meshes().visible = true // show the unskinned mesh again+})-});+ui.dom_transform_controls_switch.addEventListener('click', function (event) {+ const targetElement = event.target-ui.dom_transform_controls_switch.addEventListener('click', function(event)-{- const targetElement = event.target;-- if(targetElement.value === undefined)- {- return; // half of events for this are returning null for some reason+ if (targetElement.value === undefined) {+ return // half of events for this are returning null for some reason}- if(targetElement.value === 'translation')- {- transformControls.setMode("translate");+ if (targetElement.value === 'translation') {+ transformControls.setMode('translate')+ } else if (targetElement.value === 'rotation') {+ transformControls.setMode('rotate')}- else if(targetElement.value === 'rotation')- {- transformControls.setMode("rotate");- }--});+})// this is mostly useful after we bind the mesh so we can just see the final meshui.dom_show_skeleton_checkbox.addEventListener('click', (event) => {- skeleton_helper.visible = event.target.checked;-});+ skeleton_helper.visible = event.target.checked+})ui.dom_export_button.addEventListener('click', () => {-const all_clips = animations_listing_step.animation_clips()file_export_step.set_animation_clips_to_export(all_clips)- file_export_step.export(weight_skin_step.final_skinned_meshes(), 'exported-model');-});+ file_export_step.export(weight_skin_step.final_skinned_meshes(), 'exported-model')+})ui.dom_rotate_model_x_button.addEventListener('click', () => {load_model_step.rotate_model_by_axis('x', 90)