Files
La-Fabrik/src/components/three/models/ExplodableModel.tsx
T
Tom Boullay 317db48bcc feat(repair): make fragmented -> scanning event-driven via onSplitSettled
The fragmented -> scanning transition used to fire on a blind
setTimeout of REPAIR_FRAGMENTATION_SEQUENCE_SECONDS regardless of
whether the explode lerp had actually finished. With the new sphere-
reveal flow this got out of sync (sphere grows for 2.5s before
fragmented even mounts), so the timer could fire too early or while
the parts were still flying out.

Now the ExplodedModel emits a single 'settled' callback when its
internal lerp converges on its target (1 = fully exploded, 0 = fully
reassembled). RepairGame listens for settled-at-1 on the fragmented
ExplodableModel and advances to scanning on that event.

The legacy timer is kept as a generous safety net
(REPAIR_FRAGMENTATION_SEQUENCE_SECONDS + 2 seconds) so that if the
model fails to load (no parts -> no settled event ever fires) the
flow can never get stuck on the fragmented step.

Changes:
- ExplodedModel.ts:
  - new ExplodedModelOptions.onSettled: (settledAt: 0 | 1) => void
  - track settledAtTarget to ensure the callback fires exactly once
    per lerp (re-armed when setSplit() flips the target).
- ExplodableModel.tsx: new onSplitSettled prop, forwarded to the
  underlying ExplodedModel via a stable useCallback that reads the
  latest prop through a ref so the instance is not recreated mid-anim.
- RepairGame.tsx:
  - wire onSplitSettled on the fragmented ExplodableModel to
    setMissionStep(mission, 'scanning').
  - keep the existing setTimeout but extend it as a fallback only.

Pylon and farm benefit from the same fix automatically since they
share the same RepairGame fragmented branch.
2026-06-03 04:18:10 +02:00

229 lines
6.3 KiB
TypeScript

