Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

refactor: migrate to EditorContext and GizmoManager

esengine6f936d0313d7
diff --git a/editor/src/asset/AssetLoader.ts b/editor/src/asset/AssetLoader.ts
index d3aee5f95..ab5ad9880 100644
--- a/editor/src/asset/AssetLoader.ts
+++ b/editor/src/asset/AssetLoader.ts
@@ -5,6 +5,7 @@
import type { ESEngineModule } from 'esengine';
import type { AssetPathResolver } from './AssetPathResolver';
+import { getEditorContext } from '../context/EditorContext';
interface DecodedImage {
width: number;
@@ -241,7 +242,7 @@ export class AssetLoader {
}
private getNativeFS(): NativeFS | null {
- return (window as any).__esengine_fs ?? null;
+ return getEditorContext().fs ?? null;
}
private getEmscriptenFS(): any {
diff --git a/editor/src/asset/AssetPathResolver.ts b/editor/src/asset/AssetPathResolver.ts
index bf7a0d7a0..cca636dee 100644
--- a/editor/src/asset/AssetPathResolver.ts
+++ b/editor/src/asset/AssetPathResolver.ts
@@ -3,6 +3,8 @@
* @brief Unified path resolution for editor assets
*/
+import { getEditorContext } from '../context/EditorContext';
+
interface NativeFS {
exists(path: string): Promise<boolean>;
readFile(path: string): Promise<string | null>;
@@ -84,6 +86,6 @@ export class AssetPathResolver {
}
private getNativeFS(): NativeFS | null {
- return (window as any).__esengine_fs ?? null;
+ return getEditorContext().fs ?? null;
}
}
diff --git a/editor/src/asset/EditorAssetServer.ts b/editor/src/asset/EditorAssetServer.ts
index 89baf2792..4b93f1ef0 100644
--- a/editor/src/asset/EditorAssetServer.ts
+++ b/editor/src/asset/EditorAssetServer.ts
@@ -11,6 +11,7 @@ import { AssetLoader } from './AssetLoader';
import type { AssetPathResolver } from './AssetPathResolver';
import { parseShaderProperties, getShaderDefaultProperties } from '../shader/ShaderPropertyParser';
import { getAssetEventBus } from '../events/AssetEventBus';
+import { getEditorContext } from '../context/EditorContext';
interface NativeFS {
readFile(path: string): Promise<string | null>;
@@ -265,7 +266,7 @@ export class EditorAssetServer {
}
private getNativeFS(): NativeFS | null {
- return (window as any).__esengine_fs ?? null;
+ return getEditorContext().fs ?? null;
}
// =========================================================================
diff --git a/editor/src/builder/BuildCache.ts b/editor/src/builder/BuildCache.ts
index 1ec21c9e3..389026e9e 100644
--- a/editor/src/builder/BuildCache.ts
+++ b/editor/src/builder/BuildCache.ts
@@ -3,6 +3,9 @@
* @brief Incremental build cache for file change detection
*/
+import type { NativeFS } from '../scripting/types';
+import { getEditorContext } from '../context/EditorContext';
+
// =============================================================================
// Types
// =============================================================================
@@ -51,17 +54,19 @@ async function computeHash(content: string | Uint8Array): Promise<string> {
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}
-async function computeFileHash(fs: NativeFileSystem, filePath: string): Promise<FileHash | null> {
+async function computeFileHash(fs: NativeFS, filePath: string): Promise<FileHash | null> {
try {
const content = await fs.readFile(filePath);
- const stats = await fs.stat(filePath);
+ if (!content) return null;
+
+ const stats = await fs.getFileStats(filePath);
const hash = await computeHash(content);
return {
path: filePath,
hash,
- lastModified: stats.mtimeMs,
- size: stats.size,
+ lastModified: stats?.modified?.getTime() ?? 0,
+ size: stats?.size ?? 0,
};
} catch {
return null;
@@ -74,14 +79,14 @@ async function computeFileHash(fs: NativeFileSystem, filePath: string): Promise<
export class BuildCache {
private projectDir_: string;
- private fs_: NativeFileSystem | null;
+ private fs_: NativeFS | null;
constructor(projectDir: string) {
this.projectDir_ = projectDir;
- this.fs_ = window.__esengine_fs ?? null;
+ this.fs_ = getEditorContext().fs ?? null;
}
- private getFs(): NativeFileSystem {
+ private getFs(): NativeFS {
if (!this.fs_) {
throw new Error('Native file system not available');
}
@@ -103,9 +108,9 @@ export class BuildCache {
try {
const content = await this.fs_.readFile(cachePath);
- const decoder = new TextDecoder();
- const jsonStr = decoder.decode(content);
- const data = JSON.parse(jsonStr) as BuildCacheData;
+ if (!content) return null;
+
+ const data = JSON.parse(content) as BuildCacheData;
if (data.version !== CACHE_VERSION) {
return null;
@@ -122,15 +127,8 @@ export class BuildCache {
const cacheDir = this.getCacheDir();
const cachePath = this.getCachePath(data.configId);
- try {
- await fs.mkdir(cacheDir, { recursive: true });
- } catch {
- // Directory may already exist
- }
-
- const jsonStr = JSON.stringify(data, null, 2);
- const encoder = new TextEncoder();
- await fs.writeFile(cachePath, encoder.encode(jsonStr));
+ await fs.createDirectory(cacheDir);
+ await fs.writeFile(cachePath, JSON.stringify(data, null, 2));
}
async invalidateCache(configId: string): Promise<void> {
@@ -139,7 +137,7 @@ export class BuildCache {
const cachePath = this.getCachePath(configId);
try {
- await this.fs_.unlink(cachePath);
+ await this.fs_.writeFile(cachePath, '');
} catch {
// Cache may not exist
}
@@ -244,10 +242,10 @@ export class BuildCache {
const cacheDir = this.getCacheDir();
try {
- const entries = await this.fs_.readdir(cacheDir);
+ const entries = await this.fs_.listDirectory(cacheDir);
for (const entry of entries) {
if (entry.endsWith('.json')) {
- await this.fs_.unlink(`${cacheDir}/${entry}`);
+ await this.fs_.writeFile(`${cacheDir}/${entry}`, '');
}
}
} catch {
diff --git a/editor/src/builder/BuildConfigIO.ts b/editor/src/builder/BuildConfigIO.ts
index dcc90a76f..57e001efd 100644
--- a/editor/src/builder/BuildConfigIO.ts
+++ b/editor/src/builder/BuildConfigIO.ts
@@ -4,6 +4,7 @@
*/
import { BuildConfig, BuildPlatform } from '../types/BuildTypes';
+import { getEditorContext } from '../context/EditorContext';
// =============================================================================
// Types
@@ -32,10 +33,10 @@ const EXPORT_VERSION = '1.0';
// =============================================================================
export class BuildConfigIO {
- private fs_: NativeFileSystem | null;
+ private fs_: import('../scripting/types').NativeFS | null;
constructor() {
- this.fs_ = window.__esengine_fs ?? null;
+ this.fs_ = getEditorContext().fs ?? null;
}
async exportConfigs(configs: BuildConfig[], outputPath: string): Promise<void> {
@@ -49,9 +50,7 @@ export class BuildConfigIO {
configs: configs.map(config => this.sanitizeConfigForExport(config)),
};
- const jsonStr = JSON.stringify(exportData, null, 2);
- const encoder = new TextEncoder();
- await this.fs_.writeFile(outputPath, encoder.encode(jsonStr));
+ await this.fs_.writeFile(outputPath, JSON.stringify(exportData, null, 2));
}
async importConfigs(filePath: string): Promise<ImportResult> {
@@ -68,9 +67,8 @@ export class BuildConfigIO {
try {
const content = await this.fs_.readFile(filePath);
- const decoder = new TextDecoder();
- const jsonStr = decoder.decode(content);
- const data = JSON.parse(jsonStr);
+ if (!content) throw new Error('Empty file');
+ const data = JSON.parse(content);
if (!this.isValidExportFormat(data)) {
result.errors.push('Invalid export file format');
diff --git a/editor/src/builder/BuildConfigService.ts b/editor/src/builder/BuildConfigService.ts
index f29b8da62..c5f95a518 100644
--- a/editor/src/builder/BuildConfigService.ts
+++ b/editor/src/builder/BuildConfigService.ts
@@ -10,6 +10,7 @@ import {
createDefaultBuildSettings,
createDefaultBuildConfig,
} from '../types/BuildTypes';
+import { getEditorContext } from '../context/EditorContext';
// =============================================================================
// Types
@@ -40,14 +41,14 @@ const LEGACY_STORAGE_KEY = 'esengine_build_settings';
export class BuildConfigService {
private projectDir_: string;
private settings_: BuildSettings;
- private fs_: NativeFileSystem | null;
+ private fs_: import('../scripting/types').NativeFS | null;
private listeners_: Set<ConfigChangeListener>;
private loaded_: boolean;
constructor(projectDir: string) {
this.projectDir_ = projectDir;
this.settings_ = createDefaultBuildSettings();
- this.fs_ = window.__esengine_fs ?? null;
+ this.fs_ = getEditorContext().fs ?? null;
this.listeners_ = new Set();
this.loaded_ = false;
}
@@ -85,9 +86,8 @@ export class BuildConfigService {
try {
const content = await this.fs_.readFile(configPath);
- const decoder = new TextDecoder();
- const jsonStr = decoder.decode(content);
- const file = JSON.parse(jsonStr) as BuildSettingsFile;
+ if (!content) throw new Error('Empty config');
+ const file = JSON.parse(content) as BuildSettingsFile;
if (file.version === CONFIG_VERSION) {
this.settings_ = {
@@ -119,11 +119,7 @@ export class BuildConfigService {
const configDir = this.getConfigDir();
const configPath = this.getConfigPath();
- try {
- await this.fs_.mkdir(configDir, { recursive: true });
- } catch {
- // Directory may already exist
- }
+ await this.fs_.createDirectory(configDir);
const file: BuildSettingsFile = {
version: CONFIG_VERSION,
@@ -132,9 +128,7 @@ export class BuildConfigService {
configs: this.settings_.configs,
};
- const jsonStr = JSON.stringify(file, null, 2);
- const encoder = new TextEncoder();
- await this.fs_.writeFile(configPath, encoder.encode(jsonStr));
+ await this.fs_.writeFile(configPath, JSON.stringify(file, null, 2));
}
async migrateFromLocalStorage(): Promise<boolean> {
diff --git a/editor/src/builder/BuildHistory.ts b/editor/src/builder/BuildHistory.ts
index b8c4de13b..3165f9891 100644
--- a/editor/src/builder/BuildHistory.ts
+++ b/editor/src/builder/BuildHistory.ts
@@ -3,6 +3,8 @@
* @brief Build history tracking and management
*/
+import { getEditorContext } from '../context/EditorContext';
+
// =============================================================================
// Types
// =============================================================================
@@ -44,13 +46,13 @@ const MAX_ENTRIES_PER_CONFIG = 20;
export class BuildHistory {
private projectDir_: string;
private entries_: BuildHistoryEntry[];
- private fs_: NativeFileSystem | null;
+ private fs_: import('../scripting/types').NativeFS | null;
private loaded_: boolean;
constructor(projectDir: string) {
this.projectDir_ = projectDir;
this.entries_ = [];
- this.fs_ = window.__esengine_fs ?? null;
+ this.fs_ = getEditorContext().fs ?? null;
this.loaded_ = false;
}
@@ -72,9 +74,8 @@ export class BuildHistory {
try {
const content = await this.fs_.readFile(historyPath);
- const decoder = new TextDecoder();
- const jsonStr = decoder.decode(content);
- const data = JSON.parse(jsonStr) as BuildHistoryData;
+ if (!content) throw new Error('Empty history');
+ const data = JSON.parse(content) as BuildHistoryData;
if (data.version === HISTORY_VERSION) {
this.entries_ = data.entries;
@@ -92,20 +93,14 @@ export class BuildHistory {
const historyDir = this.getHistoryDir();
const historyPath = this.getHistoryPath();
- try {
- await this.fs_.mkdir(historyDir, { recursive: true });
- } catch {
- // Directory may already exist
- }
+ await this.fs_.createDirectory(historyDir);
const data: BuildHistoryData = {
version: HISTORY_VERSION,
entries: this.entries_,
};
- const jsonStr = JSON.stringify(data, null, 2);
- const encoder = new TextEncoder();
- await this.fs_.writeFile(historyPath, encoder.encode(jsonStr));
+ await this.fs_.writeFile(historyPath, JSON.stringify(data, null, 2));
}
addEntry(entry: Omit<BuildHistoryEntry, 'id'>): BuildHistoryEntry {
diff --git a/editor/src/builder/BuildSettingsDialog.ts b/editor/src/builder/BuildSettingsDialog.ts
index e024989d2..9b96bf0ee 100644
--- a/editor/src/builder/BuildSettingsDialog.ts
+++ b/editor/src/builder/BuildSettingsDialog.ts
@@ -12,6 +12,7 @@ import {
createDefaultBuildConfig,
createDefaultBuildSettings,
} from '../types/BuildTypes';
+import { getEditorContext, getEditorInstance } from '../context/EditorContext';
import { type BuildResult } from './BuildService';
import { showProgressToast, dismissToast, showToast } from '../ui/Toast';
import { BuildHistory, formatBuildTime, formatBuildDuration, getBuildStatusIcon, type BuildHistoryEntry } from './BuildHistory';
@@ -608,7 +609,7 @@ export class BuildSettingsDialog {
case 'add-current-scene':
if (config) {
- const editor = (window as any).__esengine_editor;
+ const editor = getEditorInstance();
const scenePath = editor?.currentScenePath;
if (scenePath) {
const relativePath = this.toRelativePath(scenePath);
@@ -709,7 +710,7 @@ export class BuildSettingsDialog {
}
private async browseFile(inputId: string, title: string, extensions: string[]): Promise<void> {
- const fs = (window as any).__esengine_fs;
+ const fs = getEditorContext().fs;
if (!fs?.showOpenDialog) return;
const result = await fs.showOpenDialog({
@@ -1086,8 +1087,8 @@ export class BuildSettingsDialog {
private async openOutputFolder(outputPath: string): Promise<void> {
try {
const dirPath = outputPath.replace(/\\/g, '/').split('/').slice(0, -1).join('/');
- const fs = (window as any).__esengine_fs;
- if (fs?.openFolder) {
+ const fs = getEditorContext().fs;
+ if (fs) {
await fs.openFolder(dirPath);
}
} catch (err) {
@@ -1097,7 +1098,7 @@ export class BuildSettingsDialog {
private async previewOutput(outputPath: string): Promise<void> {
try {
- const fs = (window as any).__esengine_fs;
+ const fs = getEditorContext().fs;
if (fs?.openFile) {
await fs.openFile(outputPath);
}
diff --git a/editor/src/builder/PlayableBuilder.ts b/editor/src/builder/PlayableBuilder.ts
index b4309656f..5fdb105d4 100644
--- a/editor/src/builder/PlayableBuilder.ts
+++ b/editor/src/builder/PlayableBuilder.ts
@@ -14,6 +14,7 @@ import * as esbuild from 'esbuild-wasm/esm/browser';
import type { BuildResult, BuildContext } from './BuildService';
import { BuildProgressReporter } from './BuildProgress';
import { BuildCache, type BuildCacheData } from './BuildCache';
+import { getEditorContext } from '../context/EditorContext';
// =============================================================================
// Types
@@ -143,7 +144,7 @@ var __STARTUP_SCENE__={{SCENE_DATA}};
export class PlayableBuilder {
constructor(context: BuildContext) {
this.context_ = context;
- this.fs_ = (window as any).__esengine_fs ?? null;
+ this.fs_ = getEditorContext().fs ?? null;
this.projectDir_ = getProjectDir(context.projectPath);
this.progress_ = context.progress || new BuildProgressReporter();
this.cache_ = context.cache || null;
diff --git a/editor/src/builder/WeChatBuilder.ts b/editor/src/builder/WeChatBuilder.ts
index 6d8c251e5..30a4baa94 100644
--- a/editor/src/builder/WeChatBuilder.ts
+++ b/editor/src/builder/WeChatBuilder.ts
@@ -7,6 +7,7 @@ import * as esbuild from 'esbuild-wasm/esm/browser';
import type { BuildResult, BuildContext } from './BuildService';
import { BuildProgressReporter } from './BuildProgress';
import { BuildCache } from './BuildCache';
+import { getEditorContext } from '../context/EditorContext';
// =============================================================================
// Types
@@ -66,7 +67,7 @@ export class WeChatBuilder {
constructor(context: BuildContext) {
this.context_ = context;
- this.fs_ = (window as any).__esengine_fs ?? null;
+ this.fs_ = getEditorContext().fs ?? null;
this.projectDir_ = getProjectDir(context.projectPath);
this.progress_ = context.progress || new BuildProgressReporter();
this.cache_ = context.cache || null;
diff --git a/editor/src/io/SceneSerializer.ts b/editor/src/io/SceneSerializer.ts
index 548ca1803..e1a995e21 100644
--- a/editor/src/io/SceneSerializer.ts
+++ b/editor/src/io/SceneSerializer.ts
@@ -4,6 +4,7 @@
*/
import type { SceneData, EntityData, ComponentData } from '../types/SceneTypes';
+import { getEditorContext } from '../context/EditorContext';
// =============================================================================
// SceneSerializer
@@ -77,7 +78,7 @@ interface NativeFS {
}
function getNativeFS(): NativeFS | null {
- return (window as any).__esengine_fs ?? null;
+ return getEditorContext().fs ?? null;
}
function isNativeApp(): boolean {
diff --git a/editor/src/panels/ContentBrowserPanel.ts b/editor/src/panels/ContentBrowserPanel.ts
index 946cc8f17..4ff1ded50 100644
--- a/editor/src/panels/ContentBrowserPanel.ts
+++ b/editor/src/panels/ContentBrowserPanel.ts
@@ -8,6 +8,7 @@ import { icons } from '../utils/icons';
import { showContextMenu } from '../ui/ContextMenu';
import { getPlatformAdapter } from '../platform/PlatformAdapter';
import { showInputDialog, showConfirmDialog } from '../ui/dialog';
+import { getEditorContext } from '../context/EditorContext';
// =============================================================================
// Types
@@ -63,11 +64,11 @@ export interface ContentBrowserOptions {
// =============================================================================
function getNativeFS(): NativeFS | null {
- return (window as any).__esengine_fs ?? null;
+ return getEditorContext().fs ?? null;
}
function getNativeShell(): NativeShell | null {
- return (window as any).__esengine_shell ?? null;
+ return getEditorContext().shell ?? null;
}
function joinPath(...parts: string[]): string {
diff --git a/editor/src/panels/HierarchyPanel.ts b/editor/src/panels/HierarchyPanel.ts
index 79ba1039d..af4c46350 100644
--- a/editor/src/panels/HierarchyPanel.ts
+++ b/editor/src/panels/HierarchyPanel.ts
@@ -10,6 +10,7 @@ import { icons } from '../utils/icons';
import { getGlobalPathResolver } from '../asset';
import { getDefaultComponentData } from '../schemas/ComponentSchemas';
import { showContextMenu } from '../ui/ContextMenu';
+import { getEditorContext } from '../context/EditorContext';
// =============================================================================
// HierarchyPanel
@@ -247,17 +248,16 @@ export class HierarchyPanel {
const dir = skeletonPath.substring(0, skeletonPath.lastIndexOf('/'));
const absoluteDir = pathResolver.toAbsolutePath(dir);
- const fs = (window as any).__esengine_fs;
- if (!fs?.listDirectoryDetailed) {
+ const fs = getEditorContext().fs;
+ if (!fs) {
return null;
}
try {
const entries = await fs.listDirectoryDetailed(absoluteDir);
const atlasFiles = entries
- .filter((e: { name: string; isFile: boolean }) =>
- e.isFile && e.name.endsWith('.atlas'))
- .map((e: { name: string }) => e.name);
+ .filter(e => e.name.endsWith('.atlas'))
+ .map(e => e.name);
if (atlasFiles.length === 1) {
return dir ? `${dir}/${atlasFiles[0]}` : atlasFiles[0];
diff --git a/editor/src/panels/InspectorPanel.ts b/editor/src/panels/InspectorPanel.ts
index 223f48d6c..9c906eb55 100644
--- a/editor/src/panels/InspectorPanel.ts
+++ b/editor/src/panels/InspectorPanel.ts
@@ -35,6 +35,7 @@ import {
getDefaultPropertyValue,
type ShaderProperty,
} from '../shader/ShaderPropertyParser';
+import { getEditorContext, getEditorInstance } from '../context/EditorContext';
// =============================================================================
// Types
@@ -63,7 +64,7 @@ interface NativeFS {
// =============================================================================
function getNativeFS(): NativeFS | null {
- return (window as any).__esengine_fs ?? null;
+ return getEditorContext().fs ?? null;
}
function getFileName(path: string): string {
@@ -1292,7 +1293,7 @@ export class InspectorPanel {
const openBtn = actionsWrapper.querySelector('.es-btn-open-scene');
openBtn?.addEventListener('click', () => {
- const editor = (window as any).__esengine_editor;
+ const editor = getEditorInstance();
if (editor && typeof editor.openSceneFromPath === 'function') {
editor.openSceneFromPath(path);
}
@@ -1535,21 +1536,21 @@ export class InspectorPanel {
}
private getProjectDir(): string | null {
- const editor = (window as any).__esengine_editor;
+ const editor = getEditorInstance();
const projectPath = editor?.projectPath;
if (!projectPath) return null;
return projectPath.replace(/\\/g, '/').replace(/\/[^/]+$/, '');
}
private navigateToAsset(assetPath: string): void {
- const editor = (window as any).__esengine_editor;
+ const editor = getEditorInstance();
if (editor && typeof editor.navigateToAsset === 'function') {
editor.navigateToAsset(assetPath);
}
}
private getAssetServer(): import('../asset/EditorAssetServer').EditorAssetServer | null {
- const editor = (window as any).__esengine_editor;
+ const editor = getEditorInstance();
return editor?.assetServer ?? null;
}
diff --git a/editor/src/panels/SceneViewPanel.ts b/editor/src/panels/SceneViewPanel.ts
index 9ae3a00f6..28bdb687a 100644
--- a/editor/src/panels/SceneViewPanel.ts
+++ b/editor/src/panels/SceneViewPanel.ts
@@ -13,22 +13,13 @@ import { icons } from '../utils/icons';
import { EditorSceneRenderer } from '../renderer/EditorSceneRenderer';
import { quatToEuler, eulerToQuat } from '../math/Transform';
import { getEntityBounds } from '../bounds';
+import { GizmoManager, getAllGizmos } from '../gizmos';
+import type { GizmoContext } from '../gizmos';
// =============================================================================
// Types
// =============================================================================
-type GizmoMode = 'select' | 'move' | 'rotate' | 'scale' | 'rect';
-type DragAxis = 'none' | 'x' | 'y' | 'xy';
-type RectHandle = 'none' | 'tl' | 'tr' | 'bl' | 'br' | 't' | 'b' | 'l' | 'r';
-
-interface GizmoColors {
- x: string;
- y: string;
- xy: string;
- hover: string;
-}
-
interface GizmoSettings {
showGrid: boolean;
gridColor: string;
@@ -37,16 +28,6 @@ interface GizmoSettings {
showSelectionBox: boolean;
}
-const GIZMO_COLORS: GizmoColors = {
- x: '#e74c3c',
- y: '#2ecc71',
- xy: '#f1c40f',
- hover: '#ffffff',
-};
-
-const GIZMO_SIZE = 80;
-const GIZMO_HANDLE_SIZE = 10;
-
const DEFAULT_GIZMO_SETTINGS: GizmoSettings = {
showGrid: true,
gridColor: '#333333',
@@ -90,21 +71,7 @@ export class SceneViewPanel {
private lastMouseX_ = 0;
private lastMouseY_ = 0;
- private gizmoMode_: GizmoMode = 'move';
- private dragAxis_: DragAxis = 'none';
- private hoveredAxis_: DragAxis = 'none';
- private rectHandle_: RectHandle = 'none';
- private hoveredRectHandle_: RectHandle = 'none';
- private isGizmoDragging_ = false;
- private gizmoDragStartX_ = 0;
- private gizmoDragStartY_ = 0;
- private gizmoDragStartValue_: { x: number; y: number; z: number } = { x: 0, y: 0, z: 0 };
- private gizmoDragOriginalValue_: unknown = null;
- private gizmoDragPropertyName_: string = '';
- private rectDragStartSize_: { x: number; y: number } = { x: 0, y: 0 };
- private rectDragStartPos_: { x: number; y: number } = { x: 0, y: 0 };
- private rectDragOriginalSize_: { x: number; y: number } | null = null;
- private rectDragOriginalPos_: { x: number; y: number; z: number } | null = null;
+ private gizmoManager_: GizmoManager;
private keydownHandler_: ((e: KeyboardEvent) => void) | null = null;
private skipNextClick_ = false;
private boundOnDocumentMouseMove_: ((e: MouseEvent) => void) | null = null;
@@ -118,12 +85,6 @@ export class SceneViewPanel {
private settingsDropdown_: HTMLElement | null = null;
private settingsDropdownClickHandler_: ((e: MouseEvent) => void) | null = null;
- private getSizeComponentType(entityData: import('../types/SceneTypes').EntityData): 'UIRect' | 'Sprite' | null {
- if (entityData.components.some(c => c.type === 'UIRect')) return 'UIRect';
- if (entityData.components.some(c => c.type === 'Sprite')) return 'Sprite';
- return null;
- }
-
private getEntityBoundsWithSpine(entityData: import('../types/SceneTypes').EntityData): { width: number; height: number; offsetX?: number; offsetY?: number } {
const hasSpine = entityData.components.some(c => c.type === 'SpineAnimation');
if (hasSpine && this.sceneRenderer_) {
@@ -145,6 +106,7 @@ export class SceneViewPanel {
this.store_ = store;
this.projectPath_ = options?.projectPath ?? null;
this.app_ = options?.app ?? null;
+ this.gizmoManager_ = new GizmoManager();
this.container_.className = 'es-sceneview-panel';
this.container_.innerHTML = `
@@ -152,11 +114,7 @@ export class SceneViewPanel {
<span class="es-panel-title">Scene</span>
<div class="es-sceneview-tools">
<div class="es-gizmo-toolbar">
- <button class="es-btn es-btn-icon es-gizmo-btn" data-mode="select" title="Select (Q)">${icons.pointer(14)}</button>
- <button class="es-btn es-btn-icon es-gizmo-btn es-active" data-mode="move" title="Move (W)">${icons.move(14)}</button>
- <button class="es-btn es-btn-icon es-gizmo-btn" data-mode="rotate" title="Rotate (E)">${icons.rotateCw(14)}</button>
- <button class="es-btn es-btn-icon es-gizmo-btn" data-mode="scale" title="Scale (R)">${icons.maximize(14)}</button>
- <button class="es-btn es-btn-icon es-gizmo-btn" data-mode="rect" title="Rect (T)">${icons.rect(14)}</button>
+ ${this.buildGizmoToolbarHTML()}
</div>
<div class="es-toolbar-divider"></div>
<button class="es-btn es-btn-icon" data-action="reset-view" title="Reset View">${icons.refresh(14)}</button>
@@ -215,6 +173,15 @@ export class SceneViewPanel {
}
}
+ private buildGizmoToolbarHTML(): string {
+ const gizmos = getAllGizmos();
+ return gizmos.map(g => {
+ const isActive = g.id === this.gizmoManager_.getActiveId();
+ const shortcutLabel = g.shortcut ? ` (${g.shortcut.toUpperCase()})` : '';
+ return `<button class="es-btn es-btn-icon es-gizmo-btn${isActive ? ' es-active' : ''}" data-mode="${g.id}" title="${g.name}${shortcutLabel}">${g.icon}</button>`;
+ }).join('');
+ }
+
dispose(): void {
this.continuousRender_ = false;
if (this.animationId_ !== null) {
@@ -385,6 +352,18 @@ export class SceneViewPanel {
this.requestRender();
}
+ private createGizmoContext(ctx: CanvasRenderingContext2D): GizmoContext {
+ return {
+ store: this.store_,
+ ctx,
+ zoom: this.zoom_,
+ screenToWorld: (clientX, clientY) => this.screenToWorld(clientX, clientY),
+ getWorldTransform: (entityId) => this.store_.getWorldTransform(entityId),
+ getEntityBounds: (entityData) => this.getEntityBoundsWithSpine(entityData),
+ requestRender: () => this.requestRender(),
+ };
+ }
+
private setupEvents(): void {
const resetBtn = this.container_.querySelector('[data-action="reset-view"]');
resetBtn?.addEventListener('click', () => {
@@ -400,7 +379,7 @@ export class SceneViewPanel {
const gizmoButtons = this.container_.querySelectorAll('.es-gizmo-btn');
gizmoButtons.forEach(btn => {
btn.addEventListener('click', () => {
- const mode = (btn as HTMLElement).dataset.mode as GizmoMode;
+ const mode = (btn as HTMLElement).dataset.mode;
if (mode) this.setGizmoMode(mode);
});
});
@@ -409,22 +388,12 @@ export class SceneViewPanel {
if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
return;
}
- switch (e.key.toLowerCase()) {
- case 'q':
- this.setGizmoMode('select');
- break;
- case 'w':
- this.setGizmoMode('move');
- break;
- case 'e':
- this.setGizmoMode('rotate');
- break;
- case 'r':
- this.setGizmoMode('scale');
- break;
- case 't':
- this.setGizmoMode('rect');
- break;
+ const gizmos = getAllGizmos();
+ for (const g of gizmos) {
+ if (g.shortcut && e.key.toLowerCase() === g.shortcut) {
+ this.setGizmoMode(g.id);
+ return;
+ }
}
};
document.addEventListener('keydown', this.keydownHandler_);
@@ -445,8 +414,8 @@ export class SceneViewPanel {
}
}
- private setGizmoMode(mode: GizmoMode): void {
- this.gizmoMode_ = mode;
+ private setGizmoMode(mode: string): void {
+ this.gizmoManager_.setActive(mode);
const buttons = this.container_.querySelectorAll('.es-gizmo-btn');
buttons.forEach(btn => {
const btnMode = (btn as HTMLElement).dataset.mode;
@@ -499,6 +468,13 @@ export class SceneViewPanel {
});
}
+ private updateGizmoContext(): void {
+ const ctx = this.overlayCanvas_?.getContext('2d') ?? this.canvas_.getContext('2d');
+ if (ctx) {
+ this.gizmoManager_.setContext(this.createGizmoContext(ctx));
+ }
+ }
+
private onMouseDown(e: MouseEvent): void {
if (e.button === 1 || (e.button === 0 && e.altKey)) {
this.isDragging_ = true;
@@ -513,64 +489,11 @@ export class SceneViewPanel {
const { worldX, worldY } = this.screenToWorld(e.clientX, e.clientY);
- if (this.gizmoMode_ !== 'select' && this.store_.selectedEntity !== null) {
- if (this.gizmoMode_ === 'rect') {
- const handle = this.hitTestRectGizmo(worldX, worldY);
- if (handle !== 'none') {
- this.isGizmoDragging_ = true;
- this.rectHandle_ = handle;
- this.gizmoDragStartX_ = worldX;
- this.gizmoDragStartY_ = worldY;
-
- const entityData = this.store_.getSelectedEntityData();
- if (entityData) {
- const transform = entityData.components.find(c => c.type === 'LocalTransform');
- const sprite = entityData.components.find(c => c.type === 'Sprite');
-
- const pos = transform?.data.position as { x: number; y: number; z: number } ?? { x: 0, y: 0, z: 0 };
- this.rectDragStartPos_ = { x: pos.x, y: pos.y };
- this.rectDragOriginalPos_ = { ...pos };
-
- if (sprite?.data.size) {
- const size = sprite.data.size as { x: number; y: number };
- this.rectDragStartSize_ = { x: size.x, y: size.y };
- this.rectDragOriginalSize_ = { x: size.x, y: size.y };
- } else {
- const bounds = this.getEntityBoundsWithSpine(entityData);
- this.rectDragStartSize_ = { x: bounds.width, y: bounds.height };
- this.rectDragOriginalSize_ = { x: bounds.width, y: bounds.height };
- }
- }
- this.startDocumentDrag();
- return;
- }
- } else {
- const axis = this.hitTestGizmo(worldX, worldY);
- if (axis !== 'none') {
- this.isGizmoDragging_ = true;
- this.dragAxis_ = axis;
- this.gizmoDragStartX_ = worldX;
- this.gizmoDragStartY_ = worldY;
-
- const entityData = this.store_.getSelectedEntityData();
- const transform = entityData?.components.find(c => c.type === 'LocalTransform');
- if (transform) {
- if (this.gizmoMode_ === 'rotate') {
- const quat = transform.data.rotation as { x: number; y: number; z: number; w: number };
- this.gizmoDragStartValue_ = quatToEuler(quat ?? { x: 0, y: 0, z: 0, w: 1 });
- this.gizmoDragPropertyName_ = 'rotation';
- this.gizmoDragOriginalValue_ = quat ? { ...quat } : { x: 0, y: 0, z: 0, w: 1 };
- } else {
- const prop = this.gizmoMode_ === 'scale' ? 'scale' : 'position';
- const value = transform.data[prop] as { x: number; y: number; z: number };
- this.gizmoDragStartValue_ = { ...value };
- this.gizmoDragPropertyName_ = prop;
- this.gizmoDragOriginalValue_ = { ...value };
- }
- }
- this.startDocumentDrag();
- return;
- }
+ if (this.gizmoManager_.getActiveId() !== 'select' && this.store_.selectedEntity !== null) {
+ this.updateGizmoContext();
+ if (this.gizmoManager_.onMouseDown(worldX, worldY)) {
+ this.startDocumentDrag();
+ return;
}
}
@@ -621,50 +544,16 @@ export class SceneViewPanel {
return;
}
- if (this.isGizmoDragging_) {
- if (this.gizmoMode_ === 'rect') {
- this.handleRectGizmoDrag(worldX, worldY);
- } else {
- this.handleGizmoDrag(worldX, worldY);
- }
+ if (this.gizmoManager_.isDragging()) {
+ this.updateGizmoContext();
+ this.gizmoManager_.onMouseMove(worldX, worldY);
return;
}
- if (this.gizmoMode_ !== 'select' && this.store_.selectedEntity !== null) {
- if (this.gizmoMode_ === 'rect') {
- const handle = this.hitTestRectGizmo(worldX, worldY);
- if (handle !== this.hoveredRectHandle_) {
- this.hoveredRectHandle_ = handle;
- this.canvas_.style.cursor = this.getRectHandleCursor(handle);
- this.requestRender();
- }
- } else {
- const axis = this.hitTestGizmo(worldX, worldY);
- if (axis !== this.hoveredAxis_) {
- this.hoveredAxis_ = axis;
- this.canvas_.style.cursor = axis !== 'none' ? 'pointer' : 'default';
- this.requestRender();
- }
- }
- }
- }
-
- private getRectHandleCursor(handle: RectHandle): string {
- switch (handle) {
- case 'tl':
- case 'br':
- return 'nwse-resize';
- case 'tr':
- case 'bl':
- return 'nesw-resize';
- case 't':
- case 'b':
- return 'ns-resize';
- case 'l':
- case 'r':
- return 'ew-resize';
- default:
- return 'default';
+ if (this.gizmoManager_.getActiveId() !== 'select' && this.store_.selectedEntity !== null) {
+ this.updateGizmoContext();
+ this.gizmoManager_.onMouseMove(worldX, worldY);
+ this.canvas_.style.cursor = this.gizmoManager_.getCursor();
}
}
@@ -675,184 +564,19 @@ export class SceneViewPanel {
this.skipNextClick_ = true;
}
- if (this.isGizmoDragging_) {
- if (this.gizmoMode_ === 'rect') {
- this.commitRectGizmoDrag();
- } else {
- this.commitGizmoDrag();
- }
- this.isGizmoDragging_ = false;
- this.dragAxis_ = 'none';
- this.rectHandle_ = 'none';
+ if (this.gizmoManager_.isDragging()) {
+ const { worldX, worldY } = this.screenToWorld(_e.clientX, _e.clientY);
+ this.updateGizmoContext();
+ this.gizmoManager_.onMouseUp(worldX, worldY);
this.skipNextClick_ = true;
}
}
- private commitGizmoDrag(): void {
- const entity = this.store_.selectedEntity;
- if (entity === null || !this.gizmoDragPropertyName_ || this.gizmoDragOriginalValue_ === null) {
- return;
- }
-
- const entityData = this.store_.getSelectedEntityData();
- const transform = entityData?.components.find(c => c.type === 'LocalTransform');
- if (!transform) return;
-
- const currentValue = transform.data[this.gizmoDragPropertyName_];
- if (!currentValue) return;
-
- const oldValue = this.gizmoDragOriginalValue_;
- const newValue = this.deepClone(currentValue);
-
- if (this.valuesEqual(oldValue, newValue)) {
- return;
- }
-
- this.store_.updateProperty(
- entity,
- 'LocalTransform',
- this.gizmoDragPropertyName_,
- oldValue,
- newValue
- );
-
- this.gizmoDragOriginalValue_ = null;
- this.gizmoDragPropertyName_ = '';
- }
-
- private handleRectGizmoDrag(worldX: number, worldY: number): void {
- const entity = this.store_.selectedEntity;
- if (entity === null) return;
-
- const entityData = this.store_.getSelectedEntityData();
- if (!entityData) return;
-
- const dx = worldX - this.gizmoDragStartX_;
- const dy = worldY - this.gizmoDragStartY_;
-
- let newWidth = this.rectDragStartSize_.x;
- let newHeight = this.rectDragStartSize_.y;
- let newPosX = this.rectDragStartPos_.x;
- let newPosY = this.rectDragStartPos_.y;
-
- switch (this.rectHandle_) {
- case 'r':
- newWidth += dx;
- newPosX += dx / 2;
- break;
- case 'l':
- newWidth -= dx;
- newPosX += dx / 2;
- break;
- case 't':
- newHeight += dy;
- newPosY += dy / 2;
- break;
- case 'b':
- newHeight -= dy;
- newPosY += dy / 2;
- break;
- case 'tr':
- newWidth += dx;
- newHeight += dy;
- newPosX += dx / 2;
- newPosY += dy / 2;
- break;
- case 'tl':
- newWidth -= dx;
- newHeight += dy;
- newPosX += dx / 2;
- newPosY += dy / 2;
- break;
- case 'br':
- newWidth += dx;
- newHeight -= dy;
- newPosX += dx / 2;
- newPosY += dy / 2;
- break;
- case 'bl':
- newWidth -= dx;
- newHeight -= dy;
- newPosX += dx / 2;
- newPosY += dy / 2;
- break;
- }
-
- newWidth = Math.max(1, newWidth);
- newHeight = Math.max(1, newHeight);
-
- const sizeType = this.getSizeComponentType(entityData);
- if (sizeType) {
- this.store_.updatePropertyDirect(entity, sizeType, 'size', { x: newWidth, y: newHeight });
- }
-
- const transform = entityData.components.find(c => c.type === 'LocalTransform');
- if (transform) {
- const pos = transform.data.position as { x: number; y: number; z: number };
- this.store_.updatePropertyDirect(entity, 'LocalTransform', 'position', {
- x: newPosX,
- y: newPosY,
- z: pos?.z ?? 0,
- });
- }
-
- this.requestRender();
- }
-
- private commitRectGizmoDrag(): void {
- const entity = this.store_.selectedEntity;
- if (entity === null) return;
-
- const entityData = this.store_.getSelectedEntityData();
- if (!entityData) return;
-
- const sizeType = this.getSizeComponentType(entityData);
- if (sizeType && this.rectDragOriginalSize_) {
- const comp = entityData.components.find(c => c.type === sizeType)!;
- const currentSize = comp.data.size as { x: number; y: number };
- if (currentSize && !this.valuesEqual(this.rectDragOriginalSize_, currentSize)) {
- this.store_.updateProperty(
- entity,
- sizeType,
- 'size',
- { ...this.rectDragOriginalSize_ },
- { ...currentSize }
- );
- }
- }
-
- const transform = entityData.components.find(c => c.type === 'LocalTransform');
- if (transform && this.rectDragOriginalPos_) {
- const currentPos = transform.data.position as { x: number; y: number; z: number };
- if (currentPos && !this.valuesEqual(this.rectDragOriginalPos_, currentPos)) {
- this.store_.updateProperty(
- entity,
- 'LocalTransform',
- 'position',
- { ...this.rectDragOriginalPos_ },
- { ...currentPos }
- );
- }
- }
-
- this.rectDragOriginalSize_ = null;
- this.rectDragOriginalPos_ = null;
- }
-
- private deepClone<T>(obj: T): T {
- if (obj === null || typeof obj !== 'object') return obj;
- return JSON.parse(JSON.stringify(obj));
- }
-
- private valuesEqual(a: unknown, b: unknown): boolean {
- return JSON.stringify(a) === JSON.stringify(b);
- }
-
private onMouseLeave(_e: MouseEvent): void {
- if (this.isDragging_ || this.isGizmoDragging_) {
+ if (this.isDragging_ || this.gizmoManager_.isDragging()) {
return;
}
- this.hoveredAxis_ = 'none';
+ this.gizmoManager_.resetHover();
this.requestRender();
}
@@ -862,13 +586,14 @@ export class SceneViewPanel {
return;
}
- if (this.isDragging_ || this.isGizmoDragging_) return;
+ if (this.isDragging_ || this.gizmoManager_.isDragging()) return;
const { worldX, worldY } = this.screenToWorld(e.clientX, e.clientY);
- if (this.gizmoMode_ !== 'select' && this.store_.selectedEntity !== null) {
- const axis = this.hitTestGizmo(worldX, worldY);
- if (axis !== 'none') return;
+ if (this.gizmoManager_.getActiveId() !== 'select' && this.store_.selectedEntity !== null) {
+ this.updateGizmoContext();
+ const result = this.gizmoManager_.hitTest(worldX, worldY);
+ if (result.hit) return;
}
const entity = this.findEntityAtPosition(worldX, worldY);
@@ -889,139 +614,6 @@ export class SceneViewPanel {
};
}
- private getSelectedEntityPosition(): { x: number; y: number; z: number } | null {
- const entityData = this.store_.getSelectedEntityData();
- if (!entityData) return null;
-
- return this.store_.getWorldTransform(entityData.id).position;
- }
-
- private hitTestGizmo(worldX: number, worldY: number): DragAxis {
- const pos = this.getSelectedEntityPosition();
- if (!pos) return 'none';
-
- const gizmoScale = GIZMO_SIZE / this.zoom_;
- const handleSize = GIZMO_HANDLE_SIZE / this.zoom_;
-
- const dx = worldX - pos.x;
- const dy = worldY - pos.y;
-
- if (this.gizmoMode_ === 'move' || this.gizmoMode_ === 'scale') {
- if (Math.abs(dx) < handleSize * 2 && Math.abs(dy) < handleSize * 2) {
- return 'xy';
- }
- if (dx > 0 && dx < gizmoScale && Math.abs(dy) < handleSize) {
- return 'x';
- }
- if (dy > 0 && dy < gizmoScale && Math.abs(dx) < handleSize) {
- return 'y';
- }
- } else if (this.gizmoMode_ === 'rotate') {
- const dist = Math.sqrt(dx * dx + dy * dy);
- if (Math.abs(dist - gizmoScale * 0.8) < handleSize * 2) {
- return 'xy';
- }
- }
-
- return 'none';
- }
-
- private hitTestRectGizmo(worldX: number, worldY: number): RectHandle {
- const entityData = this.store_.getSelectedEntityData();
- if (!entityData) return 'none';
-
- const pos = this.getSelectedEntityPosition();
- if (!pos) return 'none';
-
- const worldTransform = this.store_.getWorldTransform(entityData.id);
- const bounds = this.getEntityBoundsWithSpine(entityData);
-
- const w = bounds.width * Math.abs(worldTransform.scale.x);
- const h = bounds.height * Math.abs(worldTransform.scale.y);
- const offsetX = (bounds.offsetX ?? 0) * worldTransform.scale.x;
- const offsetY = (bounds.offsetY ?? 0) * worldTransform.scale.y;
- const halfW = w / 2;
- const halfH = h / 2;
-
- const handleSize = GIZMO_HANDLE_SIZE / this.zoom_;
- const dx = worldX - pos.x - offsetX;
- const dy = worldY - pos.y - offsetY;
-
- const handles: { x: number; y: number; key: RectHandle }[] = [
- { x: -halfW, y: halfH, key: 'tl' },
- { x: halfW, y: halfH, key: 'tr' },
- { x: -halfW, y: -halfH, key: 'bl' },
- { x: halfW, y: -halfH, key: 'br' },
- { x: 0, y: halfH, key: 't' },
- { x: 0, y: -halfH, key: 'b' },
- { x: -halfW, y: 0, key: 'l' },
- { x: halfW, y: 0, key: 'r' },
- ];
-
- for (const handle of handles) {
- if (Math.abs(dx - handle.x) < handleSize * 1.5 &&
- Math.abs(dy - handle.y) < handleSize * 1.5) {
- return handle.key;
- }
- }
-
- return 'none';
- }
-
- private handleGizmoDrag(worldX: number, worldY: number): void {
- const entity = this.store_.selectedEntity;
- if (entity === null) return;
-
- const dx = worldX - this.gizmoDragStartX_;
- const dy = worldY - this.gizmoDragStartY_;
-
- if (this.gizmoMode_ === 'move') {
- let newX = this.gizmoDragStartValue_.x;
- let newY = this.gizmoDragStartValue_.y;
-
- if (this.dragAxis_ === 'x' || this.dragAxis_ === 'xy') {
- newX += dx;
- }
- if (this.dragAxis_ === 'y' || this.dragAxis_ === 'xy') {
- newY += dy;
- }
-
- const newPos = { x: newX, y: newY, z: this.gizmoDragStartValue_.z };
- this.store_.updatePropertyDirect(entity, 'LocalTransform', 'position', newPos);
- } else if (this.gizmoMode_ === 'scale') {
- const scaleFactor = 0.01;
- let newX = this.gizmoDragStartValue_.x;
- let newY = this.gizmoDragStartValue_.y;
-
- if (this.dragAxis_ === 'x' || this.dragAxis_ === 'xy') {
- newX += dx * scaleFactor;
- }
- if (this.dragAxis_ === 'y' || this.dragAxis_ === 'xy') {
- newY += dy * scaleFactor;
- }
-
- const newScale = { x: Math.max(0.01, newX), y: Math.max(0.01, newY), z: this.gizmoDragStartValue_.z };
- this.store_.updatePropertyDirect(entity, 'LocalTransform', 'scale', newScale);
- } else if (this.gizmoMode_ === 'rotate') {
- const pos = this.getSelectedEntityPosition();
- if (!pos) return;
-
- const startAngle = Math.atan2(
- this.gizmoDragStartY_ - pos.y,
- this.gizmoDragStartX_ - pos.x
- );
- const currentAngle = Math.atan2(worldY - pos.y, worldX - pos.x);
- const deltaAngle = (currentAngle - startAngle) * (180 / Math.PI);
-
- const newRotZ = this.gizmoDragStartValue_.z + deltaAngle;
- const euler = { x: 0, y: 0, z: newRotZ };
- const quat = eulerToQuat(euler);
- this.store_.updatePropertyDirect(entity, 'LocalTransform', 'rotation', quat);
- }
-
- this.requestRender();
- }
-
private onWheel(e: WheelEvent): void {
e.preventDefault();
@@ -1160,8 +752,9 @@ export class SceneViewPanel {
this.drawCameraFrustum(ctx);
- if (this.gizmoMode_ !== 'select' && this.gizmoSettings_.showGizmos) {
- this.drawGizmo(ctx);
+ if (this.gizmoManager_.getActiveId() !== 'select' && this.gizmoSettings_.showGizmos) {
+ this.gizmoManager_.setContext(this.createGizmoContext(ctx));
+ this.gizmoManager_.draw();
}
}
@@ -1239,7 +832,7 @@ export class SceneViewPanel {
ctx.save();
ctx.translate(pos.x, -pos.y);
- if (projectionType === 1) { // 1 = Orthographic
+ if (projectionType === 1) {
const halfHeight = orthoSize;
const halfWidth = halfHeight * aspectRatio;
@@ -1292,172 +885,15 @@ export class SceneViewPanel {
if (selectedEntity !== null) {
this.drawCameraFrustum(ctx);
- if (this.gizmoMode_ !== 'select' && this.gizmoSettings_.showGizmos) {
- this.drawGizmo(ctx);
+ if (this.gizmoManager_.getActiveId() !== 'select' && this.gizmoSettings_.showGizmos) {
+ this.gizmoManager_.setContext(this.createGizmoContext(ctx));
+ this.gizmoManager_.draw();
}
}
ctx.restore();
}
- private drawGizmo(ctx: CanvasRenderingContext2D): void {
- const pos = this.getSelectedEntityPosition();
- if (!pos) return;
-
- ctx.save();
- ctx.translate(pos.x, -pos.y);
-
- const size = GIZMO_SIZE / this.zoom_;
- const lineWidth = 2 / this.zoom_;
- const handleSize = GIZMO_HANDLE_SIZE / this.zoom_;
- const arrowSize = 8 / this.zoom_;
-
- if (this.gizmoMode_ === 'move') {
- ctx.fillStyle = this.hoveredAxis_ === 'xy' ? GIZMO_COLORS.hover : GIZMO_COLORS.xy;
- ctx.fillRect(-handleSize, -handleSize, handleSize * 2, handleSize * 2);
-
- ctx.strokeStyle = this.hoveredAxis_ === 'x' ? GIZMO_COLORS.hover : GIZMO_COLORS.x;
- ctx.lineWidth = lineWidth;
- ctx.beginPath();
- ctx.moveTo(0, 0);
- ctx.lineTo(size, 0);
- ctx.stroke();
-
- ctx.fillStyle = this.hoveredAxis_ === 'x' ? GIZMO_COLORS.hover : GIZMO_COLORS.x;
- ctx.beginPath();
- ctx.moveTo(size, 0);
- ctx.lineTo(size - arrowSize, -arrowSize / 2);
- ctx.lineTo(size - arrowSize, arrowSize / 2);
- ctx.closePath();
- ctx.fill();
-
- ctx.strokeStyle = this.hoveredAxis_ === 'y' ? GIZMO_COLORS.hover : GIZMO_COLORS.y;
- ctx.beginPath();
- ctx.moveTo(0, 0);
- ctx.lineTo(0, -size);
- ctx.stroke();
-
- ctx.fillStyle = this.hoveredAxis_ === 'y' ? GIZMO_COLORS.hover : GIZMO_COLORS.y;
- ctx.beginPath();
- ctx.moveTo(0, -size);
- ctx.lineTo(-arrowSize / 2, -size + arrowSize);
- ctx.lineTo(arrowSize / 2, -size + arrowSize);
- ctx.closePath();
- ctx.fill();
- } else if (this.gizmoMode_ === 'rotate') {
- const radius = size * 0.8;
-
- const entityData = this.store_.getSelectedEntityData();
- const transform = entityData?.components.find(c => c.type === 'LocalTransform');
- const quat = transform?.data.rotation as { x: number; y: number; z: number; w: number } ?? { x: 0, y: 0, z: 0, w: 1 };
- const euler = quatToEuler(quat);
- const angleRad = -euler.z * Math.PI / 180;
-
- ctx.strokeStyle = 'rgba(100, 100, 100, 0.5)';
- ctx.lineWidth = lineWidth;
- ctx.beginPath();
- ctx.moveTo(0, 0);
- ctx.lineTo(radius, 0);
- ctx.stroke();
-
- ctx.strokeStyle = this.hoveredAxis_ === 'xy' ? GIZMO_COLORS.hover : GIZMO_COLORS.xy;
- ctx.lineWidth = lineWidth * 1.5;
- ctx.beginPath();
- ctx.arc(0, 0, radius, 0, Math.PI * 2);
- ctx.stroke();
-
- ctx.strokeStyle = '#00aaff';
- ctx.lineWidth = lineWidth * 2;
- ctx.beginPath();
- ctx.moveTo(0, 0);
- ctx.lineTo(Math.cos(angleRad) * radius, Math.sin(angleRad) * radius);
- ctx.stroke();
-
- ctx.fillStyle = '#00aaff';
- ctx.beginPath();
- ctx.arc(Math.cos(angleRad) * radius, Math.sin(angleRad) * radius, handleSize, 0, Math.PI * 2);
- ctx.fill();
- } else if (this.gizmoMode_ === 'scale') {
- ctx.fillStyle = this.hoveredAxis_ === 'xy' ? GIZMO_COLORS.hover : GIZMO_COLORS.xy;
- ctx.fillRect(-handleSize, -handleSize, handleSize * 2, handleSize * 2);
-
- ctx.strokeStyle = this.hoveredAxis_ === 'x' ? GIZMO_COLORS.hover : GIZMO_COLORS.x;
- ctx.lineWidth = lineWidth;
- ctx.beginPath();
- ctx.moveTo(0, 0);
- ctx.lineTo(size, 0);
- ctx.stroke();
-
- ctx.fillStyle = this.hoveredAxis_ === 'x' ? GIZMO_COLORS.hover : GIZMO_COLORS.x;
- ctx.fillRect(size - handleSize, -handleSize, handleSize * 2, handleSize * 2);
-
- ctx.strokeStyle = this.hoveredAxis_ === 'y' ? GIZMO_COLORS.hover : GIZMO_COLORS.y;
- ctx.beginPath();
- ctx.moveTo(0, 0);
- ctx.lineTo(0, -size);
- ctx.stroke();
-
- ctx.fillStyle = this.hoveredAxis_ === 'y' ? GIZMO_COLORS.hover : GIZMO_COLORS.y;
- ctx.fillRect(-handleSize, -size - handleSize, handleSize * 2, handleSize * 2);
- } else if (this.gizmoMode_ === 'rect') {
- this.drawRectGizmo(ctx, handleSize, lineWidth);
- }
-
- ctx.restore();
- }
-
- private drawRectGizmo(ctx: CanvasRenderingContext2D, handleSize: number, lineWidth: number): void {
- const entityData = this.store_.getSelectedEntityData();
- if (!entityData) return;
-
- const worldTransform = this.store_.getWorldTransform(entityData.id);
- const bounds = this.getEntityBoundsWithSpine(entityData);
-
- const w = bounds.width * Math.abs(worldTransform.scale.x);
- const h = bounds.height * Math.abs(worldTransform.scale.y);
- const halfW = w / 2;
- const halfH = h / 2;
-
- ctx.strokeStyle = GIZMO_COLORS.xy;
- ctx.lineWidth = lineWidth;
- ctx.setLineDash([5 / this.zoom_, 5 / this.zoom_]);
- ctx.strokeRect(-halfW, -halfH, w, h);
- ctx.setLineDash([]);
-
- const handles: { x: number; y: number; key: RectHandle }[] = [
- { x: -halfW, y: -halfH, key: 'tl' },
- { x: halfW, y: -halfH, key: 'tr' },
- { x: -halfW, y: halfH, key: 'bl' },
- { x: halfW, y: halfH, key: 'br' },
- { x: 0, y: -halfH, key: 't' },
- { x: 0, y: halfH, key: 'b' },
- { x: -halfW, y: 0, key: 'l' },
- { x: halfW, y: 0, key: 'r' },
- ];
-
- for (const handle of handles) {
- const isHovered = this.hoveredRectHandle_ === handle.key;
- const isCorner = ['tl', 'tr', 'bl', 'br'].includes(handle.key);
-
- ctx.fillStyle = isHovered ? GIZMO_COLORS.hover : (isCorner ? GIZMO_COLORS.xy : GIZMO_COLORS.x);
- ctx.fillRect(
- handle.x - handleSize,
- handle.y - handleSize,
- handleSize * 2,
- handleSize * 2
- );
-
- ctx.strokeStyle = '#000';
- ctx.lineWidth = 1 / this.zoom_;
- ctx.strokeRect(
- handle.x - handleSize,
- handle.y - handleSize,
- handleSize * 2,
- handleSize * 2
- );
- }
- }
-
private drawGrid(ctx: CanvasRenderingContext2D, w: number, h: number): void {
if (!this.gizmoSettings_.showGrid) return;
diff --git a/editor/src/preview/PreviewService.ts b/editor/src/preview/PreviewService.ts
index 98b993f51..d73affc7b 100644
--- a/editor/src/preview/PreviewService.ts
+++ b/editor/src/preview/PreviewService.ts
@@ -7,6 +7,7 @@ import type { SceneData } from '../types/SceneTypes';
import type { NativeFS } from '../scripting/types';
import type { TextureMetadata } from '../types/TextureMetadata';
import { getMetaFilePath, parseTextureMetadata } from '../types/TextureMetadata';
+import { getEditorContext } from '../context/EditorContext';
// =============================================================================
// Types
@@ -147,10 +148,10 @@ export class PreviewService {
}
private getNativeFS(): NativeFS | null {
- return (window as any).__esengine_fs ?? null;
+ return getEditorContext().fs ?? null;
}
private getTauriInvoke(): TauriInvoke | null {
- return (window as any).__esengine_invoke ?? null;
+ return getEditorContext().invoke ?? null;
}
}
diff --git a/editor/src/property/editors.ts b/editor/src/property/editors.ts
index 5dd8f3bd5..78e81f0cd 100644
--- a/editor/src/property/editors.ts
+++ b/editor/src/property/editors.ts
@@ -8,6 +8,7 @@ import {
type PropertyEditorContext,
type PropertyEditorInstance,
} from './PropertyEditor';
+import { getEditorContext, getEditorInstance } from '../context/EditorContext';
import { getPlatformAdapter } from '../platform/PlatformAdapter';
// =============================================================================
@@ -658,11 +659,11 @@ interface NativeFS {
}
function getNativeFS(): NativeFS | null {
- return (window as any).__esengine_fs ?? null;
+ return getEditorContext().fs ?? null;
}
function getProjectDir(): string | null {
- const editor = (window as any).__esengine_editor;
+ const editor = getEditorInstance();
const projectPath = editor?.projectPath;
if (!projectPath) return null;
return projectPath.replace(/\\/g, '/').replace(/\/[^/]+$/, '');
@@ -755,7 +756,7 @@ function createTextureEditor(
const texturePath = input.value;
if (!texturePath) return;
- const editor = (window as any).__esengine_editor;
+ const editor = getEditorInstance();
if (editor?.navigateToAsset) {
await editor.navigateToAsset(texturePath);
}
@@ -1256,7 +1257,7 @@ function createSpineSkinEditor(
// =============================================================================
function navigateToAsset(assetPath: string): void {
- const editor = (window as any).__esengine_editor;
+ const editor = getEditorInstance();
if (editor && typeof editor.navigateToAsset === 'function') {
editor.navigateToAsset(assetPath);
}
diff --git a/editor/src/property/materialEditors.ts b/editor/src/property/materialEditors.ts
index e1ce18eb8..130b6327c 100644
--- a/editor/src/property/materialEditors.ts
+++ b/editor/src/property/materialEditors.ts
@@ -10,20 +10,21 @@ import {
} from './PropertyEditor';
import { BLEND_MODE_OPTIONS } from '../types/MaterialMetadata';
import { getPlatformAdapter } from '../platform/PlatformAdapter';
+import { getEditorContext, getEditorInstance } from '../context/EditorContext';
// =============================================================================
// Helpers
// =============================================================================
function getProjectDir(): string | null {
- const editor = (window as any).__esengine_editor;
+ const editor = getEditorInstance();
const projectPath = editor?.projectPath;
if (!projectPath) return null;
return projectPath.replace(/\\/g, '/').replace(/\/[^/]+$/, '');
}
function navigateToAsset(assetPath: string): void {
- const editor = (window as any).__esengine_editor;
+ const editor = getEditorInstance();
if (editor && typeof editor.navigateToAsset === 'function') {
editor.navigateToAsset(assetPath);
}
@@ -187,7 +188,7 @@ interface NativeFS {
}
function getNativeFS(): NativeFS | null {
- return (window as any).__esengine_fs ?? null;
+ return getEditorContext().fs ?? null;
}
function getMimeType(path: string): string {
diff --git a/editor/src/renderer/EditorTextureManager.ts b/editor/src/renderer/EditorTextureManager.ts
index 98c1e2151..88b2599a0 100644
--- a/editor/src/renderer/EditorTextureManager.ts
+++ b/editor/src/renderer/EditorTextureManager.ts
@@ -6,6 +6,7 @@
import type { ESEngineModule } from 'esengine';
import { parseTextureMetadata, getMetaFilePath } from '../types/TextureMetadata';
import type { AssetPathResolver } from '../asset';
+import { getEditorContext } from '../context/EditorContext';
// =============================================================================
// Types
@@ -214,6 +215,6 @@ export class EditorTextureManager {
}
private getNativeFS(): NativeFS | null {
- return (window as any).__esengine_fs ?? null;
+ return getEditorContext().fs ?? null;
}
}
diff --git a/editor/src/scripting/ScriptLoader.ts b/editor/src/scripting/ScriptLoader.ts
index 72d4dbaca..7bc9cb873 100644
--- a/editor/src/scripting/ScriptLoader.ts
+++ b/editor/src/scripting/ScriptLoader.ts
@@ -6,6 +6,7 @@
import * as esbuild from 'esbuild-wasm/esm/browser';
import { virtualFsPlugin } from './esbuildPlugins';
import type { NativeFS, ScriptLoaderOptions, CompileError } from './types';
+import { getEditorContext } from '../context/EditorContext';
// =============================================================================
// Path Utilities
@@ -30,7 +31,7 @@ function getProjectDir(projectPath: string): string {
// =============================================================================
function getNativeFS(): NativeFS | null {
- return (window as any).__esengine_fs ?? null;
+ return getEditorContext().fs ?? null;
}
// =============================================================================
diff --git a/editor/src/sdk/SdkExportService.ts b/editor/src/sdk/SdkExportService.ts
index 72a5c5df7..7aa594704 100644
--- a/editor/src/sdk/SdkExportService.ts
+++ b/editor/src/sdk/SdkExportService.ts
@@ -4,6 +4,7 @@
*/
import { SDK_VERSION } from '../types/ProjectTypes';
+import { getEditorContext } from '../context/EditorContext';
// =============================================================================
// Native FS Interface
@@ -21,7 +22,7 @@ interface NativeFS {
}
function getNativeFS(): NativeFS | null {
- return (window as any).__esengine_fs ?? null;
+ return getEditorContext().fs ?? null;
}
// =============================================================================
diff --git a/editor/src/types/globals.d.ts b/editor/src/types/globals.d.ts
index fa8a8d3f2..68769facc 100644
--- a/editor/src/types/globals.d.ts
+++ b/editor/src/types/globals.d.ts
@@ -41,12 +41,3 @@ interface NativeFileSystem {
getEngineWxgameWasm(): Promise<Uint8Array>;
getSdkWechatJs(): Promise<string>;
}
-
-interface EditorGlobals {
- currentScenePath?: string;
-}
-
-interface Window {
- __esengine_fs?: NativeFileSystem;
- __esengine_editor?: EditorGlobals;
-}