File size: 10,671 Bytes
0092d86
 
e2d35c0
 
 
 
 
 
 
 
0092d86
7fee07b
 
 
 
 
 
 
0092d86
 
 
7fee07b
e2d35c0
 
0092d86
 
 
d0c158f
0092d86
 
 
 
 
 
 
 
 
81070c7
0092d86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2d35c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0092d86
e2d35c0
0092d86
 
8c23bc3
81070c7
8c23bc3
 
 
0092d86
 
 
 
 
 
 
 
 
 
7fee07b
0092d86
 
 
 
 
 
5c435e7
 
 
 
 
 
 
 
 
 
a3fd468
 
 
 
 
0092d86
 
d0c158f
7fee07b
0092d86
e2d35c0
0092d86
 
e2d35c0
5c435e7
0092d86
a3fd468
5c435e7
0092d86
 
e2d35c0
0092d86
 
 
 
 
 
e2d35c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0c158f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0092d86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c435e7
 
0092d86
5c435e7
 
 
a3fd468
 
5c435e7
0092d86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c23bc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0092d86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81070c7
0092d86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7fee07b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0092d86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
import { useCallback, useEffect, useMemo, useRef, useState } from "react";

import {
  ApiResponseError,
  fetchAdminModels,
  fetchWorldSnapshot,
  setNpcModelProfile,
  tickWorld,
} from "../api";
import type { GameLogEventSnapshot, ModelProfileSnapshot, WorldSnapshot } from "../types";

// When enabled, the manual tick controls are hidden and the world advances on its
// own. Defaults to on; set VITE_WORLD_SIMULATOR_AUTOPLAY=0/false/no to show the
// manual controls instead.
const AUTOPLAY = !["0", "false", "no"].includes(
  String(import.meta.env.VITE_WORLD_SIMULATOR_AUTOPLAY ?? "").toLowerCase(),
);

