# webcs **Repository Path**: lightsever/webcs ## Basic Information - **Project Name**: webcs - **Description**: 探索性项目,用于把c#代码编译为 ts 和 wasm,用于web和小游戏等开发环境。 以ts为主,方便调试。 wasm为辅,对数据密集型业务,提高操作性能。 你可以理解为像burst 一样,只把性能关键的代码编译为wasm - **Primary Language**: C# - **License**: MulanPSL-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 2 - **Forks**: 1 - **Created**: 2026-04-27 - **Last Updated**: 2026-05-16 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # WebCS **C# → JavaScript 转译器** 基于 Roslyn 解析 C# 源码,直接生成可在浏览器运行的 JavaScript。无需 WebAssembly,无需 GC 运行时,调试友好。

粒子风暴 TTEngine 渲染 Canvas 2D

--- ## 特性 **语言特性** - 完整 C# 语法:类、结构体、枚举、泛型、元组、Lambda、运算符重载、扩展方法、事件 - async/await → Promise 直译,Task.Delay / Task.Yield 运行时支持 - System.Math → JS Math 一一映射 **值语义 & 内存** - **struct 值语义模拟**:赋值/传参/返回自动 `_clone()` - **[JSMemoryFlat]**:结构体二进制序列化,直接读写 DataView,适用于 WebGL 顶点填充 - TypedArray 映射:`int[]` → `Int32Array`,`float[]` → `Float32Array` **JS 互操作** - **[JSModule]** 引用任意 JS 库,C# 接口描述 JS 对象结构 - **[JSInsert]** 内联 JS 代码 - 匿名对象 `new { x = 1 }` → `{ x: 1 }` **平台 API** - 浏览器 API:DOM、Canvas 2D、WebGL2、Fetch、Storage、事件 - 微信小游戏 API:触摸、文件、网络、音频、存储 - TTEngine 渲染引擎:批量精灵渲染、GPU 实例化、文字绘制、平台抽象层 **开发体验** - Source Map v3(嵌入 C# 源码),浏览器直接断点调试 C# - 单文件输出,零依赖部署 ## 快速开始 ```bash git clone webcs && cd webcs dotnet build ``` ```bash # 转译 C# 项目为 JS dotnet run --project src/webcs.builder -- conv <项目目录> <输出目录> # 打开 Edge 预览 dotnet run --project src/webcs.builder -- openedge <输出目录> ``` ## 示例 ```bash cd samples/HelloWorld && dotnet build ``` 输出到 `dist/`: ``` dist/ ├── HelloWorld.js # 转译后的 JS(含 Source Map) ├── index.html # 入口页面 ├── webcslib.math.js # 数学库 ├── webcslib.ttengine.js # TTEngine 渲染引擎 ├── webcslib.ttengine.browser.js # TTEngine 浏览器实现 ├── js/ # JS 库(png-codec、gifuct、pako) └── img/ # 静态资源 ``` ## struct 值语义 JS 没有值类型,WebCS 通过自动克隆模拟: ```csharp public struct Point { public double x, y; public double Length => Math.Sqrt(x * x + y * y); } ``` 转译结果: ```javascript class Point { x; y; static _clone(self) { const c = new Point(); c.x = self.x; c.y = self.y; return c; } } // 赋值自动克隆:let a = Point._clone(b); ``` ### [JSMemoryFlat] 二进制序列化 直接操作 DataView,零开销填充 WebGL 顶点: ```csharp [JSMemoryFlat] public struct Vertex { public float x, y, z; // 12 bytes public byte r, g, b, a; // 4 bytes } ``` ```javascript Vertex._Size() // → 16 Vertex._ReadFromDataView(self, dv, offset) // 从 DataView 读取 Vertex._WriteToDataView(dv, offset, self) // 写入 DataView ``` ## 引用 JS 库 `[JSModule]` 导入 + `[JSType]` 描述接口: ```csharp [JSModule(Path = "./js/png-codec.mjs")] [JSType] public static class PngParser { [JSAPI(Name = "decodePng")] public static Task decodePng(byte[] data) => null; } ``` 自动生成 ES6 import: ```javascript import { decodePng } from './js/png-codec.mjs'; let decoded = await decodePng(new Uint8Array(buf)); ``` ## 浏览器 API ```csharp using Webcs; using Webcs.Browser; // DOM var title = (IHTMLElement)Document.createElement("h1"); title.textContent = "Hello WebCS!"; Document.body.appendChild(title); // Canvas 2D var canvas = (IHTMLCanvasElement)Document.createElement("canvas"); canvas.width = 800; canvas.height = 600; var ctx = (ICanvasRenderingContext2D)canvas.getContext("2d"); ctx.fillStyle = "#e94560"; ctx.fillRect(10, 10, 100, 50); // WebGL2 + antialias: false var gl = (IWebGL2RenderingContext)canvas.getContext("webgl2", new { antialias = false }); // Fetch var resp = await JS.fetch("/api/data"); var json = await resp.text(); ``` ## TTEngine 渲染引擎 2D 渲染引擎,支持浏览器和微信小游戏: ```csharp // 初始化(自动 DPI 点对点 + 关闭抗锯齿) BrowserPlatform.init(canvas); // 批量精灵渲染 var batcher = new PackedTextureBatcher(); batcher.setPackElement(atlas); batcher.beginDraw(); batcher.drawSprite(sprite1); batcher.drawSprite(sprite2); batcher.endDraw(); // 合批提交 // GPU 实例化 — 8000 粒子单次 draw call var inst = new PackedTextureInstanceBatcher(); inst.beginDraw(); for (int i = 0; i < 8000; i++) inst.addElementInst(particles[i]); inst.endDraw(); ``` ## 类型映射 | C# | JavaScript | 说明 | |---|---|---| | `int` `short` `byte` | `number` | 运算自动 `\| 0` 截断 | | `double` `float` | `number` | | | `bool` | `boolean` | | | `string` | `string` | | | `int[]` | `Int32Array` | | | `float[]` | `Float32Array` | | | `byte[]` | `Uint8Array` | | | `List` | `Array` | | | `Dictionary` | `Map` | | | `Task` | `Promise` | async/await 直译 | | `ArrayBuffer` | `ArrayBuffer` | | | `new { x = 1 }` | `{ x: 1 }` | 匿名对象 | ## 架构 ```mermaid flowchart LR A["C# 源码"] --> B["Roslyn AST"] B --> C["SyntaxTranslator"] C --> D["JavaScript"] D --> E["Source Map v3"] D --> F["index.html"] ``` ``` src/ ├── webcs.builder/ # 转译器核心 │ ├── Analysis/ # Roslyn 解析 + AST → JS 转译 │ └── Generation/ # 文件生成(Source Map、HTML、模块) ├── webcsapi/ # 核心 API 绑定(DOM、Canvas、Attribute) ├── webcsapi.browser/ # 浏览器扩展 API(Fetch、WebGL、Storage) ├── webcsapi.wx/ # 微信小游戏 API(wx 全局对象) ├── webcslib.math/ # 数学库(Vector2/3/4、Color32、Rect) ├── webcslib.imgdec/ # 图像解码(PNG/GIF JSModule 绑定) ├── webcslib.ttengine/ # TTEngine 渲染引擎(平台抽象层) ├── webcslib.ttengine.browser/ # TTEngine 浏览器实现 └── webcslib.ttengine.wx/ # TTEngine 微信小游戏实现 ``` ## 文档 - [语法支持说明](docs/syntax-support.md) — C# 特性支持/不支持分类 - [JS 导出方法文档](docs/js-export.md) — Attribute 用法、JS 对象映射、接口列表 - [struct 转译说明](docs/struct.md) — 值语义模拟、JSMemoryFlat 二进制序列化 - [开发历史](history.md) — 按时间倒序 ## License MIT