feat: add Gaussian simulation workspace

This commit is contained in:
DCCONSTRUCTIONS
2026-08-26 02:09:44 +03:00
parent b111406cf8
commit d943ec853c
22 changed files with 3422 additions and 17 deletions
@@ -0,0 +1,211 @@
import {
Application,
Asset,
Color,
Entity,
Vec2,
Vec3,
type ScriptType,
} from "playcanvas";
import { CameraControls } from "playcanvas/scripts/esm/camera-controls.mjs";
import type { SimulationWorldManifest } from "../../core/simulation/projects";
export type SimulationViewMode = "visual" | "collision" | "combined";
export type SimulationQuality = "auto" | "low" | "medium" | "high";
export interface SimulationRuntime {
mount(canvas: HTMLCanvasElement): Promise<void>;
loadWorld(manifest: SimulationWorldManifest): Promise<void>;
setViewMode(mode: SimulationViewMode): void;
setQuality(quality: SimulationQuality): void;
focusBounds(): void;
dispose(): void;
}
type CameraController = ScriptType & Pick<CameraControls, "reset" | "focus">;
export class PlayCanvasRuntime implements SimulationRuntime {
private app: Application | null = null;
private canvas: HTMLCanvasElement | null = null;
private camera: Entity | null = null;
private cameraController: CameraController | null = null;
private visualEntity: Entity | null = null;
private visualAsset: Asset | null = null;
private resizeObserver: ResizeObserver | null = null;
private viewMode: SimulationViewMode = "visual";
private quality: SimulationQuality = "auto";
async mount(canvas: HTMLCanvasElement): Promise<void> {
if (this.app) throw new Error("PlayCanvas runtime уже смонтирован.");
this.canvas = canvas;
canvas.tabIndex = 0;
canvas.addEventListener("contextmenu", preventContextMenu);
const app = new Application(canvas, {
graphicsDeviceOptions: {
antialias: true,
alpha: false,
preserveDrawingBuffer: false,
powerPreference: "high-performance",
},
});
this.app = app;
app.scene.ambientLight = new Color(0.35, 0.37, 0.42);
const camera = new Entity("SimulationCamera");
camera.addComponent("camera", {
clearColor: new Color(0.025, 0.03, 0.04),
nearClip: 0.02,
farClip: 20_000,
fov: 58,
});
camera.setPosition(5, 3, 5);
camera.lookAt(0, 0, 0);
camera.addComponent("script");
const controller = camera.script?.create(CameraControls, {
properties: {
enableOrbit: true,
enableFly: true,
focusPoint: new Vec3(0, 0, 0),
zoomRange: new Vec2(0.05, 20_000),
},
}) as CameraController | null;
app.root.addChild(camera);
this.camera = camera;
this.cameraController = controller;
const light = new Entity("SimulationSun");
light.addComponent("light", {
type: "directional",
color: new Color(1, 0.97, 0.9),
intensity: 1.1,
castShadows: false,
});
light.setEulerAngles(42, 28, 0);
app.root.addChild(light);
this.resizeObserver = new ResizeObserver(() => this.resize());
this.resizeObserver.observe(canvas.parentElement ?? canvas);
this.resize();
app.start();
await Promise.resolve();
}
async loadWorld(manifest: SimulationWorldManifest): Promise<void> {
const app = this.requiredApp();
this.unloadWorld();
const sourceUrl = manifest.visual.streamedSogUrl ?? manifest.visual.previewSogUrl;
if (!sourceUrl) throw new Error("World manifest не содержит визуальный SOG.");
const asset = new Asset(`SimulationWorld:${manifest.projectId}`, "gsplat", { url: sourceUrl });
app.assets.add(asset);
this.visualAsset = asset;
await new Promise<void>((resolve, reject) => {
const ready = (loaded: Asset) => {
const visual = new Entity("GaussianWorld");
visual.enabled = false;
app.root.addChild(visual);
visual.addComponent("gsplat", {
asset: loaded,
unified: true,
});
visual.enabled = true;
this.visualEntity = visual;
this.applyQuality();
this.applyViewMode();
this.focusBounds();
resolve();
};
const failed = (error: unknown) => {
reject(new Error(error instanceof Error ? error.message : "PlayCanvas не загрузил SOG."));
};
asset.ready(ready);
asset.once("error", failed);
app.assets.load(asset);
});
}
setViewMode(mode: SimulationViewMode): void {
this.viewMode = mode;
this.applyViewMode();
}
setQuality(quality: SimulationQuality): void {
this.quality = quality;
this.applyQuality();
}
focusBounds(): void {
const bounds = this.visualEntity?.gsplat?.customAabb;
const focus = bounds?.center.clone() ?? new Vec3(0, 0, 0);
const radius = bounds?.halfExtents.length() ?? 3;
const distance = Math.max(1, radius * 2.4);
const position = new Vec3(1, 0.55, 1).normalize().mulScalar(distance).add(focus);
if (this.cameraController) {
this.cameraController.reset(focus, position);
} else if (this.camera) {
this.camera.setPosition(position);
this.camera.lookAt(focus);
}
}
dispose(): void {
this.resizeObserver?.disconnect();
this.resizeObserver = null;
this.unloadWorld();
if (this.app) this.app.destroy();
if (this.canvas) this.canvas.removeEventListener("contextmenu", preventContextMenu);
this.app = null;
this.canvas = null;
this.camera = null;
this.cameraController = null;
}
private requiredApp(): Application {
if (!this.app) throw new Error("PlayCanvas runtime не смонтирован.");
return this.app;
}
private resize(): void {
if (!this.app || !this.canvas) return;
const bounds = this.canvas.parentElement?.getBoundingClientRect();
const width = Math.max(1, Math.round(bounds?.width ?? this.canvas.clientWidth));
const height = Math.max(1, Math.round(bounds?.height ?? this.canvas.clientHeight));
this.app.resizeCanvas(width, height);
}
private applyViewMode(): void {
if (this.visualEntity) {
this.visualEntity.enabled = this.viewMode !== "collision";
}
}
private applyQuality(): void {
const gsplat = this.visualEntity?.gsplat;
if (!gsplat) return;
const profiles: Record<SimulationQuality, [number, number]> = {
auto: [5, 2],
low: [2.5, 1.7],
medium: [5, 2],
high: [9, 2.3],
};
const [baseDistance, multiplier] = profiles[this.quality];
gsplat.lodBaseDistance = baseDistance;
gsplat.lodMultiplier = multiplier;
}
private unloadWorld(): void {
if (this.visualEntity) {
this.visualEntity.destroy();
this.visualEntity = null;
}
if (this.visualAsset && this.app) {
this.app.assets.remove(this.visualAsset);
this.visualAsset.unload();
this.visualAsset = null;
}
}
}
function preventContextMenu(event: Event): void {
event.preventDefault();
}
@@ -0,0 +1,324 @@
import { useEffect, useMemo, useRef, useState, type DragEvent } from "react";
import {
ActivityIndicator,
Button,
FieldFrame,
Icon,
Select,
TextField,
Window,
WindowFooterActions,
} from "@nodedc/ui-react";
import {
createAndUploadSimulationProject,
updateSimulationProject,
type SimulationProject,
type SimulationSceneType,
type SimulationUploadCandidate,
type SimulationUploadProgress,
} from "../../core/simulation/projects";
export function SimulationProjectWindow({
open,
project,
onClose,
onSaved,
}: {
open: boolean;
project: SimulationProject | null;
onClose: () => void;
onSaved: (project: SimulationProject) => void;
}) {
const archiveInput = useRef<HTMLInputElement>(null);
const folderInput = useRef<HTMLInputElement>(null);
const [name, setName] = useState("");
const [sceneType, setSceneType] = useState<SimulationSceneType>("outdoor");
const [candidates, setCandidates] = useState<SimulationUploadCandidate[]>([]);
const [dragging, setDragging] = useState(false);
const [pending, setPending] = useState(false);
const [progress, setProgress] = useState<SimulationUploadProgress | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!open) return;
setName(project?.name ?? "");
setSceneType(project?.sceneType ?? "outdoor");
setCandidates([]);
setProgress(null);
setPending(false);
setError(null);
}, [open, project]);
const sourceSummary = useMemo(() => summarizeCandidates(candidates), [candidates]);
const canSubmit = name.trim().length > 0 && (project !== null || candidates.length > 0) && !pending;
const acceptCandidates = (next: SimulationUploadCandidate[]) => {
try {
validateCandidates(next);
setCandidates(next);
setError(null);
if (!name.trim() && next.length) {
const named = next.find((candidate) => /\.lcc2?$/i.test(candidate.logicalPath)) ?? next[0];
const first = named?.logicalPath.split("/").filter(Boolean).at(-1) ?? "Новая сцена";
setName(first.replace(/\.(lcc2?|zip|rar|7z)$/i, ""));
}
} catch (caught) {
setCandidates([]);
setError(caught instanceof Error ? caught.message : "Источник не принят.");
}
};
const submit = async () => {
if (!canSubmit) return;
setPending(true);
setError(null);
try {
const saved = project
? await updateSimulationProject(project.projectId, name, sceneType)
: await createAndUploadSimulationProject(
name,
sceneType,
candidates,
setProgress,
);
onSaved(saved);
} catch (caught) {
setError(caught instanceof Error ? caught.message : "Не удалось сохранить проект.");
setPending(false);
}
};
const handleDrop = async (event: DragEvent<HTMLDivElement>) => {
event.preventDefault();
setDragging(false);
try {
acceptCandidates(await candidatesFromDrop(event.dataTransfer));
} catch (caught) {
setError(caught instanceof Error ? caught.message : "Не удалось прочитать источник.");
}
};
return (
<Window
open={open}
title={project ? "Редактировать проект" : "Новый проект симуляции"}
subtitle={project ? "Метаданные сцены" : "LCC/LCC2 folder или ZIP/RAR/7z"}
size="md"
closeOnBackdrop={!pending}
closeOnEscape={!pending}
onClose={onClose}
footer={(
<>
<span className="simulation-project-window__footer-state">
{pending ? <><ActivityIndicator /><span>{project ? "Сохраняем" : "Загружаем источник"}</span></> : null}
</span>
<WindowFooterActions>
<Button disabled={pending} onClick={onClose}>Отмена</Button>
<Button variant="primary" disabled={!canSubmit} onClick={() => void submit()}>
{project ? "Сохранить" : "Создать и запустить"}
</Button>
</WindowFooterActions>
</>
)}
>
<div className="simulation-project-window">
<TextField
label="Название"
value={name}
maxLength={120}
disabled={pending}
autoComplete="off"
onChange={(event) => setName(event.currentTarget.value)}
/>
<FieldFrame label="Тип сцены" description="Сохраняется как профиль будущей физики и навигации.">
<Select
label="Тип сцены"
value={sceneType}
disabled={pending}
onChange={(value) => setSceneType(value)}
options={[
{ value: "outdoor", label: "Улица" },
{ value: "interior", label: "Интерьер" },
{ value: "object", label: "Отдельный объект" },
]}
/>
</FieldFrame>
{!project ? (
<FieldFrame
label="Исходник"
description="Имя родительской папки не фиксировано. Внутри должна быть ровно одна сцена LCC или LCC2."
>
<div
className="simulation-source-drop"
data-dragging={dragging ? "true" : undefined}
onDragEnter={(event) => { event.preventDefault(); setDragging(true); }}
onDragOver={(event) => event.preventDefault()}
onDragLeave={(event) => {
if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setDragging(false);
}}
onDrop={(event) => void handleDrop(event)}
>
<Icon name={candidates.length ? "check" : "upload"} size={20} />
<strong>{sourceSummary.title}</strong>
<span>{sourceSummary.detail}</span>
<div>
<Button
size="compact"
icon={<Icon name="file" size={16} />}
disabled={pending}
onClick={() => archiveInput.current?.click()}
>
Выбрать архив
</Button>
<Button
size="compact"
icon={<Icon name="folder" size={16} />}
disabled={pending}
onClick={() => folderInput.current?.click()}
>
Выбрать папку
</Button>
</div>
<input
ref={archiveInput}
type="file"
accept=".zip,.rar,.7z"
hidden
onChange={(event) => {
const file = event.currentTarget.files?.[0];
if (file) acceptCandidates([{ file, logicalPath: file.name }]);
event.currentTarget.value = "";
}}
/>
<input
ref={folderInput}
type="file"
hidden
multiple
{...({ webkitdirectory: "" } as Record<string, string>)}
onChange={(event) => {
const next = Array.from(event.currentTarget.files ?? []).map((file) => ({
file,
logicalPath: file.webkitRelativePath || file.name,
}));
if (next.length) acceptCandidates(next);
event.currentTarget.value = "";
}}
/>
</div>
</FieldFrame>
) : null}
{progress ? (
<div className="simulation-upload-progress" role="status">
<span><i style={{ width: `${Math.min(100, progress.totalBytes ? progress.uploadedBytes / progress.totalBytes * 100 : 0)}%` }} /></span>
<div>
<strong>{formatBytes(progress.uploadedBytes)} / {formatBytes(progress.totalBytes)}</strong>
<small>{progress.currentPath}</small>
</div>
</div>
) : null}
{error ? <p className="simulation-project-window__error" role="alert">{error}</p> : null}
</div>
</Window>
);
}
interface LegacyFileEntry {
isFile: boolean;
isDirectory: boolean;
name: string;
fullPath: string;
file?: (callback: (file: File) => void, error?: (error: DOMException) => void) => void;
createReader?: () => {
readEntries: (
callback: (entries: LegacyFileEntry[]) => void,
error?: (error: DOMException) => void,
) => void;
};
}
async function candidatesFromDrop(transfer: DataTransfer): Promise<SimulationUploadCandidate[]> {
const candidates: SimulationUploadCandidate[] = [];
for (const item of Array.from(transfer.items)) {
const entry = (item as DataTransferItem & {
webkitGetAsEntry?: () => LegacyFileEntry | null;
}).webkitGetAsEntry?.();
if (entry) {
await collectEntry(entry, candidates);
continue;
}
const file = item.getAsFile();
if (file) candidates.push({ file, logicalPath: file.name });
}
if (!candidates.length) {
for (const file of Array.from(transfer.files)) {
candidates.push({ file, logicalPath: file.name });
}
}
return candidates;
}
async function collectEntry(entry: LegacyFileEntry, target: SimulationUploadCandidate[]): Promise<void> {
if (entry.isFile && entry.file) {
const file = await new Promise<File>((resolve, reject) => entry.file?.(resolve, reject));
target.push({ file, logicalPath: entry.fullPath.replace(/^\//, "") || file.name });
return;
}
if (!entry.isDirectory || !entry.createReader) return;
const reader = entry.createReader();
while (true) {
const batch = await new Promise<LegacyFileEntry[]>((resolve, reject) => reader.readEntries(resolve, reject));
if (!batch.length) break;
for (const child of batch) await collectEntry(child, target);
}
}
function validateCandidates(candidates: SimulationUploadCandidate[]): void {
if (!candidates.length) throw new Error("Выберите архив или папку с результатом LCC/LCC2.");
const archives = candidates.filter((candidate) => /\.(zip|rar|7z)$/i.test(candidate.logicalPath));
if (archives.length) {
if (candidates.length !== 1) throw new Error("Архив нужно загружать одним файлом.");
return;
}
const descriptors = candidates.filter((candidate) => /\.lcc2?$/i.test(candidate.logicalPath));
if (descriptors.length !== 1) {
throw new Error("В папке должна быть ровно одна сцена .lcc или .lcc2.");
}
const paths = new Set<string>();
for (const candidate of candidates) {
const parts = candidate.logicalPath.split("/");
if (
!candidate.logicalPath ||
candidate.logicalPath.startsWith("/") ||
candidate.logicalPath.includes("\\") ||
candidate.logicalPath.includes("\0") ||
parts.some((part) => part === "" || part === "." || part === "..")
) {
throw new Error("Папка содержит небезопасный путь.");
}
if (candidate.file.size <= 0) throw new Error(`Пустой файл: ${candidate.logicalPath}`);
if (paths.has(candidate.logicalPath)) throw new Error(`Повторяющийся путь: ${candidate.logicalPath}`);
paths.add(candidate.logicalPath);
}
}
function summarizeCandidates(candidates: SimulationUploadCandidate[]): { title: string; detail: string } {
if (!candidates.length) return {
title: "Перетащите архив или папку сюда",
detail: "ZIP, RAR, 7z либо parent folder с LCC/LCC2",
};
const total = candidates.reduce((sum, candidate) => sum + candidate.file.size, 0);
const archive = candidates.length === 1 && /\.(zip|rar|7z)$/i.test(candidates[0]?.logicalPath ?? "");
return {
title: archive ? candidates[0]?.logicalPath ?? "Архив" : "Папка принята",
detail: `${candidates.length.toLocaleString("ru-RU")} файл(ов) · ${formatBytes(total)}`,
};
}
function formatBytes(value: number): string {
if (value < 1024) return `${value} Б`;
if (value < 1024 ** 2) return `${(value / 1024).toLocaleString("ru-RU", { maximumFractionDigits: 1 })} КБ`;
if (value < 1024 ** 3) return `${(value / 1024 ** 2).toLocaleString("ru-RU", { maximumFractionDigits: 1 })} МБ`;
return `${(value / 1024 ** 3).toLocaleString("ru-RU", { maximumFractionDigits: 2 })} ГБ`;
}
@@ -0,0 +1,105 @@
import { useEffect, useRef, useState } from "react";
import { ActivityIndicator, Button, SegmentedControl, StatusBadge } from "@nodedc/ui-react";
import type { SimulationProject } from "../../core/simulation/projects";
import {
PlayCanvasRuntime,
type SimulationQuality,
type SimulationViewMode,
} from "./PlayCanvasRuntime";
export function SimulationViewport({ project }: { project: SimulationProject }) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const runtimeRef = useRef<PlayCanvasRuntime | null>(null);
const [state, setState] = useState<"mounting" | "loading" | "ready" | "failed">("mounting");
const [error, setError] = useState<string | null>(null);
const [viewMode, setViewMode] = useState<SimulationViewMode>("visual");
const [quality, setQuality] = useState<SimulationQuality>("auto");
useEffect(() => {
const canvas = canvasRef.current;
const manifest = project.worldManifest;
if (!canvas || !manifest) return;
const runtime = new PlayCanvasRuntime();
runtimeRef.current = runtime;
let cancelled = false;
setState("mounting");
setError(null);
void runtime.mount(canvas).then(async () => {
if (cancelled) return;
setState("loading");
await runtime.loadWorld(manifest);
if (!cancelled) setState("ready");
}).catch((caught: unknown) => {
if (cancelled) return;
setState("failed");
setError(caught instanceof Error ? caught.message : "Не удалось открыть сцену.");
});
return () => {
cancelled = true;
runtime.dispose();
runtimeRef.current = null;
};
}, [project.projectId, project.worldManifest]);
const collisionAvailable = project.worldManifest?.collision.available ?? false;
return (
<section className="simulation-viewport" aria-label={`Сцена ${project.name}`}>
<header className="simulation-viewport__toolbar">
<div>
<StatusBadge tone={state === "ready" ? "success" : state === "failed" ? "warning" : "accent"}>
{state === "ready" ? "Runtime готов" : state === "failed" ? "Ошибка runtime" : "Загрузка сцены"}
</StatusBadge>
<span>PlayCanvas Engine 2.21.4</span>
</div>
<SegmentedControl
label="Слой сцены"
value={viewMode}
onChange={(next) => {
setViewMode(next);
runtimeRef.current?.setViewMode(next);
}}
items={[
{ value: "visual", label: "Визуал" },
{ value: "collision", label: "Коллизии", disabled: !collisionAvailable },
{ value: "combined", label: "Вместе", disabled: !collisionAvailable },
]}
/>
<SegmentedControl
label="Качество Streamed SOG"
value={quality}
onChange={(next) => {
setQuality(next);
runtimeRef.current?.setQuality(next);
}}
items={[
{ value: "auto", label: "Auto" },
{ value: "low", label: "Low" },
{ value: "medium", label: "Med" },
{ value: "high", label: "High" },
]}
/>
<Button size="compact" variant="secondary" onClick={() => runtimeRef.current?.focusBounds()}>
Вписать сцену
</Button>
</header>
<div className="simulation-viewport__stage">
<canvas ref={canvasRef} aria-label={`PlayCanvas сцена ${project.name}`} />
{state !== "ready" ? (
<div className="simulation-viewport__state" role={state === "failed" ? "alert" : "status"}>
{state === "failed" ? null : <ActivityIndicator label="Загрузка сцены" />}
<strong>{state === "failed" ? "Сцена не открылась" : "PlayCanvas загружает мир"}</strong>
<p>{error ?? "Streamed SOG догружается по мере готовности runtime."}</p>
</div>
) : null}
</div>
{!collisionAvailable ? (
<footer className="simulation-viewport__notice">
<StatusBadge tone="warning">Collision недоступен</StatusBadge>
<span>Worker 006 сейчас работает в CPU-режиме; визуальный слой настоящий, collision GLB не подменяется.</span>
</footer>
) : null}
</section>
);
}