export function useWorldSimulation() {
  const [snapshot, setSnapshot] = useState<WorldSnapshot | null>(null);
  const [isTickPending, setIsTickPending] = useState(false);
  const [isAutoTicking, setIsAutoTicking] = useState(AUTOPLAY);
  const [isModelSwitchPending, setIsModelSwitchPending] = useState(false);
  const [modelProfiles, setModelProfiles] = useState<ModelProfileSnapshot[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const isTickingRef = useRef(false);
  const eventHistory = useEventHistory(snapshot);

  const refresh = useCallback(async () => {
    const nextSnapshot = await fetchWorldSnapshot();
    setSnapshot(nextSnapshot);
    setError(null);
  }, []);

  const isServerTickPending = snapshot?.simulation.tick_in_progress ?? false;
  const isWaitingForTick = isTickPending || isServerTickPending;
  const isWorldCommandPending = isWaitingForTick;

  const step = useCallback(async () => {
    if (isTickingRef.current || snapshot?.simulation.tick_in_progress) {
      return;
    }
    isTickingRef.current = true;
    setIsTickPending(true);
    setError(null);
    try {
      await tickWorld();
      await refresh();
    } catch (nextError) {
      if (nextError instanceof ApiResponseError && nextError.status === 409) {
        await refresh().catch((refreshError: unknown) => {
          setError(refreshError instanceof Error ? refreshError.message : "World refresh failed");
        });
      } else {
        setError(nextError instanceof Error ? nextError.message : "World update failed");
        setIsAutoTicking(false);
      }
    } finally {
      isTickingRef.current = false;
      setIsTickPending(false);
    }
  }, [refresh, snapshot?.simulation.tick_in_progress]);

  const refreshModelProfiles = useCallback(async () => {
    const adminModels = await fetchAdminModels();
    setModelProfiles(adminModels.profiles);
  }, []);

  const setNpcModel = useCallback(
    async (npcId: string, profileId: string) => {
      setIsModelSwitchPending(true);
      setError(null);
      try {
        await setNpcModelProfile(npcId, profileId);
        await refresh();
        await refreshModelProfiles();
      } catch (nextError) {
        setError(nextError instanceof Error ? nextError.message : "NPC model switch failed");
      } finally {
        setIsModelSwitchPending(false);
      }
    },
    [refresh, refreshModelProfiles],
  );

  useInitialSnapshot(setSnapshot, setSelectedId, setError);
  useInitialModelProfiles(setModelProfiles);
  useSelectedEntityFallback(snapshot, setSelectedId);
  useServerTickPolling(isServerTickPending, refresh, setError);
  useIdleSnapshotPolling({
    isIdle: snapshot !== null && !isAutoTicking && !isWaitingForTick,
    refresh,
    setError,
  });
  useAutoTicks({
    currentTick: snapshot?.tick ?? null,
    isAutoTicking,
    isWaitingForTick,
    hasSnapshot: snapshot !== null,
    step,
    setError,
    setIsAutoTicking,
  });
  useModelStatusPolling(snapshot, refresh, setError);
  useAutoplayRearm(isAutoTicking, snapshot !== null, setIsAutoTicking);

  const selectedEntity = useMemo(
    () => snapshot?.entities.find((entity) => entity.id === selectedId) ?? null,
    [selectedId, snapshot],
  );

  const selectedBeast = useMemo(
    () => snapshot?.beasts?.find((beast) => beast.id === selectedId) ?? null,
    [selectedId, snapshot],
  );

  const selectedResource = useMemo(
    () => snapshot?.resource_nodes?.find((node) => node.id === selectedId) ?? null,
    [selectedId, snapshot],
  );

  const selectedHouse = useMemo(
    () => snapshot?.houses?.find((house) => house.id === selectedId) ?? null,
    [selectedId, snapshot],
  );

  return {
    error,
    eventHistory,
    hideTickControls: AUTOPLAY,
    isAutoTicking,
    isModelSwitchPending,
    isWaitingForTick,
    isWorldCommandPending,
    modelProfiles,
    selectedBeast,
    selectedEntity,
    selectedHouse,
    selectedResource,
    selectedId,
    setIsAutoTicking,
    setNpcModel,
    setSelectedId,
    snapshot,
    step,
  };
}

function useInitialModelProfiles(
  setModelProfiles: (profiles: ModelProfileSnapshot[]) => void,
) {
  useEffect(() => {
    const abortController = new AbortController();
    fetchAdminModels(abortController.signal)
      .then((adminModels) => {
        setModelProfiles(adminModels.profiles);
      })
      .catch(() => {
        if (!abortController.signal.aborted) {
          setModelProfiles([]);
        }
      });

    return () => abortController.abort();
  }, [setModelProfiles]);
}

function useEventHistory(snapshot: WorldSnapshot | null): GameLogEventSnapshot[] {
  const seenKeysRef = useRef<Set<string>>(new Set());
  const [history, setHistory] = useState<GameLogEventSnapshot[]>([]);

  useEffect(() => {
    const log = snapshot?.event_log ?? [];
    if (log.length === 0) {
      return;
    }
    const fresh: GameLogEventSnapshot[] = [];
    for (const event of log) {
      const key = [
        event.tick,
        event.type,
        event.actor_id ?? "",
        event.target_id ?? "",
        event.summary,
      ].join("|");
      if (!seenKeysRef.current.has(key)) {
        seenKeysRef.current.add(key);
        fresh.push(event);
      }
    }
    if (fresh.length > 0) {
      setHistory((current) => [...current, ...fresh].slice(-500));
    }
  }, [snapshot]);

  return history;
}

function useInitialSnapshot(
  setSnapshot: (snapshot: WorldSnapshot) => void,
  setSelectedId: (id: string | null) => void,
  setError: (error: string | null) => void,
) {
  useEffect(() => {
    const abortController = new AbortController();
    fetchWorldSnapshot(abortController.signal, { warmup: true })
      .then((nextSnapshot) => {
        setSnapshot(nextSnapshot);
        setSelectedId(nextSnapshot.entities[0]?.id ?? null);
        setError(null);
      })
      .catch((nextError: unknown) => {
        if (!abortController.signal.aborted) {
          setError(nextError instanceof Error ? nextError.message : "World load failed");
        }
      });

    return () => abortController.abort();
  }, [setError, setSelectedId, setSnapshot]);
}

function useSelectedEntityFallback(
  snapshot: WorldSnapshot | null,
  setSelectedId: (updater: (currentId: string | null) => string | null) => void,
) {
  useEffect(() => {
    if (!snapshot) {
      return;
    }

    setSelectedId((currentId) => {
      if (!currentId) {
        return null;
      }
      const stillExists =
        snapshot.entities.some((entity) => entity.id === currentId) ||
        (snapshot.beasts ?? []).some((beast) => beast.id === currentId) ||
        (snapshot.resource_nodes ?? []).some((node) => node.id === currentId) ||
        (snapshot.houses ?? []).some((house) => house.id === currentId);
      return stillExists ? currentId : null;
    });
  }, [snapshot, setSelectedId]);
}

function useServerTickPolling(
  isServerTickPending: boolean,
  refresh: () => Promise<void>,
  setError: (error: string | null) => void,
) {
  useEffect(() => {
    if (!isServerTickPending) {
      return undefined;
    }
    return pollEvery(1500, refresh, setError);
  }, [isServerTickPending, refresh, setError]);
}

type IdleSnapshotPollingOptions = {
  isIdle: boolean;
  refresh: () => Promise<void>;
  setError: (error: string | null) => void;
};

function useIdleSnapshotPolling(options: IdleSnapshotPollingOptions) {
  const { isIdle, refresh, setError } = options;
  useEffect(() => {
    if (!isIdle) {
      return undefined;
    }
    return pollEvery(2000, refresh, setError);
  }, [isIdle, refresh, setError]);
}

type AutoTickOptions = {
  currentTick: number | null;
  isAutoTicking: boolean;
  isWaitingForTick: boolean;
  hasSnapshot: boolean;
  step: () => Promise<void>;
  setError: (error: string | null) => void;
  setIsAutoTicking: (value: boolean) => void;
};

function useAutoTicks(options: AutoTickOptions) {
  const {
    currentTick,
    isAutoTicking,
    isWaitingForTick,
    hasSnapshot,
    step,
    setError,
    setIsAutoTicking,
  } = options;

  useEffect(() => {
    if (!isAutoTicking || !hasSnapshot || isWaitingForTick) {
      return undefined;
    }

    const timeoutId = window.setTimeout(() => {
      step().catch((nextError: unknown) => {
        setError(nextError instanceof Error ? nextError.message : "World update failed");
        setIsAutoTicking(false);
      });
    }, 500);

    return () => window.clearTimeout(timeoutId);
  }, [
    currentTick,
    hasSnapshot,
    isAutoTicking,
    isWaitingForTick,
    setError,
    setIsAutoTicking,
    step,
  ]);
}

// In autoplay mode the manual controls are hidden, so a transient error that
// pauses auto-ticking must be recovered automatically; otherwise the world would
// halt with no way to restart it.
function useAutoplayRearm(
  isAutoTicking: boolean,
  hasSnapshot: boolean,
  setIsAutoTicking: (value: boolean) => void,
) {
  useEffect(() => {
    if (!AUTOPLAY || isAutoTicking || !hasSnapshot) {
      return undefined;
    }
    const timeoutId = window.setTimeout(() => setIsAutoTicking(true), 2000);
    return () => window.clearTimeout(timeoutId);
  }, [isAutoTicking, hasSnapshot, setIsAutoTicking]);
}

function useModelStatusPolling(
  snapshot: WorldSnapshot | null,
  refresh: () => Promise<void>,
  setError: (error: string | null) => void,
) {
  const modelStatuses = snapshot?.simulation.models ?? [];
  useEffect(() => {
    if (!snapshot || !modelStatuses.some((model) => model.status !== "ready")) {
      return undefined;
    }
    return pollEvery(2000, refresh, setError);
  }, [modelStatuses, refresh, setError, snapshot]);
}

function pollEvery(
  intervalMs: number,
  refresh: () => Promise<void>,
  setError: (error: string | null) => void,
) {
  const intervalId = window.setInterval(() => {
    refresh().catch((nextError: unknown) => {
      setError(nextError instanceof Error ? nextError.message : "World refresh failed");
    });
  }, intervalMs);

  return () => window.clearInterval(intervalId);
}