-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseScienceGraphForceSimulation.js
More file actions
191 lines (172 loc) · 6.46 KB
/
useScienceGraphForceSimulation.js
File metadata and controls
191 lines (172 loc) · 6.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import { useEffect, useLayoutEffect, useMemo, useRef } from "react";
import {
COOLING_INITIAL_TEMPERATURE,
PHYSICS_REACT_COMMIT_INTERVAL,
STABLE_ITERATIONS,
} from "../../components/graph/canvas/physics/simConstants.js";
import { useGraphPhysicsPolicy } from "./useGraphPhysicsPolicy.js";
import { createWorldBoundsCalculator } from "./scienceGraphSimulationBounds.js";
import { buildSimulationGraphPrep } from "./scienceGraphSimulationGraphPrep.js";
import { applySimulationLifecycleResets } from "./scienceGraphSimulationResetPolicy.js";
import { createRunOnePhysicsTick } from "./scienceGraphSimulationTickEngine.js";
/**
* Force-directed simulation (fork of osint-gr useForceSimulation; no OSINT domain).
*
* @param {boolean} enabled
* @param {import("../../components/graph/model/graphSimulationAdapter.js").SimNode[]} nodes
* @param {React.Dispatch<React.SetStateAction<import("../../components/graph/model/graphSimulationAdapter.js").SimNode[]>>} setNodes
* @param {import("../../components/graph/model/graphSimulationAdapter.js").SimLink[]} links
* @param {number} repulsionStrength
* @param {boolean} isSimulationStable
* @param {(v: boolean) => void} setIsSimulationStable
* @param {React.MutableRefObject<Set<string>>} fixedNodesRef
* @param {React.MutableRefObject<{ id: string, x: number, y: number } | null>} draggedNodePositionRef
* @param {{ width: number, height: number }} canvasSize
* @param {string} topologySignature Canonical topology key (recompute communities when this changes).
* @param {string} physicsEpoch Force-run / reheat identity; bumps reset cooling without redoing community detection if topology unchanged.
* @param {string} simulationSignature Combined key for pause policy (`topology|physicsEpoch`); must change whenever topology or physicsEpoch changes.
* @param {EventTarget} [pointerEventTarget] Optional bus for canvas pointer pause events (defaults to `window` via useGraphPhysicsPolicy).
* @param {React.MutableRefObject<import("../../components/graph/model/graphSimulationAdapter.js").SimNode[]>} simNodesRef Live sim buffer (mutated in place); must match seeded React state after topology/restart.
* @param {() => void} onPhysicsVisualTick Called after each integrator commit so canvas can repaint without setState per frame.
*/
export function useScienceGraphForceSimulation(
enabled,
nodes,
setNodes,
links,
repulsionStrength,
isSimulationStable,
setIsSimulationStable,
fixedNodesRef,
draggedNodePositionRef,
canvasSize,
topologySignature,
physicsEpoch,
simulationSignature,
pointerEventTarget,
simNodesRef,
onPhysicsVisualTick,
) {
const animationRef = useRef(null);
const boundsRef = useRef(null);
const coolingTemperatureRef = useRef(COOLING_INITIAL_TEMPERATURE);
const iterationCountRef = useRef(0);
const communitiesRef = useRef(/** @type {Map<string, string> | null} */ (null));
const prevTopologySigRef = useRef("");
const prevPhysicsEpochRef = useRef("");
/** Latest stable flag for the physics integrator (avoids stale closure while RAF runs). */
const isSimStableRef = useRef(isSimulationStable);
isSimStableRef.current = isSimulationStable;
const prevRepulsionRef = useRef(repulsionStrength);
const onPhysicsVisualTickRef = useRef(() => {});
useLayoutEffect(() => {
onPhysicsVisualTickRef.current = onPhysicsVisualTick;
}, [onPhysicsVisualTick]);
const calculateWorldBounds = useMemo(
() => createWorldBoundsCalculator(canvasSize),
// eslint-disable-next-line react-hooks/exhaustive-deps -- only width/height affect bounds math; object identity may churn per parent render
[canvasSize.width, canvasSize.height],
);
const { integrationBlocked } = useGraphPhysicsPolicy({
enabled,
simulationSignature,
animationFrameRef: animationRef,
pointerEventTarget,
});
useEffect(() => {
if (!enabled || integrationBlocked || nodes.length === 0) {
if (animationRef.current) {
cancelAnimationFrame(animationRef.current);
animationRef.current = null;
}
return undefined;
}
applySimulationLifecycleResets({
prevRepulsionRef,
repulsionStrength,
prevTopologySigRef,
topologySignature,
prevPhysicsEpochRef,
physicsEpoch,
boundsRef,
coolingTemperatureRef,
iterationCountRef,
isSimStableRef,
setIsSimulationStable,
communitiesRef,
nodes,
links,
});
const stableCountRef = { current: 0 };
if (!boundsRef.current) {
boundsRef.current = calculateWorldBounds(nodes);
}
const { nodeTypeMap, linkMap, communityMap } = buildSimulationGraphPrep(
nodes,
links,
communitiesRef.current,
);
const runOnePhysicsTick = createRunOnePhysicsTick({
calculateWorldBounds,
boundsRef,
coolingTemperatureRef,
iterationCountRef,
communitiesRef,
communityMap,
nodeTypeMap,
linkMap,
fixedNodesRef,
draggedNodePositionRef,
repulsionStrength,
isSimStableRef,
setIsSimulationStable,
stableCountRef,
});
const commitInterval = Math.max(1, Math.floor(PHYSICS_REACT_COMMIT_INTERVAL));
const simulate = () => {
const buf = simNodesRef.current;
if (!buf || buf.length === 0) {
animationRef.current = null;
return;
}
let stableHalt = false;
for (let s = 0; s < commitInterval; s++) {
stableHalt = runOnePhysicsTick(buf);
if (stableHalt) break;
}
onPhysicsVisualTickRef.current?.();
if (stableHalt) {
setNodes(buf.map((n) => ({ ...n })));
}
if (!stableHalt && (stableCountRef.current < STABLE_ITERATIONS || draggedNodePositionRef.current)) {
animationRef.current = requestAnimationFrame(simulate);
}
};
animationRef.current = requestAnimationFrame(simulate);
return () => {
if (animationRef.current) {
cancelAnimationFrame(animationRef.current);
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- simulation uses simNodesRef; full `nodes` would restart every frame; `simulationSignature` is only for useGraphPhysicsPolicy above
}, [
enabled,
integrationBlocked,
simulationSignature,
topologySignature,
physicsEpoch,
pointerEventTarget,
links,
repulsionStrength,
isSimulationStable,
canvasSize.width,
canvasSize.height,
calculateWorldBounds,
setNodes,
setIsSimulationStable,
fixedNodesRef,
draggedNodePositionRef,
nodes.length,
simNodesRef,
]);
}