import type { ReactNode } from "react";
import { Component, useCallback, useEffect, useMemo, useRef } from "react";
import * as THREE from "three";
import { useFrame } from "@react-three/fiber";
import { useLoggedGLTF } from "@/hooks/three/useLoggedGLTF";
import { useClonedObject } from "@/hooks/three/useClonedObject";
import { ExplodedModel } from "@/utils/three/ExplodedModel";
import type { ExplodedPart } from "@/utils/three/ExplodedModel";
import type { ModelTransformProps, Vector3Tuple } from "@/types/three/three";
import { logModelLoadError } from "@/utils/three/modelLoadLogger";
import { toVector3Scale } from "@/utils/three/scale";
export type ExplodedNodeAnchors = Readonly<Record<string, Vector3Tuple>>;
const _anchorWorld = new THREE.Vector3();
interface ModelErrorBoundaryProps {
children: ReactNode;
modelPath: string;
position?: Vector3Tuple | undefined;
rotation?: Vector3Tuple | undefined;
scale?: ModelTransformProps["scale"] | undefined;
}
interface ModelErrorBoundaryState {
hasError: boolean;
}
class ModelErrorBoundary extends Component<
ModelErrorBoundaryProps,
ModelErrorBoundaryState
> {
constructor(props: ModelErrorBoundaryProps) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(): ModelErrorBoundaryState {
return { hasError: true };
}
componentDidCatch(error: Error): void {
logModelLoadError(
{
modelPath: this.props.modelPath,
scope: "ExplodableModel",
position: this.props.position,
rotation: this.props.rotation,
scale: this.props.scale,
},
error,
);
}
render(): ReactNode {
if (this.state.hasError) {
return (
<MissingModelFallback
position={this.props.position}
rotation={this.props.rotation}
scale={this.props.scale}
/>
);
}
return this.props.children;
}
}
interface ExplodableModelInnerProps extends ModelTransformProps {
modelPath: string;
split: boolean;
splitDistance?: number;
onPartsReady?: (parts: readonly ExplodedPart[]) => void;
/**
* Fired once each time the explode/reassemble lerp converges on its
* target. `settledAt` is 1 when the parts have fully separated, 0
* when they have fully snapped back to their original positions.
*/
onSplitSettled?: (settledAt: 0 | 1) => void;
hideNodeNames?: readonly string[];
nodeAnchorNames?: readonly string[];
onNodeAnchorsChange?: (anchors: ExplodedNodeAnchors) => void;
}
export function ExplodableModel(
props: ExplodableModelInnerProps,
): React.JSX.Element {
return (
<ModelErrorBoundary
key={props.modelPath}
modelPath={props.modelPath}
position={props.position}
rotation={props.rotation}
scale={props.scale}
>
<ExplodableModelInner {...props} />
</ModelErrorBoundary>
);
}
function ExplodableModelInner({
modelPath,
split,
position = [0, 0, 0],
rotation = [0, 0, 0],
scale = 1,
splitDistance = 1.2,
onPartsReady,
onSplitSettled,
hideNodeNames,
nodeAnchorNames,
onNodeAnchorsChange,
}: ExplodableModelInnerProps): React.JSX.Element {
const { scene } = useLoggedGLTF(modelPath, {
scope: "ExplodableModel",
position,
rotation,
scale,
});
const model = useClonedObject(scene);
// Keep the latest callback in a ref so the ExplodedModel instance can
// be created once per `model` and still call the most recent prop
// when the lerp settles. Reading `.current` happens only inside the
// settled-callback (invoked from update(), never during render).
const onSplitSettledRef = useRef(onSplitSettled);
useEffect(() => {
onSplitSettledRef.current = onSplitSettled;
}, [onSplitSettled]);
const handleSettled = useCallback((settledAt: 0 | 1) => {
onSplitSettledRef.current?.(settledAt);
}, []);
const explodedModel = useMemo(
() =>
// The `handleSettled` callback only reads `onSplitSettledRef.current`
// when invoked from `update()` (useFrame), never during render.
// eslint-disable-next-line react-hooks/refs
new ExplodedModel(model, {
distance: splitDistance,
onSettled: handleSettled,
}),
[model, splitDistance, handleSettled],
);
const parsedScale = toVector3Scale(scale);
const anchorSignatureRef = useRef("");
useEffect(() => {
if (!hideNodeNames || hideNodeNames.length === 0) return;
const hidden: THREE.Object3D[] = [];
model.traverse((child) => {
if (hideNodeNames.includes(child.name)) {
hidden.push(child);
child.visible = false;
}
});
return () => {
hidden.forEach((object) => {
object.visible = true;
});
};
}, [hideNodeNames, model]);
useEffect(() => {
explodedModel.setSplit(split);
}, [explodedModel, split]);
useEffect(() => {
onPartsReady?.(explodedModel.getParts());
}, [explodedModel, onPartsReady]);
useFrame((_, delta) => {
explodedModel.update(delta);
if (
!onNodeAnchorsChange ||
!nodeAnchorNames ||
nodeAnchorNames.length === 0
) {
return;
}
const anchors: Record<string, Vector3Tuple> = {};
nodeAnchorNames.forEach((name) => {
const node = model.getObjectByName(name);
if (!node) return;
node.getWorldPosition(_anchorWorld);
anchors[name] = [_anchorWorld.x, _anchorWorld.y, _anchorWorld.z];
});
const signature = nodeAnchorNames
.map((name) => {
const a = anchors[name];
return a
? `${name}:${a[0].toFixed(3)},${a[1].toFixed(3)},${a[2].toFixed(3)}`
: `${name}:?`;
})
.join("|");
if (signature === anchorSignatureRef.current) return;
anchorSignatureRef.current = signature;
onNodeAnchorsChange(anchors);
});
return (
<group position={position} rotation={rotation} scale={parsedScale}>
<primitive object={model} />
</group>
);
}
function MissingModelFallback({
position = [0, 0, 0],
rotation = [0, 0, 0],
scale = 1,
}: {
position?: Vector3Tuple | undefined;
rotation?: Vector3Tuple | undefined;
scale?: ModelTransformProps["scale"] | undefined;
}): React.JSX.Element {
return (
<mesh position={position} rotation={rotation} scale={toVector3Scale(scale)}>
<boxGeometry args={[0.7, 0.7, 0.7]} />
<meshStandardMaterial color="#7f1d1d" wireframe />
</mesh>
);
}