autosave fixes

This commit is contained in:
azykov@mail.ru 2026-06-02 20:07:42 +03:00
parent 9145277681
commit 8bc56a433d
No known key found for this signature in database
2 changed files with 33 additions and 27 deletions

View File

@ -59,6 +59,7 @@ export const ObjectView = observer(function ({ object }: ObjectViewProps) {
}
<group
ref={groupRef}
name={`${object.id} (${object.typeId} instance)`}
position={object.position}
rotation={object.rotation}
scale={object.scale}
@ -70,7 +71,11 @@ export const ObjectView = observer(function ({ object }: ObjectViewProps) {
const color = (v.color ?? vt?.color) ?? 'white';
const opacity = (v.opacity ?? vt?.opacity) ?? 1;
return (
<mesh key={idx} position={v.position}>
<mesh
key={idx}
name={`voxel ${idx} [${v.position}]`}
position={v.position}
>
<boxGeometry args={[1, 1, 1]} />
<meshStandardMaterial
color={color}

View File

@ -1,5 +1,4 @@
import { makeAutoObservable, reaction, toJS } from "mobx";
import { deepObserve } from "mobx-utils";
import { WorldFactory } from "../model/worldFactory";
import type { ObjectType, World } from "../types";
import type { VoxelType } from "../types/voxel";
@ -11,29 +10,29 @@ import { clone } from "../utils";
export class WorldState {
public data: World = WorldFactory.create();
private saveTimer: ReturnType<typeof setTimeout> | undefined;
private startAutoSave() {
return reaction(() => toJS(this.data), (data) => this.saveData(data), { delay: 500 });
}
private withoutAutoSave(fn: () => void) {
this._stopAutoSave();
fn();
this._stopAutoSave = this.startAutoSave();
}
private _stopAutoSave: () => void = () => { };
constructor() {
makeAutoObservable(this);
this.setupAutoSave();
}
private setupAutoSave() {
let disposeDeep: (() => void) | undefined;
reaction(
() => this.data,
(data) => {
disposeDeep?.();
disposeDeep = deepObserve(data, () => this.save());
},
{ fireImmediately: true },
);
this._stopAutoSave = this.startAutoSave();
}
public reset() {
console.log('Resetting world...');
this.withoutAutoSave(() => {
this.data = WorldFactory.create();
});
state.worldEditor.resetSelectedObject();
}
@ -83,20 +82,22 @@ export class WorldState {
public load() {
console.log('Loading world...');
this.withoutAutoSave(() => {
this.data = WorldFactory.load() ?? WorldFactory.create();
});
state.worldEditor.resetSelectedObject();
}
public save(): void {
private saveData(data: World): void {
console.log('Saving world...');
console.log((new Error('').stack!));
const { objectTypes, voxelTypes, ...debug } = toJS(this.data);
console.log(JSON.stringify(debug, undefined, 4));
// debounce
clearTimeout(this.saveTimer);
this.saveTimer = setTimeout(() => {
const stack = new Error('Saving world...').stack!.split('\n').slice(1);
const { objectTypes, voxelTypes, ...debug } = toJS(data);
console.dir({ stack, debug });
WorldFactory.save(toJS(this.data));
}, 500);
}
public save(): void {
this.saveData(this.data);
}
public getObjectTypeById(id: string): ObjectType | undefined {