⏳ This skill is pending AI review.
Scores will appear once the review pipeline completes.
threejs-architecture-effects
Build or refine real Three.js architectural construction animations, especially Chinese pavilions, pagodas and clock towers with brick-by-brick growth, timber framing, layered eaves, procedural PBR materials and interactive detail cameras. Use for 3D建筑生长、古建搭建特效、楼台逐层建造、建筑动态组装 or similar architectural miniatures; not for flat image reveals or generic website styling.
Choose how to use this skill
You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.
1. Native installer
This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.
Do not guess an installer command or replace an existing version without reviewing the diff.
2. Complete package recommended
Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.
No complete ProSkills package is published for this listing yet.3. Prompt-only
Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.
Need only the instruction file?
Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.
No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.
// RATINGS
Not yet listed on ClawHub or SkillsMP
// README
threejs-architecture-effects
Portable Agent Skill by Hailey. It builds a real, orbitable Three.js building that assembles itself: brick courses, timber frame, dougong, layered eaves, procedural PBR materials, and close-up cameras.
中文:给 Codex / Claude Code / Cursor 用的开源 skill。输出是可运行的三维古建网站,不是贴图揭幕,也不需要 API key。
GitHub README cannot play a repo .mp4 inline, so the motion preview is a GIF. Click it (or the link) to play the full video.
What you get
- A solid 3D miniature, not a video on a plane
- Construction driven by one 0–1 timeline: play, pause, scrub backward, replay
- Procedural brick, wood, plaster, tile, stone, bronze — no paid models
- Orbit, zoom, and detail cameras for eaves and stone lions
- A Vite + React + Three.js starter you can run with
npm ci && npm run dev
The bundled clock tower is a working example, not a historical reconstruction and not the only design this skill can make.
Install
Copy this folder into the agent skills directory, then start a new session:
| Runner | Path |
|---|---|
| Codex | ~/.codex/skills/threejs-architecture-effects (or $CODEX_HOME/skills/) |
| Claude Code | ~/.claude/skills/threejs-architecture-effects |
| Cursor | ~/.cursor/skills/threejs-architecture-effects |
git clone https://github.com/lhlGitHub/threejs-architecture-effects.git
cp -R threejs-architecture-effects ~/.cursor/skills/
Then ask:
Use $threejs-architecture-effects to make a Chinese pavilion like the starter: red walls, dark-green tiles, built storey by storey, orbitable, with eave close-ups.
Other useful prompts:
- Keep the current tower shape and cameras. Only refine eave thickness, timber, and the clock faces.
- Turn the template into a two-storey lakeside pavilion. Keep timber and tile assembly. No clocks or lions.
Run the starter without an agent
Needs Node.js 22.13+, npm, and a WebGL2 browser.
git clone https://github.com/lhlGitHub/threejs-architecture-effects.git
node threejs-architecture-effects/scripts/scaffold.mjs ./my-building
cd my-building
npm ci
npm run dev
The scaffold copies assets/starter/ into a new directory and refuses to overwrite an existing one. It does not install packages or start a server.
Controls: drag to orbit, scroll to zoom, timeline to scrub, 飞檐细赏 / 石狮近观 for close-ups.
How construction works
- Write an assembly plan: foundations → frame → masonry → decks → upper walls → brackets / eaves / tiles → ornament.
- Model the finished silhouette first so parts share dimensions and nothing floats.
- Give every solid piece a start, duration, and travel. Color and shadow shaders share one progress value, so seeking is deterministic.
- Author materials separately (color, roughness, micro-height). Do not hide crude joints with fog or bloom.
Details for agents: SKILL.md, construction principles, template map, verification.
Layout
threejs-architecture-effects/
├── SKILL.md Agent entry
├── LICENSE MIT, Copyright (c) 2026 Hailey
├── agents/openai.yaml Codex UI metadata
├── scripts/scaffold.mjs Copy the starter into a new project
├── references/ Construction, template map, verification
├── assets/preview.gif README motion preview
├── assets/preview.png README still
├── assets/preview.mp4 Full screen recording
└── assets/starter/ Vite + React + Three.js miniature
Limits
- Procedural geometry only. No paid model service, no background music in the starter.
- Video export is not included; the template is an interactive site.
- Desktop-oriented. Do not claim museum quality, historical accuracy, or universal 60 FPS from one machine.
- npm packages keep their own licenses. This skill does not vendor
node_modules.
License
MIT. Copyright (c) 2026 Hailey. See LICENSE.
// HOW IT'S BUILT
// FILES
27 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.
SKILL.md4.6 KB0fb8575152f6upstream ↗
--- name: threejs-architecture-effects description: Build or refine real Three.js architectural construction animations, especially Chinese pavilions, pagodas and clock towers with brick-by-brick growth, timber framing, layered eaves, procedural PBR materials and interactive detail cameras. Use for 3D建筑生长、古建搭建特效、楼台逐层建造、建筑动态组装 or similar architectural miniatures; not for flat image reveals or generic website styling. license: MIT metadata: author: Hailey version: "1.0.0" requires: "Node.js 22.13+, npm, WebGL2 browser. No API keys." --- # Three.js Architecture Effects Create an actual, orbitable 3D building assembled from solid components. The included clock-tower miniature is a working reference, not a mandatory design or a historical reconstruction. Resolve `<this-skill-dir>` from the loaded `SKILL.md`. Do not mix files from a different install of this skill. ## References | File | Read it when | | --- | --- | | [references/template-guide.md](references/template-guide.md) | scaffolding a new project or mapping starter files | | [references/construction-principles.md](references/construction-principles.md) | geometry, assembly timing, materials, or lighting | | [references/verification.md](references/verification.md) | stutter, quality checks, metrics, or handoff | ## Choose the starting point - **Existing project:** inspect its scene owner, geometry factories, timing, materials, controls, and renderer diagnostics before editing. Preserve its recognizable design, cameras, and interactions unless the user asks to change them. Do not scaffold over it. - **New project:** read the template guide, then run `node <this-skill-dir>/scripts/scaffold.mjs <new-project-directory>`. The script refuses an existing destination. It copies a self-contained Vite/React/Three.js starter; it does not install packages or start services. - **Reference video or images:** inspect the supplied media as reference only. Identify structural stages and proportions. Do not return the reference video as your work, paste screenshots onto planes, or promise an unsupported similarity percentage. ## Method 1. Translate the reference into an assembly plan: foundations → load-bearing frame → masonry courses → floor/deck → upper frame/walls → brackets/eaves/tiles → ornament. Distinguish a structural floor from a late-installed decorative roof so higher levels never float. 2. Build the stable final silhouette first. Derive adjoining parts from common dimensions and height functions. Check front, three-quarter, and underside views before refining surface detail. 3. Give each solid component a start, duration, and travel distance. Drive the whole scene from one normalized progress value shared by color and depth shaders. Seeking backward, pausing, and replaying must remain deterministic. 4. Prioritize roof thickness, rafters/purlins, bracket supports, and meaningful joints before increasing ornament count. Then separate brick, plaster, wood, ceramic, stone, and metal through independently authored color, roughness, and micro-height. 5. Use restrained deterministic variation. Preserve repeating architectural rhythm while varying UV sampling, tile tint, and small dimensions; do not randomize joints out of alignment. 6. Light as a clean architectural miniature: controlled key/fill/rim, grounded contact, legible eave undersides. Do not hide crude geometry with fog, bloom, or excessive brightness. 7. Measure the actual scene while assembling, dragging, and viewing close-ups. Preserve or improve the starter's shadow caching and demand rendering. Inspect after any shader or geometry change; a passing build is not a visual test. ## Scope No external model service, image generation, subscription, proprietary asset, or other skill is required. Procedural geometry is the default; use external assets only when requested or agreed, with their origin and license recorded. The template is silent intentionally; add music only from an authorized source. Keep this skill as instructions plus a portable starter. Do not copy the creator's private sessions, local paths, environment files, or acquisition packages into generated output. ## What goes wrong A screenshot mapped onto a plane · scaling a whole storey instead of laying courses · alpha-fading walls into existence · color and shadow shaders that disagree · upper floors with no supporting deck · fog or bloom used to hide crude joints · claiming museum quality, historical accuracy, a market price, or universal 60 FPS from one screenshot. ## Report Deliver runnable source, startup and build commands, a short account of changed surfaces, observed test results, and remaining limitations.assets/starter/README.md606 B4e3efee8d8deupstream ↗
# Architecture growth starter Vite + React + Three.js miniature of a Chinese clock tower assembling brick by brick. Scaffolded by the `threejs-architecture-effects` skill. ```sh npm ci npm run dev ``` Production check: `npm run build`, then `npm run preview`. Needs Node.js 22.13+ and a WebGL2 browser. No API key. Drag to orbit, scroll to zoom, use the timeline to scrub construction. Detail cameras jump to the eaves and stone lions. This design is a working example, not a historical reconstruction. MIT licensed, Copyright (c) 2026 Hailey; Three.js and other npm packages keep their own licenses.README.md4.5 KBcf77023e6892upstream ↗
# threejs-architecture-effects Portable [Agent Skill](https://agentskills.io) by **Hailey**. It builds a real, orbitable Three.js building that assembles itself: brick courses, timber frame, dougong, layered eaves, procedural PBR materials, and close-up cameras. 中文:给 Codex / Claude Code / Cursor 用的开源 skill。输出是可运行的三维古建网站,不是贴图揭幕,也不需要 API key。 [](https://github.com/lhlGitHub/threejs-architecture-effects/blob/main/assets/preview.mp4) <p align="center"><a href="https://github.com/lhlGitHub/threejs-architecture-effects/blob/main/assets/preview.mp4">Watch the full 20s demo →</a></p> <img src="assets/preview.png" alt="Completed clock-tower miniature" width="100%"> GitHub README cannot play a repo `.mp4` inline, so the motion preview is a GIF. Click it (or the link) to play the full video. ## What you get - A **solid 3D miniature**, not a video on a plane - Construction driven by **one 0–1 timeline**: play, pause, scrub backward, replay - **Procedural** brick, wood, plaster, tile, stone, bronze — no paid models - Orbit, zoom, and detail cameras for eaves and stone lions - A Vite + React + Three.js starter you can run with `npm ci && npm run dev` The bundled clock tower is a working example, not a historical reconstruction and not the only design this skill can make. ## Install Copy this folder into the agent skills directory, then start a new session: | Runner | Path | | --- | --- | | Codex | `~/.codex/skills/threejs-architecture-effects` (or `$CODEX_HOME/skills/`) | | Claude Code | `~/.claude/skills/threejs-architecture-effects` | | Cursor | `~/.cursor/skills/threejs-architecture-effects` | ```sh git clone https://github.com/lhlGitHub/threejs-architecture-effects.git cp -R threejs-architecture-effects ~/.cursor/skills/ ``` Then ask: > Use $threejs-architecture-effects to make a Chinese pavilion like the starter: red walls, dark-green tiles, built storey by storey, orbitable, with eave close-ups. Other useful prompts: - Keep the current tower shape and cameras. Only refine eave thickness, timber, and the clock faces. - Turn the template into a two-storey lakeside pavilion. Keep timber and tile assembly. No clocks or lions. ## Run the starter without an agent Needs Node.js 22.13+, npm, and a WebGL2 browser. ```sh git clone https://github.com/lhlGitHub/threejs-architecture-effects.git node threejs-architecture-effects/scripts/scaffold.mjs ./my-building cd my-building npm ci npm run dev ``` The scaffold copies `assets/starter/` into a new directory and **refuses to overwrite** an existing one. It does not install packages or start a server. Controls: drag to orbit, scroll to zoom, timeline to scrub, **飞檐细赏** / **石狮近观** for close-ups. ## How construction works 1. Write an assembly plan: foundations → frame → masonry → decks → upper walls → brackets / eaves / tiles → ornament. 2. Model the finished silhouette first so parts share dimensions and nothing floats. 3. Give every solid piece a start, duration, and travel. Color and shadow shaders share one progress value, so seeking is deterministic. 4. Author materials separately (color, roughness, micro-height). Do not hide crude joints with fog or bloom. Details for agents: [SKILL.md](SKILL.md), [construction principles](references/construction-principles.md), [template map](references/template-guide.md), [verification](references/verification.md). ## Layout ``` threejs-architecture-effects/ ├── SKILL.md Agent entry ├── LICENSE MIT, Copyright (c) 2026 Hailey ├── agents/openai.yaml Codex UI metadata ├── scripts/scaffold.mjs Copy the starter into a new project ├── references/ Construction, template map, verification ├── assets/preview.gif README motion preview ├── assets/preview.png README still ├── assets/preview.mp4 Full screen recording └── assets/starter/ Vite + React + Three.js miniature ``` ## Limits - Procedural geometry only. No paid model service, no background music in the starter. - Video export is not included; the template is an interactive site. - Desktop-oriented. Do not claim museum quality, historical accuracy, or universal 60 FPS from one machine. - npm packages keep their own licenses. This skill does not vendor `node_modules`. ## License MIT. Copyright (c) 2026 Hailey. See [LICENSE](LICENSE).scripts/scaffold.mjs876 Bfefa82754990upstream ↗
#!/usr/bin/env node import { cp, lstat, mkdir } from 'node:fs/promises'; import { dirname, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; const args=process.argv.slice(2); if(args.length!==1 || args[0].startsWith('-')){ console.error('Usage: node scaffold.mjs <new-project-directory>'); process.exit(1); } const destination=resolve(args[0]); try { await lstat(destination); console.error('Refusing to overwrite an existing destination: '+destination); process.exit(1); } catch(error){ if(error.code!=='ENOENT')throw error; } const source=resolve(dirname(fileURLToPath(import.meta.url)),'../assets/starter'); await mkdir(dirname(destination),{recursive:true}); await cp(source,destination,{recursive:true,errorOnExist:true,force:false}); console.log('Created: '+destination); console.log('Next: open that directory, run npm ci, then npm run dev.');references/construction-principles.md3.4 KB7c0e923b55a6upstream ↗
# From image collage to a real 3D build ## Structure - Lay brick courses bottom to top. Keep hairline joints and a backing wall. Openings are real voids with wedge voussoirs, not dark decals on a solid wall. - Column bases sit on foundations or decks. Beams meet capitals. Purlins, rafters, and dougong (斗拱) carry the roof. Do not hover a complete timber cage above finished masonry. - Separate load-bearing structure from late ornament. Flying eaves (飞檐) may install later; upper walls still need a solid deck. Do not ignore the back and soffit just to match one camera. - When a pagoda shaft is segmented, every segment shares one taper function and continuous UVs. Relaying texture per segment creates horizontal bands and loading-bar seams. - Adjacent roof slopes share a boundary and height function. Tiles follow that surface. A roof needs top, soffit, fascia thickness, and ridge covers. Watch winding so undersides do not vanish. - Do not scale an entire storey in place of masonry. That also scales mortar, openings, and wood grain. ## Reversible assembly timeline Template `aBuild` stores start, duration, and travel per vertex. `uBuildProgress` is the one shared clock. Every vertex of a piece uses the same time so the piece lands as a rigid body and does not warp. Unstarted pieces `discard`. Pieces under construction stay opaque — do not fade walls in with alpha. Color and shadow-depth materials use the same displacement. Otherwise unfinished parts cast shadows early. Any shader edit must update `customProgramCacheKey`. At completion, displacement is exactly zero. The last ornament's start + duration must not exceed 1. Large members settle first; small pieces follow. Easing and a small landing bounce should feel like weight, not a spring toy. Ornament must not land before the deck that supports it. Variation uses a fixed seed so replay, scrubbing, and reload do not reshuffle. ## Materials - **Tiles:** small range of grey-green / dark jade / aged bronze. Keep mortar, overlap, and eave-end discs. Avoid high-contrast noise or huge per-tile hue jumps. - **Wood:** grain along the member, warm/dark brown shifts, slight worn edges. Sampling must not be identical on every stick, and must not break a continuous wall with random UVs. - **Brick:** real joints and small chamfers. Calm colour. Do not wrap one brick photo around a smooth box. - **Plaster:** fine grain, weak rain streaks, a little exposed brick. Exposure edges should not be regular sawteeth or a repeating per-course stamp. Ageing is not a ruin. - **Stone:** micro-height and roughness for grain; modelling for carving. Noise-stacked spheres can still read as toys — report that gap honestly. - **Bronze / clocks:** a little metal, thick frames, inset dials, solid hands and ticks. Glass is a cheap transparent reflection, not per-face transmission with extra scene renders. Color maps use sRGB. Roughness and micro-height maps do not. Paint stains are not bump pits. The template's downward vertex darkening is a stand-in, not physical AO, and does not replace contact shadows. ## Working with an existing design Prefer refining the original factories. Do not replace composition, silhouette, and interaction just because the user said “premium”. Verify art as silhouette → functional detail → material → light, not as a triangle-count race. New buildings may reuse the method without copying this clock tower's ornaments.references/template-guide.md2.9 KBa765b17c7b34upstream ↗
# Template map ## Environment Need Node.js 22.13+, npm, and a WebGL2 browser. Template dependency versions are pinned. The first install needs network. No API key, Cloudflare, or original author project is required. ```sh node <this-skill-dir>/scripts/scaffold.mjs /path/to/my-building cd /path/to/my-building npm ci npm run dev ``` The dev server listens on `127.0.0.1:5173` by default. Production check: `npm run build`, then `npm run preview`. If the port is taken, read the actual URL from the terminal. The starter ships `package-lock.json`; prefer `npm ci` so versions stay pinned. ## File roles | File | Change it when | | --- | --- | | `src/App.tsx` | playback, pause, timeline, stage names, detail-camera buttons | | `src/PagodaThreeScene.tsx` | lights, camera presets, OrbitControls, shadow cache, demand rendering, disposal | | `src/heritage/architecture.ts` | `roof` curved roofs; `bracketBand` dougong; `guardian` stone lions; `shaft` white pagoda; `buildArchitecture` main mass; `courtyard` terrace and pines | | `src/heritage/materials.ts` | shared palette and procedural color / micro-height / roughness textures | | `src/heritage/builder.ts` | geometry cache, material batching, per-piece timing, color/depth vertex animation | | `src/style.css` | exhibit layout and narrow screens, not the building's appearance | Component props: `progress` (0–1), `view` (`overview` / `roof` / `guardian`), `onReady`. The template building is about 32 scene units tall. The clocks are architectural ornaments, not a live system clock. Do not relabel scene units as metres. ## Adaptation order 1. Keep the full template running. Capture overview, eave, and lion close-ups as the baseline. 2. Change palette, title, and duration. Keep the timeline normalized to 0–1. 3. When changing eave projection, storey count, or tower taper, update that level's wall radius, column grid, dougong, floors, roof inner opening, and elevations together. Current geometry uses explicit design constants; it is not an automatic N-storey system. 4. For a style change, replace part factories one at a time — keep course-by-course masonry, swap clock frames, finials, or railings. If lions are removed, also remove their close-up button and camera target. 5. Stage labels are display-only. Real timing lives in `architecture.ts` start/duration arguments. Update both. ## Example requests - “Use this skill to make a similar three-storey Chinese clock tower, red walls, dark-green tiles, white background, built storey by storey, orbitable.” - “Keep the current tower shape and cameras. Only refine eave thickness, timber, and the clock faces. Do not replace the model.” - “Turn the template into a two-storey lakeside pavilion. Keep timber and tile assembly. No clocks, lions, or background music.” The template already includes source. Do not copy server dependencies, export dumps, or private config from an author's machine.references/verification.md3.2 KB12c5be622224upstream ↗
# Verification and performance ## Required checks Run a production build and inspect it in a real browser. A passing compile is not a visual pass. - Overview, eave close-up, lion close-up; orbit the back and soffit. - Play 0 → 1. Pause on brick, timber, shaft, and clock stages. Scrub forward and backward. - Confirm no floating beams, top-first masonry, walls through frame, missing roof backs, pixel cracks, or missing ornaments at completion. - Check narrow and desktop canvas size, button overlap, camera switches, and window resize. - Check browser errors, shader compile errors, and failed network requests. - After React unmount / HMR, dispose geometries, materials, textures, PMREM, shadow maps, controls, ResizeObserver, and rAF. ## Starter metrics The scene host `.three-scene` exposes `data-render-stats` as live JSON. Fields: `calls`, `triangles`, `geometries`, `textures`, `pieces`, `fps`, `renderFps`, `shadowUpdatesPerSecond`, `idle`, `dpr`. `fps` is rAF callback rate, not GPU-finished frames. `renderFps` is submitted redraws. At rest, `renderFps=0` and `idle=true` is expected power saving, not a freeze. `calls` / `triangles` are from the last actual draw, including that draw's shadow pass; they are not an idle per-second cost. Compare before/after at the same window size, DPR, camera, and construction stage. Prefer sustained samples and frame-time spikes. Do not treat a single peak FPS as a performance guarantee. ## Locked-in optimizations - Repeated small parts share materials and are batched by material. Construction displacement runs on the GPU; the CPU does not update tens of thousands of meshes per frame. - `shadowMap.autoUpdate = false`. Orbiting a fixed light does not rebuild shadows. - During construction, shadows update at most ~30 Hz. The 0 and 1 endpoints flush immediately. A paused in-between pose also flushes once. - No redraw while progress is unchanged, camera damping has settled, and there is no resize. Interaction and progress changes wake immediately. - Do not hide stutter by dropping animation frames. Shadow update rate may drop; the main timeline stays continuous. ## Tradeoffs The current template has about 13,000 logical pieces. A desktop overview color pass is about 680k triangles; with a shadow refresh about 1.31M; about 12 batched geometries and 37 textures. Numbers move with version, camera, and culling. They are not a budget promise. This is not a low-end phone model. Measure first, then choose: lower DPR / shadow resolution, cull pieces that have not started, instance truly identical geometry, or add distant LOD. Do not make every tile its own Mesh. If you instance, keep per-instance timing/tint, correct transforms, and the same shadowed construction motion. Investigate shader compile, texture upload, and init spikes before deleting detail. Demand rendering does not remove first-build cost. Do not claim that caching alone makes every device smooth. ## Handoff Report the run URL, preserved design, real changes, measured stats, tests that passed, and devices not checked. Do not auto-publish, buy assets, or export private chats. An MP4 needs a separate deterministic frame capture and its own review; the template is an interactive site, not a video exporter.assets/preview.gif1.9 MBa1539323c4f2upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
assets/preview.mp423.2 MB62310ab0ec98upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
assets/preview.png317 KBc9e68ca8e55cupstream ↗
Contents are not inlined in the catalog. Open the upstream file.
assets/starter/.gitignore56 B1466bb49390bupstream ↗
node_modules/ dist/ .env* *.log .DS_Store *.tsbuildinfoassets/starter/index.html272 B2d19b75c05eeupstream ↗
<!doctype html> <html lang="zh-CN"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><title>营造 · 建筑生长</title></head><body><div id="root"></div><script type="module" src="/src/main.tsx"></script></body></html>assets/starter/LICENSE1.0 KBb6383cdb9f08upstream ↗
MIT License Copyright (c) 2026 Hailey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.assets/starter/package-lock.json33 KB1386e1f39541upstream ↗
Contents are not inlined in the catalog. Open the upstream file.
assets/starter/package.json542 B9efc73d4a5e5upstream ↗
{ "name": "architecture-growth-starter", "version": "1.0.0", "private": true, "type": "module", "engines": { "node": ">=22.13.0" }, "scripts": { "dev": "vite --host 127.0.0.1", "build": "tsc --noEmit && vite build", "preview": "vite preview --host 127.0.0.1" }, "dependencies": { "react": "19.2.6", "react-dom": "19.2.6", "three": "0.185.1" }, "devDependencies": { "@types/react": "19.2.14", "@types/react-dom": "19.2.3", "@types/three": "0.185.4", "@vitejs/plugin-react": "6.0.2", "typescript": "5.9.3", "vite": "8.0.13" } }assets/starter/src/App.tsx3.5 KBea43862958b6upstream ↗
import { useCallback, useEffect, useRef, useState } from 'react'; import PagodaThreeScene, { type DetailView } from './PagodaThreeScene'; const DURATION=12.4; const stages=[['础石落位',.06],['梁柱榫接',.11],['砖墙逐层砌筑',.28],['斗拱与首层飞檐',.412],['木构廊层',.606],['墙心逐层砌筑',.785],['望楼装配',.905],['屋瓦与屋脊',.995],['落成',1]] as const; export default function App(){ const [progress,setProgress]=useState(0),[playing,setPlaying]=useState(true); const [ready,setReady]=useState(false),[view,setView]=useState<DetailView>('overview'); const started=useRef(0); const onReady=useCallback(()=>{started.current=performance.now();setReady(true);},[]); useEffect(()=>{ if(!ready || !playing)return; let frame=0; const tick=(now:number)=>{ const next=Math.min(1,(now-started.current)/(DURATION*1000));setProgress(next); if(next===1)setPlaying(false);else frame=requestAnimationFrame(tick); }; frame=requestAnimationFrame(tick);return()=>cancelAnimationFrame(frame); },[ready,playing]); const seek=useCallback((p:number)=>{const next=Math.max(0,Math.min(1,p));started.current=performance.now()-next*DURATION*1000;setProgress(next);},[]); const replay=()=>{setView('overview');seek(0);setPlaying(true);}; const toggle=()=>{seek(progress===1?0:progress);setPlaying(progress===1 || !playing);}; const detail=(v:DetailView)=>{setView(v);if(v!=='overview'){seek(1);setPlaying(false);}}; const stage=stages.find(([,end])=>progress<end)?.[0]??'落成'; return <main className="poster"> <header><span className="wordmark"><i>营</i>营造<em>HERITAGE ATELIER</em></span><small>ANATOMY OF CONSTRUCTION · 3D</small><div className="header-actions"><button disabled={!ready} onClick={replay}>重新建造 ↺</button></div></header> <section className="scene"> <aside className="brief"><p className="micro">THE ART OF ASSEMBLY<br/>藏品 〇一 / 砖木楼阁</p><h2>一木一石,<br/>自有千年。</h2><p className="accent">在方寸之间,重见营造之美。</p><blockquote>砖石垒砌,梁柱相承。<br/>斗拱托举,重檐舒展。</blockquote><div className="index"><b>01</b><i/><span>真实三维建造演示</span></div></aside> <div className="tower-stage"> <PagodaThreeScene progress={progress} view={view} onReady={onReady}/> {!ready&&<div className="scene-loading">展卷 · 营造中</div>} <div className="stage-label"><i/>{stage}<span>{Math.round(progress*100)}%</span></div> <div className="view-selector" role="group" aria-label="观赏视角">{([['overview','全景'],['roof','飞檐细赏'],['guardian','石狮近观']] as const).map(([id,label])=><button key={id} disabled={!ready} aria-pressed={view===id} onClick={()=>detail(id)}>{label}</button>)}</div> <div className="orbit-hint">拖动环视 · 滚轮近观</div> </div> <aside className="title-block"><span className="symbols">中国建筑 · 时间的形状</span><h1>建<br/>生</h1><p>BRICK · TIMBER · TIME</p><div className="original-mark"><b>榫卯相承</b></div></aside> </section> <footer><button className="play" disabled={!ready} onClick={toggle} aria-label={playing?'暂停':'播放'}>{playing?'Ⅱ':'▶'}</button><div className="timeline"><span style={{width:`${progress*100}%`}}/><input aria-label="施工进度" disabled={!ready} type="range" min="0" max="1000" value={Math.round(progress*1000)} onChange={e=>seek(Number(e.target.value)/1000)}/></div><time>{(progress*DURATION).toFixed(1)} / {DURATION} S</time></footer> </main>; }assets/starter/src/heritage/architecture.ts25 KB29caba795f10upstream ↗
import * as THREE from "three"; import { HeritageBuilder, type Point } from "./builder"; const TAU=Math.PI*2; const variation=(n:number)=>{const v=Math.sin(n*127.1+31.7)*43758.5453;return v-Math.floor(v);}; function surfaceGrid(nx:number,ny:number,point:(u:number,v:number)=>Point,uvMap?:(u:number,v:number)=>[number,number]){ const p:number[]=[],uv:number[]=[],idx:number[]=[]; for(let j=0;j<=ny;j++)for(let i=0;i<=nx;i++){ const u=i/nx,v=j/ny;p.push(...point(u,v));uv.push(...(uvMap?uvMap(u,v):[u,v])); } for(let j=0;j<ny;j++)for(let i=0;i<nx;i++){ const a=j*(nx+1)+i,b=a+1,c=a+nx+1,d=c+1;idx.push(a,c,b,b,c,d); } const g=new THREE.BufferGeometry();g.setAttribute("position",new THREE.Float32BufferAttribute(p,3));g.setAttribute("uv",new THREE.Float32BufferAttribute(uv,2));g.setIndex(idx);g.computeVertexNormals();return g; } const facePoint=(x:number,y:number,z:number,angle:number):Point=>[x*Math.cos(angle)+z*Math.sin(angle),y,z*Math.cos(angle)-x*Math.sin(angle)]; export function roof(b:HeritageBuilder,y:number,outer:number,inner:number,height:number,start:number){ const profile=(x:number,z:number)=>{ const t=(z-inner)/(outer-inner); return height*Math.pow(1-t,1.75)+.2*Math.pow(t,5)+.85*Math.pow(Math.abs(x)/outer,8)*Math.pow(t,3); }; for(let side=0;side<4;side++){ const a=side*Math.PI/2; // Continuous roof boards: no intersecting flat slabs at the hips. const deck=surfaceGrid(28,18,(u,v)=>{const z=inner+v*(outer-inner),x=(u*2-1)*z;return facePoint(x,y+profile(x,z)-.045,z,a);}); b.add(deck,"tile",start,{duration:.025,lift:.35});deck.dispose(); // Closed, shaded soffit and fascia give the eave physical thickness. const soffit=surfaceGrid(20,10,(u,v)=>{const z=inner+v*(outer-inner),x=(u*2-1)*z;return facePoint(x,y+profile(x,z)-.24,z,a);}); const si=soffit.index!;for(let n=0;n<si.count;n+=3){const tmp=si.getX(n+1);si.setX(n+1,si.getX(n+2));si.setX(n+2,tmp);}soffit.computeVertexNormals(); b.add(soffit,"wood",start,{shade:.79,lift:.35});soffit.dispose(); const fascia=surfaceGrid(32,1,(u,v)=>{const x=(u*2-1)*outer;return facePoint(x,y+profile(x,outer)-.24+v*.23,outer,a);}); b.add(fascia,"jade",start+.005,{shade:.8,lift:.35});fascia.dispose(); for(let j=0;j<22;j++){ const x=(j/21-.5)*outer*1.87,z0=Math.max(inner,Math.abs(x)+.1); if(z0>=outer-.2)continue; const pts:Point[]=[]; for(let k=0;k<6;k++){const z=z0+(outer-z0)*k/5;pts.push(facePoint(x,y+profile(x,z)-.32,z,a));} b.tube(pts,.075,"wood",start,{shade:.9,duration:.022},8); } for(const t of [.24,.57,.88]){ const z=inner+(outer-inner)*t,pts:Point[]=[]; for(let k=0;k<12;k++){const x=(k/11*2-1)*z;pts.push(facePoint(x,y+profile(x,z)-.43,z,a));} b.tube(pts,.105,"wood",start,{shade:.83},12); } // Actual overlapping curved ceramic shells, parallel from eave to ridge. const spacing=.29; for(let i=0;i<=Math.floor(outer*2/spacing);i++){ const x=-outer+i*spacing; const z0=Math.max(inner,Math.abs(x)+.055); const count=Math.max(1,Math.ceil((outer-z0)/.52)); for(let row=0;row<count;row++){ const seed=i*13+row*47+side*109+y*7; const front=outer-row*.52,back=Math.max(z0,front-.56-(variation(seed)-.5)*.024); if(back>=front-.035)continue; const tile=surfaceGrid(5,2,(u,v)=>{ const theta=(1-u)*Math.PI,z=back+(front-back)*v; const xx=x+Math.cos(theta)*(.145+(variation(seed+4)-.5)*.006)+(v-.5)*(variation(seed+8)-.5)*.014; return facePoint(xx,y+profile(xx,z)+Math.sin(theta)*(.12+(variation(seed+2)-.5)*.008)+.025,z,a); }); b.add(tile,"tile",start+.014+row*.003+i*.00012,{shade:.9+variation(seed)*.16,tint:[.96+variation(seed+1)*.08,.98+variation(seed+2)*.04,.96+variation(seed+3)*.09],duration:.016,lift:.22});tile.dispose(); } if(Math.abs(x)<outer-.12){ const yy=y+profile(x,outer); const disk=new THREE.CylinderGeometry(.139,.139,.06,12);disk.rotateX(Math.PI/2); b.add(disk,"tile",start+.049,{p:facePoint(x,yy+.045,outer+.025,a),r:[0,a,0],shade:1.1});disk.dispose(); // A shallow raised central boss on each circular tile end. b.sphere(facePoint(x,yy+.045,outer+.068,a),[.043,.043,.022],"stone",start+.052,{r:[0,a,0],shade:.73}); const lip=new THREE.TorusGeometry(.105,.012,4,12); b.add(lip,"jade",start+.052,{p:facePoint(x,yy+.045,outer+.062,a),r:[0,a,0],shade:.88});lip.dispose(); if(i%2===0){ const drop=new THREE.Shape();drop.moveTo(-.1,0);drop.lineTo(.1,0);drop.quadraticCurveTo(.095,-.13,0,-.18);drop.quadraticCurveTo(-.095,-.13,-.1,0); const dg=new THREE.ExtrudeGeometry(drop,{depth:.035,bevelEnabled:false,curveSegments:3}); b.add(dg,"jade",start+.053,{p:facePoint(x+.145,yy-.035,outer,a),r:[0,a,0],shade:.86});dg.dispose(); } } } // Three nested fascia courses follow the rising eave exactly. for(let layer=0;layer<3;layer++){ const points:Point[]=[]; for(let i=0;i<=32;i++){const x=-outer+2*outer*i/32;points.push(facePoint(x,y+profile(x,outer)-.15-layer*.12,outer-.07*layer,a));} b.tube(points,layer===1?.043:.092,layer===1?"bronze":"jade",start+.043,{lift:.3},40); } // Carved rafter ends, set back beneath the tile ends. for(let i=0;i<38;i++){ const x=(i/37-.5)*outer*1.92; b.box([.14,.15,.85],facePoint(x,y+profile(x,outer)-.36,outer-.42,a),"wood",start+.01,{r:[0,a,0],shade:i%2?.96:1.08}); b.box([.11,.11,.035],facePoint(x,y+profile(x,outer)-.36,outer+.02,a),"stone",start+.032,{r:[0,a,0],shade:.85}); } // Swept hip ridges and strongly lifted terminal beasts. const ridge:Point[]=[]; for(let i=0;i<=18;i++){const z=inner+(outer-inner)*i/18;ridge.push(facePoint(z,y+profile(z,z)+.13,z,a));} b.tube(ridge,.15,"tile",start+.065,{lift:.3},28); // Overlapping saddle tiles interrupt the otherwise pipe-like hip ridge. for(let j=1;j<Math.floor((outer-inner)/.55);j++){ const z=inner+j*.55,points:Point[]=[]; for(let k=0;k<=8;k++){ const t=k/8*Math.PI,dx=Math.cos(t)*.153; points.push(facePoint(z+dx,y+profile(z,z)+.13+Math.sin(t)*.155,z-dx,a)); } b.tube(points,.021,"jade",start+.066,{shade:.82+variation(j)*.12},8); } const corner=facePoint(outer,y+1.16,outer,a); const flourish:Point[]=[facePoint(outer-.65,y+.64,outer-.65,a),corner,facePoint(outer+.22,y+1.78,outer+.22,a),facePoint(outer-.04,y+1.86,outer-.04,a)]; b.tube(flourish,.115,"jade",start+.071,{lift:.25},18); for(let beast=0;beast<3;beast++){ const z=outer-.75-beast*.48,yy=y+profile(z,z)+.26; b.sphere(facePoint(z,yy,z,a),[.11,.21,.14],"tile",start+.069+beast*.002); b.sphere(facePoint(z,yy+.22,z+.05,a),[.105,.09,.12],"tile",start+.07+beast*.002); } const bellPos=facePoint(outer-.12,y+.38,outer-.12,a); b.cylinder(.018,.018,.54,bellPos,"bronze",start+.077); b.cylinder(.095,.19,.25,[bellPos[0],bellPos[1]-.35,bellPos[2]],"bronze",start+.079); b.sphere([bellPos[0],bellPos[1]-.49,bellPos[2]],[.045,.065,.045],"bronze",start+.08); const rim=new THREE.TorusGeometry(.183,.017,4,12);rim.rotateX(Math.PI/2); b.add(rim,"bronze",start+.08,{p:[bellPos[0],bellPos[1]-.475,bellPos[2]]});rim.dispose(); } // Closed ridge cap, never exposed scaffolding on the finished roof. b.box([inner*2+.12,.15,inner*2+.12],[0,y+height+.01,0],"tile",start+.068); } export function bracketBand(b:HeritageBuilder,y:number,r:number,start:number){ // A cloud-shaped arm with a concave underside and slightly raised tips. const outline=new THREE.Shape(); outline.moveTo(-.65,.13);outline.lineTo(.65,.13);outline.lineTo(.59,-.02); outline.bezierCurveTo(.36,-.03,.33,-.22,.12,-.23);outline.lineTo(-.12,-.23); outline.bezierCurveTo(-.33,-.22,-.36,-.03,-.59,-.02);outline.closePath(); const arm=new THREE.ExtrudeGeometry(outline,{depth:.22,bevelEnabled:true,bevelThickness:.018,bevelSize:.02,bevelSegments:1,steps:1,curveSegments:6});arm.translate(0,0,-.11); for(let side=0;side<4;side++){ const a=side*Math.PI/2; b.box([r*2+.45,.3,.45],facePoint(0,y,r,a),"wood",start,{r:[0,a,0]}); for(let i=-4;i<=4;i++){ const along=i*r/4.4; b.box([.33,.3,.42],facePoint(along,y-.64,r,a),"brick",start+.002,{r:[0,a,0]}); for(let level=0;level<3;level++){ const z=r+.12+level*.2,yy=y-.46+level*.22; b.add(arm,"jade",start+.005+level*.005,{p:facePoint(along,yy,z,a),r:[0,a,0],s:[.7+level*.22,1,1]}); b.add(arm,"jade",start+.006+level*.005,{p:facePoint(along,yy+.1,z,a),r:[0,a+Math.PI/2,0],s:[.75+level*.2,1,1]}); for(const sign of [-1,1])b.box([.17,.16,.19],facePoint(along+sign*(.28+level*.1),yy+.17,z,a),"brick",start+.009+level*.005,{r:[0,a,0],shade:.85}); } } // Painted continuous beam under the rafters. b.box([r*2+.7,.2,.25],facePoint(0,y+.3,r+.55,a),"jade",start+.025,{r:[0,a,0]}); b.box([r*2+.6,.034,.025],facePoint(0,y+.32,r+.69,a),"bronze",start+.028,{r:[0,a,0]}); for(let i=-6;i<=6;i++){ b.box([.39,.105,.03],facePoint(i*r/6.6,y+.04,r+.245,a),"jade",start+.023,{r:[0,a,0],shade:1.07}); } }arm.dispose(); } function railing(b:HeritageBuilder,y:number,r:number,start:number){ for(let side=0;side<4;side++){ const a=side*Math.PI/2; for(const h of [0,.37,.95])b.box([r*2+.18,.1,.16],facePoint(0,y+h,r,a),"wood",start+h*.004,{r:[0,a,0]}); for(let i=-6;i<=6;i++){ const x=i*r/6; b.box([.13,1.08,.14],facePoint(x,y+.47,r,a),"wood",start+.008,{r:[0,a,0]}); for(const h of [.05,.9]){ b.box([.19,.12,.2],facePoint(x,y+h,r,a),"wood",start+.009,{r:[0,a,0],shade:.88}); b.sphere(facePoint(x,y+h,r+.105,a),[.021,.021,.009],"wood",start+.01,{r:[0,a,0],shade:.66}); } b.cylinder(.09,.1,.065,facePoint(x,y+1.04,r,a),"bronze",start+.012); if(i<6){ const cx=x+r/12; for(const sign of [-1,1])b.box([.052,.58,.065],facePoint(cx,y+.64,r,a),"wood",start+.013,{r:[0,a,sign*.69]}); b.box([r/6-.18,.065,.065],facePoint(cx,y+.21,r,a),"jade",start+.014,{r:[0,a,0]}); } } } } export function guardian(b:HeritageBuilder,center:Point,rotation:number,start:number,scale=1.3){ const point=(x:number,y:number,z:number):Point=>{const p=facePoint(x*scale,y*scale,z*scale,rotation);return[p[0]+center[0],p[1]+center[1],p[2]+center[2]];}; const ell=(p:Point,s:Point,m:"stone"|"recess"="stone",shade=1)=>b.sphere(point(...p),s.map(v=>v*scale)as Point,m,start,{r:[0,rotation,0],shade}); // Sumeru pedestal, inset waist, lotus mouldings and relief medallion. for(const [w,h,d,y]of[[1.4,.16,1.25,.08],[1.24,.1,1.12,.21],[1.02,.3,.93,.4],[1.27,.1,1.14,.6]])b.box([w*scale,h*scale,d*scale],point(0,y,0),"stone",start,{r:[0,rotation,0],shade:.92}); for(let j=-3;j<=3;j++){ ell([j*.15,.24,.555],[.065,.035,.02],"stone",.83); ell([j*.15,.56,.575],[.055,.026,.018],"stone",1.03); } ell([0,1.2,-.14],[.45,.63,.38]);ell([0,1.35,.17],[.43,.6,.31]); ell([0,1.97,.08],[.51,.48,.42]); // Sculpted spirals on cheeks, crown and shoulders, not a single doughnut mane. for(let ring=0;ring<3;ring++)for(let i=0;i<11;i++){ const a=(i/11)*TAU+ring*.24; const x=Math.cos(a)*(.43+ring*.015),yy=1.99+Math.sin(a)*.43,z=.04-ring*.12; const pts:Point[]=[]; for(let k=0;k<=13;k++){const t=k/13,rr=.105*(1-t*.83),th=t*TAU*1.38;pts.push(point(x+Math.cos(th)*rr,yy+Math.sin(th)*rr,z+.31));} b.tube(pts,.028*scale,"stone",start,{shade:.92},14); } ell([0,1.78,.45],[.3,.19,.22]);ell([0,1.69,.52],[.22,.075,.12],"recess"); ell([0,1.59,.44],[.26,.08,.18]);ell([0,1.89,.58],[.15,.09,.095],"stone",.69); for(const sign of [-1,1]){ ell([sign*.39,2.24,-.03],[.17,.23,.095]);ell([sign*.39,2.25,.04],[.09,.13,.032],"stone",.72); ell([sign*.195,2.03,.432],[.112,.081,.035],"recess");ell([sign*.193,2.038,.46],[.045,.047,.026],"stone",.8); b.tube([point(sign*.065,2.09,.47),point(sign*.16,2.16,.49),point(sign*.31,2.18,.4)],.052*scale,"stone",start,{},12); ell([sign*.32,1.89,.37],[.16,.19,.13]); ell([sign*.29,1.02,.27],[.14,.5,.16]);ell([sign*.3,.7,.44],[.25,.125,.29]); ell([sign*.37,.92,-.28],[.28,.32,.29]); for(let toe=0;toe<3;toe++){ ell([sign*.3+(toe-1)*.12,.69,.65],[.061,.062,.1]); b.tube([point(sign*.3+(toe-1)*.12-.037,.76,.48),point(sign*.3+(toe-1)*.12-.037,.75,.64)],.009*scale,"recess",start,{},3); } b.cylinder(.035,.009,.16*scale,point(sign*.13,1.72,.62),"stone",start); for(let j=0;j<3;j++)b.tube([point(sign*.14,1.84-j*.055,.54),point(sign*.32,1.83-j*.065,.53),point(sign*.39,1.92-j*.055,.44)],.014*scale,"stone",start,{shade:.72},10); } b.tube([point(.1,1.03,-.43),point(.55,1.19,-.38),point(.62,1.52,-.25),point(.46,1.62,-.2),point(.43,1.46,-.19)],.085*scale,"stone",start,{},18); // Collar, bell and embroidered ball distinguish a ceremonial guardian. const collar:Point[]=[];for(let i=0;i<=18;i++){const a=i/18*Math.PI;collar.push(point(Math.cos(a)*.35,1.44-Math.sin(a)*.17,.4));} b.tube(collar,.025*scale,"stone",start);ell([0,1.16,.43],[.085,.11,.06]); ell([-.33,.75,.65],[.16,.16,.16]); } function shaft(b:HeritageBuilder){ const base=13.52,h=8.5,rows=34; for(let row=0;row<rows;row++){ const v0=row/rows,v1=(row+1)/rows; for(let side=0;side<4;side++){ const a=side*Math.PI/2; // The exact same slope and UVs on adjacent courses eliminate striping. const g=surfaceGrid(1,1,(u,v)=>{ const t=THREE.MathUtils.lerp(v0,v1,v),r=4.25-t*.97; return facePoint((u*2-1)*r,base+t*h,r,a); },(u,v)=>[side%2?1-u:u,THREE.MathUtils.lerp(v0,v1,v)]); const indices=g.index!; for(let i=0;i<indices.count;i+=3){const v=indices.getX(i+1);indices.setX(i+1,indices.getX(i+2));indices.setX(i+2,v);} g.computeVertexNormals(); b.add(g,"plaster",.606+row*.0048,{duration:.012,lift:.28});g.dispose(); } } // Fine recessed vents, built after the wall courses reach them. for(let side=0;side<4;side++){ const a=side*Math.PI/2,r=3.72; b.box([.39,.57,.025],facePoint(0,18.25,r,a),"recess",.72,{r:[0,a,0]}); for(const sign of [-1,1])b.box([.045,.66,.08],facePoint(sign*.23,18.25,r+.03,a),"stone",.724,{r:[0,a,0]}); for(const h of [-.33,.33])b.box([.5,.055,.09],facePoint(0,18.25+h,r+.03,a),"stone",.724,{r:[0,a,0]}); } } export function buildArchitecture(b:HeritageBuilder){ // Ashlar footing and true masonry courses with a continuous arched opening. for(let side=0;side<4;side++){ const a=side*Math.PI/2; for(let row=0;row<3;row++)for(let col=0;col<11;col++){ const x=-5.05+col*1.01; if(Math.abs(x)<1.35)continue; b.box([.992,.29,.64],facePoint(x,.2+row*.3,5.25,a),"stone",.009+row*.012+col*.0007,{r:[0,a,0],shade:.91+(col%4)*.02}); } for(let row=0;row<24;row++){ const y=1.03+row*.274; const opening=y<4.7?1.82:y<6.48?Math.sqrt(Math.max(0,1.78**2-(y-4.7)**2))+.15:0; for(const sign of [-1,1]){ const width=5.35-opening; b.box([width,.274,.5],facePoint(sign*(opening+width/2),y,5.2,a),"brick",.11+row*.0062,{r:[0,a,0],shade:.65,lift:.3,duration:.009}); } for(let col=0;col<16;col++){ const x=-5.1+col*.675+(row%2)*.31; if(x>5.23)continue; const gap=y<4.7?1.42:y<6.12?Math.sqrt(Math.max(0,1.42**2-(y-4.7)**2)):0; if(Math.abs(x)<gap+.21)continue; b.box([.657,.265,.56],facePoint(x,y,5.23,a),"brick",.11+row*.0062+col*.00023,{r:[0,a,0],shade:.94+((row*7+col*3)%11)*.009,lift:.3,duration:.009}); } } // Dress stone arch and jambs: wedge-shaped voussoirs follow the opening. for(const sign of [-1,1])for(let row=0;row<14;row++)b.box([.35,.275,.7],facePoint(sign*1.55,.92+row*.277,5.3,a),"jade",.13+row*.009,{r:[0,a,0],shade:.94+(row%3)*.035}); for(let i=0;i<17;i++){ const shape=new THREE.Shape(),t0=i*Math.PI/17+.012,t1=(i+1)*Math.PI/17-.012; shape.absarc(0,0,1.76,t0,t1,false);shape.absarc(0,0,1.39,t1,t0,true);shape.closePath(); const g=new THREE.ExtrudeGeometry(shape,{depth:.72,bevelEnabled:true,bevelThickness:.008,bevelSize:.008,bevelSegments:1,steps:1,curveSegments:4});g.translate(0,0,-.36); b.add(g,"jade",.26+i*.001,{p:facePoint(0,4.7,5.3,a),r:[0,a,0],shade:.93+(i%4)*.025});g.dispose(); } } // Interior column grid stays behind the actual exterior wall thickness. for(const x of [-4.1,0,4.1])for(const z of [-4.1,4.1]){ b.cylinder(.15,.21,6.7,[x,4.05,z],"wood",.062,{duration:.035,lift:3}); b.cylinder(.25,.32,.28,[x,.88,z],"stone",.047); } for(const y of [3.15,6.95])for(const side of [0,1])for(const sign of [-1,1])b.box([8.5,.24,.28],side?[sign*4.1,y,0]:[0,y,sign*4.1],"wood",.085,{r:[0,side*Math.PI/2,0]}); bracketBand(b,7.57,5.15,.285); roof(b,8.0,7.2,4.12,1.5,.32); // Open gallery: substantial footings, round posts, pierced lattice and plaques. b.box([10.25,.25,10.25],[0,9.24,0],"wood",.412); for(let side=0;side<4;side++){ const a=side*Math.PI/2; for(const x of [-4.72,-2.36,0,2.36,4.72]){ b.cylinder(.26,.3,.26,facePoint(x,9.47,4.72,a),"stone",.42); b.cylinder(.15,.19,3.0,facePoint(x,11.05,4.72,a),"wood",.435,{duration:.03,lift:1.5}); b.cylinder(.22,.22,.12,facePoint(x,12.45,4.72,a),"jade",.467); for(const sign of [-1,1]){ b.tube([facePoint(x+sign*.58,12.42,4.72,a),facePoint(x+sign*.31,12.18,4.72,a),facePoint(x,12.02,4.72,a)],.065,"wood",.47,{shade:.9},6); } } b.box([9.8,.35,.38],facePoint(0,12.55,4.72,a),"wood",.475,{r:[0,a,0]}); for(let i=-6;i<=6;i++){ const x=i*.68; b.box([.56,.3,.07],facePoint(x,12.28,4.76,a),"jade",.48,{r:[0,a,0]}); b.tube([facePoint(x-.24,12.34,4.81,a),facePoint(x,12.16,4.81,a),facePoint(x+.24,12.34,4.81,a)],.021,"bronze",.484,{},6); } } railing(b,9.55,4.82,.49); for(const [i,[x,z,a]]of[[-4.55,4.98,0],[0,4.98,0],[4.55,4.98,0],[4.98,0,Math.PI/2],[-4.98,0,-Math.PI/2]].entries())guardian(b,[x,9.35,z],a+(i-2)*.025,.532,1.16+variation(i)*.035); for(const x of [-2.35,2.35])lantern(b,[x,11.64,4.95],.51); bracketBand(b,12.87,4.78,.545); roof(b,13.18,6.35,4.02,1.24,.568); shaft(b); // Heavy corbels gather the narrow shaft into the upper balcony. for(let side=0;side<4;side++){ const a=side*Math.PI/2; for(let level=0;level<3;level++)b.box([6.7+level*.32,.16,.28],facePoint(0,21.84+level*.19,3.3+level*.16,a),level===1?"brick":"stone",.775+level*.003,{r:[0,a,0],shade:.87}); b.box([8.8,.28,.38],facePoint(0,22.62,4.18,a),"wood",.809,{r:[0,a,0]}); } for(let side=0;side<4;side++){ const a=side*Math.PI/2; for(const sign of [-1,1])b.tube([facePoint(sign*1.3,20.45,3.48,a),facePoint(sign*1.65,21.15,3.68,a),facePoint(sign*2.22,21.9,4.03,a),facePoint(sign*2.4,22.65,4.5,a)],.15,"jade",.78,{},18); } bracketBand(b,22.58,4.45,.785); b.box([10.4,.26,10.4],[0,22.94,0],"wood",.814); railing(b,23.1,5.1,.852); // The belfry walls are separate masonry strips, cut around a true circular aperture. for(let side=0;side<4;side++){ const a=side*Math.PI/2; for(let row=0;row<14;row++){ const y0=23.03+row*.246,y1=y0+.241; const minY=Math.max(-1.16,Math.min(1.16,y0-24.83)),maxY=Math.max(-1.16,Math.min(1.16,y1-24.83)); const inHole=y1>23.67&&y0<25.99; for(const sign of [-1,1]){ const s=new THREE.Shape();s.moveTo(sign*4.06,y0);s.lineTo(sign*4.06,y1); if(inHole){for(let j=0;j<=8;j++){const yy=y1+(y0-y1)*j/8,dy=THREE.MathUtils.clamp(yy-24.83,minY,maxY);s.lineTo(sign*Math.sqrt(Math.max(0,1.16**2-dy**2)),yy);}} else{s.lineTo(0,y1);s.lineTo(0,y0);}s.closePath(); const g=new THREE.ExtrudeGeometry(s,{depth:.42,bevelEnabled:false,steps:1,curveSegments:4});g.translate(0,0,-.21); b.add(g,"brick",.824+row*.002,{p:facePoint(0,0,4.02,a),r:[0,a,0],shade:.97+row%3*.012});g.dispose(); } } const ring=new THREE.TorusGeometry(1.26,.14,7,64); b.add(ring,"stone",.868,{p:facePoint(0,24.83,4.27,a),r:[0,a,0]});ring.dispose(); const surround=new THREE.Shape();surround.absarc(0,0,1.185,0,TAU,false); const hole=new THREE.Path();hole.absarc(0,0,1.105,0,TAU,true);surround.holes.push(hole); const sleeve=new THREE.ExtrudeGeometry(surround,{depth:.31,bevelEnabled:true,bevelThickness:.012,bevelSize:.012,bevelSegments:1,curveSegments:32}); b.add(sleeve,"bronze",.87,{p:facePoint(0,24.83,4.0,a),r:[0,a,0],shade:.78});sleeve.dispose(); const face=new THREE.CylinderGeometry(1.13,1.13,.055,48);face.rotateX(Math.PI/2); b.add(face,"recess",.873,{p:facePoint(0,24.83,4.05,a),r:[0,a,0]});face.dispose(); for(let i=0;i<60;i++){ const t=i/60*TAU; b.box([i%5?.018:.045,i%5?.065:.16,.024],facePoint(Math.sin(t)*.98,24.83+Math.cos(t)*.98,4.105,a),"stone",.88,{r:[0,a,-t]}); } for(const r of [.82,1.05]){const ring=new THREE.TorusGeometry(r,.009,4,48);b.add(ring,"bronze",.882,{p:facePoint(0,24.83,4.11,a),r:[0,a,0]});ring.dispose();} b.tube([facePoint(-.05,24.76,4.13,a),facePoint(.49,25.39,4.13,a)],.035,"stone",.887,{},2); b.tube([facePoint(.03,24.79,4.15,a),facePoint(-.45,25.07,4.15,a)],.045,"stone",.887,{},2); b.sphere(facePoint(0,24.83,4.17,a),[.075,.075,.035],"bronze",.89,{r:[0,a,0]}); const glazing=new THREE.CircleGeometry(1.095,48); b.add(glazing,"glass",.892,{p:facePoint(0,24.83,4.29,a),r:[0,a,0],lift:.1});glazing.dispose(); } bracketBand(b,26.55,4.08,.895); roof(b,26.9,6.6,.2,3.24,.905); // Lotus finial, fully finished from ridge to pearl. for(let i=0;i<5;i++)b.cylinder(.34-i*.041,.45-i*.055,.18,[0,30.3+i*.23,0],"bronze",.989+i*.001); b.sphere([0,31.5,0],[.21,.32,.21],"bronze",.997,{duration:.003,lift:.22}); } function lantern(b:HeritageBuilder,p:Point,start:number){ b.sphere(p,[.28,.43,.28],"paper",start); for(const sign of [-1,1])b.cylinder(.2,.2,.065,[p[0],p[1]+sign*.37,p[2]],"bronze",start); for(let i=0;i<8;i++){ const a=i/8*TAU; b.tube([[p[0]+Math.sin(a)*.15,p[1]-.37,p[2]+Math.cos(a)*.15],[p[0]+Math.sin(a)*.29,p[1],p[2]+Math.cos(a)*.29],[p[0]+Math.sin(a)*.15,p[1]+.37,p[2]+Math.cos(a)*.15]],.009,"wood",start,{},10); } b.cylinder(.01,.01,.65,[p[0],p[1]+.7,p[2]],"bronze",start); b.cylinder(.03,.055,.38,[p[0],p[1]-.58,p[2]],"brick",start); } export function courtyard(b:HeritageBuilder){ b.box([23.6,.45,23.6],[0,-.45,0],"stone",-1,{lift:0,shade:.92}); b.box([23.9,.12,23.9],[0,-.18,0],"stone",-1,{lift:0}); for(let x=-8;x<=8;x++)for(let z=-8;z<=8;z++){ if(Math.abs(x)<4&&Math.abs(z)<4)continue; b.box([1.344,.08,1.344],[x*1.37,-.085+(variation(x*71+z*13)-.5)*.012,z*1.37],"stone",-1,{lift:0,shade:.86+variation(x*3+z*7)*.13}); } for(let i=0;i<5;i++)b.box([4.4,.17,1.02],[0,i*.17,9.3-i*.85],"stone",-1,{lift:0}); for(const sign of [-1,1]){ b.box([.36,.3,4.8],[sign*2.46,.44,7.65],"stone",-1,{r:[-.14,0,0],lift:0}); for(const z of [5.45,9.85]){ const y=z<6?1.05:.28; b.box([.48,.78,.48],[sign*2.46,y,z],"stone",-1,{lift:0}); b.sphere([sign*2.46,y+.5,z],[.24,.25,.24],"stone",-1,{lift:0}); } // Quiet stone garden, botanically shaped needles rather than stacked blobs. const px=sign*9.3,pz=-7.8; b.box([3.1,.23,3.1],[px,.02,pz],"stone",-1,{lift:0}); b.tube([[px,0,pz],[px+.25,1.5,pz],[px-.25,3.1,pz-.1],[px+.12,4.7,pz]],.15,"wood",-1,{lift:0},16); for(let branch=0;branch<7;branch++){ const a=branch*2.3,h=1.9+branch*.39,x=px+Math.cos(a)*1.25,z=pz+Math.sin(a)*1.2; b.tube([[px,h-.25,pz],[x-.2,h,z],[x,h+.18,z]],.05,"wood",-1,{lift:0},8); for(let n=0;n<28;n++){ const an=n*2.4,r=Math.sqrt(n/28)*.75,seed=branch*41+n; const px=x+Math.cos(an)*r,py=h+.22+Math.sin(n)*.16,pz=z+Math.sin(an)*r; b.sphere([px,py,pz],[.17+variation(seed)*.13,.065+variation(seed+1)*.05,.13+variation(seed+2)*.09],"moss",-1,{r:[variation(seed)*.5,an,variation(seed+3)*.5],lift:0,shade:.75+variation(seed+4)*.25}); if(n%3===0)b.tube([[x,h,z],[px,py-.08,pz]],.012,"wood",-1,{lift:0},2); } } // Architectural lantern: open frame with warm paper at its heart. const lx=sign*7.5,lz=7.2; b.box([.92,.2,.92],[lx,.1,lz],"stone",-1,{lift:0}); b.cylinder(.12,.2,1.3,[lx,.8,lz],"stone",-1,{lift:0}); b.box([.72,.12,.72],[lx,1.47,lz],"stone",-1,{lift:0}); for(const dx of [-.27,.27])for(const dz of [-.27,.27])b.box([.075,.65,.075],[lx+dx,1.8,lz+dz],"stone",-1,{lift:0}); b.sphere([lx,1.8,lz],[.2,.26,.2],"paper",-1,{lift:0}); b.cylinder(.07,.64,.34,[lx,2.27,lz],"tile",-1,{lift:0}); b.sphere([lx,2.5,lz],[.09,.13,.09],"stone",-1,{lift:0}); } // One scale figure with a pleated scholar's robe and crossed collar. const x=-7.1,z=5.4; const robe=new THREE.LatheGeometry(Array.from({length:15},(_,i)=>new THREE.Vector2(.24+.28*Math.pow(1-i/14,1.6),i/14*1.85)),32); b.add(robe,"cloth",.005,{p:[x,.05,z],duration:.018,lift:.05});robe.dispose(); for(let i=0;i<18;i++){ const a=i/18*TAU; b.tube([[x+Math.sin(a)*.5,.08,z+Math.cos(a)*.5],[x+Math.sin(a)*.34,1.02,z+Math.cos(a)*.34],[x+Math.sin(a)*.25,1.84,z+Math.cos(a)*.25]],.012,"cloth",.005,{shade:i%2?.8:1.1,lift:.05},8); } b.cylinder(.25,.31,.55,[x,1.94,z],"cloth",.005,{lift:.05}); b.sphere([x,2.47,z],[.16,.21,.17],"stone",.005,{lift:.05}); b.sphere([x,2.66,z-.045],[.11,.1,.12],"recess",.005,{lift:.05}); b.box([.33,.045,.29],[x,2.62,z],"recess",.005,{lift:.05}); b.box([.065,.25,.07],[x,2.76,z],"recess",.005,{lift:.05}); for(const sign of [-1,1]){ b.cylinder(.16,.23,.71,[x+sign*.33,1.84,z+.04],"cloth",.005,{r:[0,0,sign*.5],lift:.05}); b.box([.055,.48,.045],[x+sign*.08,2.05,z+.25],"stone",.005,{r:[0,0,sign*.4],lift:.05}); } }assets/starter/src/heritage/builder.ts6.0 KBa39d34f5047bupstream ↗
import * as THREE from "three"; import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js"; import type { SurfaceName } from "./materials"; export type Point = [number, number, number]; type Transform = { p?: Point; r?: Point; s?: Point; shade?: number; tint?: Point; duration?: number; lift?: number }; /** Batch by material, with construction timing baked into each vertex. * Each real brick/beam/tile moves on the GPU; shadows use the same motion. * Construction changes no opacity, so walls remain solid and occlude framing. */ export class HeritageBuilder { private batches = new Map<SurfaceName, THREE.BufferGeometry[]>(); private cache = new Map<string, THREE.BufferGeometry>(); private transform = new THREE.Object3D(); readonly progress = {value:0}; readonly meshes: THREE.Mesh[] = []; private depths: THREE.MeshDepthMaterial[] = []; pieces = 0; constructor(readonly materials: Record<SurfaceName,THREE.MeshStandardMaterial>) {} add(geometry:THREE.BufferGeometry,material:SurfaceName,start:number,options:Transform={}) { this.transform.position.set(...(options.p??[0,0,0])); this.transform.rotation.set(...(options.r??[0,0,0])); this.transform.scale.set(...(options.s??[1,1,1])); this.transform.updateMatrix(); const g=geometry.index?geometry.toNonIndexed():geometry.clone(); g.applyMatrix4(this.transform.matrix); const n=g.getAttribute("position").count; const schedule=new Float32Array(n*3),color=new Float32Array(n*3); const shade=options.shade??1,tint=options.tint??[1,1,1]; // Per-piece atlas offsets remove identical grain on repeated masonry/wood. const uv=g.getAttribute("uv"); if(uv && !["plaster","glass"].includes(material)){ const offset=(Math.sin(this.pieces*127.1)*43758.5453)%1; for(let i=0;i<uv.count;i++)uv.setXY(i,uv.getX(i)+offset,uv.getY(i)+offset*.731); } for(let i=0;i<n;i++){ schedule.set([start,options.duration??.013,options.lift??.45],i*3); const normal=g.getAttribute("normal"); const underside=normal?THREE.MathUtils.lerp(.76,1,THREE.MathUtils.smoothstep(normal.getY(i),-.8,.2)):1; color.set(tint.map(v=>v*shade*underside),i*3); } g.setAttribute("aBuild",new THREE.BufferAttribute(schedule,3)); g.setAttribute("color",new THREE.BufferAttribute(color,3)); if(!g.getAttribute("uv"))g.setAttribute("uv",new THREE.BufferAttribute(new Float32Array(n*2),2)); if(!g.getAttribute("normal"))g.computeVertexNormals(); for(const name of Object.keys(g.attributes))if(!["position","normal","uv","aBuild","color"].includes(name))g.deleteAttribute(name); if(!this.batches.has(material))this.batches.set(material,[]); this.batches.get(material)!.push(g); this.pieces++; } geo(key:string,fn:()=>THREE.BufferGeometry){if(!this.cache.has(key))this.cache.set(key,fn());return this.cache.get(key)!;} box(size:Point,p:Point,material:SurfaceName,start:number,options:Transform={}) { const key=`box:${size.join(",")}`; const geometry=this.geo(key,()=>{ if(Math.min(...size)<.18)return new THREE.BoxGeometry(...size); const [w,h,d]=size,r=Math.min(...size)*.055; const outline=new THREE.Shape(); outline.moveTo(-w/2+r,-h/2+r);outline.lineTo(w/2-r,-h/2+r); outline.lineTo(w/2-r,h/2-r);outline.lineTo(-w/2+r,h/2-r);outline.closePath(); const g=new THREE.ExtrudeGeometry(outline,{depth:d-2*r,bevelEnabled:true,bevelThickness:r,bevelSize:r,bevelSegments:1,steps:1}); g.translate(0,0,-d/2+r);return g; }); this.add(geometry,material,start,{...options,p}); } sphere(p:Point,s:Point,material:SurfaceName,start:number,options:Transform={}){ const detail=Math.max(...s)>.3; this.add(this.geo(`sphere:${detail}`,()=>new THREE.SphereGeometry(1,detail?16:10,detail?12:7)),material,start,{...options,p,s}); } cylinder(top:number,bottom:number,height:number,p:Point,material:SurfaceName,start:number,options:Transform={}){ this.add(this.geo(`cyl:${top}/${bottom}/${height}`,()=>new THREE.CylinderGeometry(top,bottom,height,12)),material,start,{...options,p}); } tube(points:Point[],radius:number,material:SurfaceName,start:number,options:Transform={},segments=18){ const curve=new THREE.CatmullRomCurve3(points.map(p=>new THREE.Vector3(...p))); const geometry=new THREE.TubeGeometry(curve,segments,radius,5,false); this.add(geometry,material,start,options);geometry.dispose(); } finish(scene:THREE.Scene){ const inject=(m:THREE.Material)=>{ m.onBeforeCompile=shader=>{ shader.uniforms.uBuildProgress=this.progress; shader.vertexShader="attribute vec3 aBuild; uniform float uBuildProgress; varying float vConstruction;\n"+shader.vertexShader.replace("#include <begin_vertex>",`#include <begin_vertex> float buildT=clamp((uBuildProgress-aBuild.x)/max(.0001,aBuild.y),0.0,1.0); vConstruction=buildT; float settle=sin(buildT*6.2831853)*pow(1.0-buildT,2.0)*0.035; transformed.y+=aBuild.z*(pow(1.0-buildT,3.0)-settle);`); shader.fragmentShader="varying float vConstruction;\n"+shader.fragmentShader.replace("void main() {","void main() { if(vConstruction<=0.0) discard;"); }; m.customProgramCacheKey=()=>"heritage-solid-assembly-v2"; }; for(const [name,geometries]of this.batches){ const combined=mergeGeometries(geometries,false)!; combined.computeBoundingSphere();geometries.forEach(g=>g.dispose()); const material=this.materials[name];inject(material); const mesh=new THREE.Mesh(combined,material); mesh.name=`heritage-${name}`;mesh.receiveShadow=name!=="glass";mesh.castShadow=!["moss","glass"].includes(name); const depth=new THREE.MeshDepthMaterial({depthPacking:THREE.RGBADepthPacking});inject(depth); mesh.customDepthMaterial=depth;this.depths.push(depth);this.meshes.push(mesh);scene.add(mesh); } this.cache.forEach(g=>g.dispose());this.cache.clear();this.batches.clear(); } dispose(){this.meshes.forEach(m=>{m.geometry.dispose();m.removeFromParent();});this.depths.forEach(m=>m.dispose());} }assets/starter/src/heritage/materials.ts6.7 KB79ccec586a51upstream ↗
import * as THREE from "three"; export type SurfaceName = "brick" | "wood" | "jade" | "stone" | "plaster" | "tile" | "bronze" | "recess" | "cloth" | "paper" | "moss" | "glass"; // Deterministic multi-scale wear: architecture should age in coherent patches, // rather than looking as if every brick was painted a different colour. export function createHeritageMaterials(renderer: THREE.WebGLRenderer) { const textures: THREE.Texture[] = []; const palette: Record<SurfaceName, string> = { brick: "#914735", wood: "#513825", jade: "#355d50", stone: "#9b9688", plaster: "#dad6c9", tile: "#3e584f", bronze: "#887040", recess: "#282921", cloth: "#555c53", paper: "#d9ab70", moss: "#45573a", glass: "#b6c8c3", }; const output = {} as Record<SurfaceName, THREE.MeshStandardMaterial>; for (const [name, base] of Object.entries(palette) as [SurfaceName, string][]) { if(name==="glass"){ output[name]=new THREE.MeshPhysicalMaterial({color:base,roughness:.16,metalness:0,transparent:true,opacity:.09,depthWrite:false,clearcoat:.65,clearcoatRoughness:.18,vertexColors:true}); continue; } const canvas = document.createElement("canvas"); const size = name === "plaster" ? 1024 : 512; canvas.width = canvas.height = size; const ctx = canvas.getContext("2d")!; let seed = 83 + name.length * 101; const rand = () => ((seed = (seed * 16807) % 2147483647) - 1) / 2147483646; ctx.fillStyle = base; ctx.fillRect(0, 0, size, size); // Mineral clouding and worn pigment, with transparent soft edges. for (let i = 0; i < 180; i++) { const x = rand() * size, y = rand() * size, r = size * (.02 + rand() * .13); const gradient = ctx.createRadialGradient(x, y, 0, x, y, r); gradient.addColorStop(0, name === "tile" ? (i % 3 ? "rgba(25,30,27,.035)" : "rgba(210,217,201,.025)") : (i % 3 ? "rgba(45,34,19,.038)" : "rgba(252,244,217,.045)")); gradient.addColorStop(1, "rgba(100,80,50,0)"); ctx.fillStyle = gradient; ctx.fillRect(x-r, y-r, r*2, r*2); } if (name === "wood") { for (let i = 0; i < 290; i++) { const x = rand() * size; ctx.strokeStyle = i % 3 ? "rgba(30,19,10,.16)" : "rgba(223,184,127,.13)"; ctx.lineWidth = .4 + rand() * 1.8; ctx.beginPath(); ctx.moveTo(x, 0); for (let y = 0; y <= size; y += 8) ctx.lineTo(x + Math.sin(y*.035 + x)*2 + Math.sin(y*.008)*5, y); ctx.stroke(); } for (let i=0;i<6;i++) { const x=rand()*size,y=rand()*size; for(let k=1;k<7;k++){ctx.strokeStyle="rgba(35,22,12,.16)";ctx.beginPath();ctx.ellipse(x,y,k*1.8,k*7,.1,0,Math.PI*2);ctx.stroke();} } } if (name === "plaster") { // Fallen lime plaster exposes masonry toward the foot of the shaft. const noise=(x:number,y:number)=> Math.sin(x*.024+y*.019)*.5+Math.sin(x*.065-y*.035)*.25+Math.sin(x*.111+y*.073)*.16; ctx.save(); ctx.beginPath(); ctx.moveTo(0,size); for(let x=0;x<=size;x+=4){ const edge=size*(.87+.034*Math.sin(x*.008)+.027*Math.sin(x*.021)+.007*Math.sin(x*.193)) + noise(x,100)*28; ctx.lineTo(x,edge); } ctx.lineTo(size,size);ctx.closePath();ctx.clip(); ctx.fillStyle="#a49a85";ctx.fillRect(0,0,size,size); for(let row=0;row<29;row++)for(let col=-1;col<16;col++){ const x=col*74+(row%2)*37,y=row*39; const v=Math.floor(126+rand()*23); ctx.fillStyle=`rgb(${v+29},${v+8},${v-14})`; ctx.fillRect(x+2,y+2,70,35); ctx.fillStyle="rgba(240,226,202,.28)";ctx.fillRect(x+2,y+2,70,1.5); } ctx.restore(); // Hairline cracks branch naturally and stay thin at the viewing distance. const crack=(x:number,y:number,length:number,angle:number,width:number,depth:number)=>{ ctx.strokeStyle="rgba(83,70,49,.20)";ctx.lineWidth=width;ctx.beginPath();ctx.moveTo(x,y); for(let j=0;j<9;j++){ angle+=(rand()-.5)*.9;x+=Math.cos(angle)*length/9;y+=Math.sin(angle)*length/9;ctx.lineTo(x,y); if(j===4&&depth>0)crack(x,y,length*.5,angle+.9,width*.55,depth-1); }ctx.stroke(); }; for(let i=0;i<22;i++)crack(rand()*size,rand()*size,size*(.06+rand()*.16),.6+rand()*2,.65+rand()*.8,2); // Narrow rain runs below the cornice, not repeated circular stains. for(let i=0;i<45;i++){ const x=rand()*size,w=2+rand()*18,h=40+rand()*240; const g=ctx.createLinearGradient(0,0,0,h);g.addColorStop(0,"rgba(80,82,55,.12)");g.addColorStop(1,"rgba(80,82,55,0)"); ctx.fillStyle=g;ctx.fillRect(x,0,w,h); } } for(let i=0;i<(name==="plaster"?45000:17000);i++){ ctx.globalAlpha=name==="tile"?.18:1; ctx.fillStyle=rand()>.45?`rgba(255,242,214,${.04+rand()*.13})`:`rgba(31,26,18,${.025+rand()*.1})`; const s=.4+rand()*1.6;ctx.fillRect(rand()*size,rand()*size,s,s); } ctx.globalAlpha=1; const texture=new THREE.CanvasTexture(canvas); texture.colorSpace=THREE.SRGBColorSpace; texture.wrapS=texture.wrapT=THREE.RepeatWrapping; texture.anisotropy=Math.min(8,renderer.capabilities.getMaxAnisotropy()); textures.push(texture); // Micro-height and roughness are independent of pigment: stains are not craters. const detail=document.createElement("canvas");detail.width=detail.height=256; const dc=detail.getContext("2d")!,pixels=dc.createImageData(256,256); for(let y=0;y<256;y++)for(let x=0;x<256;x++){ const i=(y*256+x)*4; const grain=name==="wood"?Math.sin(x*.83+Math.sin(y*.033)*2)*20:0; const v=128+(rand()-.5)*(name==="stone"?65:32)+grain; pixels.data[i]=pixels.data[i+1]=pixels.data[i+2]=v;pixels.data[i+3]=255; } dc.putImageData(pixels,0,0); const bump=new THREE.CanvasTexture(detail);bump.wrapS=bump.wrapT=THREE.RepeatWrapping;bump.anisotropy=texture.anisotropy;textures.push(bump); const roughCanvas=document.createElement("canvas");roughCanvas.width=roughCanvas.height=256; const rc=roughCanvas.getContext("2d")!;rc.fillStyle=name==="tile"?"#aaaaaa":name==="wood"?"#d4d4d4":"#ededed";rc.fillRect(0,0,256,256); for(let i=0;i<90;i++){rc.fillStyle=`rgba(60,60,60,${.02+rand()*.045})`;rc.fillRect(rand()*256,rand()*256,8+rand()*35,8+rand()*35);} const roughness=new THREE.CanvasTexture(roughCanvas);roughness.wrapS=roughness.wrapT=THREE.RepeatWrapping;textures.push(roughness); output[name]=new THREE.MeshStandardMaterial({map:texture,bumpMap:bump,roughnessMap:roughness,bumpScale:name==="plaster"?.013:name==="tile"?.006:.024,roughness:name==="bronze"?.62:name==="tile"?.82:.96,metalness:name==="bronze"?.65:0,vertexColors:true}); if(name==="paper"){output[name].emissive.set("#9d5020");output[name].emissiveIntensity=.28;} } return {materials:output,dispose(){textures.forEach(t=>t.dispose());Object.values(output).forEach(m=>m.dispose());}}; }assets/starter/src/main.tsx155 Bde5f1c9d2ac7upstream ↗
import { createRoot } from 'react-dom/client'; import App from './App'; import './style.css'; createRoot(document.getElementById('root')!).render(<App/>);assets/starter/src/PagodaThreeScene.tsx6.6 KBce97c4db57e4upstream ↗
import { useEffect, useRef } from "react"; import * as THREE from "three"; import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js"; import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js"; import { createHeritageMaterials } from "./heritage/materials"; import { HeritageBuilder } from "./heritage/builder"; import { buildArchitecture, courtyard } from "./heritage/architecture"; export type DetailView="overview"|"roof"|"guardian"; type Props={progress:number;view?:DetailView;onReady?:()=>void}; export default function PagodaThreeScene({progress,view="overview",onReady}:Props){ const mountRef=useRef<HTMLDivElement>(null); const progressRef=useRef(progress),viewRef=useRef(view),readyRef=useRef(onReady); useEffect(()=>{progressRef.current=progress;},[progress]); useEffect(()=>{viewRef.current=view;},[view]); useEffect(()=>{readyRef.current=onReady;},[onReady]); useEffect(()=>{ const mount=mountRef.current;if(!mount)return; const scene=new THREE.Scene(); const camera=new THREE.PerspectiveCamera(34,1,.1,180); camera.position.set(38,22.5,57); const renderer=new THREE.WebGLRenderer({antialias:true,alpha:true,powerPreference:"high-performance"}); renderer.setPixelRatio(Math.min(devicePixelRatio,window.innerWidth<700?1.5:2)); renderer.setClearColor(0xf4f1e9,0); renderer.outputColorSpace=THREE.SRGBColorSpace; renderer.toneMapping=THREE.ACESFilmicToneMapping;renderer.toneMappingExposure=1.0; renderer.shadowMap.enabled=true;renderer.shadowMap.type=THREE.PCFSoftShadowMap; // Camera movement does not change a directional light's shadow map. renderer.shadowMap.autoUpdate=false; mount.appendChild(renderer.domElement); const room=new RoomEnvironment(),pmrem=new THREE.PMREMGenerator(renderer); const environment=pmrem.fromScene(room,.06);scene.environment=environment.texture;scene.environmentIntensity=.32; room.dispose();pmrem.dispose(); scene.add(new THREE.HemisphereLight(0xfaf7ef,0x706a5c,.72)); const key=new THREE.DirectionalLight(0xfff2e2,2.4);key.position.set(-22,38,30);key.castShadow=true; key.shadow.mapSize.set(2048,2048);key.shadow.camera.left=-22;key.shadow.camera.right=22; key.shadow.camera.top=25;key.shadow.camera.bottom=-20;key.shadow.camera.near=.5;key.shadow.camera.far=100; key.target.position.set(0,12,0);key.shadow.normalBias=.025;key.shadow.bias=-.00015;key.shadow.radius=3; scene.add(key,key.target); const fill=new THREE.DirectionalLight(0xe5eced,.55);fill.position.set(25,18,-10);scene.add(fill); const rim=new THREE.DirectionalLight(0xfff4de,.7);rim.position.set(-12,30,-24);scene.add(rim); const controls=new OrbitControls(camera,renderer.domElement); controls.target.set(0,15.35,0);controls.enableDamping=true;controls.dampingFactor=.075; controls.enablePan=true;controls.minDistance=12;controls.maxDistance=110; controls.minPolarAngle=.35;controls.maxPolarAngle=Math.PI*.51; const materialKit=createHeritageMaterials(renderer),builder=new HeritageBuilder(materialKit.materials); courtyard(builder);buildArchitecture(builder);builder.finish(scene); const reducedMotion=window.matchMedia("(prefers-reduced-motion: reduce)").matches; const presets={ overview:{position:new THREE.Vector3(38,22.5,57),target:new THREE.Vector3(0,15.35,0)}, roof:{position:new THREE.Vector3(16,30.3,22),target:new THREE.Vector3(0,26.9,0)}, guardian:{position:new THREE.Vector3(8.5,12.7,17),target:new THREE.Vector3(.4,11,4.5)}, }; let lastView:DetailView="overview",transition=false,raf=0,lastNow=performance.now(),frames=0,elapsed=0; let needsFrame=true,lastProgress=-2,lastShadowProgress=-2,lastShadowTime=-Infinity; let renderedFrames=0,shadowUpdates=0; const interrupt=()=>{transition=false;};controls.addEventListener("start",interrupt); const resize=()=>{ const w=Math.max(1,mount.clientWidth),h=Math.max(1,mount.clientHeight); renderer.setSize(w,h,false);camera.aspect=w/h; camera.fov=camera.aspect<.58?39:34;camera.updateProjectionMatrix(); needsFrame=true; }; const ro=new ResizeObserver(resize);ro.observe(mount);resize(); builder.progress.value=progressRef.current; renderer.compile(scene,camera); const render=(now:number)=>{ const frameSeconds=(now-lastNow)/1000; const dt=Math.min(frameSeconds,.1);lastNow=now; builder.progress.value=progressRef.current; if(lastView!==viewRef.current){lastView=viewRef.current;transition=true;} if(transition){ const preset=presets[lastView],amount=reducedMotion?1:1-Math.exp(-dt*5); camera.position.lerp(preset.position,amount);controls.target.lerp(preset.target,amount); if(camera.position.distanceTo(preset.position)<.02)transition=false; } const cameraChanged=controls.update(); const progressChanged=lastProgress!==progressRef.current; // Limit construction shadow work to 30 Hz. Final/rewound poses flush // immediately, and a paused intermediate pose flushes on the next tick. const shadowChanged=lastShadowProgress!==progressRef.current && (now-lastShadowTime>=1000/30 || progressRef.current===0 || progressRef.current===1); if(!document.hidden && (needsFrame || cameraChanged || transition || progressChanged || shadowChanged)){ if(shadowChanged){ renderer.shadowMap.needsUpdate=true; lastShadowProgress=progressRef.current;lastShadowTime=now;shadowUpdates++; } renderer.render(scene,camera);renderedFrames++; needsFrame=false;lastProgress=progressRef.current; } frames++;elapsed+=frameSeconds; if(elapsed>.6){ mount.dataset.renderStats=JSON.stringify({calls:renderer.info.render.calls,triangles:renderer.info.render.triangles,geometries:renderer.info.memory.geometries,textures:renderer.info.memory.textures,pieces:builder.pieces,fps:Math.round(frames/elapsed),renderFps:Math.round(renderedFrames/elapsed),shadowUpdatesPerSecond:Math.round(shadowUpdates/elapsed),idle:renderedFrames===0,dpr:renderer.getPixelRatio(),shadowLights:1,postPasses:0}); frames=0;elapsed=0;renderedFrames=0;shadowUpdates=0; } raf=requestAnimationFrame(render); }; raf=requestAnimationFrame(render);readyRef.current?.(); return()=>{ cancelAnimationFrame(raf);ro.disconnect();controls.removeEventListener("start",interrupt);controls.dispose(); builder.dispose();materialKit.dispose();environment.dispose(); key.shadow.map?.dispose();renderer.dispose();renderer.domElement.remove(); }; },[]); return <div ref={mountRef} className="three-scene" aria-label="可旋转的三维中国古塔施工动画" />; }assets/starter/src/style.css6.7 KBfa2e839079f7upstream ↗
:root { --paper: #f4f1e9; --ink: #423e33; --red: #924c3a; --line: rgba(76, 65, 43, .16); } * { box-sizing: border-box; } html, body { margin: 0; min-height: 100%; background: var(--paper); color: var(--ink); } body { overflow: hidden; font-family: "Songti SC", "STSong", "Noto Serif CJK SC", Georgia, serif; } button, input { font: inherit; } .poster { min-height: 560px; height: 100svh; display: grid; grid-template-rows: 76px 1fr 70px; overflow: hidden; background: radial-gradient(ellipse at 48% 36%, #fffefa 0, rgba(255,255,255,0) 72%), var(--paper); } header { margin: 0 3vw; border-bottom: 1px solid var(--line); display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; position: relative; z-index: 5; } header > span { font: 500 24px/1 "Songti SC", serif; letter-spacing: .15em; } .wordmark { display: flex; align-items: center; gap: 12px; } .wordmark i { display: grid; place-items: center; width: 27px; height: 30px; border: 1px solid var(--red); color: var(--red); font: 18px/1 "Songti SC",serif; } .wordmark em { margin-left: 8px; font: 500 8px/1.5 Arial,sans-serif; letter-spacing: .16em; } header small { font: 600 8px/1 Arial, sans-serif; letter-spacing: .2em; opacity: .55; } header button { border: 0; border-bottom: 1px solid currentColor; background: none; padding: 5px 0; font: 600 9px/1 Arial, sans-serif; letter-spacing: .13em; cursor: pointer; } .header-actions { justify-self: end; display: flex; align-items: center; gap: 18px; } .scene { min-height: 0; display: grid; grid-template-columns: minmax(170px, 20vw) minmax(390px, 1fr) minmax(140px, 16vw); align-items: center; padding: 0 3vw; } .brief { z-index: 3; padding-left: .7vw; pointer-events: none; } .micro { font: 500 9px/1.8 Arial, sans-serif; letter-spacing: .18em; opacity: .55; margin-bottom: 4vh; } .micro span { display: block; margin-top: 10px; font-family: "Songti SC",serif; } .brief h2 { font-size: clamp(29px, 3vw, 47px); line-height: 1.55; font-weight: 400; letter-spacing: -.03em; margin: 0; } .brief .accent { color: var(--red); font-size: 12px; margin: 18px 0 4vh; } .brief blockquote { margin: 0; font-size: clamp(11px,1vw,16px); line-height: 1.85; color: #898171; text-decoration: none; text-decoration-thickness: 1px; text-decoration-color: rgba(59,58,52,.4); text-underline-offset: 5px; } .index { display: flex; align-items: center; gap: 9px; margin-top: 4vh; font: 700 9px/1 Arial,sans-serif; } .index i { display: block; width: 62px; height: 1px; background: var(--ink); opacity: .4; } .tower-stage { height: 100%; min-height: 0; position: relative; z-index: 2; overflow: visible; } .three-scene { position: absolute; inset: 0 -8% 4%; cursor: grab; touch-action: none; } .three-scene:active { cursor: grabbing; } .three-scene canvas { display: block; width: 100%; height: 100%; outline: none; } .stage-label { position: absolute; z-index: 4; left: 50%; top: 17px; bottom: auto; transform: translateX(-50%); background: transparent; border: 0; padding: 7px 0; font: 500 10px/1 Arial, sans-serif; letter-spacing: .16em; white-space: nowrap; pointer-events: none; } .stage-label i { display:inline-block; width:4px; height:4px; margin-right:9px; background:var(--red); border-radius:50%; vertical-align:middle; } .stage-label span { margin-left:13px; font-size:8px; color:#aaa18e; font-variant-numeric:tabular-nums; } .view-selector { position:absolute; bottom:27px; left:50%; transform:translateX(-50%); display:flex; gap:3px; border:1px solid var(--line); border-radius:30px; padding:4px; background:rgba(249,247,241,.9); } .view-selector button { white-space:nowrap; border:0; background:none; color:#847a66; border-radius:24px; padding:9px 16px; font:11px/1 "Songti SC",serif; cursor:pointer; transition:background .2s,color .2s; } .view-selector button[aria-pressed="true"] { color:#f7f3e9; background:#4b5146; } .view-selector button:hover { color:var(--red); } .view-selector button[aria-pressed="true"]:hover { color:white; } .scene-loading { position:absolute; inset:0; display:grid; place-items:center; background:var(--paper); color:var(--red); font:16px/1 serif; letter-spacing:.4em; } button:focus-visible,input:focus-visible { outline:2px solid var(--red); outline-offset:4px; } .orbit-hint { position: absolute; left: 50%; bottom: 10px; transform: translateX(-50%); color: rgba(59,58,52,.52); font: 600 8px/1 Arial, sans-serif; letter-spacing: .12em; pointer-events: none; } .title-block { z-index: 3; align-self: center; pointer-events: none; text-align:center; } .symbols { font: 10px/1.8 "Songti SC",serif; letter-spacing: .15em; opacity: .48; } .title-block h1 { margin: 6vh 0 10px; font-size: clamp(58px, 7.2vw, 108px); line-height: 1.02; font-weight: 400; letter-spacing: -.13em; } .title-block > p { margin: 22px 0 0; text-align: center; color:#918875; font:italic 12px/1.65 Georgia,serif; } .original-mark { margin: 6vh auto 0; width: max-content; padding: 12px 0 0; border-top:1px solid var(--line); color: var(--red); font: 500 7px/2 Arial,sans-serif; letter-spacing: .15em; } .original-mark b { font:400 13px/2 "Songti SC",serif; letter-spacing:.25em; } footer { margin: 0 3vw; border-top: 1px solid var(--line); display: grid; grid-template-columns: 34px 1fr 105px; align-items: center; gap: 14px; position: relative; z-index: 5; } .play { width: 30px; height: 30px; border: 0; border-radius: 50%; color: var(--paper); background: var(--ink); cursor: pointer; font: 700 11px/1 Arial,sans-serif; } .timeline { height: 4px; position: relative; background: rgba(59,58,52,.13); } .timeline span { position: absolute; inset: 0 auto 0 0; background: var(--red); } .timeline input { position: absolute; inset: -12px 0; width: 100%; margin: 0; opacity: 0; cursor: ew-resize; } footer time { text-align: right; font: 700 9px/1 Arial,sans-serif; letter-spacing: .1em; } @media (max-width: 900px) { .poster { min-height: 0; grid-template-rows: 48px 1fr 58px; } header { margin: 0 16px; } header small { display: none; } header > span { font-size: 21px; } .wordmark em { display:none; } .header-actions { gap: 10px; } .scene { grid-template-columns: 1fr; padding: 0; } .brief, .title-block { display: none; } .tower-stage { min-height: 0; } .three-scene { inset: 0 -3% 6%; } .stage-label { top:10px; } footer { margin: 0 16px; grid-template-columns: 34px 1fr 83px; } } @media (max-height: 720px) and (min-width: 901px) { .brief blockquote { line-height: 1.55; } .brief .accent { margin-bottom: 2vh; } .micro { margin-bottom: 2vh; } .title-block h1 { margin-top: 3vh; } .original-mark { margin-top: 4vh; } } @media (prefers-reduced-motion: reduce) { .three-scene { cursor: default; } }assets/starter/tsconfig.json294 B0b1191d6366bupstream ↗
{ "compilerOptions": { "target": "ES2022", "lib": ["ES2022", "DOM", "DOM.Iterable"], "module": "ESNext", "moduleResolution": "bundler", "jsx": "react-jsx", "strict": true, "skipLibCheck": true, "noEmit": true, "esModuleInterop": true }, "include": ["src", "vite.config.ts"] }assets/starter/vite.config.ts132 Bbd5899b6dbb9upstream ↗
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()] });.gitignore56 B998861fba9aaupstream ↗
.DS_Store node_modules/ dist/ .env* *.log *.tsbuildinfoagents/openai.yaml382 Ba749951ae5f8upstream ↗
interface: display_name: "Architecture Growth · Three.js" short_description: "Build 3D heritage construction animations with eaves and cameras" default_prompt: "Use $threejs-architecture-effects to make a three-storey Chinese pavilion from the bundled starter: red walls, dark-green tiles, timber eaves, brick-by-brick assembly, orbitable cameras, and a verified local run."LICENSE1.0 KBb6383cdb9f08upstream ↗
MIT License Copyright (c) 2026 Hailey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Plain-text copy, no login: /skill-bundles/lhlgithub-threejs-architecture-effects.md
