refactor: reorganize package structure and decouple framework packages (#338)
* refactor: reorganize package structure and decouple framework packages ## Package Structure Reorganization - Reorganized 55 packages into categorized subdirectories: - packages/framework/ - Generic framework (Laya/Cocos compatible) - packages/engine/ - ESEngine core modules - packages/rendering/ - Rendering modules (WASM dependent) - packages/physics/ - Physics modules - packages/streaming/ - World streaming - packages/network-ext/ - Network extensions - packages/editor/ - Editor framework and plugins - packages/rust/ - Rust WASM engine - packages/tools/ - Build tools and SDK ## Framework Package Decoupling - Decoupled behavior-tree and blueprint packages from ESEngine dependencies - Created abstracted interfaces (IBTAssetManager, IBehaviorTreeAssetContent) - ESEngine-specific code moved to esengine/ subpath exports - Framework packages now usable with Cocos/Laya without ESEngine ## CI Configuration - Updated CI to only type-check and lint framework packages - Added type-check:framework and lint:framework scripts ## Breaking Changes - Package import paths changed due to directory reorganization - ESEngine integrations now use subpath imports (e.g., '@esengine/behavior-tree/esengine') * fix: update es-engine file path after directory reorganization * docs: update README to focus on framework over engine * ci: only build framework packages, remove Rust/WASM dependencies * fix: remove esengine subpath from behavior-tree and blueprint builds ESEngine integration code will only be available in full engine builds. Framework packages are now purely engine-agnostic. * fix: move network-protocols to framework, build both in CI * fix: update workflow paths from packages/core to packages/framework/core * fix: exclude esengine folder from type-check in behavior-tree and blueprint * fix: update network tsconfig references to new paths * fix: add test:ci:framework to only test framework packages in CI * fix: only build core and math npm packages in CI * fix: exclude test files from CodeQL and fix string escaping security issue
This commit is contained in:
519
packages/rust/engine-shared/src/traits/backend.rs
Normal file
519
packages/rust/engine-shared/src/traits/backend.rs
Normal file
@@ -0,0 +1,519 @@
|
||||
//! 图形后端主 trait
|
||||
//!
|
||||
//! Main graphics backend trait.
|
||||
|
||||
use crate::types::{
|
||||
handle::*,
|
||||
vertex::*,
|
||||
blend::*,
|
||||
texture::*,
|
||||
uniform::UniformValue,
|
||||
};
|
||||
use glam::{Vec2, Vec3, Vec4, Mat3, Mat4};
|
||||
use thiserror::Error;
|
||||
|
||||
// ==================== 错误类型 | Error Types ====================
|
||||
|
||||
/// 图形后端错误
|
||||
///
|
||||
/// Graphics backend error.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum GraphicsError {
|
||||
/// 着色器编译失败 | Shader compilation failed
|
||||
#[error("Shader compilation failed: {0}")]
|
||||
ShaderCompilation(String),
|
||||
|
||||
/// 着色器链接失败 | Shader linking failed
|
||||
#[error("Shader linking failed: {0}")]
|
||||
ShaderLinking(String),
|
||||
|
||||
/// 纹理创建失败 | Texture creation failed
|
||||
#[error("Texture creation failed: {0}")]
|
||||
TextureCreation(String),
|
||||
|
||||
/// 缓冲区创建失败 | Buffer creation failed
|
||||
#[error("Buffer creation failed: {0}")]
|
||||
BufferCreation(String),
|
||||
|
||||
/// 无效句柄 | Invalid handle
|
||||
#[error("Invalid handle: {0}")]
|
||||
InvalidHandle(String),
|
||||
|
||||
/// 上下文丢失 | Context lost
|
||||
#[error("Context lost")]
|
||||
ContextLost,
|
||||
|
||||
/// 不支持的操作 | Unsupported operation
|
||||
#[error("Unsupported operation: {0}")]
|
||||
Unsupported(String),
|
||||
|
||||
/// 后端错误 | Backend error
|
||||
#[error("Backend error: {0}")]
|
||||
Backend(String),
|
||||
|
||||
/// 资源不存在 | Resource not found
|
||||
#[error("Resource not found: {0}")]
|
||||
ResourceNotFound(String),
|
||||
|
||||
/// 数据大小不匹配 | Data size mismatch
|
||||
#[error("Data size mismatch: expected {expected}, got {actual}")]
|
||||
DataSizeMismatch { expected: usize, actual: usize },
|
||||
}
|
||||
|
||||
/// 图形操作结果
|
||||
///
|
||||
/// Graphics operation result.
|
||||
pub type GraphicsResult<T> = Result<T, GraphicsError>;
|
||||
|
||||
// ==================== 缓冲区用途 | Buffer Usage ====================
|
||||
|
||||
/// 缓冲区用途
|
||||
///
|
||||
/// Buffer usage.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
||||
pub enum BufferUsage {
|
||||
/// 静态数据(不常更新)| Static data (rarely updated)
|
||||
#[default]
|
||||
Static,
|
||||
/// 动态数据(经常更新)| Dynamic data (frequently updated)
|
||||
Dynamic,
|
||||
/// 流式数据(每帧更新)| Streaming data (updated every frame)
|
||||
Stream,
|
||||
}
|
||||
|
||||
// ==================== 图形功能 | Graphics Features ====================
|
||||
|
||||
/// 图形功能
|
||||
///
|
||||
/// Graphics feature.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum GraphicsFeature {
|
||||
/// 各向异性过滤 | Anisotropic filtering
|
||||
AnisotropicFiltering,
|
||||
/// 实例化渲染 | Instanced rendering
|
||||
Instancing,
|
||||
/// 计算着色器 | Compute shaders
|
||||
ComputeShaders,
|
||||
/// 多渲染目标 | Multiple render targets
|
||||
MultipleRenderTargets,
|
||||
/// 浮点纹理 | Float textures
|
||||
FloatTextures,
|
||||
/// WebGPU | WebGPU support
|
||||
WebGPU,
|
||||
}
|
||||
|
||||
// ==================== 图形后端 Trait | Graphics Backend Trait ====================
|
||||
|
||||
/// 图形后端主 trait
|
||||
///
|
||||
/// 定义所有图形操作的抽象接口,由具体后端(WebGL2、WGPU 等)实现。
|
||||
///
|
||||
/// Main graphics backend trait.
|
||||
/// Defines abstract interface for all graphics operations,
|
||||
/// implemented by concrete backends (WebGL2, WGPU, etc.).
|
||||
pub trait GraphicsBackend: Sized {
|
||||
// ==================== 基本信息 | Basic Info ====================
|
||||
|
||||
/// 后端名称
|
||||
///
|
||||
/// Backend name.
|
||||
fn name(&self) -> &'static str;
|
||||
|
||||
/// 后端版本
|
||||
///
|
||||
/// Backend version.
|
||||
fn version(&self) -> &str;
|
||||
|
||||
// ==================== 生命周期 | Lifecycle ====================
|
||||
|
||||
/// 调整视口大小
|
||||
///
|
||||
/// Resize viewport.
|
||||
fn resize(&mut self, width: u32, height: u32);
|
||||
|
||||
/// 获取当前宽度
|
||||
///
|
||||
/// Get current width.
|
||||
fn width(&self) -> u32;
|
||||
|
||||
/// 获取当前高度
|
||||
///
|
||||
/// Get current height.
|
||||
fn height(&self) -> u32;
|
||||
|
||||
// ==================== 帧控制 | Frame Control ====================
|
||||
|
||||
/// 开始新帧
|
||||
///
|
||||
/// Begin new frame.
|
||||
fn begin_frame(&mut self);
|
||||
|
||||
/// 结束当前帧
|
||||
///
|
||||
/// End current frame.
|
||||
fn end_frame(&mut self);
|
||||
|
||||
/// 清屏
|
||||
///
|
||||
/// Clear screen.
|
||||
fn clear(&mut self, r: f32, g: f32, b: f32, a: f32);
|
||||
|
||||
/// 设置视口
|
||||
///
|
||||
/// Set viewport.
|
||||
fn set_viewport(&mut self, x: i32, y: i32, width: u32, height: u32);
|
||||
|
||||
// ==================== 缓冲区操作 | Buffer Operations ====================
|
||||
|
||||
/// 创建顶点缓冲区
|
||||
///
|
||||
/// Create vertex buffer.
|
||||
fn create_vertex_buffer(
|
||||
&mut self,
|
||||
data: &[u8],
|
||||
usage: BufferUsage,
|
||||
) -> GraphicsResult<BufferHandle>;
|
||||
|
||||
/// 创建指定大小的顶点缓冲区(预分配)
|
||||
///
|
||||
/// Create vertex buffer with specified size (pre-allocate).
|
||||
fn create_vertex_buffer_sized(
|
||||
&mut self,
|
||||
size: usize,
|
||||
usage: BufferUsage,
|
||||
) -> GraphicsResult<BufferHandle>;
|
||||
|
||||
/// 创建索引缓冲区
|
||||
///
|
||||
/// Create index buffer.
|
||||
fn create_index_buffer(
|
||||
&mut self,
|
||||
data: &[u16],
|
||||
usage: BufferUsage,
|
||||
) -> GraphicsResult<BufferHandle>;
|
||||
|
||||
/// 创建索引缓冲区(u32)
|
||||
///
|
||||
/// Create index buffer (u32).
|
||||
fn create_index_buffer_u32(
|
||||
&mut self,
|
||||
data: &[u32],
|
||||
usage: BufferUsage,
|
||||
) -> GraphicsResult<BufferHandle>;
|
||||
|
||||
/// 更新缓冲区数据
|
||||
///
|
||||
/// Update buffer data.
|
||||
fn update_buffer(
|
||||
&mut self,
|
||||
handle: BufferHandle,
|
||||
offset: usize,
|
||||
data: &[u8],
|
||||
) -> GraphicsResult<()>;
|
||||
|
||||
/// 销毁缓冲区
|
||||
///
|
||||
/// Destroy buffer.
|
||||
fn destroy_buffer(&mut self, handle: BufferHandle);
|
||||
|
||||
/// 创建顶点数组对象
|
||||
///
|
||||
/// Create vertex array object.
|
||||
fn create_vertex_array(
|
||||
&mut self,
|
||||
vertex_buffer: BufferHandle,
|
||||
index_buffer: Option<BufferHandle>,
|
||||
layout: &VertexLayout,
|
||||
) -> GraphicsResult<VertexArrayHandle>;
|
||||
|
||||
/// 销毁顶点数组对象
|
||||
///
|
||||
/// Destroy vertex array object.
|
||||
fn destroy_vertex_array(&mut self, handle: VertexArrayHandle);
|
||||
|
||||
// ==================== 着色器操作 | Shader Operations ====================
|
||||
|
||||
/// 编译着色器程序
|
||||
///
|
||||
/// Compile shader program.
|
||||
fn compile_shader(
|
||||
&mut self,
|
||||
vertex_src: &str,
|
||||
fragment_src: &str,
|
||||
) -> GraphicsResult<ShaderHandle>;
|
||||
|
||||
/// 销毁着色器
|
||||
///
|
||||
/// Destroy shader.
|
||||
fn destroy_shader(&mut self, handle: ShaderHandle);
|
||||
|
||||
/// 绑定着色器
|
||||
///
|
||||
/// Bind shader.
|
||||
fn bind_shader(&mut self, handle: ShaderHandle) -> GraphicsResult<()>;
|
||||
|
||||
/// 设置 Uniform(float)
|
||||
///
|
||||
/// Set uniform (float).
|
||||
fn set_uniform_f32(&mut self, name: &str, value: f32) -> GraphicsResult<()>;
|
||||
|
||||
/// 设置 Uniform(vec2)
|
||||
///
|
||||
/// Set uniform (vec2).
|
||||
fn set_uniform_vec2(&mut self, name: &str, value: Vec2) -> GraphicsResult<()>;
|
||||
|
||||
/// 设置 Uniform(vec3)
|
||||
///
|
||||
/// Set uniform (vec3).
|
||||
fn set_uniform_vec3(&mut self, name: &str, value: Vec3) -> GraphicsResult<()>;
|
||||
|
||||
/// 设置 Uniform(vec4)
|
||||
///
|
||||
/// Set uniform (vec4).
|
||||
fn set_uniform_vec4(&mut self, name: &str, value: Vec4) -> GraphicsResult<()>;
|
||||
|
||||
/// 设置 Uniform(mat3)
|
||||
///
|
||||
/// Set uniform (mat3).
|
||||
fn set_uniform_mat3(&mut self, name: &str, value: &Mat3) -> GraphicsResult<()>;
|
||||
|
||||
/// 设置 Uniform(mat4)
|
||||
///
|
||||
/// Set uniform (mat4).
|
||||
fn set_uniform_mat4(&mut self, name: &str, value: &Mat4) -> GraphicsResult<()>;
|
||||
|
||||
/// 设置 Uniform(int/sampler)
|
||||
///
|
||||
/// Set uniform (int/sampler).
|
||||
fn set_uniform_i32(&mut self, name: &str, value: i32) -> GraphicsResult<()>;
|
||||
|
||||
/// 设置 Uniform(通用)
|
||||
///
|
||||
/// Set uniform (generic).
|
||||
fn set_uniform(&mut self, name: &str, value: &UniformValue) -> GraphicsResult<()> {
|
||||
match value {
|
||||
UniformValue::Float(v) => self.set_uniform_f32(name, *v),
|
||||
UniformValue::Float2(v) => self.set_uniform_vec2(name, *v),
|
||||
UniformValue::Float3(v) => self.set_uniform_vec3(name, *v),
|
||||
UniformValue::Float4(v) => self.set_uniform_vec4(name, *v),
|
||||
UniformValue::Int(v) => self.set_uniform_i32(name, *v),
|
||||
UniformValue::Mat3(v) => self.set_uniform_mat3(name, v),
|
||||
UniformValue::Mat4(v) => self.set_uniform_mat4(name, v),
|
||||
UniformValue::Texture(unit) => self.set_uniform_i32(name, *unit as i32),
|
||||
_ => Err(GraphicsError::Unsupported(format!(
|
||||
"Uniform type {} not supported",
|
||||
value.type_name()
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 纹理操作 | Texture Operations ====================
|
||||
|
||||
/// 创建纹理
|
||||
///
|
||||
/// Create texture.
|
||||
fn create_texture(&mut self, desc: &TextureDescriptor) -> GraphicsResult<TextureHandle>;
|
||||
|
||||
/// 创建空白纹理(用于动态图集)
|
||||
///
|
||||
/// Create blank texture (for dynamic atlas).
|
||||
fn create_blank_texture(&mut self, width: u32, height: u32) -> GraphicsResult<TextureHandle>;
|
||||
|
||||
/// 上传纹理数据
|
||||
///
|
||||
/// Upload texture data.
|
||||
fn upload_texture_data(
|
||||
&mut self,
|
||||
handle: TextureHandle,
|
||||
data: &[u8],
|
||||
width: u32,
|
||||
height: u32,
|
||||
) -> GraphicsResult<()>;
|
||||
|
||||
/// 更新纹理区域
|
||||
///
|
||||
/// Update texture region.
|
||||
fn update_texture_region(
|
||||
&mut self,
|
||||
handle: TextureHandle,
|
||||
x: u32,
|
||||
y: u32,
|
||||
width: u32,
|
||||
height: u32,
|
||||
data: &[u8],
|
||||
) -> GraphicsResult<()>;
|
||||
|
||||
/// 销毁纹理
|
||||
///
|
||||
/// Destroy texture.
|
||||
fn destroy_texture(&mut self, handle: TextureHandle);
|
||||
|
||||
/// 绑定纹理到纹理单元
|
||||
///
|
||||
/// Bind texture to texture unit.
|
||||
fn bind_texture(&mut self, handle: TextureHandle, unit: u32) -> GraphicsResult<()>;
|
||||
|
||||
/// 获取纹理尺寸
|
||||
///
|
||||
/// Get texture dimensions.
|
||||
fn get_texture_size(&self, handle: TextureHandle) -> Option<(u32, u32)>;
|
||||
|
||||
// ==================== 渲染状态 | Render State ====================
|
||||
|
||||
/// 应用渲染状态
|
||||
///
|
||||
/// Apply render state.
|
||||
fn apply_render_state(&mut self, state: &RenderState);
|
||||
|
||||
/// 设置混合模式
|
||||
///
|
||||
/// Set blend mode.
|
||||
fn set_blend_mode(&mut self, mode: BlendMode);
|
||||
|
||||
/// 设置裁剪矩形
|
||||
///
|
||||
/// Set scissor rectangle.
|
||||
fn set_scissor(&mut self, rect: Option<ScissorRect>);
|
||||
|
||||
// ==================== 绘制命令 | Draw Commands ====================
|
||||
|
||||
/// 绘制(索引,u16)
|
||||
///
|
||||
/// Draw indexed (u16).
|
||||
fn draw_indexed(
|
||||
&mut self,
|
||||
vao: VertexArrayHandle,
|
||||
index_count: u32,
|
||||
index_offset: u32,
|
||||
) -> GraphicsResult<()>;
|
||||
|
||||
/// 绘制(索引,u32)
|
||||
///
|
||||
/// Draw indexed (u32).
|
||||
fn draw_indexed_u32(
|
||||
&mut self,
|
||||
vao: VertexArrayHandle,
|
||||
index_count: u32,
|
||||
index_offset: u32,
|
||||
) -> GraphicsResult<()> {
|
||||
// 默认实现使用 u16 版本,后端可覆盖
|
||||
self.draw_indexed(vao, index_count, index_offset)
|
||||
}
|
||||
|
||||
/// 绘制(非索引)
|
||||
///
|
||||
/// Draw non-indexed.
|
||||
fn draw(
|
||||
&mut self,
|
||||
vao: VertexArrayHandle,
|
||||
vertex_count: u32,
|
||||
vertex_offset: u32,
|
||||
) -> GraphicsResult<()>;
|
||||
|
||||
/// 绘制线段
|
||||
///
|
||||
/// Draw lines.
|
||||
fn draw_lines(
|
||||
&mut self,
|
||||
vao: VertexArrayHandle,
|
||||
vertex_count: u32,
|
||||
vertex_offset: u32,
|
||||
) -> GraphicsResult<()>;
|
||||
|
||||
/// 绘制闭合线条
|
||||
///
|
||||
/// Draw line loop.
|
||||
fn draw_line_loop(
|
||||
&mut self,
|
||||
vao: VertexArrayHandle,
|
||||
vertex_count: u32,
|
||||
vertex_offset: u32,
|
||||
) -> GraphicsResult<()>;
|
||||
|
||||
/// 绘制连续线条
|
||||
///
|
||||
/// Draw line strip.
|
||||
fn draw_line_strip(
|
||||
&mut self,
|
||||
vao: VertexArrayHandle,
|
||||
vertex_count: u32,
|
||||
vertex_offset: u32,
|
||||
) -> GraphicsResult<()>;
|
||||
|
||||
// ==================== 查询 | Queries ====================
|
||||
|
||||
/// 获取最大纹理尺寸
|
||||
///
|
||||
/// Get max texture size.
|
||||
fn max_texture_size(&self) -> u32;
|
||||
|
||||
/// 是否支持某功能
|
||||
///
|
||||
/// Check feature support.
|
||||
fn supports_feature(&self, feature: GraphicsFeature) -> bool;
|
||||
|
||||
/// 获取最大纹理单元数
|
||||
///
|
||||
/// Get max texture units.
|
||||
fn max_texture_units(&self) -> u32 {
|
||||
16 // 默认值,后端可覆盖
|
||||
}
|
||||
|
||||
/// 获取最大顶点属性数
|
||||
///
|
||||
/// Get max vertex attributes.
|
||||
fn max_vertex_attributes(&self) -> u32 {
|
||||
16 // 默认值,后端可覆盖
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 扩展 Trait | Extension Traits ====================
|
||||
|
||||
/// 帧缓冲区操作扩展
|
||||
///
|
||||
/// Framebuffer operations extension.
|
||||
pub trait FramebufferExt: GraphicsBackend {
|
||||
/// 创建帧缓冲区
|
||||
///
|
||||
/// Create framebuffer.
|
||||
fn create_framebuffer(
|
||||
&mut self,
|
||||
color_attachment: TextureHandle,
|
||||
depth_attachment: Option<TextureHandle>,
|
||||
) -> GraphicsResult<FramebufferHandle>;
|
||||
|
||||
/// 销毁帧缓冲区
|
||||
///
|
||||
/// Destroy framebuffer.
|
||||
fn destroy_framebuffer(&mut self, handle: FramebufferHandle);
|
||||
|
||||
/// 绑定帧缓冲区
|
||||
///
|
||||
/// Bind framebuffer.
|
||||
fn bind_framebuffer(&mut self, handle: Option<FramebufferHandle>) -> GraphicsResult<()>;
|
||||
}
|
||||
|
||||
/// 实例化渲染扩展
|
||||
///
|
||||
/// Instanced rendering extension.
|
||||
pub trait InstancingExt: GraphicsBackend {
|
||||
/// 绘制实例化(索引)
|
||||
///
|
||||
/// Draw instanced (indexed).
|
||||
fn draw_indexed_instanced(
|
||||
&mut self,
|
||||
vao: VertexArrayHandle,
|
||||
index_count: u32,
|
||||
instance_count: u32,
|
||||
) -> GraphicsResult<()>;
|
||||
|
||||
/// 绘制实例化(非索引)
|
||||
///
|
||||
/// Draw instanced (non-indexed).
|
||||
fn draw_instanced(
|
||||
&mut self,
|
||||
vao: VertexArrayHandle,
|
||||
vertex_count: u32,
|
||||
instance_count: u32,
|
||||
) -> GraphicsResult<()>;
|
||||
}
|
||||
7
packages/rust/engine-shared/src/traits/mod.rs
Normal file
7
packages/rust/engine-shared/src/traits/mod.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
//! 图形后端 trait 定义
|
||||
//!
|
||||
//! Graphics backend trait definitions.
|
||||
|
||||
pub mod backend;
|
||||
pub mod platform;
|
||||
pub mod renderer;
|
||||
441
packages/rust/engine-shared/src/traits/platform.rs
Normal file
441
packages/rust/engine-shared/src/traits/platform.rs
Normal file
@@ -0,0 +1,441 @@
|
||||
//! 平台抽象 trait
|
||||
//!
|
||||
//! Platform abstraction trait.
|
||||
|
||||
use super::backend::{GraphicsBackend, GraphicsResult};
|
||||
use crate::types::texture::ImageData;
|
||||
use std::future::Future;
|
||||
|
||||
// ==================== 后端配置 | Backend Configuration ====================
|
||||
|
||||
/// 后端配置
|
||||
///
|
||||
/// Backend configuration.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BackendConfig {
|
||||
/// 画布/窗口 ID
|
||||
///
|
||||
/// Canvas/Window ID.
|
||||
pub canvas_id: Option<String>,
|
||||
|
||||
/// 初始宽度
|
||||
///
|
||||
/// Initial width.
|
||||
pub width: u32,
|
||||
|
||||
/// 初始高度
|
||||
///
|
||||
/// Initial height.
|
||||
pub height: u32,
|
||||
|
||||
/// 是否启用抗锯齿
|
||||
///
|
||||
/// Enable antialiasing.
|
||||
pub antialias: bool,
|
||||
|
||||
/// 是否使用高 DPI
|
||||
///
|
||||
/// Use high DPI.
|
||||
pub high_dpi: bool,
|
||||
|
||||
/// 电源偏好
|
||||
///
|
||||
/// Power preference.
|
||||
pub power_preference: PowerPreference,
|
||||
|
||||
/// 是否保留绘制缓冲区
|
||||
///
|
||||
/// Preserve drawing buffer.
|
||||
pub preserve_drawing_buffer: bool,
|
||||
|
||||
/// Alpha 模式
|
||||
///
|
||||
/// Alpha mode.
|
||||
pub alpha: bool,
|
||||
|
||||
/// 深度缓冲区大小(0 表示禁用)
|
||||
///
|
||||
/// Depth buffer size (0 to disable).
|
||||
pub depth_size: u8,
|
||||
|
||||
/// 模板缓冲区大小(0 表示禁用)
|
||||
///
|
||||
/// Stencil buffer size (0 to disable).
|
||||
pub stencil_size: u8,
|
||||
}
|
||||
|
||||
impl Default for BackendConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
canvas_id: None,
|
||||
width: 800,
|
||||
height: 600,
|
||||
antialias: false,
|
||||
high_dpi: true,
|
||||
power_preference: PowerPreference::HighPerformance,
|
||||
preserve_drawing_buffer: false,
|
||||
alpha: true,
|
||||
depth_size: 0,
|
||||
stencil_size: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BackendConfig {
|
||||
/// 创建新配置
|
||||
///
|
||||
/// Create new configuration.
|
||||
pub fn new(width: u32, height: u32) -> Self {
|
||||
Self {
|
||||
width,
|
||||
height,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// 设置画布 ID
|
||||
///
|
||||
/// Set canvas ID.
|
||||
pub fn with_canvas(mut self, canvas_id: impl Into<String>) -> Self {
|
||||
self.canvas_id = Some(canvas_id.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// 设置抗锯齿
|
||||
///
|
||||
/// Set antialiasing.
|
||||
pub fn with_antialias(mut self, antialias: bool) -> Self {
|
||||
self.antialias = antialias;
|
||||
self
|
||||
}
|
||||
|
||||
/// 设置高 DPI
|
||||
///
|
||||
/// Set high DPI.
|
||||
pub fn with_high_dpi(mut self, high_dpi: bool) -> Self {
|
||||
self.high_dpi = high_dpi;
|
||||
self
|
||||
}
|
||||
|
||||
/// 设置电源偏好
|
||||
///
|
||||
/// Set power preference.
|
||||
pub fn with_power_preference(mut self, preference: PowerPreference) -> Self {
|
||||
self.power_preference = preference;
|
||||
self
|
||||
}
|
||||
|
||||
/// 启用深度缓冲区
|
||||
///
|
||||
/// Enable depth buffer.
|
||||
pub fn with_depth(mut self, bits: u8) -> Self {
|
||||
self.depth_size = bits;
|
||||
self
|
||||
}
|
||||
|
||||
/// 启用模板缓冲区
|
||||
///
|
||||
/// Enable stencil buffer.
|
||||
pub fn with_stencil(mut self, bits: u8) -> Self {
|
||||
self.stencil_size = bits;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// 电源偏好
|
||||
///
|
||||
/// Power preference.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum PowerPreference {
|
||||
/// 低功耗(集成显卡)
|
||||
///
|
||||
/// Low power (integrated GPU).
|
||||
LowPower,
|
||||
|
||||
/// 高性能(独立显卡,默认)
|
||||
///
|
||||
/// High performance (discrete GPU, default).
|
||||
#[default]
|
||||
HighPerformance,
|
||||
}
|
||||
|
||||
// ==================== 资产加载器 | Asset Loader ====================
|
||||
|
||||
/// 资产加载错误
|
||||
///
|
||||
/// Asset loading error.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AssetError {
|
||||
/// 错误消息
|
||||
///
|
||||
/// Error message.
|
||||
pub message: String,
|
||||
|
||||
/// 资产路径
|
||||
///
|
||||
/// Asset path.
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for AssetError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "Failed to load '{}': {}", self.path, self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for AssetError {}
|
||||
|
||||
/// 资产加载结果
|
||||
///
|
||||
/// Asset loading result.
|
||||
pub type AssetResult<T> = Result<T, AssetError>;
|
||||
|
||||
/// 资产加载器 trait
|
||||
///
|
||||
/// Asset loader trait.
|
||||
pub trait AssetLoader {
|
||||
/// 加载二进制数据
|
||||
///
|
||||
/// Load binary data.
|
||||
fn load_bytes(&self, path: &str) -> impl Future<Output = AssetResult<Vec<u8>>> + Send;
|
||||
|
||||
/// 加载文本
|
||||
///
|
||||
/// Load text.
|
||||
fn load_text(&self, path: &str) -> impl Future<Output = AssetResult<String>> + Send;
|
||||
|
||||
/// 加载图片(返回 RGBA 数据)
|
||||
///
|
||||
/// Load image (returns RGBA data).
|
||||
fn load_image(&self, path: &str) -> impl Future<Output = AssetResult<ImageData>> + Send;
|
||||
}
|
||||
|
||||
// ==================== 输入系统 | Input System ====================
|
||||
|
||||
/// 鼠标按钮
|
||||
///
|
||||
/// Mouse button.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum MouseButton {
|
||||
/// 左键 | Left button
|
||||
Left,
|
||||
/// 中键 | Middle button
|
||||
Middle,
|
||||
/// 右键 | Right button
|
||||
Right,
|
||||
/// 其他按钮 | Other button
|
||||
Other(u8),
|
||||
}
|
||||
|
||||
/// 键盘键码(常用键)
|
||||
///
|
||||
/// Keyboard key code (common keys).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum KeyCode {
|
||||
// 字母键
|
||||
A, B, C, D, E, F, G, H, I, J, K, L, M,
|
||||
N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
|
||||
|
||||
// 数字键
|
||||
Key0, Key1, Key2, Key3, Key4,
|
||||
Key5, Key6, Key7, Key8, Key9,
|
||||
|
||||
// 功能键
|
||||
F1, F2, F3, F4, F5, F6,
|
||||
F7, F8, F9, F10, F11, F12,
|
||||
|
||||
// 控制键
|
||||
Escape, Tab, CapsLock, Shift, Control, Alt,
|
||||
Space, Enter, Backspace, Delete, Insert,
|
||||
Home, End, PageUp, PageDown,
|
||||
|
||||
// 方向键
|
||||
Up, Down, Left, Right,
|
||||
|
||||
// 符号键
|
||||
Minus, Equal, BracketLeft, BracketRight,
|
||||
Backslash, Semicolon, Quote, Comma, Period, Slash,
|
||||
Backquote,
|
||||
|
||||
// 其他
|
||||
Unknown(u32),
|
||||
}
|
||||
|
||||
/// 输入状态 trait
|
||||
///
|
||||
/// Input state trait.
|
||||
pub trait InputState {
|
||||
/// 检查按键是否按下
|
||||
///
|
||||
/// Check if key is pressed.
|
||||
fn is_key_down(&self, key: KeyCode) -> bool;
|
||||
|
||||
/// 检查按键是否刚按下(本帧)
|
||||
///
|
||||
/// Check if key was just pressed (this frame).
|
||||
fn is_key_just_pressed(&self, key: KeyCode) -> bool;
|
||||
|
||||
/// 检查按键是否刚释放(本帧)
|
||||
///
|
||||
/// Check if key was just released (this frame).
|
||||
fn is_key_just_released(&self, key: KeyCode) -> bool;
|
||||
|
||||
/// 检查鼠标按钮是否按下
|
||||
///
|
||||
/// Check if mouse button is pressed.
|
||||
fn is_mouse_button_down(&self, button: MouseButton) -> bool;
|
||||
|
||||
/// 获取鼠标位置
|
||||
///
|
||||
/// Get mouse position.
|
||||
fn mouse_position(&self) -> (f32, f32);
|
||||
|
||||
/// 获取鼠标滚轮增量
|
||||
///
|
||||
/// Get mouse wheel delta.
|
||||
fn mouse_wheel_delta(&self) -> f32;
|
||||
|
||||
/// 更新输入状态(每帧调用)
|
||||
///
|
||||
/// Update input state (call every frame).
|
||||
fn update(&mut self);
|
||||
}
|
||||
|
||||
// ==================== 平台 Trait | Platform Trait ====================
|
||||
|
||||
/// 平台抽象 trait
|
||||
///
|
||||
/// 定义平台相关操作的抽象接口。
|
||||
///
|
||||
/// Platform abstraction trait.
|
||||
/// Defines abstract interface for platform-specific operations.
|
||||
pub trait Platform {
|
||||
/// 后端类型
|
||||
///
|
||||
/// Backend type.
|
||||
type Backend: GraphicsBackend;
|
||||
|
||||
/// 资产加载器类型
|
||||
///
|
||||
/// Asset loader type.
|
||||
type AssetLoader: AssetLoader;
|
||||
|
||||
/// 输入状态类型
|
||||
///
|
||||
/// Input state type.
|
||||
type Input: InputState;
|
||||
|
||||
/// 创建图形后端
|
||||
///
|
||||
/// Create graphics backend.
|
||||
fn create_backend(&self, config: BackendConfig) -> GraphicsResult<Self::Backend>;
|
||||
|
||||
/// 获取资产加载器
|
||||
///
|
||||
/// Get asset loader.
|
||||
fn asset_loader(&self) -> &Self::AssetLoader;
|
||||
|
||||
/// 获取输入状态
|
||||
///
|
||||
/// Get input state.
|
||||
fn input(&self) -> &Self::Input;
|
||||
|
||||
/// 获取输入状态(可变)
|
||||
///
|
||||
/// Get input state (mutable).
|
||||
fn input_mut(&mut self) -> &mut Self::Input;
|
||||
|
||||
/// 获取屏幕尺寸
|
||||
///
|
||||
/// Get screen size.
|
||||
fn screen_size(&self) -> (u32, u32);
|
||||
|
||||
/// 获取设备像素比
|
||||
///
|
||||
/// Get device pixel ratio.
|
||||
fn device_pixel_ratio(&self) -> f32;
|
||||
|
||||
/// 获取当前时间(秒)
|
||||
///
|
||||
/// Get current time (seconds).
|
||||
fn time(&self) -> f64;
|
||||
|
||||
/// 请求下一帧
|
||||
///
|
||||
/// Request next frame.
|
||||
fn request_animation_frame(&self, callback: impl FnOnce(f64) + 'static);
|
||||
}
|
||||
|
||||
// ==================== 平台类型枚举 | Platform Type Enum ====================
|
||||
|
||||
/// 平台类型
|
||||
///
|
||||
/// Platform type.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum PlatformType {
|
||||
/// Web 浏览器
|
||||
///
|
||||
/// Web browser.
|
||||
Web,
|
||||
|
||||
/// 微信小游戏
|
||||
///
|
||||
/// WeChat Mini Game.
|
||||
WeChatMiniGame,
|
||||
|
||||
/// Windows 桌面
|
||||
///
|
||||
/// Windows desktop.
|
||||
Windows,
|
||||
|
||||
/// macOS 桌面
|
||||
///
|
||||
/// macOS desktop.
|
||||
MacOS,
|
||||
|
||||
/// Linux 桌面
|
||||
///
|
||||
/// Linux desktop.
|
||||
Linux,
|
||||
|
||||
/// Android
|
||||
Android,
|
||||
|
||||
/// iOS
|
||||
IOS,
|
||||
|
||||
/// 未知平台
|
||||
///
|
||||
/// Unknown platform.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl PlatformType {
|
||||
/// 是否为桌面平台
|
||||
///
|
||||
/// Check if desktop platform.
|
||||
pub const fn is_desktop(&self) -> bool {
|
||||
matches!(self, Self::Windows | Self::MacOS | Self::Linux)
|
||||
}
|
||||
|
||||
/// 是否为移动平台
|
||||
///
|
||||
/// Check if mobile platform.
|
||||
pub const fn is_mobile(&self) -> bool {
|
||||
matches!(self, Self::Android | Self::IOS)
|
||||
}
|
||||
|
||||
/// 是否为 Web 平台
|
||||
///
|
||||
/// Check if web platform.
|
||||
pub const fn is_web(&self) -> bool {
|
||||
matches!(self, Self::Web | Self::WeChatMiniGame)
|
||||
}
|
||||
|
||||
/// 是否为原生平台
|
||||
///
|
||||
/// Check if native platform.
|
||||
pub const fn is_native(&self) -> bool {
|
||||
!self.is_web()
|
||||
}
|
||||
}
|
||||
293
packages/rust/engine-shared/src/traits/renderer.rs
Normal file
293
packages/rust/engine-shared/src/traits/renderer.rs
Normal file
@@ -0,0 +1,293 @@
|
||||
//! 高级渲染器 trait
|
||||
//!
|
||||
//! High-level renderer trait.
|
||||
|
||||
use super::backend::{GraphicsBackend, GraphicsResult};
|
||||
use crate::camera::Camera2D;
|
||||
|
||||
// ==================== 精灵批处理数据 | Sprite Batch Data ====================
|
||||
|
||||
/// 精灵批处理数据
|
||||
///
|
||||
/// 与现有 TypeScript 层的 RenderBatcher 数据格式兼容。
|
||||
///
|
||||
/// Sprite batch data.
|
||||
/// Compatible with existing TypeScript RenderBatcher data format.
|
||||
#[derive(Debug)]
|
||||
pub struct SpriteBatchData<'a> {
|
||||
/// 变换数据:[x, y, rotation, scaleX, scaleY, originX, originY] per sprite
|
||||
///
|
||||
/// Transform data: [x, y, rotation, scaleX, scaleY, originX, originY] per sprite.
|
||||
pub transforms: &'a [f32],
|
||||
|
||||
/// 纹理 ID(每个精灵一个)
|
||||
///
|
||||
/// Texture ID (one per sprite).
|
||||
pub texture_ids: &'a [u32],
|
||||
|
||||
/// UV 坐标:[u0, v0, u1, v1] per sprite
|
||||
///
|
||||
/// UV coordinates: [u0, v0, u1, v1] per sprite.
|
||||
pub uvs: &'a [f32],
|
||||
|
||||
/// 打包的 RGBA 颜色(每个精灵一个)
|
||||
///
|
||||
/// Packed RGBA color (one per sprite).
|
||||
pub colors: &'a [u32],
|
||||
|
||||
/// 材质 ID(每个精灵一个,0 = 默认)
|
||||
///
|
||||
/// Material ID (one per sprite, 0 = default).
|
||||
pub material_ids: &'a [u32],
|
||||
}
|
||||
|
||||
impl<'a> SpriteBatchData<'a> {
|
||||
/// 获取精灵数量
|
||||
///
|
||||
/// Get sprite count.
|
||||
pub fn sprite_count(&self) -> usize {
|
||||
self.texture_ids.len()
|
||||
}
|
||||
|
||||
/// 验证数据一致性
|
||||
///
|
||||
/// Validate data consistency.
|
||||
pub fn validate(&self) -> Result<(), &'static str> {
|
||||
let count = self.sprite_count();
|
||||
|
||||
if self.transforms.len() != count * 7 {
|
||||
return Err("transforms length mismatch (expected count * 7)");
|
||||
}
|
||||
if self.uvs.len() != count * 4 {
|
||||
return Err("uvs length mismatch (expected count * 4)");
|
||||
}
|
||||
if self.colors.len() != count {
|
||||
return Err("colors length mismatch");
|
||||
}
|
||||
if self.material_ids.len() != count {
|
||||
return Err("material_ids length mismatch");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 相机状态
|
||||
///
|
||||
/// Camera state.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct CameraState {
|
||||
/// X 坐标 | X coordinate
|
||||
pub x: f32,
|
||||
/// Y 坐标 | Y coordinate
|
||||
pub y: f32,
|
||||
/// 缩放 | Zoom
|
||||
pub zoom: f32,
|
||||
/// 旋转(弧度)| Rotation (radians)
|
||||
pub rotation: f32,
|
||||
}
|
||||
|
||||
impl CameraState {
|
||||
/// 创建新的相机状态
|
||||
///
|
||||
/// Create new camera state.
|
||||
pub const fn new(x: f32, y: f32, zoom: f32, rotation: f32) -> Self {
|
||||
Self { x, y, zoom, rotation }
|
||||
}
|
||||
|
||||
/// 创建默认相机状态
|
||||
///
|
||||
/// Create default camera state.
|
||||
pub const fn identity() -> Self {
|
||||
Self {
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
zoom: 1.0,
|
||||
rotation: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// 转换为 Camera2D
|
||||
///
|
||||
/// Convert to Camera2D.
|
||||
pub fn to_camera2d(&self, width: f32, height: f32) -> Camera2D {
|
||||
Camera2D::new(width, height)
|
||||
.with_position(self.x, self.y)
|
||||
.with_zoom(self.zoom)
|
||||
.with_rotation(self.rotation)
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 2D 渲染器 Trait | 2D Renderer Trait ====================
|
||||
|
||||
/// 2D 渲染器 trait
|
||||
///
|
||||
/// 在 GraphicsBackend 基础上提供更高级的 2D 渲染 API。
|
||||
///
|
||||
/// 2D renderer trait.
|
||||
/// Provides higher-level 2D rendering API built on top of GraphicsBackend.
|
||||
pub trait Renderer2D {
|
||||
/// 后端类型
|
||||
///
|
||||
/// Backend type.
|
||||
type Backend: GraphicsBackend;
|
||||
|
||||
/// 获取底层后端
|
||||
///
|
||||
/// Get underlying backend.
|
||||
fn backend(&self) -> &Self::Backend;
|
||||
|
||||
/// 获取底层后端(可变)
|
||||
///
|
||||
/// Get underlying backend (mutable).
|
||||
fn backend_mut(&mut self) -> &mut Self::Backend;
|
||||
|
||||
/// 提交精灵批次
|
||||
///
|
||||
/// Submit sprite batch.
|
||||
fn submit_sprite_batch(&mut self, data: SpriteBatchData) -> GraphicsResult<()>;
|
||||
|
||||
/// 设置相机
|
||||
///
|
||||
/// Set camera.
|
||||
fn set_camera(&mut self, state: CameraState);
|
||||
|
||||
/// 获取相机状态
|
||||
///
|
||||
/// Get camera state.
|
||||
fn camera(&self) -> CameraState;
|
||||
|
||||
/// 渲染当前帧
|
||||
///
|
||||
/// Render current frame.
|
||||
fn render(&mut self) -> GraphicsResult<()>;
|
||||
|
||||
/// 清屏
|
||||
///
|
||||
/// Clear screen.
|
||||
fn clear(&mut self, r: f32, g: f32, b: f32, a: f32) {
|
||||
self.backend_mut().clear(r, g, b, a);
|
||||
}
|
||||
|
||||
/// 屏幕坐标转世界坐标
|
||||
///
|
||||
/// Screen to world coordinates.
|
||||
fn screen_to_world(&self, screen_x: f32, screen_y: f32) -> (f32, f32);
|
||||
|
||||
/// 世界坐标转屏幕坐标
|
||||
///
|
||||
/// World to screen coordinates.
|
||||
fn world_to_screen(&self, world_x: f32, world_y: f32) -> (f32, f32);
|
||||
}
|
||||
|
||||
// ==================== Gizmo 渲染器 Trait | Gizmo Renderer Trait ====================
|
||||
|
||||
/// Gizmo 类型
|
||||
///
|
||||
/// Gizmo type.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum GizmoShape {
|
||||
/// 矩形
|
||||
///
|
||||
/// Rectangle.
|
||||
Rect {
|
||||
x: f32,
|
||||
y: f32,
|
||||
width: f32,
|
||||
height: f32,
|
||||
rotation: f32,
|
||||
origin_x: f32,
|
||||
origin_y: f32,
|
||||
show_handles: bool,
|
||||
},
|
||||
|
||||
/// 圆形
|
||||
///
|
||||
/// Circle.
|
||||
Circle {
|
||||
x: f32,
|
||||
y: f32,
|
||||
radius: f32,
|
||||
},
|
||||
|
||||
/// 线段/多边形
|
||||
///
|
||||
/// Line/polygon.
|
||||
Line {
|
||||
points: Vec<(f32, f32)>,
|
||||
closed: bool,
|
||||
},
|
||||
|
||||
/// 胶囊体
|
||||
///
|
||||
/// Capsule.
|
||||
Capsule {
|
||||
x: f32,
|
||||
y: f32,
|
||||
radius: f32,
|
||||
half_height: f32,
|
||||
rotation: f32,
|
||||
},
|
||||
}
|
||||
|
||||
/// Gizmo 渲染器 trait(编辑器功能)
|
||||
///
|
||||
/// Gizmo renderer trait (editor feature).
|
||||
pub trait GizmoRenderer {
|
||||
/// 添加 Gizmo
|
||||
///
|
||||
/// Add gizmo.
|
||||
fn add_gizmo(&mut self, shape: GizmoShape, r: f32, g: f32, b: f32, a: f32);
|
||||
|
||||
/// 清空 Gizmo
|
||||
///
|
||||
/// Clear gizmos.
|
||||
fn clear_gizmos(&mut self);
|
||||
|
||||
/// 渲染 Gizmo
|
||||
///
|
||||
/// Render gizmos.
|
||||
fn render_gizmos(&mut self) -> GraphicsResult<()>;
|
||||
|
||||
/// 是否显示 Gizmo
|
||||
///
|
||||
/// Check if gizmos are visible.
|
||||
fn gizmos_visible(&self) -> bool;
|
||||
|
||||
/// 设置 Gizmo 可见性
|
||||
///
|
||||
/// Set gizmo visibility.
|
||||
fn set_gizmos_visible(&mut self, visible: bool);
|
||||
}
|
||||
|
||||
// ==================== 网格渲染器 Trait | Grid Renderer Trait ====================
|
||||
|
||||
/// 网格渲染器 trait(编辑器功能)
|
||||
///
|
||||
/// Grid renderer trait (editor feature).
|
||||
pub trait GridRenderer {
|
||||
/// 是否显示网格
|
||||
///
|
||||
/// Check if grid is visible.
|
||||
fn grid_visible(&self) -> bool;
|
||||
|
||||
/// 设置网格可见性
|
||||
///
|
||||
/// Set grid visibility.
|
||||
fn set_grid_visible(&mut self, visible: bool);
|
||||
|
||||
/// 渲染网格
|
||||
///
|
||||
/// Render grid.
|
||||
fn render_grid(&mut self) -> GraphicsResult<()>;
|
||||
|
||||
/// 设置网格大小
|
||||
///
|
||||
/// Set grid size.
|
||||
fn set_grid_size(&mut self, size: f32);
|
||||
|
||||
/// 设置网格颜色
|
||||
///
|
||||
/// Set grid color.
|
||||
fn set_grid_color(&mut self, r: f32, g: f32, b: f32, a: f32);
|
||||
}
|
||||
Reference in New Issue
Block a user