feat: 集成Rust WASM渲染引擎与TypeScript ECS框架 (#228)

* feat: 集成Rust WASM渲染引擎与TypeScript ECS框架

* feat: 增强编辑器UI功能与跨平台支持

* fix: 修复CI测试和类型检查问题

* fix: 修复CI问题并提高测试覆盖率

* fix: 修复CI问题并提高测试覆盖率
This commit is contained in:
YHH
2025-11-21 10:03:18 +08:00
committed by GitHub
parent 8b9616837d
commit a768b890fd
107 changed files with 10221 additions and 477 deletions

View File

@@ -1,29 +1,37 @@
import { useState, useEffect } from 'react';
import { Entity, Core } from '@esengine/ecs-framework';
import { EntityStoreService, MessageHub, SceneManagerService } from '@esengine/editor-core';
import { EntityStoreService, MessageHub, SceneManagerService, CommandManager } from '@esengine/editor-core';
import { useLocale } from '../hooks/useLocale';
import { Box, Layers, Wifi, Search, Plus, Trash2 } from 'lucide-react';
import { Box, Layers, Wifi, Search, Plus, Trash2, Monitor, Globe } from 'lucide-react';
import { ProfilerService, RemoteEntity } from '../services/ProfilerService';
import { confirm } from '@tauri-apps/plugin-dialog';
import { CreateEntityCommand, DeleteEntityCommand } from '../application/commands/entity';
import '../styles/SceneHierarchy.css';
type ViewMode = 'local' | 'remote';
interface SceneHierarchyProps {
entityStore: EntityStoreService;
messageHub: MessageHub;
commandManager: CommandManager;
}
export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps) {
export function SceneHierarchy({ entityStore, messageHub, commandManager }: SceneHierarchyProps) {
const [entities, setEntities] = useState<Entity[]>([]);
const [remoteEntities, setRemoteEntities] = useState<RemoteEntity[]>([]);
const [isRemoteConnected, setIsRemoteConnected] = useState(false);
const [viewMode, setViewMode] = useState<ViewMode>('local');
const [selectedId, setSelectedId] = useState<number | null>(null);
const [searchQuery, setSearchQuery] = useState('');
const [sceneName, setSceneName] = useState<string>('Untitled');
const [remoteSceneName, setRemoteSceneName] = useState<string | null>(null);
const [sceneFilePath, setSceneFilePath] = useState<string | null>(null);
const [isSceneModified, setIsSceneModified] = useState<boolean>(false);
const [contextMenu, setContextMenu] = useState<{ x: number; y: number; entityId: number | null } | null>(null);
const { t, locale } = useLocale();
const isShowingRemote = viewMode === 'remote' && isRemoteConnected;
// Subscribe to scene changes
useEffect(() => {
const sceneManager = Core.services.resolve(SceneManagerService);
@@ -182,14 +190,15 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
};
const handleCreateEntity = () => {
const scene = Core.scene;
if (!scene) return;
const entityCount = entityStore.getAllEntities().length;
const entityName = `Entity ${entityCount + 1}`;
const entity = scene.createEntity(entityName);
entityStore.addEntity(entity);
entityStore.selectEntity(entity);
const command = new CreateEntityCommand(
entityStore,
messageHub,
entityName
);
commandManager.execute(command);
};
const handleDeleteEntity = async () => {
@@ -200,8 +209,8 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
const confirmed = await confirm(
locale === 'zh'
? `确定要删除实体 "${entity.name}" 吗?此操作无法撤销。`
: `Are you sure you want to delete entity "${entity.name}"? This action cannot be undone.`,
? `确定要删除实体 "${entity.name}" 吗?`
: `Are you sure you want to delete entity "${entity.name}"?`,
{
title: locale === 'zh' ? '删除实体' : 'Delete Entity',
kind: 'warning'
@@ -209,22 +218,44 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
);
if (confirmed) {
entity.destroy();
entityStore.removeEntity(entity);
const command = new DeleteEntityCommand(
entityStore,
messageHub,
entity
);
commandManager.execute(command);
}
};
const handleContextMenu = (e: React.MouseEvent, entityId: number | null) => {
e.preventDefault();
setContextMenu({ x: e.clientX, y: e.clientY, entityId });
};
const closeContextMenu = () => {
setContextMenu(null);
};
// Close context menu on click outside
useEffect(() => {
const handleClick = () => closeContextMenu();
if (contextMenu) {
window.addEventListener('click', handleClick);
return () => window.removeEventListener('click', handleClick);
}
}, [contextMenu]);
// Listen for Delete key
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Delete' && selectedId && !isRemoteConnected) {
if (e.key === 'Delete' && selectedId && !isShowingRemote) {
handleDeleteEntity();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [selectedId, isRemoteConnected]);
}, [selectedId, isShowingRemote]);
// Filter entities based on search query
const filterRemoteEntities = (entityList: RemoteEntity[]): RemoteEntity[] => {
@@ -262,11 +293,11 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
};
// Determine which entities to display
const displayEntities = isRemoteConnected
const displayEntities = isShowingRemote
? filterRemoteEntities(remoteEntities)
: filterLocalEntities(entities);
const showRemoteIndicator = isRemoteConnected && remoteEntities.length > 0;
const displaySceneName = isRemoteConnected && remoteSceneName ? remoteSceneName : sceneName;
const showRemoteIndicator = isShowingRemote && remoteEntities.length > 0;
const displaySceneName = isShowingRemote && remoteSceneName ? remoteSceneName : sceneName;
return (
<div className="scene-hierarchy">
@@ -282,6 +313,24 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
{displaySceneName}{!isRemoteConnected && isSceneModified ? '*' : ''}
</span>
</div>
{isRemoteConnected && (
<div className="view-mode-toggle">
<button
className={`mode-btn ${viewMode === 'local' ? 'active' : ''}`}
onClick={() => setViewMode('local')}
title={locale === 'zh' ? '本地场景' : 'Local Scene'}
>
<Monitor size={14} />
</button>
<button
className={`mode-btn ${viewMode === 'remote' ? 'active' : ''}`}
onClick={() => setViewMode('remote')}
title={locale === 'zh' ? '远程实体' : 'Remote Entities'}
>
<Globe size={14} />
</button>
</div>
)}
{showRemoteIndicator && (
<div className="remote-indicator" title="Showing remote entities">
<Wifi size={12} />
@@ -297,18 +346,17 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div>
{!isRemoteConnected && (
{!isShowingRemote && (
<div className="hierarchy-toolbar">
<button
className="toolbar-btn"
className="toolbar-btn icon-only"
onClick={handleCreateEntity}
title={locale === 'zh' ? '创建实体' : 'Create Entity'}
>
<Plus size={14} />
<span>{locale === 'zh' ? '创建实体' : 'Create Entity'}</span>
</button>
<button
className="toolbar-btn"
className="toolbar-btn icon-only"
onClick={handleDeleteEntity}
disabled={!selectedId}
title={locale === 'zh' ? '删除实体' : 'Delete Entity'}
@@ -317,18 +365,18 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
</button>
</div>
)}
<div className="hierarchy-content scrollable">
<div className="hierarchy-content scrollable" onContextMenu={(e) => !isShowingRemote && handleContextMenu(e, null)}>
{displayEntities.length === 0 ? (
<div className="empty-state">
<Box size={48} strokeWidth={1.5} className="empty-icon" />
<div className="empty-title">{t('hierarchy.empty')}</div>
<div className="empty-hint">
{isRemoteConnected
{isShowingRemote
? 'No entities in remote game'
: 'Create an entity to get started'}
</div>
</div>
) : isRemoteConnected ? (
) : isShowingRemote ? (
<ul className="entity-list">
{(displayEntities as RemoteEntity[]).map((entity) => (
<li
@@ -357,14 +405,45 @@ export function SceneHierarchy({ entityStore, messageHub }: SceneHierarchyProps)
key={entity.id}
className={`entity-item ${selectedId === entity.id ? 'selected' : ''}`}
onClick={() => handleEntityClick(entity)}
onContextMenu={(e) => {
e.stopPropagation();
handleEntityClick(entity);
handleContextMenu(e, entity.id);
}}
>
<Box size={14} className="entity-icon" />
<span className="entity-name">Entity {entity.id}</span>
<span className="entity-name">{entity.name || `Entity ${entity.id}`}</span>
</li>
))}
</ul>
)}
</div>
{contextMenu && !isShowingRemote && (
<div
className="context-menu"
style={{
position: 'fixed',
left: contextMenu.x,
top: contextMenu.y,
zIndex: 1000
}}
>
<button onClick={() => { handleCreateEntity(); closeContextMenu(); }}>
<Plus size={12} />
<span>{locale === 'zh' ? '创建实体' : 'Create Entity'}</span>
</button>
{contextMenu.entityId && (
<>
<div className="context-menu-divider" />
<button onClick={() => { handleDeleteEntity(); closeContextMenu(); }}>
<Trash2 size={12} />
<span>{locale === 'zh' ? '删除实体' : 'Delete Entity'}</span>
</button>
</>
)}
</div>
)}
</div>
);
}

View File

@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import { Play, Pause, RotateCcw, Maximize2, Grid3x3, Eye, EyeOff, Activity, Box, Square } from 'lucide-react';
import { Play, Pause, RotateCcw, Maximize2, Grid3x3, Eye, EyeOff, Activity, Box, Square, Zap } from 'lucide-react';
import '../styles/Viewport.css';
import { useEngine } from '../hooks/useEngine';
interface ViewportProps {
locale?: string;
@@ -14,6 +15,11 @@ export function Viewport({ locale = 'en' }: ViewportProps) {
const [showGizmos, setShowGizmos] = useState(true);
const [showStats, setShowStats] = useState(false);
const [is3D, setIs3D] = useState(true);
const [useRustEngine, setUseRustEngine] = useState(false);
// Rust engine hook (only active in 2D mode with engine enabled)
// Rust引擎钩子仅在2D模式且启用引擎时激活
const engine = useEngine('viewport-canvas', useRustEngine && !is3D);
const animationFrameRef = useRef<number>();
const glRef = useRef<WebGLRenderingContext | null>(null);
const gridProgramRef = useRef<WebGLProgram | null>(null);
@@ -573,7 +579,17 @@ export function Viewport({ locale = 'en' }: ViewportProps) {
};
const handlePlayPause = () => {
setIsPlaying(!isPlaying);
const newPlaying = !isPlaying;
setIsPlaying(newPlaying);
// Control Rust engine if active | 控制Rust引擎如果激活
if (useRustEngine && !is3D && engine.state.initialized) {
if (newPlaying) {
engine.start();
} else {
engine.stop();
}
}
};
const handleReset = () => {
@@ -634,6 +650,15 @@ export function Viewport({ locale = 'en' }: ViewportProps) {
>
{is3D ? <Box size={16} /> : <Square size={16} />}
</button>
{!is3D && (
<button
className={`viewport-btn ${useRustEngine ? 'active' : ''}`}
onClick={() => setUseRustEngine(!useRustEngine)}
title={locale === 'zh' ? 'Rust引擎' : 'Rust Engine'}
>
<Zap size={16} />
</button>
)}
</div>
<div className="viewport-toolbar-right">
<button
@@ -652,17 +677,33 @@ export function Viewport({ locale = 'en' }: ViewportProps) {
</button>
</div>
</div>
<canvas ref={canvasRef} className="viewport-canvas" />
<canvas ref={canvasRef} id="viewport-canvas" className="viewport-canvas" />
{showStats && (
<div className="viewport-stats">
<div className="viewport-stat">
<span className="viewport-stat-label">FPS:</span>
<span className="viewport-stat-value">{fps}</span>
<span className="viewport-stat-value">
{useRustEngine && !is3D ? engine.state.fps : fps}
</span>
</div>
<div className="viewport-stat">
<span className="viewport-stat-label">Draw Calls:</span>
<span className="viewport-stat-value">{drawCalls}</span>
<span className="viewport-stat-value">
{useRustEngine && !is3D ? engine.state.drawCalls : drawCalls}
</span>
</div>
{useRustEngine && !is3D && (
<div className="viewport-stat">
<span className="viewport-stat-label">Sprites:</span>
<span className="viewport-stat-value">{engine.state.spriteCount}</span>
</div>
)}
{useRustEngine && !is3D && engine.state.error && (
<div className="viewport-stat viewport-stat-error">
<span className="viewport-stat-label">Error:</span>
<span className="viewport-stat-value">{engine.state.error}</span>
</div>
)}
</div>
)}
</div>

View File

@@ -12,7 +12,7 @@ import {
EntityInspector
} from './views';
export function Inspector({ entityStore: _entityStore, messageHub, inspectorRegistry, projectPath }: InspectorProps) {
export function Inspector({ entityStore: _entityStore, messageHub, inspectorRegistry, projectPath, commandManager }: InspectorProps) {
const [target, setTarget] = useState<InspectorTarget>(null);
const [componentVersion, setComponentVersion] = useState(0);
const [autoRefresh, setAutoRefresh] = useState(true);
@@ -196,7 +196,7 @@ export function Inspector({ entityStore: _entityStore, messageHub, inspectorRegi
}
if (target.type === 'entity') {
return <EntityInspector entity={target.data} messageHub={messageHub} componentVersion={componentVersion} />;
return <EntityInspector entity={target.data} messageHub={messageHub} commandManager={commandManager} componentVersion={componentVersion} />;
}
return null;

View File

@@ -1,11 +1,12 @@
import { Entity } from '@esengine/ecs-framework';
import { EntityStoreService, MessageHub, InspectorRegistry } from '@esengine/editor-core';
import { EntityStoreService, MessageHub, InspectorRegistry, CommandManager } from '@esengine/editor-core';
export interface InspectorProps {
entityStore: EntityStoreService;
messageHub: MessageHub;
inspectorRegistry: InspectorRegistry;
projectPath?: string | null;
commandManager: CommandManager;
}
export interface AssetFileInfo {

View File

@@ -1,18 +1,24 @@
import { useState } from 'react';
import { Settings, ChevronDown, ChevronRight, X } from 'lucide-react';
import { Entity, Component } from '@esengine/ecs-framework';
import { MessageHub } from '@esengine/editor-core';
import { Settings, ChevronDown, ChevronRight, X, Plus } from 'lucide-react';
import { Entity, Component, Core } from '@esengine/ecs-framework';
import { MessageHub, CommandManager, ComponentRegistry } from '@esengine/editor-core';
import { PropertyInspector } from '../../PropertyInspector';
import { RemoveComponentCommand, UpdateComponentCommand, AddComponentCommand } from '../../../application/commands/component';
import '../../../styles/EntityInspector.css';
interface EntityInspectorProps {
entity: Entity;
messageHub: MessageHub;
commandManager: CommandManager;
componentVersion: number;
}
export function EntityInspector({ entity, messageHub, componentVersion }: EntityInspectorProps) {
export function EntityInspector({ entity, messageHub, commandManager, componentVersion }: EntityInspectorProps) {
const [expandedComponents, setExpandedComponents] = useState<Set<number>>(new Set());
const [showComponentMenu, setShowComponentMenu] = useState(false);
const componentRegistry = Core.services.resolve(ComponentRegistry);
const availableComponents = componentRegistry?.getAllComponents() || [];
const toggleComponentExpanded = (index: number) => {
setExpandedComponents((prev) => {
@@ -26,21 +32,33 @@ export function EntityInspector({ entity, messageHub, componentVersion }: Entity
});
};
const handleAddComponent = (ComponentClass: new () => Component) => {
const command = new AddComponentCommand(messageHub, entity, ComponentClass);
commandManager.execute(command);
setShowComponentMenu(false);
};
const handleRemoveComponent = (index: number) => {
const component = entity.components[index];
if (component) {
entity.removeComponent(component);
messageHub.publish('component:removed', { entity, component });
const command = new RemoveComponentCommand(
messageHub,
entity,
component
);
commandManager.execute(command);
}
};
const handlePropertyChange = (component: Component, propertyName: string, value: unknown) => {
messageHub.publish('component:property:changed', {
const command = new UpdateComponentCommand(
messageHub,
entity,
component,
propertyName,
value
});
);
commandManager.execute(command);
};
return (
@@ -63,10 +81,77 @@ export function EntityInspector({ entity, messageHub, componentVersion }: Entity
</div>
</div>
{entity.components.length > 0 && (
<div className="inspector-section">
<div className="section-title"></div>
{entity.components.map((component: Component, index: number) => {
<div className="inspector-section">
<div className="section-title" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<span></span>
<div style={{ position: 'relative' }}>
<button
onClick={() => setShowComponentMenu(!showComponentMenu)}
style={{
background: 'transparent',
border: '1px solid #4a4a4a',
borderRadius: '4px',
color: '#e0e0e0',
cursor: 'pointer',
padding: '2px 6px',
display: 'flex',
alignItems: 'center',
gap: '4px',
fontSize: '11px'
}}
>
<Plus size={12} />
</button>
{showComponentMenu && (
<div
style={{
position: 'absolute',
top: '100%',
right: 0,
marginTop: '4px',
backgroundColor: '#2a2a2a',
border: '1px solid #4a4a4a',
borderRadius: '4px',
boxShadow: '0 4px 12px rgba(0,0,0,0.3)',
zIndex: 1000,
minWidth: '150px',
maxHeight: '200px',
overflowY: 'auto'
}}
>
{availableComponents.length === 0 ? (
<div style={{ padding: '8px 12px', color: '#888', fontSize: '11px' }}>
</div>
) : (
availableComponents.map((info) => (
<button
key={info.name}
onClick={() => info.type && handleAddComponent(info.type)}
style={{
display: 'block',
width: '100%',
padding: '6px 12px',
background: 'transparent',
border: 'none',
color: '#e0e0e0',
fontSize: '12px',
textAlign: 'left',
cursor: 'pointer'
}}
onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = '#3a3a3a')}
onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = 'transparent')}
>
{info.name}
</button>
))
)}
</div>
)}
</div>
</div>
{entity.components.map((component: Component, index: number) => {
const isExpanded = expandedComponents.has(index);
const componentName = component.constructor?.name || 'Component';
@@ -140,8 +225,7 @@ export function EntityInspector({ entity, messageHub, componentVersion }: Entity
</div>
);
})}
</div>
)}
</div>
</div>
</div>
);