Skip to content

Import a 3D Model and automatically assign and export animations

TypeScript

Show bones as octohedral. Color them with bone classification

Scott Petrovic20d10764b8bf
diff --git a/src/Mesh2MotionEngine.ts b/src/Mesh2MotionEngine.ts
index f28c385..5272b9d 100644
--- a/src/Mesh2MotionEngine.ts
+++ b/src/Mesh2MotionEngine.ts
@@ -72,7 +72,7 @@ export class Mesh2MotionEngine {
public debugging_visual_object: Group = new Group()
// when editing the skeleton, what type of mesh will we see
- public mesh_preview_display_type: ModelPreviewDisplay = ModelPreviewDisplay.WeightPainted
+ public mesh_preview_display_type: ModelPreviewDisplay = ModelPreviewDisplay.Textured
public transform_controls_type: TransformControlType = TransformControlType.Translation
public transform_space_type: TransformSpace = TransformSpace.Global
@@ -196,12 +196,11 @@ export class Mesh2MotionEngine {
public regenerate_skeleton_helper (new_skeleton: Skeleton, helper_name = 'Skeleton Helper'): void {
// if skeleton helper exists...remove it
- if (this.skeleton_helper !== undefined) {
- this.scene.remove(this.skeleton_helper)
- }
+ this.dispose_skeleton_helper()
if (this.use_custom_skeleton_helper) {
- this.skeleton_helper = new CustomSkeletonHelper(new_skeleton.bones[0], { linewidth: 4, color: 0x4e7d58 }) // line segment color
+ // no color passed, so bone shapes and joints both use the bone category colors
+ this.skeleton_helper = new CustomSkeletonHelper(new_skeleton.bones[0])
} else {
this.skeleton_helper = new THREE.SkeletonHelper(new_skeleton.bones[0])
}
@@ -210,6 +209,30 @@ export class Mesh2MotionEngine {
this.scene.add(this.skeleton_helper)
}
+ /**
+ * Takes the current skeleton helper out of the scene and releases its GPU
+ * resources. Skipping the dispose leaked a geometry, materials and (for the
+ * custom helper) an instance matrix buffer on every rebuild, and rebuilds
+ * happen on every skeleton edit undo/redo.
+ */
+ private dispose_skeleton_helper (): void {
+ if (this.skeleton_helper === undefined) {
+ return
+ }
+
+ this.scene.remove(this.skeleton_helper)
+
+ if (this.skeleton_helper instanceof CustomSkeletonHelper) {
+ this.skeleton_helper.dispose()
+ } else {
+ // three's stock SkeletonHelper is a plain LineSegments with no dispose()
+ this.skeleton_helper.geometry.dispose()
+ ;(this.skeleton_helper.material as THREE.Material).dispose()
+ }
+
+ this.skeleton_helper = undefined
+ }
+
public sync_skeleton_helper_joint_visibility (): void {
if (!(this.skeleton_helper instanceof CustomSkeletonHelper)) {
return
@@ -383,9 +406,7 @@ export class Mesh2MotionEngine {
}
else if (this.process_step === ProcessStep.LoadSkeleton) {
// if skeleton helper existed because we are going back to this
- if (this.skeleton_helper !== undefined) {
- this.scene.remove(this.skeleton_helper)
- }
+ this.dispose_skeleton_helper()
// need to change the texture display to normal material in
this.mesh_preview_display_type = ModelPreviewDisplay.Textured
@@ -412,7 +433,6 @@ export class Mesh2MotionEngine {
this.sync_skeleton_helper_joint_visibility()
- this.mesh_preview_display_type = ModelPreviewDisplay.WeightPainted
this.changed_model_preview_display(this.mesh_preview_display_type) // show weight painted mesh by default
}
else if (this.process_step === ProcessStep.BindPose) {
diff --git a/src/lib/CustomSkeletonHelper.ts b/src/lib/CustomSkeletonHelper.ts
index 5d68bb3..015d32e 100644
--- a/src/lib/CustomSkeletonHelper.ts
+++ b/src/lib/CustomSkeletonHelper.ts
@@ -3,64 +3,121 @@
// and ideas from
// https://discourse.threejs.org/t/extend-skeletonhelper-to-accommodate-fat-lines-perhaps-with-linesegments2/59436/2
-import { Color, Matrix4, Vector3, Points, PointsMaterial, BufferGeometry, Float32BufferAttribute, TextureLoader, LineSegments, LineBasicMaterial, type Bone, type ColorRepresentation } from 'three'
+import { Color, Matrix4, Quaternion, Vector3, Points, PointsMaterial, BufferGeometry, Float32BufferAttribute, InstancedBufferAttribute, TextureLoader, InstancedMesh, MeshBasicMaterial, FrontSide, DynamicDrawUsage, type Bone, type Camera, type ColorRepresentation, type Material, type Texture } from 'three'
import { BoneCategory, BoneClassifier } from './solvers/BoneClassifier'
+import { create_octahedral_bone_geometry } from './geometry/OctahedralBoneGeometry'
const _vector = /*@__PURE__*/ new Vector3()
const _boneMatrix = /*@__PURE__*/ new Matrix4()
const _matrixWorldInv = /*@__PURE__*/ new Matrix4()
+const _head = /*@__PURE__*/ new Vector3()
+const _tail = /*@__PURE__*/ new Vector3()
+const _direction = /*@__PURE__*/ new Vector3()
+const _scale = /*@__PURE__*/ new Vector3()
+const _quaternion = /*@__PURE__*/ new Quaternion()
+const _instance_matrix = /*@__PURE__*/ new Matrix4()
+const _view_matrix = /*@__PURE__*/ new Matrix4()
+
+// the octahedral template geometry is built pointing up the +y axis
+const _bone_up = /*@__PURE__*/ new Vector3(0, 1, 0)
+
+// bones shorter than this are treated as having no shape at all, which also
+// keeps Vector3.normalize() from producing NaN on a zero length direction
+const MINIMUM_BONE_LENGTH = 1e-6
interface CustomSkeletonHelperOptions {
color?: ColorRepresentation
jointColor?: ColorRepresentation
+ thickness_ratio?: number
+ opacity?: number
}
const bone_category_colors: Record<BoneCategory, number> = {
- [BoneCategory.Torso]: 0xff9f1c,
+ [BoneCategory.Torso]: 0x0E9747,
[BoneCategory.Limb]: 0x3a86ff,
[BoneCategory.Extremity]: 0x8338ec,
[BoneCategory.Other]: 0xadb5bd
}
-class CustomSkeletonHelper extends LineSegments {
+// shared across every helper instance. Loading this per instance meant a fresh
+// HTTP request and a fresh GPU texture on every skeleton rebuild
+let shared_joint_texture: Texture | undefined
+
+function get_joint_texture (): Texture {
+ shared_joint_texture ??= new TextureLoader().load('/images/skeleton-joint-point.png')
+ return shared_joint_texture
+}
+
+class CustomSkeletonHelper extends InstancedMesh {
+ // kept for parity with three's own SkeletonHelper, which callers duck type against
+ public readonly isSkeletonHelper: boolean = true
+ public readonly type: string = 'CustomSkeletonHelper'
+ public readonly root: any
+ public readonly bones: any[]
+
private readonly joint_points: Points
- private readonly jointTexture = new TextureLoader().load('/images/skeleton-joint-point.png')
private hide_right_side_joints: boolean = false
+ private is_disposed: boolean = false
- constructor (object: any, options: CustomSkeletonHelperOptions = {}) {
- const bones = getBoneList(object)
- const geometry = new BufferGeometry()
+ // one octahedron instance per bone that has a bone for a parent. The shape
+ // spans from the parent's joint (head) to the bone's own joint (tip)
+ private readonly segment_bone_indices: number[]
+ private readonly segment_heads: Float32Array
+ private readonly segment_tails: Float32Array
- const vertices = []
- const colors = []
- const color = new Color(options.color || 0x0000ff) // Default color blue
- const joint_color = new Color(options.jointColor ?? 0x0000ff) // Default joint color blue
+ // instances are written back to front so the nearest bone paints last. The
+ // material has depthTest off, so draw order is the only thing separating
+ // them, and it is also the order alpha blending has to happen in
+ private readonly segment_depths: Float32Array
+ private readonly segment_draw_order: number[]
- for (let i = 0; i < bones.length; i++) {
- const bone = bones[i]
+ // bone category colors, in segment order. Undefined when a flat color was
+ // supplied, in which case the material color covers every bone
+ private readonly segment_colors: Float32Array | undefined
+
+ private readonly thickness_ratio: number
+
+ private _joint_color: Color = new Color(0x0F89B9) // Default joint color blue
- if (bone.parent && bone.parent.isBone) {
- vertices.push(0, 0, 0) // Start
- vertices.push(0, 0, 0) // End
- colors.push(color.r, color.g, color.b)
- colors.push(color.r, color.g, color.b)
+ constructor (object: any, options: CustomSkeletonHelperOptions = {}) {
+ const bones = getBoneList(object)
+ const segment_bone_indices: number[] = []
+ for (let i = 0; i < bones.length; i++) {
+ if (bones[i].parent && bones[i].parent.isBone) {
+ segment_bone_indices.push(i)
}
}
- geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3))
- geometry.setAttribute('color', new Float32BufferAttribute(colors, 3))
-
- const material = new LineBasicMaterial({
- vertexColors: true,
+ // without an explicit color, the bone shapes fall back to the bone category
+ // colors. The joints are deliberately left a single neutral color: the bones
+ // already carry the category, and repeating it on the joints made both
+ // harder to pick out
+ const use_category_bone_colors = options.color === undefined
+ const bone_classifier = use_category_bone_colors
+ ? new BoneClassifier(bones as Bone[])
+ : undefined
+
+ const material = new MeshBasicMaterial({
+ // white lets the per instance category color through untouched. A supplied
+ // color instead applies to every bone, and skips instance colors entirely
+ color: use_category_bone_colors ? 0xffffff : options.color,
+ vertexColors: true, // the template geometry bakes flat shading into its colors
+ side: FrontSide, // culling backfaces makes each convex bone shape self-occlude correctly
+ transparent: true, // also load bearing: keeps the helper in the transparent pass, which
+ // renders after the opaque model, so the skeleton still draws over the mesh
+ opacity: options.opacity ?? 0.5,
depthTest: false,
- depthWrite: false,
- transparent: true
+ depthWrite: false
})
- super(geometry, material)
+ // InstancedMesh needs a count of at least 1 to allocate its buffers
+ super(create_octahedral_bone_geometry(), material, Math.max(segment_bone_indices.length, 1))
+ this.count = segment_bone_indices.length
+ this.instanceMatrix.setUsage(DynamicDrawUsage)
- this.isSkeletonHelper = true
- this.type = 'CustomSkeletonHelper'
+ if(options.jointColor) {
+ this._joint_color = new Color(options.jointColor)
+ }
this.root = object
this.bones = bones
@@ -68,50 +125,71 @@ class CustomSkeletonHelper extends LineSegments {
this.matrix = object.matrixWorld
this.matrixAutoUpdate = false
+ // the helper is positioned entirely from bone matrices, so its own bounds
+ // never reflect where it actually is. Culling it by them hid the skeleton
+ // whenever the root bone on the ground went off camera
+ this.frustumCulled = false
+
+ this.thickness_ratio = options.thickness_ratio ?? 0.1
+
+ this.segment_bone_indices = segment_bone_indices
+ this.segment_heads = new Float32Array(segment_bone_indices.length * 3)
+ this.segment_tails = new Float32Array(segment_bone_indices.length * 3)
+ this.segment_depths = new Float32Array(segment_bone_indices.length)
+ this.segment_draw_order = segment_bone_indices.map((_, index) => index)
+
+ if (bone_classifier !== undefined) {
+ // a segment runs from its parent's joint up to its own, so it takes the
+ // category of its own bone. That matches the joint sprite on its tip
+ const segment_colors = new Float32Array(segment_bone_indices.length * 3)
+
+ segment_bone_indices.forEach((bone_index, segment) => {
+ const bone_category = bone_classifier.get_category(bone_index)
+ const category_color = new Color(bone_category_colors[bone_category])
+ category_color.toArray(segment_colors, segment * 3)
+ })
+
+ this.segment_colors = segment_colors
+
+ // instance colors are rewritten every frame because the depth sort keeps
+ // moving each segment to a different instance slot
+ this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3), 3)
+ this.instanceColor.setUsage(DynamicDrawUsage)
+ }
+
// Add points for joints
const pointsGeometry = new BufferGeometry()
const pointsMaterial = new PointsMaterial({
size: 30, // Size of the joint circles on skeleton
- color: options.jointColor !== undefined ? joint_color : 0xffffff,
+ color: this._joint_color,
depthTest: false,
sizeAttenuation: false, // Disable size attenuation to keep size constant in screen space
- map: this.jointTexture,
+ map: get_joint_texture(),
transparent: true, // Enable transparency for the circular texture
opacity: 0.8,
- vertexColors: options.jointColor === undefined
+ //vertexColors: true
})
const pointPositions = new Float32BufferAttribute(bones.length * 3, 3)
pointsGeometry.setAttribute('position', pointPositions)
- // use bone category to color joints to help with seeing a bunch of them
- if (options.jointColor === undefined) {
- const bone_classifier = new BoneClassifier(bones as Bone[])
- const point_colors: number[] = []
-
- bones.forEach((bone, idx) => {
- const bone_category = bone_classifier.get_category(idx)
- const category_color = new Color(bone_category_colors[bone_category])
- point_colors.push(category_color.r, category_color.g, category_color.b)
- })
-
- pointsGeometry.setAttribute('color', new Float32BufferAttribute(point_colors, 3))
- }
-
this.joint_points = new Points(pointsGeometry, pointsMaterial)
+ this.joint_points.frustumCulled = false
this.add(this.joint_points)
+
+ // the bone shapes have to be sorted by camera distance, and onBeforeRender
+ // is where the camera for the current pass is available
+ this.onBeforeRender = (_renderer, _scene, camera) => {
+ this.update_bone_instances(camera)
+ }
}
updateMatrixWorld (force: boolean): void {
const bones = this.bones
const pointPositions = this.joint_points.geometry.getAttribute('position')
- const geometry = this.geometry
- const positions = geometry.getAttribute('position')
-
_matrixWorldInv.copy(this.root.matrixWorld).invert()
- let lineIndex = 0
for (let i = 0; i < bones.length; i++) {
const bone = bones[i]
_boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld)
@@ -122,42 +200,127 @@ class CustomSkeletonHelper extends LineSegments {
} else {
pointPositions.setXYZ(i, _vector.x, _vector.y, _vector.z) // Update point position
}
+ }
- if (bone.parent && bone.parent.isBone) {
- _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld)
- _vector.setFromMatrixPosition(_boneMatrix)
- positions.setXYZ(lineIndex * 2, _vector.x, _vector.y, _vector.z)
+ // record where each bone shape starts and ends. Turning those into instance
+ // matrices needs the camera, so that waits until onBeforeRender
+ for (let segment = 0; segment < this.segment_bone_indices.length; segment++) {
+ const bone = bones[this.segment_bone_indices[segment]]
+ const offset = segment * 3
- _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld)
- _vector.setFromMatrixPosition(_boneMatrix)
- positions.setXYZ(lineIndex * 2 + 1, _vector.x, _vector.y, _vector.z)
- lineIndex++
- }
+ _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld)
+ _vector.setFromMatrixPosition(_boneMatrix)
+ this.segment_heads[offset] = _vector.x
+ this.segment_heads[offset + 1] = _vector.y
+ this.segment_heads[offset + 2] = _vector.z
+
+ _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld)
+ _vector.setFromMatrixPosition(_boneMatrix)
+ this.segment_tails[offset] = _vector.x
+ this.segment_tails[offset + 1] = _vector.y
+ this.segment_tails[offset + 2] = _vector.z
}
pointPositions.needsUpdate = true
- positions.needsUpdate = true
-
- // Update bounding box and bounding sphere
- // otherwise the skeleton will be hidden when root bone on ground is off camera
- geometry.computeBoundingBox()
- geometry.computeBoundingSphere()
super.updateMatrixWorld(force)
}
- dispose (): void {
+ /**
+ * Turns the head/tail positions recorded in updateMatrixWorld into instance
+ * matrices, written far to near so the painter's algorithm resolves overlap
+ * between bones. That is exact here because each shape is convex and adjacent
+ * bones meet tip to head rather than interpenetrating.
+ */
+ private update_bone_instances (camera: Camera): void {
+ const segment_count = this.segment_bone_indices.length
+ if (segment_count === 0) {
+ return
+ }
+
+ _view_matrix.multiplyMatrices(camera.matrixWorldInverse, this.matrixWorld)
+
+ for (let segment = 0; segment < segment_count; segment++) {
+ const offset = segment * 3
+
+ // view space depth of the shape's midpoint. The camera looks down -z, so
+ // the more negative the value, the further away the bone is
+ _vector.set(
+ (this.segment_heads[offset] + this.segment_tails[offset]) * 0.5,
+ (this.segment_heads[offset + 1] + this.segment_tails[offset + 1]) * 0.5,
+ (this.segment_heads[offset + 2] + this.segment_tails[offset + 2]) * 0.5
+ )
+ this.segment_depths[segment] = _vector.applyMatrix4(_view_matrix).z
+ }
+
+ this.segment_draw_order.sort(this.compare_segment_depth)
+
+ for (let slot = 0; slot < segment_count; slot++) {
+ const segment = this.segment_draw_order[slot]
+ const offset = segment * 3
+
+ _head.set(this.segment_heads[offset], this.segment_heads[offset + 1], this.segment_heads[offset + 2])
+ _tail.set(this.segment_tails[offset], this.segment_tails[offset + 1], this.segment_tails[offset + 2])
+
+ const bone_length = _direction.subVectors(_tail, _head).length()
+
+ if (bone_length < MINIMUM_BONE_LENGTH) {
+ _quaternion.identity()
+ _scale.set(0, 0, 0)
+ } else {
+ _quaternion.setFromUnitVectors(_bone_up, _direction.divideScalar(bone_length))
+ const thickness = bone_length * this.thickness_ratio
+ _scale.set(thickness, bone_length, thickness)
+ }
+
+ _instance_matrix.compose(_head, _quaternion, _scale)
+ this.setMatrixAt(slot, _instance_matrix)
+
+ // the color has to follow its segment into whichever slot the sort put it
+ if (this.segment_colors !== undefined && this.instanceColor !== null) {
+ this.instanceColor.setXYZ(
+ slot,
+ this.segment_colors[offset],
+ this.segment_colors[offset + 1],
+ this.segment_colors[offset + 2]
+ )
+ }
+ }
+
+ this.instanceMatrix.needsUpdate = true
+
+ if (this.instanceColor !== null) {
+ this.instanceColor.needsUpdate = true
+ }
+ }
+
+ private readonly compare_segment_depth = (a: number, b: number): number => {
+ return this.segment_depths[a] - this.segment_depths[b]
+ }
+
+ dispose (): this {
+ if (this.is_disposed) {
+ return this
+ }
+ this.is_disposed = true
+
this.geometry.dispose()
- this.material.dispose()
+ ;(this.material as Material).dispose()
this.joint_points.geometry.dispose()
- this.joint_points.material.dispose()
+ ;(this.joint_points.material as Material).dispose()
+
+ // shared_joint_texture is intentionally left alone. It outlives any single
+ // helper and gets reused by the next one
+
+ // InstancedMesh.dispose() is what releases the instanceMatrix buffer
+ return super.dispose()
}
- public show(): void {
+ public show (): void {
this.visible = true
}
- public hide(): void {
+ public hide (): void {
this.visible = false
}
diff --git a/src/lib/geometry/OctahedralBoneGeometry.ts b/src/lib/geometry/OctahedralBoneGeometry.ts
new file mode 100644
index 0000000..793979e
--- /dev/null
+++ b/src/lib/geometry/OctahedralBoneGeometry.ts
@@ -0,0 +1,63 @@
+import { BufferAttribute, BufferGeometry } from 'three'
+
+type Vertex = [number, number, number]
+
+// A Blender-style octahedral bone shape, built in a unit space that runs from
+// y = 0 (the head, sitting on the parent joint) to y = 1 (the tip, sitting on
+// the child joint). The widest part is a 4 vertex ring 10% along the bone.
+// Callers scale this: x/z by bone thickness, y by bone length.
+const RING_HEIGHT = 0.1
+const RING_RADIUS = 0.5
+
+// Fake flat shading, baked per facet into vertex colors, so the shape reads as
+// 3D without needing any lights. MeshBasicMaterial multiplies material.color by
+// the vertex color, so the helper keeps its exact configured color.
+// The shape is convex, so only 2 of these 4 quadrants are visible at a time and
+// they are always neighbors. That means every *adjacent* pair has to contrast,
+// which is why these alternate rather than ramping in one direction.
+const QUADRANT_SHADING = [1.0, 0.7, 0.92, 0.62]
+
+// the head cone is darkened relative to the tip cone. This makes the widest
+// ring show up as an edge, which is the cue for which end of the bone is which.
+const HEAD_SHADING_FALLOFF = 0.85
+
+export function create_octahedral_bone_geometry (): BufferGeometry {
+ const geometry = new BufferGeometry()
+
+ const head: Vertex = [0, 0, 0]
+ const tip: Vertex = [0, 1, 0]
+ const ring: Vertex[] = [
+ [RING_RADIUS, RING_HEIGHT, RING_RADIUS],
+ [RING_RADIUS, RING_HEIGHT, -RING_RADIUS],
+ [-RING_RADIUS, RING_HEIGHT, -RING_RADIUS],
+ [-RING_RADIUS, RING_HEIGHT, RING_RADIUS]
+ ]
+
+ const vertices: number[] = []
+ const colors: number[] = []
+
+ const add_triangle = (a: Vertex, b: Vertex, c: Vertex, shade: number): void => {
+ vertices.push(...a, ...b, ...c)
+ for (let corner = 0; corner < 3; corner++) {
+ colors.push(shade, shade, shade)
+ }
+ }
+
+ // 8 triangles total: a 4 triangle fan from the ring down to the head,
+ // and a 4 triangle fan from the ring up to the tip
+ for (let quadrant = 0; quadrant < 4; quadrant++) {
+ const current = ring[quadrant]
+ const next = ring[(quadrant + 1) % ring.length]
+ const shade = QUADRANT_SHADING[quadrant]
+
+ // winding is counter-clockwise seen from outside the shape, so the front
+ // faces point outward. The material culls backfaces to get correct
+ // self-occlusion without relying on the depth buffer.
+ add_triangle(next, current, head, shade * HEAD_SHADING_FALLOFF)
+ add_triangle(current, next, tip, shade)
+ }
+
+ geometry.setAttribute('position', new BufferAttribute(new Float32Array(vertices), 3))
+ geometry.setAttribute('color', new BufferAttribute(new Float32Array(colors), 3))
+ return geometry
+}