Skip to content

Import a 3D Model and automatically assign and export animations

TypeScript

Turn script file into typescript

Scott Petrovicc291cab99b37
diff --git a/src/index.html b/src/index.html
index e675e22..ea729cf 100644
--- a/src/index.html
+++ b/src/index.html
@@ -6,7 +6,7 @@
<title style="display: none">Model Motionizer</title>
</head>
<body style="margin: 0">
- <script type="module" src="./script.js"></script>
+ <script type="module" src="./script.ts"></script>
<link href="./styles.css" rel="stylesheet" crossorigin="anonymous" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0" />
diff --git a/src/lib/Utilities.ts b/src/lib/Utilities.ts
index d4a4725..07689f8 100644
--- a/src/lib/Utilities.ts
+++ b/src/lib/Utilities.ts
@@ -1,8 +1,12 @@
-import { Vector3, Vector2, Object3D, Mesh, Group, Bone, Skeleton, Euler, Raycaster} from 'three'
+import {
+ Vector3, Vector2, type Object3D, Mesh, Group, Bone, type Skeleton, Euler, Raycaster,
+ type PerspectiveCamera, type Scene, type Object3DEventMap, type BufferAttribute
+} from 'three'
import BoneTransformState from './models/BoneTransformState'
+// eslint-disable-next-line @typescript-eslint/no-extraneous-class
export class Utility {
- static distance_between_objects(
+ static distance_between_objects (
object_1: Object3D,
object_2: Object3D
): number {
@@ -21,32 +25,37 @@ export class Utility {
* @param {*} object
* @returns local position for object in a Vector3 object
*/
- static world_position_from_object(object: Object3D): Vector3 {
+ static world_position_from_object (object: Object3D): Vector3 {
const position: Vector3 = new Vector3()
return object.getWorldPosition(position)
}
- static direction_between_points(point_1: Vector3, point_2: Vector3): Vector3 {
- let direction: Vector3 = new Vector3()
+ static direction_between_points (point_1: Vector3, point_2: Vector3): Vector3 {
+ const direction: Vector3 = new Vector3()
direction.subVectors(point_2, point_1).normalize()
return direction
}
- static is_point_in_box(point: Vector3, box_mesh: Mesh): boolean {
- //Transform the point from world space into the objects space
+ static is_point_in_box (point: Vector3, box_mesh: Mesh): boolean {
+ if (box_mesh.geometry.boundingBox === null) {
+ console.warn('is_point_in_box() - box_mesh does not have a bounding box')
+ return false
+ }
+
+ // Transform the point from world space into the objects space
box_mesh.updateMatrixWorld()
- let localPt: Vector3 = box_mesh.worldToLocal(point.clone())
- return box_mesh.geometry.boundingBox.containsPoint(localPt)
+ const local_point: Vector3 = box_mesh.worldToLocal(point.clone())
+ return box_mesh.geometry.boundingBox.containsPoint(local_point)
}
- static remove_object_array(obj: Object3D): void {
+ static remove_object_array (obj: Object3D): void {
obj.traverse((child: any) => {
if (child instanceof Mesh) {
child.geometry.dispose()
for (const key in child.material) {
const value = child.material[key]
- if (value && typeof value.dispose === "function") {
+ if (value && typeof value.dispose === 'function') {
value.dispose()
}
}
@@ -56,7 +65,7 @@ export class Utility {
})
}
- static remove_object_with_children(obj: Object3D): void {
+ static remove_object_with_children (obj: Object3D): void {
if (obj.children.length > 0) {
obj.children.forEach((child) => {
this.remove_object_with_children(child)
@@ -64,11 +73,11 @@ export class Utility {
}
if (obj instanceof Mesh) {
- if (obj.geometry) {
+ if (obj.geometry !== null) {
obj.geometry.dispose()
}
- if (obj.material) {
+ if (obj.material !== undefined) {
if (obj.material.map) {
obj.material.map.dispose()
}
@@ -77,14 +86,14 @@ export class Utility {
}
}
- if (obj.parent) {
+ if (obj.parent != null) {
obj.parent.remove(obj)
}
obj.removeFromParent()
}
- static bone_list_from_hierarchy(bone_hierarchy: Object3D): Bone[] {
+ static bone_list_from_hierarchy (bone_hierarchy: Object3D): Bone[] {
if (bone_hierarchy === undefined || bone_hierarchy === null) {
throw new Error(
'bone_list_from_hierarchy() - bone_hierarchy parameter is undefined or null'
@@ -100,18 +109,16 @@ export class Utility {
return bone_list
}
- static intersection_points_between_positions_and_mesh(positions, envelope_mesh) {
- const vertex_positions_inside_bone_envelope: Array<Vector3> = []
+ static intersection_points_between_positions_and_mesh (positions: BufferAttribute, envelope_mesh: Mesh) {
+ const vertex_positions_inside_bone_envelope: Vector3[] = []
const vertex_indexes_inside_bone_evelope: number[] = []
const vertex_count: number = positions.array.length / 3
- for( let i = 0; i < vertex_count; i++)
- {
+ for (let i = 0; i < vertex_count; i++) {
const vertex_position: Vector3 = new Vector3().fromBufferAttribute(positions, i)
const is_intersecting: boolean = Utility.is_point_in_box(vertex_position, envelope_mesh)
- if(is_intersecting)
- {
+ if (is_intersecting) {
vertex_positions_inside_bone_envelope.push(vertex_position)
vertex_indexes_inside_bone_evelope.push(i)
}
@@ -127,8 +134,8 @@ export class Utility {
* @param {*} mouse_event
* @returns x and y coordinates normalized between -1 and 1
*/
- static normalized_mouse_position(mouse_event): Vector2 {
- let mouse: Vector2 = new Vector2()
+ static normalized_mouse_position (mouse_event: MouseEvent): Vector2 {
+ const mouse: Vector2 = new Vector2()
mouse.x = (mouse_event.clientX / window.innerWidth) * 2 - 1
mouse.y = -(mouse_event.clientY / window.innerHeight) * 2 + 1
return mouse
@@ -140,17 +147,19 @@ export class Utility {
* @param {*} scene
* @returns
*/
- static regenerate_debugging_scene(scene): Group {
- const debugging_object_name: string = "Skinning Debug Container"
+ static regenerate_debugging_scene (scene: Scene): Group {
+ const debugging_object_name: string = 'Skinning Debug Container'
// clear out debugging container if it exists
- const existing_debugging_container: Object3D = scene.getObjectByName(
+ const existing_debugging_container: Object3D<Object3DEventMap> | undefined = scene.getObjectByName(
debugging_object_name
)
- if (existing_debugging_container) {
+ if (existing_debugging_container !== undefined) {
this.remove_object_array(existing_debugging_container)
existing_debugging_container.clear()
scene.remove(existing_debugging_container)
+ } else {
+ console.warn('regenerate_debugging_scene() error - debugging container does not exist')
}
// add a reusable container for debugging
@@ -160,13 +169,15 @@ export class Utility {
return debugging_scene_object
}
- static store_bone_transforms(skeleton: Skeleton): Array<BoneTransformState> {
- const bone_transforms: Array<BoneTransformState> = []
+ static store_bone_transforms (skeleton: Skeleton): BoneTransformState[] {
+ const bone_transforms: BoneTransformState[] = []
skeleton.bones.forEach((bone) => {
+ const new_rotation: Vector3 = new Vector3().setFromEuler(bone.rotation)
+
const new_transform_state = new BoneTransformState(
bone.name,
bone.position.clone(),
- bone.rotation.clone(),
+ new_rotation,
bone.scale.clone()
)
bone_transforms.push(new_transform_state)
@@ -175,10 +186,10 @@ export class Utility {
return bone_transforms
}
- static restore_bone_transforms(
+ static restore_bone_transforms (
skeleton: Skeleton,
- original_bone_transforms: Array<BoneTransformState>
- ) {
+ original_bone_transforms: BoneTransformState[]
+ ): void {
original_bone_transforms.forEach((bone_transform) => {
const bone: Bone | null =
skeleton.bones.find((bone) => bone.name === bone_transform.name) ??
@@ -186,7 +197,7 @@ export class Utility {
if (bone !== null) {
bone.position.copy(bone_transform.position)
- let euler = new Euler()
+ const euler: Euler = new Euler()
euler.setFromVector3(bone_transform.rotation)
bone.rotation.copy(euler)
bone.scale.copy(bone_transform.scale)
@@ -194,51 +205,46 @@ export class Utility {
})
}
- static calculate_bone_base_name(bone_name) {
+ static calculate_bone_base_name (bone_name: string): string {
return bone_name
- .replace("mixamorig_", "")
- .replace(/(Right|Right_|R_|_Right|_R|Left|Left_|_Left|L_)/g, "")
+ .replace('mixamorig_', '')
+ .replace(/(Right|Right_|R_|_Right|_R|Left|Left_|_Left|L_)/g, '')
}
- static raycast_closest_bone_test(camera, mouse_event, skeleton)
- {
+ static raycast_closest_bone_test (camera: PerspectiveCamera, mouse_event: MouseEvent, skeleton: Skeleton): Array<number | null> {
// Find the closest bone for raycaster. Select that
- let raycaster = new Raycaster()
+ const raycaster: Raycaster = new Raycaster()
raycaster.setFromCamera(Utility.normalized_mouse_position(mouse_event), camera)
- let closestBone = null
- let closestBoneIndex = 0
- let closestDistance = Infinity
-
+ let closest_bone = null
+ let closest_bone_index = 0
+ let closest_distance = Infinity
+
skeleton.bones.forEach((bone, bone_index) => {
- let worldPosition = Utility.world_position_from_object(bone)
- let target = new Vector3()
- let point = raycaster.ray.closestPointToPoint(worldPosition, target)
- let distance = point.distanceTo(worldPosition)
-
- if (distance < closestDistance) {
- closestBone = bone
- closestDistance = distance
- closestBoneIndex = bone_index
+ const world_position = Utility.world_position_from_object(bone)
+ const target = new Vector3()
+ const point = raycaster.ray.closestPointToPoint(world_position, target)
+ const distance = point.distanceTo(world_position)
+
+ if (distance < closest_distance) {
+ closest_bone = bone
+ closest_distance = distance
+ closest_bone_index = bone_index
}
})
-
- return [closestBone, closestBoneIndex, closestDistance]
+
+ const output = [closest_bone, closest_bone_index, closest_distance]
+ return output
}
- static scale_armature_by_scalar(armature, scalar)
- {
+ static scale_armature_by_scalar (armature: Object3D, scalar: number): void {
armature.traverse((bone) => {
- if(bone.type === 'Bone')
- {
+ if (bone.type === 'Bone') {
bone.position.multiplyScalar(scalar)
}
})
-
}
- static clean_bone_name_for_messaging(bone_name: string): string
- {
+ static clean_bone_name_for_messaging (bone_name: string): string {
return bone_name.replace('mixamorig_', '')
}
-
}
diff --git a/src/lib/processes/StepWeightSkin.ts b/src/lib/processes/StepWeightSkin.ts
index 5c5bcbd..176659f 100644
--- a/src/lib/processes/StepWeightSkin.ts
+++ b/src/lib/processes/StepWeightSkin.ts
@@ -8,27 +8,34 @@ import { SkinningFormula } from '../enums/SkinningFormula.ts'
import { Generators } from '../Generators.ts'
-import { type BufferGeometry, type Material, type Object3D, type Skeleton, SkinnedMesh } from 'three'
+import { type BufferGeometry, type Material, type Object3D, type Skeleton, SkinnedMesh, type Scene } from 'three'
// Note: EventTarget is a built-ininterface and do not need to import it
-export class StepWeightSkin extends EventTarget
-{
+export class StepWeightSkin extends EventTarget {
private readonly ui: UI = new UI()
- skinning_armature: Object3D | undefined
- bone_skinning_formula = null
- binding_skeleton: Skeleton | undefined
- skinned_meshes: SkinnedMesh[] = []
+ private skinning_armature: Object3D | undefined
+ private bone_skinning_formula = null
+ private binding_skeleton: Skeleton | undefined
+ private skinned_meshes: SkinnedMesh[] = []
// debug options for bone skinning formula
- enable_debugging = false
- show_debug = false
- debug_scene_object = null
- bone_index_to_test = -1
+ private enable_debugging: boolean = false
+ private show_debug: boolean = false
+ private debug_scene_object: Scene | undefined
+ private bone_index_to_test: number = -1
public begin (): void {
- this.ui.dom_current_step_index.innerHTML = '3.5'
- this.ui.dom_current_step_element.innerHTML = 'Skin Debug'
- this.ui.dom_skinned_mesh_tools.style.display = 'flex'
+ if (this.ui.dom_current_step_index !== null) {
+ this.ui.dom_current_step_index.innerHTML = '3.5'
+ }
+
+ if (this.ui.dom_current_step_element !== null) {
+ this.ui.dom_current_step_element.innerHTML = 'Skin Debug'
+ }
+
+ if (this.ui.dom_skinned_mesh_tools !== null) {
+ this.ui.dom_skinned_mesh_tools.style.display = 'flex'
+ }
}
public instructions_text (): string {
@@ -41,7 +48,7 @@ export class StepWeightSkin extends EventTarget
</ol>`
}
- public create_bone_formula_object(editable_armature: Object3D, skinning_formula: string): any {
+ public create_bone_formula_object (editable_armature: Object3D, skinning_formula: string): any {
this.skinning_armature = editable_armature.clone()
this.skinning_armature.name = 'Armature for skinning'
@@ -57,18 +64,16 @@ export class StepWeightSkin extends EventTarget
return this.bone_skinning_formula
}
- public skeleton (): Skeleton | undefined
- {
+ public skeleton (): Skeleton | undefined {
// gets bone hierarchy from the armature
return this.binding_skeleton
}
- public set_mesh_geometry(geometry: BufferGeometry): void
- {
+ public set_mesh_geometry (geometry: BufferGeometry): void {
this.bone_skinning_formula.set_geometry(geometry)
}
- public test_geometry() {
+ public test_geometry () {
if (this.show_debug) {
this.bone_skinning_formula.set_show_debug(this.show_debug)
this.bone_skinning_formula.set_debugging_scene_object(this.debug_scene_object)
@@ -78,7 +83,7 @@ export class StepWeightSkin extends EventTarget
return this.bone_skinning_formula.test_bones_outside_in_mesh()
}
- public create_binding_skeleton(): void {
+ public create_binding_skeleton (): void {
if (this.skinning_armature !== undefined) {
// when we copy over the armature with the bind, we will lose the reference in the variable
this.binding_skeleton = Generators.create_skeleton(this.skinning_armature.children[0])
@@ -88,8 +93,7 @@ export class StepWeightSkin extends EventTarget
}
}
- public clear_skinned_meshes(): void
- {
+ public clear_skinned_meshes (): void {
this.skinned_meshes = []
}
@@ -112,24 +116,28 @@ export class StepWeightSkin extends EventTarget
this.skinned_meshes.push(skinned_mesh)
}
- public final_skinned_meshes(): SkinnedMesh[] {
+ public final_skinned_meshes (): SkinnedMesh[] {
return this.skinned_meshes
}
- public set_show_debug(value: boolean): void
- {
+ public set_show_debug (value: boolean): void {
this.show_debug = value
}
- public set_debug_scene_object(scene): void {
+ public set_debug_scene_object (scene: Scene): void {
this.debug_scene_object = scene
}
- public set_bone_index_to_test(index): void {
+ public set_bone_index_to_test (index: number): void {
this.bone_index_to_test = index
}
- public calculate_weights() {
+ public calculate_weights (): void {
+ if (this.bone_skinning_formula === null) {
+ console.warn('Tried to calculate_weights() but bone_skinning_formula is null!')
+ return
+ }
+
return this.bone_skinning_formula.calculate_indexes_and_weights()
}
}
diff --git a/src/lib/solvers/BoneWeightsByMedianDistance.ts b/src/lib/solvers/BoneWeightsByMedianDistance.ts
index 52a757d..063cf46 100644
--- a/src/lib/solvers/BoneWeightsByMedianDistance.ts
+++ b/src/lib/solvers/BoneWeightsByMedianDistance.ts
@@ -1,135 +1,117 @@
-import { Utility } from '../Utilities.js';
-import { Bone, BufferGeometry, Scene, Vector3 } from 'three';
-import BoneCalculationData from '../models/BoneCalculationData.js';
-
+import { Utility } from '../Utilities.js'
+import { type Bone, BufferGeometry, type Object3D, type Scene, Vector3 } from 'three'
+import BoneCalculationData from '../models/BoneCalculationData.js'
/**
- * This calculation is similar to the normal bone weights by distance, but uses the
+ * This calculation is similar to the normal bone weights by distance, but uses the
* location half way between the bone and the child's bone. This gives better results with the joints
* If there is no child bone, it just uses the bone's position for the distance calculation
*/
-export default class BoneWeightsByMedianDistance
-{
- private geometry: BufferGeometry;
- private skinIndices: number[] = [];
- private skinWeights: number[] = [];
- private show_debug: boolean = false;
- private bone_idx_test: number = -1;
- private bones_master_data: Array<BoneCalculationData> = [];
- private debugging_scene_object: Scene;
-
- constructor(bone_hier)
- {
+export default class BoneWeightsByMedianDistance {
+ private geometry: BufferGeometry = new BufferGeometry()
+ private readonly skin_indices: number[] = []
+ private readonly skin_weights: number[] = []
+ private show_debug: boolean = false
+ private bone_idx_test: number = -1
+ private readonly bones_master_data: BoneCalculationData[] = []
+ private debugging_scene_object: Scene
+
+ constructor (bone_hier: Object3D) {
this.init_bone_weights_data_structure(bone_hier)
}
- private get_vertex_count()
- {
- if(this.geometry === null) {
- return -1;
+ private get_vertex_count (): number {
+ if (this.geometry === null) {
+ return -1
}
return this.geometry.attributes.position.array.length / 3
}
- public set_show_debug(debug_value)
- {
- this.show_debug = debug_value;
+ public set_show_debug (debug_value: boolean): void {
+ this.show_debug = debug_value
}
- public set_bone_index_to_test(bone_idx)
- {
- this.bone_idx_test = bone_idx;
+ public set_bone_index_to_test (bone_idx: number): void {
+ this.bone_idx_test = bone_idx
}
- public set_debugging_scene_object(scene_object)
- {
- this.debugging_scene_object = scene_object;
+ public set_debugging_scene_object (scene_object: Scene): void {
+ this.debugging_scene_object = scene_object
}
- public set_geometry(geom: BufferGeometry): void
- {
- this.geometry = geom;
+ public set_geometry (geom: BufferGeometry): void {
+ this.geometry = geom
}
-
- private init_bone_weights_data_structure(bone_hier)
- {
- const bones_list = Utility.bone_list_from_hierarchy(bone_hier)
- bones_list.forEach( (bone) => {
+ private init_bone_weights_data_structure (bone_hier: Object3D): void {
+ const bones_list = Utility.bone_list_from_hierarchy(bone_hier)
+ bones_list.forEach((bone) => {
const has_child_bone = bone.children.length > 0
const supports_envelope = false
const new_bone_object = 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()
- {
+ public calculate_indexes_and_weights (): 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++)
- {
- let closest_bone_index: number =
+ for (let i = 0; i < this.get_vertex_count(); i++) {
+ const closest_bone_index: number =
this.find_closest_bone_index_from_vertex_index(i, this.geometry, this.bones_master_data)
- // assign to final weights. closest bone is always 100% weight
- this.skinIndices.push(closest_bone_index, 0, 0, 0);
- this.skinWeights.push(1.0, 0, 0, 0);
+ // assign to final weights. closest bone is always 100% weight
+ this.skin_indices.push(closest_bone_index, 0, 0, 0)
+ this.skin_weights.push(1.0, 0, 0, 0)
}
-
- if(this.show_debug)
- {
+
+ if (this.show_debug) {
console.log('Assigned all the bones to vertices: ', this.bones_master_data)
}
- return [this.skinIndices, this.skinWeights]
+ const output = [this.skin_indices, this.skin_weights]
+ return output
}
- private find_closest_bone_index_from_vertex_index(vertex_index: number,
- geometry: BufferGeometry, bones: Array<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;
+ private 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
bones.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 results
if (bone.has_child_bone) {
- const child_bone: Bone = bone.bone_object.children[0];
- 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
}
- 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 output = [[], []]
+ return output
}
-
-
} // end class
-
-
-
diff --git a/src/script.js b/src/script.ts
similarity index 81%
rename from src/script.js
rename to src/script.ts
index f1542d7..d1ba58d 100644
--- a/src/script.js
+++ b/src/script.ts
@@ -16,6 +16,7 @@ import { StepExportToFile } from './lib/processes/StepExportToFile.ts'
import { StepWeightSkin } from './lib/processes/StepWeightSkin.ts'
import { ProcessStep } from './lib/enums/ProcessStep.ts'
+import { type Bone, Group, Scene, type Skeleton, type Vector3, type SkeletonHelper, type Points } from 'three'
// Initialize basic sene things that are not related to the main work that is being tested
const camera = Generators.create_camera()
@@ -29,11 +30,11 @@ 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.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)
+const transform_controls = new TransformControls(camera, renderer.domElement)
let is_transform_controls_dragging = false
// has UI elements on the HTML page that we will reference/use
@@ -45,11 +46,11 @@ 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: Scene = new Scene()
+scene.add(transform_controls)
// basic things in another group, to better isolate what we are working on
-const environment_container = new THREE.Group()
+const environment_container: Group = new Group()
environment_container.name = 'Setup objects'
environment_container.add(...Generators.create_default_lights())
environment_container.add(...Generators.create_grid_helper())
@@ -61,17 +62,17 @@ const fog_color = 0x0d2525
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: SkeletonHelper
+let debugging_visual_object: Group = new Group()
+let process_step: ProcessStep = ProcessStep.LoadModel
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: Skeleton, helper_name = 'Skeleton Helper'): void {
// if skeleton helper exists...remove it
- if (skeleton_helper) {
+ if (skeleton_helper !== undefined) {
scene.remove(skeleton_helper)
}
@@ -80,33 +81,38 @@ function regenerate_skeleton_helper (new_skeleton, helper_name = 'Skeleton Helpe
scene.add(skeleton_helper)
}
-function handle_transform_controls_moving () {
+function handle_transform_controls_moving (): void {
if (edit_skeleton_step.is_mirror_mode_enabled()) {
- const selected_bone = transformControls.object
- edit_skeleton_step.apply_mirror_mode(selected_bone, transformControls.getMode())
+ const selected_bone: Bone = transform_controls.object as Bone
+ edit_skeleton_step.apply_mirror_mode(selected_bone, transform_controls.getMode())
}
}
-function show_skin_failure_message (bones_with_errors) {
+function show_skin_failure_message (bones_with_errors: Vector3[]): void {
// add the bone vertices as sphere to debugging object
- const sphere_failures = Generators.create_spheres_for_points(bones_with_errors, 0.02, 0xff0000)
+ const sphere_failures: Points = Generators.create_spheres_for_points(bones_with_errors, 0.02, 0xff0000)
debugging_visual_object.add(sphere_failures)
// add information to the info panel
+ if (ui.dom_info_panel === null) {
+ console.warn('There was a skin failure, but the UI Info panel DOM element is not set to show the message.')
+ return
+ }
+
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 list
let 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 += `<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 () {
+function test_bone_weighting_success (): boolean {
debugging_visual_object = Utility.regenerate_debugging_scene(scene) // clear out the debugging scene
weight_skin_step.create_bone_formula_object(edit_skeleton_step.armature(), edit_skeleton_step.algorithm())
@@ -122,10 +128,10 @@ function test_bone_weighting_success () {
let testing_geometry_success = true
load_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()
+ const [bone_names_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})`)
+ const 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
}
@@ -138,7 +144,7 @@ function test_bone_weighting_success () {
return true
}
-function start_skin_weighting_step () {
+function start_skin_weighting_step (): void {
// we only need one binding skeleton. All skinned meshes will use this.
weight_skin_step.create_binding_skeleton()
@@ -161,9 +167,15 @@ function start_skin_weighting_step () {
// 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)
+ if (weight_skin_step.skeleton() === undefined) {
+ console.warn('Tried to regenerate skeleton helper, but skeleton is undefined!')
+ return
+ }
+
+ // not sure why typescript linter cannot figure out that the skeleton is defined here as I did a check above
regenerate_skeleton_helper(weight_skin_step.skeleton())
// we might want to test out the binding algorithm to see various hitboxes
@@ -175,7 +187,7 @@ function start_skin_weighting_step () {
process_step_changed(ProcessStep.AnimationsListing)
}
-function process_step_changed (process_step) {
+function process_step_changed (process_step: ProcessStep): ProcessStep {
// we will have the current step turn on the UI elements it needs
ui.hide_all_elements()
@@ -196,8 +208,8 @@ function process_step_changed (process_step) {
case ProcessStep.EditSkeleton:
process_step = ProcessStep.EditSkeleton
edit_skeleton_step.begin()
- transformControls.enabled = true
- transformControls.setMode('translate')
+ transform_controls.enabled = true
+ transform_controls.setMode('translate')
ui.dom_transform_controls_switch.style.display = 'none' // hide the UI control until we have a bone selected
ui.dom_info_panel.innerHTML = edit_skeleton_step.instructions_text()
break
@@ -205,14 +217,14 @@ function process_step_changed (process_step) {
process_step = ProcessStep.BindPose
ui.dom_info_panel.innerHTML = weight_skin_step.instructions_text()
weight_skin_step.begin()
- transformControls.enabled = false // shouldn't be editing bones
+ transform_controls.enabled = false // shouldn't be editing bones
start_skin_weighting_step()
break
case ProcessStep.AnimationsListing:
process_step = ProcessStep.AnimationsListing
ui.dom_info_panel.innerHTML = animations_listing_step.instructions_text()
animations_listing_step.begin()
- transformControls.setMode('rotate')
+ transform_controls.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
@@ -220,26 +232,24 @@ function process_step_changed (process_step) {
// 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()
+ transform_controls.detach()
return process_step
}
-const animate = () => {
+const animate = (): void => {
requestAnimationFrame(animate)
- if (animations_listing_step?.mixer()) {
- const deltaTime = clock.getDelta()
- animations_listing_step.mixer().update(deltaTime)
- }
+ const delta_time = clock.getDelta()
+ animations_listing_step.mixer().update(delta_time)
renderer.render(scene, camera)
-};
+}
animate()
-//////////////////////////////////
-// EVENT LISTENERS
-//////////////////////////////////
+/**
+* EVENT LISTENERS
+ */
renderer.domElement.addEventListener('mousemove', (event) => {
if (is_transform_controls_dragging) {
@@ -251,16 +261,14 @@ 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 (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) {
+ if (!transform_controls.enabled) {
return
}
-
// 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 skeleton
@@ -280,17 +288,17 @@ renderer.domElement.addEventListener('mousedown', (event) => {
}
if (closestBone !== null) {
- transformControls.attach(closestBone)
+ transform_controls.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) {
+transform_controls.addEventListener('dragging-changed', function (event) {
is_transform_controls_dragging = event.value // monitor the dragging state for transform control
})
-transformControls.addEventListener('dragging-changed', function (event) {
+transform_controls.addEventListener('dragging-changed', function (event) {
controls.enabled = !event.value
})
@@ -309,10 +317,9 @@ load_skeleton_step.addEventListener('skeletonLoaded', (event) => {
process_step = process_step_changed(ProcessStep.EditSkeleton)
})
-
-//////////////////////////////////
+/// ///////////////////////////////
// EVENT LISTENERS FOR UI ELEMENTS
-//////////////////////////////////
+/// ///////////////////////////////
ui.dom_bind_pose_button.addEventListener('click', () => {
// make sure we have a valid bone position before we try to do any weighting
@@ -340,7 +347,6 @@ ui.dom_back_to_edit_skeleton_button.addEventListener('click', () => {
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
@@ -349,9 +355,9 @@ ui.dom_transform_controls_switch.addEventListener('click', function (event) {
}
if (targetElement.value === 'translation') {
- transformControls.setMode('translate')
+ transform_controls.setMode('translate')
} else if (targetElement.value === 'rotation') {
- transformControls.setMode('rotate')
+ transform_controls.setMode('rotate')
}
})
@@ -374,7 +380,6 @@ ui.dom_rotate_model_y_button.addEventListener('click', () => {
load_model_step.rotate_model_by_axis('y', 90)
})
-
ui.dom_rotate_model_z_button.addEventListener('click', () => {
load_model_step.rotate_model_by_axis('z', 90)
-})
\ No newline at end of file
+})