feat: 纹理路径稳定 ID 与架构改进 (#305)

* feat(asset-system): 实现路径稳定 ID 生成器

使用 FNV-1a hash 算法为纹理生成稳定的运行时 ID:
- 新增 _pathIdCache 静态缓存,跨 Play/Stop 循环保持稳定
- 新增 getStableIdForPath() 方法,相同路径永远返回相同 ID
- 修改 loadTextureForComponent/loadTextureByGuid 使用稳定 ID
- clearTextureMappings() 不再清除 _pathIdCache

这解决了 Play/Stop 后纹理 ID 失效的根本问题。

* fix(runtime-core): 移除 Play/Stop 循环中的 clearTextureMappings 调用

使用路径稳定 ID 后,不再需要在快照保存/恢复时清除纹理缓存:
- saveSceneSnapshot() 移除 clearTextureMappings() 调用
- restoreSceneSnapshot() 移除 clearTextureMappings() 调用
- 组件保存的 textureId 在 Play/Stop 后仍然有效

* fix(editor-core): 修复场景切换时的资源泄漏

在 openScene() 加载新场景前先卸载旧场景资源:
- 调用 sceneResourceManager.unloadSceneResources() 释放旧资源
- 使用引用计数机制,仅卸载不再被引用的资源
- 路径稳定 ID 缓存不受影响,保持 ID 稳定性

* fix(runtime-core): 修复 PluginManager 组件注册类型错误

将 ComponentRegistry 类改为 GlobalComponentRegistry 实例:
- registerComponents() 期望 IComponentRegistry 接口实例
- GlobalComponentRegistry 是 ComponentRegistry 的全局实例

* refactor(core): 提取 IComponentRegistry 接口

将组件注册表抽象为接口,支持场景级组件注册:
- 新增 IComponentRegistry 接口定义
- Scene 持有独立的 componentRegistry 实例
- 支持从 GlobalComponentRegistry 克隆
- 各系统支持传入自定义注册表

* refactor(engine-core): 改进插件服务注册机制

- 更新 IComponentRegistry 类型引用
- 优化 PluginServiceRegistry 服务管理

* refactor(modules): 适配新的组件注册接口

更新各模块 RuntimeModule 使用 IComponentRegistry 接口:
- audio, behavior-tree, camera
- sprite, tilemap, world-streaming

* fix(physics-rapier2d): 修复物理插件组件注册

- PhysicsEditorPlugin 添加 runtimeModule 引用
- 适配 IComponentRegistry 接口
- 修复物理组件在场景加载时未注册的问题

* feat(editor-core): 添加 UserCodeService 就绪信号机制

- 新增 waitForReady()/signalReady() API
- 支持等待用户脚本编译完成
- 解决场景加载时组件未注册的时序问题

* fix(editor-app): 在编译完成后调用 signalReady()

确保用户脚本编译完成后发出就绪信号:
- 编译成功后调用 userCodeService.signalReady()
- 编译失败也要发出信号,避免阻塞场景加载

* feat(editor-core): 改进编辑器核心服务

- EntityStoreService 添加调试日志
- AssetRegistryService 优化资产注册
- PluginManager 改进插件管理
- IFileAPI 添加 getFileMtime 接口

* feat(engine): 改进 Rust 纹理管理器

- 支持任意 ID 的纹理加载(非递增)
- 添加纹理状态追踪 API
- 优化纹理缓存清理机制
- 更新 TypeScript 绑定

* feat(ui): 添加场景切换和文本闪烁组件

新增组件:
- SceneLoadTriggerComponent: 场景切换触发器
- TextBlinkComponent: 文本闪烁效果

新增系统:
- SceneLoadTriggerSystem: 处理场景切换逻辑
- TextBlinkSystem: 处理文本闪烁动画

其他改进:
- UIRuntimeModule 适配新组件注册接口
- UI 渲染系统优化

* feat(editor-app): 添加外部文件修改检测

- 新增 ExternalModificationDialog 组件
- TauriFileAPI 支持 getFileMtime
- 场景文件被外部修改时提示用户

* feat(editor-app): 添加渲染调试面板

- 新增 RenderDebugService 和调试面板 UI
- App/ContentBrowser 添加调试日志
- TitleBar/Viewport 优化
- DialogManager 改进

* refactor(editor-app): 编辑器服务和组件优化

- EngineService 改进引擎集成
- EditorEngineSync 同步优化
- AssetFileInspector 改进
- VectorFieldEditors 优化
- InstantiatePrefabCommand 改进

* feat(i18n): 更新国际化翻译

- 添加新功能相关翻译
- 更新中文、英文、西班牙文

* feat(tauri): 添加文件修改时间查询命令

- 新增 get_file_mtime 命令
- 支持检测文件外部修改

* refactor(particle): 粒子系统改进

- 适配新的组件注册接口
- ParticleSystem 优化
- 添加单元测试

* refactor(platform): 平台适配层优化

- BrowserRuntime 改进
- 新增 RuntimeSceneManager 服务
- 导出优化

* refactor(asset-system-editor): 资产元数据改进

- AssetMetaFile 优化
- 导出调整

* fix(asset-system): 移除未使用的 TextureLoader 导入

* fix(tests): 更新测试以使用 GlobalComponentRegistry 实例

修复多个测试文件以适配 ComponentRegistry 从静态类变为实例类的变更:
- ComponentStorage.test.ts: 使用 GlobalComponentRegistry.reset()
- EntitySerializer.test.ts: 使用 GlobalComponentRegistry 实例
- IncrementalSerialization.test.ts: 使用 GlobalComponentRegistry 实例
- SceneSerializer.test.ts: 使用 GlobalComponentRegistry 实例
- ComponentRegistry.extended.test.ts: 使用 GlobalComponentRegistry,同时注册到 scene.componentRegistry
- SystemTypes.test.ts: 在 Scene 创建前注册组件
- QuerySystem.test.ts: mockScene 添加 componentRegistry
This commit is contained in:
YHH
2025-12-16 12:46:14 +08:00
committed by GitHub
parent d834ca5e77
commit ed8f6e283b
107 changed files with 7399 additions and 847 deletions

View File

@@ -1,4 +1,4 @@
import type { ComponentRegistry as ComponentRegistryType, IScene } from '@esengine/ecs-framework';
import type { IComponentRegistry, IScene } from '@esengine/ecs-framework';
import type { IRuntimeModule, IRuntimePlugin, ModuleManifest, SystemContext } from '@esengine/engine-core';
import { TransformTypeToken, CanvasElementToken } from '@esengine/engine-core';
import { AssetManagerToken } from '@esengine/asset-system';
@@ -20,7 +20,7 @@ class ParticleRuntimeModule implements IRuntimeModule {
private _updateSystem: ParticleUpdateSystem | null = null;
private _loaderRegistered = false;
registerComponents(registry: typeof ComponentRegistryType): void {
registerComponents(registry: IComponentRegistry): void {
registry.register(ParticleSystemComponent);
registry.register(ClickFxComponent);
}
@@ -73,13 +73,10 @@ class ParticleRuntimeModule implements IRuntimeModule {
scene.addSystem(this._updateSystem);
// 添加点击特效系统 | Add click FX system
// ClickFxSystem 不再需要 AssetManager资产由 ParticleUpdateSystem 统一加载
// ClickFxSystem no longer needs AssetManager, assets are loaded by ParticleUpdateSystem
const clickFxSystem = new ClickFxSystem();
// 设置资产管理器 | Set asset manager
if (assetManager) {
clickFxSystem.setAssetManager(assetManager);
}
// 设置 EngineBridge用于屏幕坐标转世界坐标
// Set EngineBridge (for screen to world coordinate conversion)
if (engineBridge) {

View File

@@ -9,6 +9,7 @@ import { SizeOverLifetimeModule } from './modules/SizeOverLifetimeModule';
import { CollisionModule, BoundaryType, CollisionBehavior } from './modules/CollisionModule';
import { ForceFieldModule, ForceFieldType, type ForceField } from './modules/ForceFieldModule';
import { Physics2DCollisionModule } from './modules/Physics2DCollisionModule';
import { TextureSheetAnimationModule, AnimationPlayMode, AnimationLoopMode } from './modules/TextureSheetAnimationModule';
import type { IParticleAsset, IBurstConfig } from './loaders/ParticleLoader';
// Re-export for backward compatibility
@@ -828,6 +829,42 @@ export class ParticleSystemComponent extends Component implements ISortable {
this._modules.push(forceModule);
break;
}
case 'TextureSheetAnimation': {
// 纹理图集动画模块 | Texture sheet animation module
const textureModule = new TextureSheetAnimationModule();
// moduleConfig 直接包含属性(非 params 嵌套)
// moduleConfig contains properties directly (not nested in params)
const cfg = moduleConfig as unknown as Record<string, unknown>;
textureModule.enabled = true;
if (cfg.tilesX !== undefined) textureModule.tilesX = cfg.tilesX as number;
if (cfg.tilesY !== undefined) textureModule.tilesY = cfg.tilesY as number;
if (cfg.totalFrames !== undefined) textureModule.totalFrames = cfg.totalFrames as number;
if (cfg.startFrame !== undefined) textureModule.startFrame = cfg.startFrame as number;
if (cfg.frameRate !== undefined) textureModule.frameRate = cfg.frameRate as number;
if (cfg.speedMultiplier !== undefined) textureModule.speedMultiplier = cfg.speedMultiplier as number;
if (cfg.cycleCount !== undefined) textureModule.cycleCount = cfg.cycleCount as number;
// 播放模式 | Play mode
if (cfg.playMode !== undefined) {
const playModeMap: Record<string, AnimationPlayMode> = {
'lifetimeLoop': AnimationPlayMode.LifetimeLoop,
'fixedFps': AnimationPlayMode.FixedFPS,
'random': AnimationPlayMode.Random,
'speedBased': AnimationPlayMode.SpeedBased,
};
textureModule.playMode = playModeMap[cfg.playMode as string] ?? AnimationPlayMode.LifetimeLoop;
}
// 循环模式 | Loop mode
if (cfg.loopMode !== undefined) {
const loopModeMap: Record<string, AnimationLoopMode> = {
'once': AnimationLoopMode.Once,
'loop': AnimationLoopMode.Loop,
'pingPong': AnimationLoopMode.PingPong,
};
textureModule.loopMode = loopModeMap[cfg.loopMode as string] ?? AnimationLoopMode.Once;
}
this._modules.push(textureModule);
break;
}
// 可扩展其他模块类型 | Extensible for other module types
default:
console.warn(`[ParticleSystem] Unknown module type: ${moduleConfig.type}`);

View File

@@ -0,0 +1,401 @@
<!DOCTYPE html>
<html>
<head>
<title>Particle System End-to-End Test</title>
<style>
body { font-family: monospace; background: #1a1a1a; color: #fff; padding: 20px; }
canvas { border: 1px solid #444; margin: 10px; background: #333; }
.section { margin: 20px 0; padding: 15px; background: #252525; border-radius: 8px; }
h2 { color: #8cf; margin-top: 0; }
pre { background: #333; padding: 10px; border-radius: 4px; overflow-x: auto; font-size: 11px; }
.pass { color: #2a5; }
.fail { color: #f55; }
.log { color: #aaa; font-size: 11px; }
table { border-collapse: collapse; margin: 10px 0; }
td, th { border: 1px solid #444; padding: 5px 10px; text-align: left; }
th { background: #333; }
</style>
</head>
<body>
<h1>Particle System End-to-End Test</h1>
<p>This test simulates the COMPLETE particle rendering pipeline.</p>
<div class="section">
<h2>Step 1: Test Texture</h2>
<pre>
2x2 Spritesheet (128x128 pixels):
┌───────────┬───────────┐
│ RED (0) │ GREEN (1) │ row=0, v: 0.0 - 0.5
├───────────┼───────────┤
│ BLUE (2) │ YELLOW(3) │ row=1, v: 0.5 - 1.0
└───────────┴───────────┘
</pre>
<canvas id="texturePreview" width="128" height="128"></canvas>
</div>
<div class="section">
<h2>Step 2: TextureSheetAnimationModule._setParticleUV()</h2>
<pre id="step2Log"></pre>
</div>
<div class="section">
<h2>Step 3: ParticleRenderDataProvider._updateRenderData()</h2>
<pre id="step3Log"></pre>
</div>
<div class="section">
<h2>Step 4: EngineRenderSystem.convertProviderDataToSprites()</h2>
<pre id="step4Log"></pre>
</div>
<div class="section">
<h2>Step 5: sprite_batch.rs add_sprite_vertices_to_batch()</h2>
<pre id="step5Log"></pre>
</div>
<div class="section">
<h2>Step 6: Final Rendering Result</h2>
<canvas id="mainCanvas" width="500" height="150"></canvas>
<div id="renderResult"></div>
</div>
<div class="section">
<h2>Test Results</h2>
<table>
<tr><th>Frame</th><th>Expected</th><th>Got</th><th>Status</th></tr>
<tbody id="resultsTable"></tbody>
</table>
</div>
<div class="section">
<h2>Conclusion</h2>
<pre id="conclusion"></pre>
</div>
<script>
// ========== Shaders ==========
const vsSource = `
attribute vec2 aPosition;
attribute vec2 aTexCoord;
varying vec2 vTexCoord;
uniform mat4 uProjection;
void main() {
gl_Position = uProjection * vec4(aPosition, 0.0, 1.0);
vTexCoord = aTexCoord;
}
`;
const fsSource = `
precision mediump float;
varying vec2 vTexCoord;
uniform sampler2D uTexture;
void main() {
gl_FragColor = texture2D(uTexture, vTexCoord);
}
`;
// ========== WebGL Setup ==========
function createShader(gl, type, source) {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
return shader;
}
function createProgram(gl) {
const vs = createShader(gl, gl.VERTEX_SHADER, vsSource);
const fs = createShader(gl, gl.FRAGMENT_SHADER, fsSource);
const program = gl.createProgram();
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.linkProgram(program);
return program;
}
function createTestTexture(gl) {
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0); // NO FLIP - same as engine
const data = new Uint8Array([
255, 50, 50, 255, 50, 255, 50, 255, // Row 0: Red, Green
50, 50, 255, 255, 255, 255, 50, 255 // Row 1: Blue, Yellow
]);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 2, 2, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
return texture;
}
// ========== Step 2: TextureSheetAnimationModule._setParticleUV ==========
function simulateTextureSheetAnimationModule(frameIndex, tilesX, tilesY) {
const col = frameIndex % tilesX;
const row = Math.floor(frameIndex / tilesX);
// This is what TextureSheetAnimationModule stores on the particle
return {
_animFrame: frameIndex,
_animTilesX: tilesX,
_animTilesY: tilesY,
col,
row
};
}
// ========== Step 3: ParticleRenderDataProvider._updateRenderData ==========
function simulateParticleRenderDataProvider(particle, tilesX, tilesY) {
const frame = particle._animFrame;
const col = frame % tilesX;
const row = Math.floor(frame / tilesX);
const uWidth = 1 / tilesX;
const vHeight = 1 / tilesY;
// This is exactly what ParticleRenderDataProvider does
const u0 = col * uWidth;
const u1 = (col + 1) * uWidth;
const v0 = row * vHeight;
const v1 = (row + 1) * vHeight;
return {
uvs: [u0, v0, u1, v1],
transforms: [0, 0, 0, 64, 64, 0.5, 0.5], // x, y, rotation, scaleX, scaleY, originX, originY
tileCount: 1
};
}
// ========== Step 4: EngineRenderSystem.convertProviderDataToSprites ==========
function simulateConvertProviderDataToSprites(providerData, x, y) {
const tOffset = 0;
const uvOffset = 0;
return {
x: x,
y: y,
rotation: providerData.transforms[tOffset + 2],
scaleX: providerData.transforms[tOffset + 3],
scaleY: providerData.transforms[tOffset + 4],
originX: providerData.transforms[tOffset + 5],
originY: providerData.transforms[tOffset + 6],
uv: [
providerData.uvs[0],
providerData.uvs[1],
providerData.uvs[2],
providerData.uvs[3]
]
};
}
// ========== Step 5: sprite_batch.rs add_sprite_vertices_to_batch ==========
function simulateSpriteBatch(sprite, batch) {
const { x, y, scaleX: width, scaleY: height, rotation, originX, originY } = sprite;
const [u0, v0, u1, v1] = sprite.uv;
const ox = originX * width;
const oy = originY * height;
const cos = Math.cos(rotation);
const sin = Math.sin(rotation);
// Exactly as sprite_batch.rs
const corners = [
[-ox, height - oy], // 0: Top-left (high Y)
[width - ox, height - oy], // 1: Top-right
[width - ox, -oy], // 2: Bottom-right (low Y)
[-ox, -oy] // 3: Bottom-left
];
const texCoords = [
[u0, v0], // 0: Top-left vertex gets (u0, v0)
[u1, v0], // 1: Top-right vertex gets (u1, v0)
[u1, v1], // 2: Bottom-right vertex gets (u1, v1)
[u0, v1] // 3: Bottom-left vertex gets (u0, v1)
];
for (let i = 0; i < 4; i++) {
const [lx, ly] = corners[i];
const rx = lx * cos - ly * sin;
const ry = lx * sin + ly * cos;
const px = rx + x;
const py = ry + y;
batch.positions.push(px, py);
batch.texCoords.push(texCoords[i][0], texCoords[i][1]);
}
const base = batch.vertexCount;
batch.indices.push(base, base + 1, base + 2, base + 2, base + 3, base);
batch.vertexCount += 4;
return { corners, texCoords };
}
// ========== Utility ==========
function colorName(r, g, b) {
if (r > 200 && g < 100 && b < 100) return 'RED';
if (r < 100 && g > 200 && b < 100) return 'GREEN';
if (r < 100 && g < 100 && b > 200) return 'BLUE';
if (r > 200 && g > 200 && b < 100) return 'YELLOW';
return `RGB(${r},${g},${b})`;
}
// ========== Main Test ==========
function runTest() {
const tilesX = 2, tilesY = 2;
const expectedColors = ['RED', 'GREEN', 'BLUE', 'YELLOW'];
const results = [];
let step2Log = '';
let step3Log = '';
let step4Log = '';
let step5Log = '';
// Draw texture preview
const previewCanvas = document.getElementById('texturePreview');
const previewCtx = previewCanvas.getContext('2d');
previewCtx.fillStyle = '#ff3232'; previewCtx.fillRect(0, 0, 64, 64);
previewCtx.fillStyle = '#32ff32'; previewCtx.fillRect(64, 0, 64, 64);
previewCtx.fillStyle = '#3232ff'; previewCtx.fillRect(0, 64, 64, 64);
previewCtx.fillStyle = '#ffff32'; previewCtx.fillRect(64, 64, 64, 64);
previewCtx.fillStyle = '#fff'; previewCtx.font = '20px monospace';
previewCtx.fillText('0', 28, 38); previewCtx.fillText('1', 92, 38);
previewCtx.fillText('2', 28, 102); previewCtx.fillText('3', 92, 102);
// Setup WebGL
const canvas = document.getElementById('mainCanvas');
const gl = canvas.getContext('webgl2') || canvas.getContext('webgl');
const program = createProgram(gl);
const texture = createTestTexture(gl);
gl.useProgram(program);
const projLoc = gl.getUniformLocation(program, 'uProjection');
const left = 0, right = 500, bottom = 0, top = 150;
const projection = new Float32Array([
2/(right-left), 0, 0, 0,
0, 2/(top-bottom), 0, 0,
0, 0, -1, 0,
-(right+left)/(right-left), -(top+bottom)/(top-bottom), 0, 1
]);
gl.uniformMatrix4fv(projLoc, false, projection);
gl.viewport(0, 0, 500, 150);
gl.clearColor(0.15, 0.15, 0.15, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
const batch = { positions: [], texCoords: [], indices: [], vertexCount: 0 };
// Process each frame
for (let frame = 0; frame < 4; frame++) {
const x = 60 + frame * 110;
const y = 75;
// Step 2
const particleData = simulateTextureSheetAnimationModule(frame, tilesX, tilesY);
step2Log += `Frame ${frame}: _animFrame=${particleData._animFrame}, col=${particleData.col}, row=${particleData.row}\n`;
// Step 3
const providerData = simulateParticleRenderDataProvider(particleData, tilesX, tilesY);
step3Log += `Frame ${frame}: uvs=[${providerData.uvs.map(v => v.toFixed(2)).join(', ')}]\n`;
// Step 4
const sprite = simulateConvertProviderDataToSprites(providerData, x, y);
step4Log += `Frame ${frame}: uv=[${sprite.uv.map(v => v.toFixed(2)).join(', ')}], pos=(${x}, ${y})\n`;
// Step 5
const batchResult = simulateSpriteBatch(sprite, batch);
step5Log += `Frame ${frame}: vertex0(top-left)=[${batchResult.texCoords[0].map(v => v.toFixed(2)).join(', ')}], `;
step5Log += `vertex2(bottom-right)=[${batchResult.texCoords[2].map(v => v.toFixed(2)).join(', ')}]\n`;
}
document.getElementById('step2Log').textContent = step2Log;
document.getElementById('step3Log').textContent = step3Log;
document.getElementById('step4Log').textContent = step4Log;
document.getElementById('step5Log').textContent = step5Log;
// Render
const posLoc = gl.getAttribLocation(program, 'aPosition');
const texLoc = gl.getAttribLocation(program, 'aTexCoord');
const posBuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, posBuf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(batch.positions), gl.STATIC_DRAW);
gl.enableVertexAttribArray(posLoc);
gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 0, 0);
const texBuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, texBuf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(batch.texCoords), gl.STATIC_DRAW);
gl.enableVertexAttribArray(texLoc);
gl.vertexAttribPointer(texLoc, 2, gl.FLOAT, false, 0, 0);
const idxBuf = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, idxBuf);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(batch.indices), gl.STATIC_DRAW);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.drawElements(gl.TRIANGLES, batch.indices.length, gl.UNSIGNED_SHORT, 0);
// Read back and verify
const tableBody = document.getElementById('resultsTable');
let allPassed = true;
for (let frame = 0; frame < 4; frame++) {
const x = 60 + frame * 110;
const y = 75;
const pixels = new Uint8Array(4);
gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
const actual = colorName(pixels[0], pixels[1], pixels[2]);
const expected = expectedColors[frame];
const passed = actual === expected;
if (!passed) allPassed = false;
results.push({ frame, expected, actual, passed });
tableBody.innerHTML += `
<tr class="${passed ? 'pass' : 'fail'}">
<td>Frame ${frame}</td>
<td>${expected}</td>
<td>${actual}</td>
<td>${passed ? '✓ PASS' : '✗ FAIL'}</td>
</tr>
`;
}
// Conclusion
const conclusionEl = document.getElementById('conclusion');
if (allPassed) {
conclusionEl.innerHTML = `<span class="pass">ALL TESTS PASSED!</span>
The entire particle rendering pipeline is CORRECT:
- TextureSheetAnimationModule ✓
- ParticleRenderDataProvider ✓
- EngineRenderSystem ✓
- sprite_batch.rs ✓
If your actual particles still show wrong colors, the problem must be:
1. Your spritesheet image has a different layout
2. Something else is modifying the UV values
3. The texture is being loaded differently
Try using the test image: F:\\ecs-framework\\test_spritesheet_2x2.png`;
} else {
const failedFrames = results.filter(r => !r.passed);
conclusionEl.innerHTML = `<span class="fail">TESTS FAILED!</span>
Failed frames:
${failedFrames.map(f => `Frame ${f.frame}: expected ${f.expected}, got ${f.actual}`).join('\n')}
This indicates a bug in the rendering pipeline.`;
}
}
window.onload = runTest;
</script>
</body>
</html>

View File

@@ -0,0 +1,328 @@
<!DOCTYPE html>
<html>
<head>
<title>Sprite Batch Rendering Test (模拟 sprite_batch.rs)</title>
<style>
body { font-family: monospace; background: #1a1a1a; color: #fff; padding: 20px; }
canvas { border: 1px solid #444; margin: 10px; background: #333; }
.test-row { display: flex; align-items: flex-start; margin: 20px 0; gap: 20px; }
.info { background: #333; padding: 10px; border-radius: 4px; font-size: 12px; }
h2 { color: #8cf; }
pre { background: #333; padding: 10px; border-radius: 4px; overflow-x: auto; }
.pass { color: #2a5; }
.fail { color: #f55; }
</style>
</head>
<body>
<h1>Sprite Batch Rendering Test</h1>
<p>This test simulates exactly how sprite_batch.rs renders sprites with UV coordinates.</p>
<h2>Test Texture (2x2 spritesheet)</h2>
<pre>
┌─────────┬─────────┐
│ RED (0) │ GREEN(1)│ v: 0.0 - 0.5
├─────────┼─────────┤
│ BLUE(2) │ YELLOW(3)│ v: 0.5 - 1.0
└─────────┴─────────┘
</pre>
<h2>Rendering Test (same as sprite_batch.rs)</h2>
<div class="test-row">
<div>
<canvas id="mainCanvas" width="400" height="300"></canvas>
<div>Main rendering canvas</div>
</div>
<div class="info">
<h3>sprite_batch.rs vertex mapping:</h3>
<pre>
corners = [
(-ox, height-oy), // 0: Top-left (high Y)
(width-ox, height-oy), // 1: Top-right
(width-ox, -oy), // 2: Bottom-right (low Y)
(-ox, -oy), // 3: Bottom-left
];
tex_coords = [
[u0, v0], // 0: Top-left
[u1, v0], // 1: Top-right
[u1, v1], // 2: Bottom-right
[u0, v1], // 3: Bottom-left
];
indices = [0, 1, 2, 2, 3, 0];
</pre>
</div>
</div>
<h2>Frame-by-Frame Test Results</h2>
<div id="results"></div>
<h2>Conclusion</h2>
<pre id="conclusion"></pre>
<script>
const vsSource = `
attribute vec2 aPosition;
attribute vec2 aTexCoord;
varying vec2 vTexCoord;
uniform mat4 uProjection;
void main() {
gl_Position = uProjection * vec4(aPosition, 0.0, 1.0);
vTexCoord = aTexCoord;
}
`;
const fsSource = `
precision mediump float;
varying vec2 vTexCoord;
uniform sampler2D uTexture;
void main() {
gl_FragColor = texture2D(uTexture, vTexCoord);
}
`;
function createShader(gl, type, source) {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.error(gl.getShaderInfoLog(shader));
return null;
}
return shader;
}
function createProgram(gl, vsSource, fsSource) {
const vs = createShader(gl, gl.VERTEX_SHADER, vsSource);
const fs = createShader(gl, gl.FRAGMENT_SHADER, fsSource);
const program = gl.createProgram();
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.linkProgram(program);
return program;
}
function createTestTexture(gl) {
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
// NO FLIP_Y - same as our engine
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
// 2x2 texture: Red, Green, Blue, Yellow
const data = new Uint8Array([
255, 0, 0, 255, 0, 255, 0, 255, // Row 0: Red, Green
0, 0, 255, 255, 255, 255, 0, 255 // Row 1: Blue, Yellow
]);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 2, 2, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
return texture;
}
// Simulate sprite_batch.rs add_sprite_vertices_to_batch
function addSpriteVertices(batch, x, y, width, height, rotation, originX, originY, u0, v0, u1, v1, color) {
const ox = originX * width;
const oy = originY * height;
const cos = Math.cos(rotation);
const sin = Math.sin(rotation);
// Same as sprite_batch.rs
const corners = [
[-ox, height - oy], // 0: Top-left
[width - ox, height - oy], // 1: Top-right
[width - ox, -oy], // 2: Bottom-right
[-ox, -oy] // 3: Bottom-left
];
const texCoords = [
[u0, v0], // 0: Top-left
[u1, v0], // 1: Top-right
[u1, v1], // 2: Bottom-right
[u0, v1] // 3: Bottom-left
];
// Transform and add vertices
for (let i = 0; i < 4; i++) {
const [lx, ly] = corners[i];
// Apply rotation
const rx = lx * cos - ly * sin;
const ry = lx * sin + ly * cos;
// Apply translation
const px = rx + x;
const py = ry + y;
batch.positions.push(px, py);
batch.texCoords.push(texCoords[i][0], texCoords[i][1]);
}
// Add indices (0, 1, 2, 2, 3, 0)
const base = batch.vertexCount;
batch.indices.push(base, base + 1, base + 2, base + 2, base + 3, base);
batch.vertexCount += 4;
}
function calculateUV(frame, tilesX, tilesY) {
const col = frame % tilesX;
const row = Math.floor(frame / tilesX);
const uWidth = 1 / tilesX;
const vHeight = 1 / tilesY;
return {
u0: col * uWidth,
v0: row * vHeight,
u1: (col + 1) * uWidth,
v1: (row + 1) * vHeight
};
}
function colorName(r, g, b) {
if (r > 200 && g < 100 && b < 100) return 'RED';
if (r < 100 && g > 200 && b < 100) return 'GREEN';
if (r < 100 && g < 100 && b > 200) return 'BLUE';
if (r > 200 && g > 200 && b < 100) return 'YELLOW';
return `RGB(${r},${g},${b})`;
}
function runTest() {
const canvas = document.getElementById('mainCanvas');
const gl = canvas.getContext('webgl2') || canvas.getContext('webgl');
if (!gl) {
document.getElementById('conclusion').textContent = 'WebGL not supported!';
return;
}
const program = createProgram(gl, vsSource, fsSource);
const texture = createTestTexture(gl);
gl.useProgram(program);
// Set up orthographic projection (Y-up, like our engine)
const projLoc = gl.getUniformLocation(program, 'uProjection');
const left = 0, right = 400, bottom = 0, top = 300;
const projection = new Float32Array([
2/(right-left), 0, 0, 0,
0, 2/(top-bottom), 0, 0,
0, 0, -1, 0,
-(right+left)/(right-left), -(top+bottom)/(top-bottom), 0, 1
]);
gl.uniformMatrix4fv(projLoc, false, projection);
// Clear
gl.viewport(0, 0, 400, 300);
gl.clearColor(0.2, 0.2, 0.2, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
// Create batch
const batch = { positions: [], texCoords: [], indices: [], vertexCount: 0 };
// Add 4 sprites for 4 frames
const spriteSize = 80;
const spacing = 90;
const startX = 50;
const startY = 150;
const expectedColors = ['RED', 'GREEN', 'BLUE', 'YELLOW'];
for (let frame = 0; frame < 4; frame++) {
const uv = calculateUV(frame, 2, 2);
const x = startX + frame * spacing;
const y = startY;
addSpriteVertices(
batch,
x, y, // position
spriteSize, spriteSize, // size
0, // rotation
0.5, 0.5, // origin (center)
uv.u0, uv.v0, uv.u1, uv.v1, // UV
[1, 1, 1, 1] // color
);
}
// Upload and render
const posLoc = gl.getAttribLocation(program, 'aPosition');
const texLoc = gl.getAttribLocation(program, 'aTexCoord');
const posBuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, posBuf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(batch.positions), gl.STATIC_DRAW);
gl.enableVertexAttribArray(posLoc);
gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 0, 0);
const texBuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, texBuf);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(batch.texCoords), gl.STATIC_DRAW);
gl.enableVertexAttribArray(texLoc);
gl.vertexAttribPointer(texLoc, 2, gl.FLOAT, false, 0, 0);
const idxBuf = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, idxBuf);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(batch.indices), gl.STATIC_DRAW);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.drawElements(gl.TRIANGLES, batch.indices.length, gl.UNSIGNED_SHORT, 0);
// Read back colors and verify
const resultsDiv = document.getElementById('results');
let allPassed = true;
for (let frame = 0; frame < 4; frame++) {
const x = startX + frame * spacing;
const y = startY;
const pixels = new Uint8Array(4);
gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
const actual = colorName(pixels[0], pixels[1], pixels[2]);
const expected = expectedColors[frame];
const passed = actual === expected;
if (!passed) allPassed = false;
const uv = calculateUV(frame, 2, 2);
resultsDiv.innerHTML += `
<div class="${passed ? 'pass' : 'fail'}">
Frame ${frame}: UV=[${uv.u0.toFixed(2)}, ${uv.v0.toFixed(2)}, ${uv.u1.toFixed(2)}, ${uv.v1.toFixed(2)}]
→ Expected: ${expected}, Got: ${actual} ${passed ? '✓' : '✗'}
</div>
`;
}
const conclusionEl = document.getElementById('conclusion');
if (allPassed) {
conclusionEl.innerHTML = `
<span class="pass">ALL TESTS PASSED!</span>
The sprite_batch.rs rendering logic is CORRECT.
UV calculation is CORRECT.
If particles still show wrong frames in the actual engine, possible causes:
1. The spritesheet image layout is different (frame 0 not at top-left)
2. Image loading is flipping the texture somewhere
3. The particle system is using different UV values than expected
<b>NEXT STEP:</b> Check the actual spritesheet image in the editor.
Is frame 0 really at the top-left corner of the image?
`;
} else {
conclusionEl.innerHTML = `
<span class="fail">SOME TESTS FAILED!</span>
There's a bug in the vertex/UV mapping logic.
`;
}
}
window.onload = runTest;
</script>
</body>
</html>

View File

@@ -0,0 +1,142 @@
/**
* UV 计算测试
* UV Calculation Test
*
* 用于验证 TextureSheetAnimation 的 UV 坐标计算是否正确
* Used to verify TextureSheetAnimation UV coordinate calculation
*/
/**
* 模拟 ParticleRenderDataProvider 中的 UV 计算
* Simulate UV calculation from ParticleRenderDataProvider
*/
function calculateUV(frame: number, tilesX: number, tilesY: number) {
const col = frame % tilesX;
const row = Math.floor(frame / tilesX);
const uWidth = 1 / tilesX;
const vHeight = 1 / tilesY;
const u0 = col * uWidth;
const u1 = (col + 1) * uWidth;
const v0 = row * vHeight;
const v1 = (row + 1) * vHeight;
return { u0, v0, u1, v1, col, row };
}
/**
* 测试 4x4 spritesheet (16帧)
*
* 预期布局(标准 spritesheet从左上角开始
* ┌────┬────┬────┬────┐
* │ 0 │ 1 │ 2 │ 3 │ row=0, v: 0.00 - 0.25
* ├────┼────┼────┼────┤
* │ 4 │ 5 │ 6 │ 7 │ row=1, v: 0.25 - 0.50
* ├────┼────┼────┼────┤
* │ 8 │ 9 │ 10 │ 11 │ row=2, v: 0.50 - 0.75
* ├────┼────┼────┼────┤
* │ 12 │ 13 │ 14 │ 15 │ row=3, v: 0.75 - 1.00
* └────┴────┴────┴────┘
*/
function test4x4Spritesheet() {
console.log('=== 4x4 Spritesheet UV Test ===\n');
const tilesX = 4;
const tilesY = 4;
console.log('Expected layout (standard spritesheet, top-left origin):');
console.log('Frame 0 should be at TOP-LEFT (v: 0.00-0.25)');
console.log('Frame 12 should be at BOTTOM-LEFT (v: 0.75-1.00)\n');
// 测试关键帧
const testFrames = [0, 1, 4, 5, 12, 15];
for (const frame of testFrames) {
const uv = calculateUV(frame, tilesX, tilesY);
console.log(`Frame ${frame.toString().padStart(2)}: col=${uv.col}, row=${uv.row}`);
console.log(` UV: [${uv.u0.toFixed(2)}, ${uv.v0.toFixed(2)}, ${uv.u1.toFixed(2)}, ${uv.v1.toFixed(2)}]`);
console.log('');
}
}
/**
* 测试 2x2 spritesheet (4帧) - 最简单的情况
*/
function test2x2Spritesheet() {
console.log('=== 2x2 Spritesheet UV Test ===\n');
const tilesX = 2;
const tilesY = 2;
console.log('Layout:');
console.log('┌─────┬─────┐');
console.log('│ 0 │ 1 │ v: 0.0 - 0.5');
console.log('├─────┼─────┤');
console.log('│ 2 │ 3 │ v: 0.5 - 1.0');
console.log('└─────┴─────┘\n');
for (let frame = 0; frame < 4; frame++) {
const uv = calculateUV(frame, tilesX, tilesY);
console.log(`Frame ${frame}: col=${uv.col}, row=${uv.row}`);
console.log(` UV: [${uv.u0.toFixed(2)}, ${uv.v0.toFixed(2)}, ${uv.u1.toFixed(2)}, ${uv.v1.toFixed(2)}]`);
}
console.log('');
}
/**
* WebGL 纹理坐标系说明
*/
function explainWebGLTextureCoords() {
console.log('=== WebGL Texture Coordinate System ===\n');
console.log('Without UNPACK_FLIP_Y_WEBGL:');
console.log('- Image row 0 (top of image file) -> stored at texture row 0');
console.log('- Texture coordinate V=0 samples texture row 0');
console.log('- Therefore: V=0 = image top, V=1 = image bottom');
console.log('');
console.log('sprite_batch.rs vertex mapping:');
console.log('- Vertex 0 (top-left on screen, high Y) uses tex_coords[0] = [u0, v0]');
console.log('- Vertex 2 (bottom-right on screen, low Y) uses tex_coords[2] = [u1, v1]');
console.log('');
console.log('Expected behavior:');
console.log('- Frame 0 UV [0, 0, 0.25, 0.25] should show TOP-LEFT quarter of spritesheet');
console.log('- If frame 0 shows BOTTOM-LEFT, the image is being rendered upside down');
console.log('');
}
/**
* 诊断当前问题
*/
function diagnoseIssue() {
console.log('=== Diagnosis ===\n');
console.log('If TextureSheetAnimation shows wrong frames, check:');
console.log('');
console.log('1. Is frame 0 showing the TOP-LEFT of the spritesheet?');
console.log(' - YES: UV calculation is correct');
console.log(' - NO (shows bottom-left): Image is flipped vertically in WebGL');
console.log('');
console.log('2. Are frames playing in wrong ORDER (e.g., 3,2,1,0 instead of 0,1,2,3)?');
console.log(' - Check animation frame index calculation');
console.log('');
console.log('3. Is the spritesheet itself laid out correctly?');
console.log(' - Frame 0 should be at TOP-LEFT of the image file');
console.log('');
}
// 运行所有测试
export function runUVTests() {
explainWebGLTextureCoords();
test2x2Spritesheet();
test4x4Spritesheet();
diagnoseIssue();
}
// 如果直接运行此文件
if (typeof window !== 'undefined') {
runUVTests();
}
export { calculateUV, test2x2Spritesheet, test4x4Spritesheet };

View File

@@ -0,0 +1,278 @@
<!DOCTYPE html>
<html>
<head>
<title>WebGL UV Coordinate Test</title>
<style>
body { font-family: monospace; background: #1a1a1a; color: #fff; padding: 20px; }
canvas { border: 1px solid #444; margin: 10px; }
.test-row { display: flex; align-items: center; margin: 20px 0; }
.label { width: 200px; }
.result { margin-left: 20px; padding: 5px 10px; border-radius: 4px; }
.pass { background: #2a5; }
.fail { background: #a33; }
h2 { color: #8cf; }
pre { background: #333; padding: 10px; border-radius: 4px; }
</style>
</head>
<body>
<h1>WebGL UV Coordinate System Test</h1>
<h2>1. Test Texture (2x2 grid)</h2>
<pre>
Image file layout (how it looks in image editor):
┌─────────┬─────────┐
│ RED (0) │ GREEN(1)│ row 0 (top of image file)
├─────────┼─────────┤
│ BLUE(2) │ YELLOW(3)│ row 1 (bottom of image file)
└─────────┴─────────┘
</pre>
<canvas id="texturePreview" width="128" height="128"></canvas>
<span>← This is the source texture</span>
<h2>2. UV Sampling Test</h2>
<p>Each square below samples a different UV region. We test what color appears.</p>
<div class="test-row">
<div class="label">UV [0, 0, 0.5, 0.5] (Frame 0):</div>
<canvas id="uv0" width="64" height="64"></canvas>
<div id="result0" class="result"></div>
</div>
<div class="test-row">
<div class="label">UV [0.5, 0, 1, 0.5] (Frame 1):</div>
<canvas id="uv1" width="64" height="64"></canvas>
<div id="result1" class="result"></div>
</div>
<div class="test-row">
<div class="label">UV [0, 0.5, 0.5, 1] (Frame 2):</div>
<canvas id="uv2" width="64" height="64"></canvas>
<div id="result2" class="result"></div>
</div>
<div class="test-row">
<div class="label">UV [0.5, 0.5, 1, 1] (Frame 3):</div>
<canvas id="uv3" width="64" height="64"></canvas>
<div id="result3" class="result"></div>
</div>
<h2>3. Conclusion</h2>
<pre id="conclusion"></pre>
<script>
// Vertex shader
const vsSource = `
attribute vec2 aPosition;
attribute vec2 aTexCoord;
varying vec2 vTexCoord;
void main() {
gl_Position = vec4(aPosition, 0.0, 1.0);
vTexCoord = aTexCoord;
}
`;
// Fragment shader
const fsSource = `
precision mediump float;
varying vec2 vTexCoord;
uniform sampler2D uTexture;
void main() {
gl_FragColor = texture2D(uTexture, vTexCoord);
}
`;
function createShader(gl, type, source) {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.error(gl.getShaderInfoLog(shader));
return null;
}
return shader;
}
function createProgram(gl) {
const vs = createShader(gl, gl.VERTEX_SHADER, vsSource);
const fs = createShader(gl, gl.FRAGMENT_SHADER, fsSource);
const program = gl.createProgram();
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.linkProgram(program);
return program;
}
// Create 2x2 test texture data
// Row 0: Red, Green
// Row 1: Blue, Yellow
function createTestTextureData() {
const size = 2;
const data = new Uint8Array(size * size * 4);
// Row 0 (will be uploaded first)
data[0] = 255; data[1] = 0; data[2] = 0; data[3] = 255; // Red
data[4] = 0; data[5] = 255; data[6] = 0; data[7] = 255; // Green
// Row 1
data[8] = 0; data[9] = 0; data[10] = 255; data[11] = 255; // Blue
data[12] = 255; data[13] = 255; data[14] = 0; data[15] = 255; // Yellow
return data;
}
function createTexture(gl, flipY = false) {
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
// Set FLIP_Y if requested
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipY ? 1 : 0);
const data = createTestTextureData();
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 2, 2, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
return texture;
}
function renderQuad(gl, program, u0, v0, u1, v1) {
gl.useProgram(program);
const posLoc = gl.getAttribLocation(program, 'aPosition');
const texLoc = gl.getAttribLocation(program, 'aTexCoord');
// Full screen quad
const positions = new Float32Array([
-1, -1, 1, -1, -1, 1,
-1, 1, 1, -1, 1, 1
]);
// UV coordinates - map corners to the specified UV region
// Vertex order: bottom-left, bottom-right, top-left, top-left, bottom-right, top-right
const texCoords = new Float32Array([
u0, v1, u1, v1, u0, v0,
u0, v0, u1, v1, u1, v0
]);
const posBuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, posBuf);
gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);
gl.enableVertexAttribArray(posLoc);
gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 0, 0);
const texBuf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, texBuf);
gl.bufferData(gl.ARRAY_BUFFER, texCoords, gl.STATIC_DRAW);
gl.enableVertexAttribArray(texLoc);
gl.vertexAttribPointer(texLoc, 2, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
function getCanvasColor(canvas) {
const ctx = canvas.getContext('2d') || canvas.getContext('webgl2') || canvas.getContext('webgl');
if (ctx instanceof WebGLRenderingContext || ctx instanceof WebGL2RenderingContext) {
const pixels = new Uint8Array(4);
ctx.readPixels(32, 32, 1, 1, ctx.RGBA, ctx.UNSIGNED_BYTE, pixels);
return { r: pixels[0], g: pixels[1], b: pixels[2] };
}
return null;
}
function colorName(r, g, b) {
if (r > 200 && g < 100 && b < 100) return 'RED';
if (r < 100 && g > 200 && b < 100) return 'GREEN';
if (r < 100 && g < 100 && b > 200) return 'BLUE';
if (r > 200 && g > 200 && b < 100) return 'YELLOW';
return `RGB(${r},${g},${b})`;
}
function runTest() {
// Draw texture preview
const previewCanvas = document.getElementById('texturePreview');
const previewCtx = previewCanvas.getContext('2d');
previewCtx.fillStyle = 'red';
previewCtx.fillRect(0, 0, 64, 64);
previewCtx.fillStyle = 'green';
previewCtx.fillRect(64, 0, 64, 64);
previewCtx.fillStyle = 'blue';
previewCtx.fillRect(0, 64, 64, 64);
previewCtx.fillStyle = 'yellow';
previewCtx.fillRect(64, 64, 64, 64);
// Test UV regions
const uvTests = [
{ id: 'uv0', uv: [0, 0, 0.5, 0.5], expected: 'RED' },
{ id: 'uv1', uv: [0.5, 0, 1, 0.5], expected: 'GREEN' },
{ id: 'uv2', uv: [0, 0.5, 0.5, 1], expected: 'BLUE' },
{ id: 'uv3', uv: [0.5, 0.5, 1, 1], expected: 'YELLOW' }
];
const results = [];
for (const test of uvTests) {
const canvas = document.getElementById(test.id);
const gl = canvas.getContext('webgl2') || canvas.getContext('webgl');
if (!gl) {
document.getElementById('result' + test.id.slice(-1)).textContent = 'WebGL not supported';
continue;
}
const program = createProgram(gl);
const texture = createTexture(gl, false); // No FLIP_Y
gl.viewport(0, 0, 64, 64);
gl.clearColor(0, 0, 0, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
renderQuad(gl, program, ...test.uv);
// Read back color
const pixels = new Uint8Array(4);
gl.readPixels(32, 32, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
const actual = colorName(pixels[0], pixels[1], pixels[2]);
const passed = actual === test.expected;
results.push({ test: test.id, expected: test.expected, actual, passed });
const resultEl = document.getElementById('result' + test.id.slice(-1));
resultEl.textContent = `Expected: ${test.expected}, Got: ${actual}`;
resultEl.className = 'result ' + (passed ? 'pass' : 'fail');
}
// Conclusion
const allPassed = results.every(r => r.passed);
const conclusionEl = document.getElementById('conclusion');
if (allPassed) {
conclusionEl.textContent = `
ALL TESTS PASSED!
UV coordinate system (without FLIP_Y):
- V=0 samples the TOP of the image (row 0)
- V=1 samples the BOTTOM of the image (row N)
This means the current particle UV calculation should be CORRECT:
v0 = row * vHeight; // row 0 -> v0=0 -> image top
v1 = (row + 1) * vHeight;
If particles still show wrong frames, the problem is elsewhere.
`;
} else {
const failedTests = results.filter(r => !r.passed);
conclusionEl.textContent = `
SOME TESTS FAILED!
${failedTests.map(t => `${t.test}: expected ${t.expected}, got ${t.actual}`).join('\n')}
This indicates the UV coordinate system behaves differently than expected.
The V axis may need to be flipped in particle UV calculation.
`;
}
}
window.onload = runTest;
</script>
</body>
</html>

View File

@@ -194,17 +194,40 @@ export class ParticleRenderDataProvider implements IRenderDataProvider {
this._transforms[tOffset + 5] = 0.5; // originX
this._transforms[tOffset + 6] = 0.5; // originY
// Texture ID: 设置为 0让 EngineRenderSystem 通过 textureGuid 解析
// Set to 0, let EngineRenderSystem resolve via textureGuid
// 这样可以避免场景恢复后 textureId 过期导致的纹理混乱问题
// This avoids texture confusion when textureId becomes stale after scene restore
this._textureIds[particleIndex] = 0;
// Texture ID: 优先使用组件上预加载的 textureId否则让 EngineRenderSystem 通过 textureGuid 解析
// Prefer using pre-loaded textureId from component, otherwise let EngineRenderSystem resolve via textureGuid
this._textureIds[particleIndex] = component.textureId;
// UV (full texture)
this._uvs[uvOffset] = 0;
this._uvs[uvOffset + 1] = 0;
this._uvs[uvOffset + 2] = 1;
this._uvs[uvOffset + 3] = 1;
// UV - 支持精灵图帧动画 | Support spritesheet animation
if (p._animTilesX !== undefined && p._animTilesY !== undefined && p._animFrame !== undefined) {
// 计算帧的 UV 坐标 | Calculate frame UV coordinates
// WebGL 纹理坐标V=0 采样纹理行0即图像顶部
// WebGL texture coords: V=0 samples texture row 0 (image top)
const tilesX = p._animTilesX;
const tilesY = p._animTilesY;
const frame = p._animFrame;
const col = frame % tilesX;
const row = Math.floor(frame / tilesX);
const uWidth = 1 / tilesX;
const vHeight = 1 / tilesY;
// UV: u0, v0, u1, v1
const u0 = col * uWidth;
const u1 = (col + 1) * uWidth;
const v0 = row * vHeight;
const v1 = (row + 1) * vHeight;
this._uvs[uvOffset] = u0;
this._uvs[uvOffset + 1] = v0;
this._uvs[uvOffset + 2] = u1;
this._uvs[uvOffset + 3] = v1;
} else {
// 默认:使用完整纹理 | Default: use full texture
this._uvs[uvOffset] = 0;
this._uvs[uvOffset + 1] = 0;
this._uvs[uvOffset + 2] = 1;
this._uvs[uvOffset + 3] = 1;
}
// Color (packed ABGR for WebGL)
this._colors[particleIndex] = Color.packABGR(

View File

@@ -8,10 +8,8 @@
import { EntitySystem, Matcher, Entity, ECSSystem, PluginServiceRegistry, createServiceToken } from '@esengine/ecs-framework';
import { Input, MouseButton, TransformComponent, SortingLayers } from '@esengine/engine-core';
import type { IAssetManager } from '@esengine/asset-system';
import { ClickFxComponent, ClickFxTriggerMode } from '../ClickFxComponent';
import { ParticleSystemComponent, RenderSpace } from '../ParticleSystemComponent';
import type { IParticleAsset } from '../loaders/ParticleLoader';
// ============================================================================
// 本地服务令牌定义 | Local Service Token Definitions
@@ -66,7 +64,6 @@ const RenderSystemToken = createServiceToken<IEngineRenderSystem>('renderSystem'
export class ClickFxSystem extends EntitySystem {
private _engineBridge: IEngineBridge | null = null;
private _renderSystem: IEngineRenderSystem | null = null;
private _assetManager: IAssetManager | null = null;
private _entitiesToDestroy: Entity[] = [];
private _canvas: HTMLCanvasElement | null = null;
@@ -74,14 +71,6 @@ export class ClickFxSystem extends EntitySystem {
super(Matcher.empty().all(ClickFxComponent));
}
/**
* 设置资产管理器
* Set asset manager
*/
setAssetManager(assetManager: IAssetManager | null): void {
this._assetManager = assetManager;
}
/**
* 设置服务注册表(用于获取 EngineBridge 和 RenderSystem
* Set service registry (for getting EngineBridge and RenderSystem)
@@ -339,8 +328,11 @@ export class ClickFxSystem extends EntitySystem {
const transform = effectEntity.addComponent(new TransformComponent(screenSpaceX, screenSpaceY));
transform.setScale(clickFx.scale, clickFx.scale, 1);
// 添加 ParticleSystem | Add ParticleSystem
const particleSystem = effectEntity.addComponent(new ParticleSystemComponent());
// 创建 ParticleSystemComponent 并预先设置 GUID在添加到实体前
// Create ParticleSystemComponent and set GUID before adding to entity
// 这样 ParticleUpdateSystem.onAdded 触发时已经有 GUID 了
// So ParticleUpdateSystem.onAdded has the GUID when triggered
const particleSystem = new ParticleSystemComponent();
particleSystem.particleAssetGuid = particleGuid;
particleSystem.autoPlay = true;
// 使用 ScreenOverlay 层和屏幕空间渲染
@@ -349,31 +341,12 @@ export class ClickFxSystem extends EntitySystem {
particleSystem.orderInLayer = 0;
particleSystem.renderSpace = RenderSpace.Screen;
// 添加组件到实体(触发 ParticleUpdateSystem 的初始化和资产加载)
// Add component to entity (triggers ParticleUpdateSystem initialization and asset loading)
effectEntity.addComponent(particleSystem);
// 记录活跃特效 | Record active effect
clickFx.addActiveEffect(effectEntity.id);
// 异步加载并播放 | Async load and play
if (this._assetManager) {
this._assetManager.loadAsset<IParticleAsset>(particleGuid).then(result => {
if (result?.asset) {
particleSystem.setAssetData(result.asset);
// 应用资产的排序属性 | Apply sorting properties from asset
if (result.asset.sortingLayer) {
particleSystem.sortingLayer = result.asset.sortingLayer;
}
if (result.asset.orderInLayer !== undefined) {
particleSystem.orderInLayer = result.asset.orderInLayer;
}
particleSystem.play();
} else {
console.warn(`[ClickFxSystem] Failed to load particle asset: ${particleGuid}`);
}
}).catch(error => {
console.error(`[ClickFxSystem] Error loading particle asset ${particleGuid}:`, error);
});
} else {
console.warn('[ClickFxSystem] AssetManager not set, cannot load particle asset');
}
}
/**

View File

@@ -185,6 +185,11 @@ export class ParticleUpdateSystem extends EntitySystem {
}
}
// 如果正在初始化中,跳过处理 | Skip processing if initializing
if (this._loadingComponents.has(particle)) {
continue;
}
// 检测资产 GUID 变化并重新加载 | Detect asset GUID change and reload
// 这使得编辑器中选择新的粒子资产时能够立即切换
// This allows immediate switching when selecting a new particle asset in the editor
@@ -205,8 +210,9 @@ export class ParticleUpdateSystem extends EntitySystem {
particle.update(deltaTime, worldX, worldY, worldRotation, worldScaleX, worldScaleY);
}
// 尝试加载纹理(如果还没有加载| Try to load texture if not loaded yet
if (particle.textureId === 0) {
// 尝试加载纹理(如果还没有加载且不在初始化中)
// Try to load texture if not loaded yet and not initializing
if (particle.textureId === 0 && !this._loadingComponents.has(particle)) {
this.loadParticleTexture(particle);
}
@@ -262,56 +268,65 @@ export class ParticleUpdateSystem extends EntitySystem {
* Async initialize particle system
*/
private async _initializeParticle(entity: Entity, particle: ParticleSystemComponent): Promise<void> {
// 如果有资产 GUID先加载资产 | Load asset first if GUID is set
if (particle.particleAssetGuid) {
const asset = await this._loadParticleAsset(particle.particleAssetGuid);
if (asset) {
particle.setAssetData(asset);
// 应用资产的排序属性 | Apply sorting properties from asset
if (asset.sortingLayer) {
particle.sortingLayer = asset.sortingLayer;
}
if (asset.orderInLayer !== undefined) {
particle.orderInLayer = asset.orderInLayer;
// 标记为正在初始化,防止 process 中重复调用 loadParticleTexture
// Mark as initializing to prevent duplicate loadParticleTexture calls in process
this._loadingComponents.add(particle);
try {
// 如果有资产 GUID先加载资产 | Load asset first if GUID is set
if (particle.particleAssetGuid) {
const asset = await this._loadParticleAsset(particle.particleAssetGuid);
if (asset) {
particle.setAssetData(asset);
// 应用资产的排序属性 | Apply sorting properties from asset
if (asset.sortingLayer) {
particle.sortingLayer = asset.sortingLayer;
}
if (asset.orderInLayer !== undefined) {
particle.orderInLayer = asset.orderInLayer;
}
}
}
}
// 初始化粒子系统(不自动播放,由下面的逻辑控制)
// Initialize particle system (don't auto play, controlled by logic below)
particle.ensureBuilt();
// 初始化粒子系统(不自动播放,由下面的逻辑控制)
// Initialize particle system (don't auto play, controlled by logic below)
particle.ensureBuilt();
// 加载纹理 | Load texture
await this.loadParticleTexture(particle);
// 加载纹理 | Load texture
await this.loadParticleTexture(particle);
// 注册到渲染数据提供者 | Register to render data provider
// 尝试获取 Transform如果没有则使用默认位置 | Try to get Transform, use default position if not available
let transform: ITransformComponent | null = null;
if (this._transformType) {
transform = entity.getComponent(this._transformType);
}
// 即使没有 Transform也要注册粒子系统使用原点位置 | Register particle system even without Transform (use origin position)
if (transform) {
this._renderDataProvider.register(particle, transform);
} else {
this._renderDataProvider.register(particle, { position: { x: 0, y: 0 } });
}
// 记录已加载的资产 GUID | Record loaded asset GUID
this._lastLoadedGuids.set(particle, particle.particleAssetGuid);
// 决定是否自动播放 | Decide whether to auto play
// 编辑器模式:有资产时自动播放预览 | Editor mode: auto play preview if has asset
// 运行时模式:根据 autoPlay 设置 | Runtime mode: based on autoPlay setting
const isEditorMode = this.scene?.isEditorMode ?? false;
if (particle.particleAssetGuid && particle.loadedAsset) {
if (isEditorMode) {
// 编辑器模式:始终播放预览 | Editor mode: always play preview
particle.play();
} else if (particle.autoPlay) {
// 运行时模式:根据 autoPlay 设置 | Runtime mode: based on autoPlay
particle.play();
// 注册到渲染数据提供者 | Register to render data provider
// 尝试获取 Transform如果没有则使用默认位置 | Try to get Transform, use default position if not available
let transform: ITransformComponent | null = null;
if (this._transformType) {
transform = entity.getComponent(this._transformType);
}
// 即使没有 Transform也要注册粒子系统使用原点位置 | Register particle system even without Transform (use origin position)
if (transform) {
this._renderDataProvider.register(particle, transform);
} else {
this._renderDataProvider.register(particle, { position: { x: 0, y: 0 } });
}
// 记录已加载的资产 GUID | Record loaded asset GUID
this._lastLoadedGuids.set(particle, particle.particleAssetGuid);
// 决定是否自动播放 | Decide whether to auto play
// 编辑器模式:有资产时自动播放预览 | Editor mode: auto play preview if has asset
// 运行时模式:根据 autoPlay 设置 | Runtime mode: based on autoPlay setting
const isEditorMode = this.scene?.isEditorMode ?? false;
if (particle.particleAssetGuid && particle.loadedAsset) {
if (isEditorMode) {
// 编辑器模式:始终播放预览 | Editor mode: always play preview
particle.play();
} else if (particle.autoPlay) {
// 运行时模式:根据 autoPlay 设置 | Runtime mode: based on autoPlay
particle.play();
}
}
} finally {
// 初始化完成,移除加载标记 | Initialization complete, remove loading mark
this._loadingComponents.delete(particle);
}
}
@@ -329,9 +344,25 @@ export class ParticleUpdateSystem extends EntitySystem {
const currentGuid = particle.particleAssetGuid;
const lastGuid = this._lastLoadedGuids.get(particle);
// 如果 GUID 没有变化,或者正在加载中,跳过
// Skip if GUID hasn't changed or already loading
if (currentGuid === lastGuid || this._loadingComponents.has(particle)) {
// 如果正在加载中,跳过
// Skip if already loading
if (this._loadingComponents.has(particle)) {
return;
}
// 检查是否需要重新加载:
// 1. GUID 变化了
// 2. 或者 GUID 相同但资产数据丢失(场景恢复后)
// 3. 或者 GUID 相同但纹理 ID 无效(纹理被清除后)
// Check if reload is needed:
// 1. GUID changed
// 2. Or GUID is same but asset data is lost (after scene restore)
// 3. Or GUID is same but texture ID is invalid (after texture clear)
const needsReload = currentGuid !== lastGuid ||
(currentGuid && !particle.loadedAsset) ||
(currentGuid && particle.textureId === 0);
if (!needsReload) {
return;
}
@@ -410,35 +441,70 @@ export class ParticleUpdateSystem extends EntitySystem {
} catch (error) {
console.error('[ParticleUpdateSystem] Failed to load texture by GUID:', textureGuid, error);
// 加载失败时使用默认纹理 | Use default texture on load failure
await this._ensureDefaultTexture();
particle.textureId = DEFAULT_PARTICLE_TEXTURE_ID;
const loaded = await this._ensureDefaultTexture();
if (loaded) {
particle.textureId = DEFAULT_PARTICLE_TEXTURE_ID;
}
}
} else {
// 没有纹理 GUID 时使用默认粒子纹理 | Use default particle texture when no GUID
await this._ensureDefaultTexture();
particle.textureId = DEFAULT_PARTICLE_TEXTURE_ID;
const loaded = await this._ensureDefaultTexture();
if (loaded) {
particle.textureId = DEFAULT_PARTICLE_TEXTURE_ID;
}
}
}
/**
* 确保默认粒子纹理已加载
* Ensure default particle texture is loaded
*
* 使用 loadTextureAsync API 等待纹理实际加载完成,
* 避免显示灰色占位符的问题。
* Uses loadTextureAsync API to wait for actual texture completion,
* avoiding the gray placeholder issue.
*
* @returns 是否成功加载 | Whether successfully loaded
*/
private async _ensureDefaultTexture(): Promise<void> {
if (this._defaultTextureLoaded || this._defaultTextureLoading) return;
if (!this._engineBridge) return;
private async _ensureDefaultTexture(): Promise<boolean> {
// 已加载过 | Already loaded
if (this._defaultTextureLoaded) return true;
// 正在加载中,等待完成 | Loading in progress, wait for completion
if (this._defaultTextureLoading) {
// 轮询等待加载完成 | Poll until loading completes
while (this._defaultTextureLoading) {
await new Promise(resolve => setTimeout(resolve, 10));
}
return this._defaultTextureLoaded;
}
// 没有引擎桥接,无法加载 | No engine bridge, cannot load
if (!this._engineBridge) {
console.warn('[ParticleUpdateSystem] EngineBridge not set, cannot load default texture');
return false;
}
this._defaultTextureLoading = true;
try {
const dataUrl = generateDefaultParticleTextureDataURL();
if (dataUrl) {
await this._engineBridge.loadTexture(DEFAULT_PARTICLE_TEXTURE_ID, dataUrl);
// 优先使用 loadTextureAsync等待纹理就绪
// Prefer loadTextureAsync (waits for texture ready)
if (this._engineBridge.loadTextureAsync) {
await this._engineBridge.loadTextureAsync(DEFAULT_PARTICLE_TEXTURE_ID, dataUrl);
} else {
// 回退到旧 API可能显示灰色占位符
// Fallback to old API (may show gray placeholder)
await this._engineBridge.loadTexture(DEFAULT_PARTICLE_TEXTURE_ID, dataUrl);
}
this._defaultTextureLoaded = true;
}
} catch (error) {
console.error('[ParticleUpdateSystem] Failed to create default particle texture:', error);
}
this._defaultTextureLoading = false;
return this._defaultTextureLoaded;
}
protected override onRemoved(entity: Entity): void {