[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-115142":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":9,"language":10,"languages":9,"totalLinesOfCode":9,"stars":11,"forks":12,"watchers":13,"openIssues":14,"contributorsCount":14,"subscribersCount":14,"size":14,"stars1d":15,"stars7d":16,"stars30d":16,"stars90d":14,"forks30d":14,"starsTrendScore":17,"compositeScore":18,"rankGlobal":9,"rankLanguage":9,"license":19,"archived":20,"fork":20,"defaultBranch":21,"hasWiki":22,"hasPages":20,"topics":23,"createdAt":9,"pushedAt":29,"updatedAt":30,"readmeContent":31,"aiSummary":32,"trendingCount":14,"starSnapshotCount":14,"syncStatus":33,"lastSyncTime":34,"discoverSource":35},115142,"three-nanite","apekshik\u002Fthree-nanite","apekshik","Nanite-style virtual geometry (cluster LOD) for three.js: an offline GLB preprocessor and a WebGL2 runtime that works with stock materials.",null,"JavaScript",84,11,54,0,1,30,3,63.24,"MIT License",false,"main",true,[24,25,26,27,28],"lod","meshoptimizer","nanite","threejs","webgl","2026-11-15 10:17:28","2026-11-23 08:29:53","# three-nanite\n\nNanite-style virtual geometry for three.js: a cluster LOD hierarchy (a DAG of meshlets) built offline from a GLB, and a small runtime that picks a crack-free cut of it every frame and draws it with stock three.js materials.\n\n![96 instances of three 262k-triangle models, coloured by cluster](docs\u002Fimages\u002Fdemo_clusters.jpg)\n\nTwo parts:\n\n- **A preprocessor** (`three-nanite build model.glb out\u002F`). Node, no native code. It uses the WASM build of [meshoptimizer](https:\u002F\u002Fgithub.com\u002Fzeux\u002Fmeshoptimizer) and follows its `clusterlod.h`.\n- **A runtime** (`import { ClodBatch, ClodSelector } from 'three-nanite'`). About 500 lines with `three` as its only dependency. Selection runs on the CPU; drawing is one `WEBGL_multi_draw` call per mesh type through three's own `BatchedMesh` shader path, so `MeshStandardMaterial` and the other built-in materials work unchanged.\n\n> **Status: an experiment that works, not a production engine feature.** Read [what it does not do](#what-it-does-and-does-not-do) before you plan around it. \"Nanite\" is a trademark of Epic Games; this project is not affiliated with or derived from Unreal Engine code.\n\n## What it does and does not do\n\nIt does:\n\n- Turn a dense mesh (tested up to 1.97M triangles) into a hierarchy of 128-triangle clusters in 4 to 7 seconds.\n- Pick detail per cluster from projected error in pixels, so one mesh can be coarse on its far side and fine on its near side with no cracks between the two. An offline crack test (`three-nanite verify`) is included.\n- Or pick detail from a **scene-wide triangle budget**: refine the worst cluster group anywhere in the scene first until the budget is spent. This holds a 300k budget to within 0.3% and its cost does not grow with scene size.\n- Frustum-cull per instance, per group and per cluster. Optionally occlusion-cull whole instances against an older depth buffer.\n- Optionally stream geometry by level with HTTP Range requests.\n- Draw many instances of each mesh with stock materials and stock shadow maps.\n\nIt does not, and the measurements in [docs\u002FREPORT.md](docs\u002FREPORT.md) are blunt about it:\n\n- **It does not make triangles free.** There is no compute or software rasteriser and no visibility buffer, which is how Unreal affords pixel-sized triangles. Everything goes through the normal hardware rasteriser and forward shading. On the integrated AMD GPU used for testing, a PBR material at 1080p cost **about 8 ms per million drawn triangles**. A 1 px error threshold really does ask for roughly one triangle per pixel, so the practical settings on such hardware are a 4 to 8 px threshold or a triangle budget.\n- **The data is big.** A 1.9M-triangle model becomes about 67 MB of uncompressed hierarchy (25 MB vertices, 42 MB of 32-bit indices), plus about 18 MB if the optional discrete LODs are kept. Nothing is quantised or compressed. meshopt codecs would roughly halve it (estimated by running the encoder; the decoder is not wired in). Use `--max-tris` to cap the source: 60k triangles gives about 3 MB.\n- **It leans on `WEBGL_multi_draw`.** Chrome, Edge and Safari 15+ have it. **Firefox does not**, and three.js then issues one draw call per cluster, which is thousands per frame. There is no fallback path here yet. Even where the extension exists, ANGLE implements it as a loop, so cost per cluster is not zero (about 0.2 ms per thousand clusters on D3D11, inferred from a few runs).\n- **Static, opaque, rigid meshes only.** No skinning, no morph targets, no transparency sorting. Instance transforms are fixed when the batch is created and must use uniform scale.\n- **One material and one UV set per asset.** The preprocessor keeps position, normal and `TEXCOORD_0`, and the textures of the first material it meets. No tangents, vertex colours or second UV set.\n- **No geomorphing.** Clusters swap instantly. At 1 to 2 px this was not visible in captured frames; at high thresholds or tight budgets it is.\n- **The coarsest levels look bad.** When edge collapse gets stuck on UV seams the builder falls back to vertex clustering, which smears textures and merges thin parts. Expect this from about 8 to 10 px of effective error.\n- **Streaming is coarse.** It loads whole levels per asset and never evicts. Nanite streams 128 KB pages of cluster groups.\n- **Occlusion culling is partial.** Whole instances only, against depth that is a frame or more old, with no second pass, so newly revealed objects appear late.\n- **Shadows redraw the camera's cut.** Triangle cost doubles and objects outside the view cast no shadow.\n- **Raycasting and collision need their own mesh.** `Mesh.raycast` on a batch would see every level at once.\n- **It depends on three.js internals.** `ClodBatch` poses as a `BatchedMesh` by filling its private fields. Tested with three 0.186.1 and 0.187.0; a later release can break it.\n\nIf your target is WebGPU only, look at [three-virtual-geometry](https:\u002F\u002Fgithub.com\u002Felad12390\u002Fthree-virtual-geometry) first: it does culling in compute shaders inside `WebGPURenderer`. It was not evaluated here.\n\n## Install\n\n```bash\nnpm install github:apekshik\u002Fthree-nanite three\n```\n\n`three` is a peer dependency (0.186 or newer). Node 20 or newer for the CLI.\n\n## Quick start\n\n### 1. Build a model\n\n```bash\nnpx three-nanite build model.glb public\u002Fdata --name rock\n```\n\nThis writes `public\u002Fdata\u002Frock.bin`, `public\u002Fdata\u002Frock.json` and the model's textures. Options:\n\n| Option | Meaning |\n|---|---|\n| `--name \u003Cname>` | Output file stem. Default: the GLB's file name. |\n| `--max-tris \u003Cn>` | Simplify the source to at most `n` triangles first. The main lever on file size. |\n| `--tex \u003Cpx>` | Resize textures to `px` x `px` JPEG. Needs `ffmpeg` on the PATH. Without it, textures are copied out unchanged. |\n| `--edge-limit \u003Cf>` | Cap each group's error at `f` x its longest edge, as `clusterlod.h` does. Fewer triangles far away (up to 46% beyond 100 m in one test). Try `1`. |\n| `--no-lods` | Skip the four discrete LODs. They are only needed by `DiscreteLodSet` and add about a quarter to the file. |\n| `--quiet` | No progress output. |\n\nInput must be a binary glTF (`.glb`) with uncompressed geometry. Draco and meshopt-compressed files are rejected with a message; decompress them first. All triangle meshes in the default scene are merged into one, with node transforms applied.\n\nTwo more commands check the result:\n\n```bash\nnpx three-nanite verify public\u002Fdata rock\n```\n\n```bash\nnpx three-nanite stats public\u002Fdata rock\n```\n\n`verify` selects cuts by brute force from seven camera positions at five thresholds and counts open edges; it exits non-zero if any cut has a crack. `stats` prints how many triangles a cut holds at 1, 2 and 4 px for distances from 1.5 m to 200 m.\n\n### 2. Draw it\n\n```js\nimport * as THREE from 'three';\nimport { loadClod, loadClodMaterial, ClodBatch, ClodSelector } from 'three-nanite';\n\nconst asset = await loadClod('\u002Fdata', 'rock');\nconst material = loadClodMaterial('\u002Fdata', asset);        \u002F\u002F or any stock three.js material\n\n\u002F\u002F one Matrix4 per instance, world space, uniform scale\nconst matrices = [];\nfor (let i = 0; i \u003C 100; i++) matrices.push(new THREE.Matrix4().makeTranslation((i % 10) * 3, 0, Math.floor(i \u002F 10) * 3));\n\nconst batch = new ClodBatch(asset, material, matrices);\nscene.add(batch);\n\nconst selector = new ClodSelector([batch \u002F*, batches of other assets *\u002F]);\n\nrenderer.setAnimationLoop(() => {\n  \u002F\u002F pick the cut, then render as usual\n  selector.select(camera, renderer.domElement.height, { errorPx: 4, budget: 0 });\n  renderer.render(scene, camera);\n});\n```\n\n`errorPx` is the allowed geometric error in pixels. `budget` is a triangle count for the whole selector; when it is above zero the selector refines worst-first until the budget is spent, and `errorPx` becomes the floor below which it stops refining. Something like `{ errorPx: 0.5, budget: 300000 }` gives a fixed cost per frame.\n\nThe data folder can be served by anything. Streaming additionally needs a host that honours HTTP Range requests.\n\n## Demo\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Fapekshik\u002Fthree-nanite.git\n```\n\n```bash\nnpm install\n```\n\n```bash\nnpm run dev\n```\n\nThen open `http:\u002F\u002Flocalhost:5291\u002F`. The first run generates three procedural models (a boulder, a rope knot and a fluted column, 262k triangles each) and builds them into `examples\u002Fpublic\u002Fdata`, which takes a few seconds. No model files are stored in the repository.\n\nTo see your own model in the demo, build it into the same folder and restart:\n\n```bash\nnpx three-nanite build model.glb examples\u002Fpublic\u002Fdata\n```\n\nControls: drag to look, WASD and Q\u002FE to fly, shift to go faster. The panel switches between the cluster hierarchy, discrete LODs and full meshes, sets the error threshold and the triangle budget, and colours by cluster or by hierarchy level. Query parameters: `?stream=1` loads geometry on demand, `?occ=1&walls=1` turns on occlusion culling with some walls to hide behind, `?assets=a,b` picks assets, `?count=384` sets the instance count. `\u002Fwebgpu.html` runs the same batch under `WebGPURenderer`, and `\u002Fminimal.html` ([examples\u002Fminimal.js](examples\u002Fminimal.js)) is the quick start above as a complete page.\n\n![Textured view](docs\u002Fimages\u002Fdemo_textured.jpg)\n\n## API\n\n### Runtime: `three-nanite`\n\n**`loadClod(base, name)`** → `Promise\u003Casset>`\nFetches `\u003Cbase>\u002F\u003Cname>.json` and `\u003Cbase>\u002F\u003Cname>.bin` whole. The asset holds `meta` (the JSON), `geometry` (a `BufferGeometry` with every level in it; do not draw it directly), `sphere` (bounding sphere in model space) and the hierarchy arrays.\n\n**`loadClodStream(base, name, { rootBytes = 96 * 1024, delayMs = 0 })`** → `Promise\u003Casset>`\nLoads the hierarchy and the coarsest levels that fit in `rootBytes`, and fetches finer levels later with Range requests. Use with `updateStreaming`. Useful fields: `loadedLevel` (0 means everything is loaded), `residentBytes`, `fullBytes`. Streaming assets cannot be used with `DiscreteLodSet`.\n\n**`updateStreaming(assets)`** → `Promise[]`\nCall once per frame after `select()`. Starts a fetch for each streaming asset whose last selection wanted finer levels than it has.\n\n**`loadClodMaterial(base, asset, params?)`** → `MeshStandardMaterial`\nConvenience: wires up the base colour, normal and occlusion\u002Froughness\u002Fmetal textures and the material factors that the preprocessor copied out of the GLB. `params` overrides anything.\n\n**`new ClodBatch(asset, material, matrices)`**\nA `THREE.Mesh` that draws all instances of one asset. `matrices` is an array of `Matrix4` in world space. Leave the batch's own transform at identity. Set `castShadow` and `receiveShadow` as on any mesh. Custom shaders must include three's `batching` shader chunks.\n\n**`new ClodSelector(batches)`**\n\n- `select(camera, viewportHeightPx, { errorPx, budget })` writes the draw list of every batch and returns `{ tris, clusters, visited, ms, threshold, occluded }`. `threshold` is the effective error in pixels, which in budget mode tells you how much quality the budget bought. The camera must be a `PerspectiveCamera`.\n- `frustumCull` (default `true`).\n- `hzb`: set to a depth snapshot `{ data, w, h, vp, near, far, px, py }` to occlusion-cull instances. `examples\u002Fmain.js` shows how to produce one from a depth texture with an asynchronous readback.\n\n**`new DiscreteLodSet(asset, material, matrices)`**\nThe conventional baseline, for comparison: one `InstancedMesh` per discrete LOD. `select(cameraPosition, frustum, K, errorPx, forceFull)` picks a level per instance, where `K = viewportHeight \u002F (2 * tan(fov \u002F 2))`.\n\n**`patchDebug(material)`**, **`debugUniform`**\nAdds cluster and level colouring to a material for `WebGLRenderer`. Set `debugUniform.value` to `0` (off), `1` (clusters) or `2` (hierarchy level).\n\n**`sphereOccluded(hzb, x, y, z, r)`** → `boolean`\nThe occlusion test the selector uses, exported for testing other bounds.\n\n### Preprocessor: `three-nanite\u002Fbuild` (Node)\n\n```js\nimport { buildClod, verifyClod, cutStats } from 'three-nanite\u002Fbuild';\n\nconst { meta } = await buildClod({\n  input: 'model.glb', outDir: 'public\u002Fdata', name: 'rock',\n  maxTriangles: 0, textureSize: 0, edgeLimit: 0, lods: true,\n  log: console.log,\n});\nconst { ok } = await verifyClod('public\u002Fdata', 'rock');\n```\n\nFurther tuning options of `buildClod`: `normalWeight` (0.5) and `uvWeight` (0.1) for the simplifier, `sloppyAt` (0.7) for when to fall back to vertex clustering, `errorCap` (0.15 of the group radius).\n\n### File format\n\n`\u003Cname>.json` describes sections of `\u003Cname>.bin` by offset, byte length and typed-array type: `positions` (3 floats), `normals` (4 signed bytes, normalised), `uvs` (2 floats), `indices` (32-bit), and the hierarchy: `clusterF` (bounding sphere per cluster), `clusterU` (index offset, index count, producing group or -1, level), `groupF` (bounding sphere and error per group), `memberOff` and `memberIds` (clusters consumed by each group). Clusters are stored coarsest level first and vertices are numbered in that order, so \"everything down to level L\" is a prefix of both buffers. That is what makes level streaming a plain Range request, and it also halved frame time on the integrated GPU because coarse clusters read a compact part of the vertex buffer. The format has a `version` field (currently 3) and no stability promise.\n\n## How it works\n\nBuild, following meshoptimizer's `clusterlod.h`:\n\n1. Split the mesh into meshlets of at most 128 triangles.\n2. Group about 16 adjacent meshlets and lock every vertex shared between two groups.\n3. Simplify each group to half its triangles with attribute-aware edge collapse (normals and UVs weighted, UV seams protected). If that gets stuck, fall back to vertex clustering and double the recorded error.\n4. Split the result into meshlets again. Each new cluster remembers the group that produced it. Error and bounding sphere are forced to grow going up.\n5. Repeat until one cluster is left.\n\nAt run time a cluster is drawn when the group that produced it has projected error at or below the threshold while the group that consumes it is above it. Because error is monotonic and group borders were locked, neighbouring clusters always agree and no cracks appear, even with five levels mixed in one mesh.\n\n## Relation to Unreal's Nanite\n\nThe hierarchy and the selection rule are the ones Karis, Stubbe and Wihlidal describe. Most of what makes Nanite fast is missing:\n\n| | Nanite | three-nanite |\n|---|---|---|\n| Cluster DAG with locked group borders, monotonic error | Yes | Yes |\n| Cut selection | GPU, parallel, per view | CPU, single thread, about 1 ms for 96 instances |\n| Rasterisation | Compute-shader rasteriser for small triangles, hardware for large | Hardware only |\n| Shading | Visibility buffer, deferred materials | Forward, stock three.js materials |\n| Occlusion culling | Two-pass hierarchical Z per cluster | One pass, whole instances, stale depth |\n| Streaming | 128 KB pages of cluster groups, with eviction | Whole levels per asset, no eviction |\n| Compression | Quantised, entropy-coded, about 14 bits per triangle on disk | None |\n| Shadows | Virtual shadow maps with their own cuts | Stock shadow maps reusing the camera's cut |\n| Triangle budget across the scene | No, it chases pixel error | Yes, because here triangles are not cheap |\n\n[docs\u002FRESEARCH.md](docs\u002FRESEARCH.md) goes through Nanite stage by stage, lists other reimplementations, and says for each stage what a browser can and cannot do, with sources.\n\n## Relation to meshoptimizer's `clusterlod.h`\n\nThe build is a JavaScript port of that algorithm on top of the meshoptimizer WASM modules (`buildMeshlets`, `simplifyWithAttributes`, `simplifySloppy`). The differences:\n\n- The JS build of meshoptimizer has no `meshopt_partitionClusters`, so grouping is written here: heavy-edge matching on shared boundary vertices, with a Morton-order fallback for islands. The original's partitioner is likely better.\n- The edge-length error limit is optional here (`--edge-limit`) and off by default.\n- Output is this library's own file format, laid out for prefix streaming.\n\nIf you can run native code, the C++ original is the better builder.\n\n## Development\n\n```bash\nnpm test\n```\n\nbuilds a procedural model into a temporary folder and runs the crack test on it. The demo page exposes `window.demo.bench()`, `trace()` and `capture()` for timing runs; with `?auto=\u003Cname>` it runs a whole suite and saves `out\u002Fbench\u002F\u003Cname>.json`, which `node examples\u002Fbench-table.mjs` prints.\n\n## Credits and sources\n\n- Brian Karis, Rune Stubbe, Graham Wihlidal, [\"Nanite: A Deep Dive\"](https:\u002F\u002Fadvances.realtimerendering.com\u002Fs2021\u002FKaris_Nanite_SIGGRAPH_Advances_2021_final.pdf), SIGGRAPH 2021 Advances in Real-Time Rendering.\n- [meshoptimizer](https:\u002F\u002Fgithub.com\u002Fzeux\u002Fmeshoptimizer) by Arseny Kapoulkine (MIT), both the library this builds on and the `demo\u002Fclusterlod.h` it follows.\n- [three.js](https:\u002F\u002Fthreejs.org\u002F) (MIT), in particular the `BatchedMesh` multi-draw path this reuses.\n- Full source list with a read \u002F not-verified mark per claim: [docs\u002FRESEARCH.md](docs\u002FRESEARCH.md) and `docs\u002Fresearch\u002F`.\n\n## Licence\n\nMIT, see [LICENSE](LICENSE).\n","three-nanite 是一个为 three.js 设计的 Nanite 风格虚拟几何体（集群 LOD）实现，包含离线 GLB 预处理器和轻量 WebGL2 运行时。它将高模网格离线切分为 128 三角形的 meshlet 集群，构建 DAG 层次结构，并在运行时基于像素误差或全局三角形预算动态选择无裂缝的 LOD 切片；支持实例化渲染、逐集群视锥裁剪、可选深度缓冲遮挡剔除及 HTTP Range 分块流式加载。所有功能兼容 three.js 原生材质（如 MeshStandardMaterial）与批处理管线，无需修改着色器。适用于 Web 端中高复杂度静态模型的实时 LOD 渲染场景，如数字孪生、建筑可视化与轻量 3D 展示应用。",2,"2026-11-24 04:50:30","CREATED_QUERY"]