Ethscriptions commited on
Commit
b02b26f
·
verified ·
1 Parent(s): 545083f

暮归江南 · v2 优化:性能(三角形 -60%、预烘焙天光、着色器预编译)、去闪烁(反向深度、稳定阴影、灯光平滑)、骨骼人物与精细民居

Browse files
README.md CHANGED
@@ -138,6 +138,10 @@ tools/jiangnan/ # 旁白生成、字体子集化、实况图
138
  - **步骤 9** ✅ Blender 场景脚本 `blender/jiangnan_village.py`:已在沙盒里用 Blender 4.2 LTS(bpy)实际运行,生成 218 栋民居、178 盏灯笼(含关键帧点亮)、石拱桥、水车(旋转动画)、古樟、竹林、Nishita 天空 + 日落关键帧 + 蓝调天光、暮霭体积、10 个镜头(时间轴标记自动切换),并用 Cycles 试渲通过。
139
  - **步骤 10** ✅ 全片检查与调优:用无头浏览器逐镜头渲染(横屏 + 竖屏)并做构图 / 曝光量化检查,修正了:远山遮挡夕阳、开场机位、河面朝向、太阳水面倒影过曝导致的辉光泛白(加入高光压缩)、古樟镜头机位穿进民居、夜河镜头里看不到船、终章大全景构图、Blender 夜景镜头穿模与 Nishita 天空在日落后发黑;新增每个镜头独立曝光、水车水花、夜里河岸萤火虫;播放器加入音频时钟失效时的兜底;整页冒烟测试(加载、合成音频、播放、横竖屏切换、封面渲染)无报错。
140
  - **补充验证** ✅ 全尺寸实测:① 720p 60fps 导出(H.264 60/1、90 帧 + 音轨,ffmpeg 完整解码通过);② 1080×1440 实况图(90 帧 30fps H.264 + 同尺寸封面 JPEG,3.7 MB MOV),用 LiveCanvas 原版 `verify_pair` 与 `package_live_photo.py` 校验通过(内容标识一致、still-image-time = 1.5 s、单个时间样本、完整解码)。
 
 
 
 
141
 
142
 
143
  ---
 
138
  - **步骤 9** ✅ Blender 场景脚本 `blender/jiangnan_village.py`:已在沙盒里用 Blender 4.2 LTS(bpy)实际运行,生成 218 栋民居、178 盏灯笼(含关键帧点亮)、石拱桥、水车(旋转动画)、古樟、竹林、Nishita 天空 + 日落关键帧 + 蓝调天光、暮霭体积、10 个镜头(时间轴标记自动切换),并用 Cycles 试渲通过。
139
  - **步骤 10** ✅ 全片检查与调优:用无头浏览器逐镜头渲染(横屏 + 竖屏)并做构图 / 曝光量化检查,修正了:远山遮挡夕阳、开场机位、河面朝向、太阳水面倒影过曝导致的辉光泛白(加入高光压缩)、古樟镜头机位穿进民居、夜河镜头里看不到船、终章大全景构图、Blender 夜景镜头穿模与 Nishita 天空在日落后发黑;新增每个镜头独立曝光、水车水花、夜里河岸萤火虫;播放器加入音频时钟失效时的兜底;整页冒烟测试(加载、合成音频、播放、横竖屏切换、封面渲染)无报错。
140
  - **补充验证** ✅ 全尺寸实测:① 720p 60fps 导出(H.264 60/1、90 帧 + 音轨,ffmpeg 完整解码通过);② 1080×1440 实况图(90 帧 30fps H.264 + 同尺寸封面 JPEG,3.7 MB MOV),用 LiveCanvas 原版 `verify_pair` 与 `package_live_photo.py` 校验通过(内容标识一致、still-image-time = 1.5 s、单个时间样本、完整解码)。
141
+ - **步骤 11(v2 优化:卡顿 / 闪烁 / 模型)** ✅
142
+ - **卡顿**:实测每帧从约 950 万三角形、近 1000 次绘制调用降到约 350 万、约 200 次(远山林木降面、竹林减段,地形 / 林木 / 小物件不再进入阴影与倒影通道,用 Three.js 图层 Layers 区分「主画面专用」与「可倒影」物体;树木、竹林在山茶与梯田镜头里不画水面反射);环境光(PMREM)改为加载时一次性预烘焙 173 张,播放中不再每 0.5 秒重算;所有镜头(横 / 竖、昼 / 夜)的着色器在加载时预编译,播放中不再出现「第一次出现某镜头时卡一下」;页面时间显示独立刷新,播放时不再整页重渲染;自适应分辨率加入迟滞与冷却,不会来回切换。新增画质档位(高 / 中 / 流畅,手机默认「中」)。
143
+ - **闪烁**:启用 Three.js 反向深度缓冲(reversedDepthBuffer + 32 位浮点深度纹理),远处屋面、路面不再深度冲突;水面倒影改用裁剪平面(clippingPlanes),兼容反向深度;阴影取景框按镜头固定并在光源空间按纹素对齐,投影用的太阳方向每个镜头固定,阴影不再爬动;街上灯笼的点光源按「第 N+1 盏的距离」平滑淡入淡出,换灯时不再突亮突灭;树叶开启 alpha-to-coverage 抗锯齿;水面细波纹与碎金随距离淡化;胶片颗粒减弱。静态相机实测:除了在飞的白鹭与行人,逐帧跳变像素 ≈ 0%。导出 MP4 / 封面 / 实况图改为超采样渲染(1.4–2 倍分辨率再缩小),细节不抖。
144
+ - **模型**:村民、牛车、白鹭改为骨骼蒙皮模型(每个角色一次绘制):车削建模的上衣、长衫、袖口、手、头部五官轮廓、发髻与蓝印花布头巾、竹编斗笠(内外两层)、扁担与箩筐;牛有桶形身体、肩峰、垂皮、口鼻、弯角、耳朵、尾巴、蹄子,走路时四腿交替、头尾摆动,车轮带辐条;白鹭有 S 形颈和带飞羽的翅膀。临街临河民居的屋面改为真实起伏的阴阳瓦(近处立体、远处自动淡化防锯齿),檐口加瓦当与滴水;门两侧贴红春联与横批,店铺挂黑底金字店招(米铺、茶馆、酱园、布庄、药铺、豆腐坊、酒坊、竹器),门口有水缸、柴垛、盆栽。
145
 
146
 
147
  ---
src/jiangnan/JiangnanApp.tsx CHANGED
@@ -1,4 +1,4 @@
1
- import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
2
  import './jiangnan.css'
3
  import { buildMix } from './audio/mixer'
4
  import blenderScript from './blender/jiangnan_village.py?raw'
@@ -69,7 +69,7 @@ export default function JiangnanApp() {
69
  const [load, setLoad] = useState({ p: 0, label: '准备中' })
70
  const [audioReady, setAudioReady] = useState(false)
71
  const [playing, setPlaying] = useState(false)
72
- const [time, setTime] = useState(0)
73
  const [aspect, setAspect] = useState<Aspect>(() => (typeof window !== 'undefined' && window.innerHeight > window.innerWidth && isMobile() ? 'portrait' : 'landscape'))
74
  const [subs, setSubs] = useState(true)
75
  const [muted, setMuted] = useState(false)
@@ -223,7 +223,6 @@ export default function JiangnanApp() {
223
  const seek = useCallback((t: number) => {
224
  const c = clockRef.current
225
  c.t = Math.max(0, Math.min(DURATION, t))
226
- setTime(c.t)
227
  dirtyRef.current = true
228
  if (c.playing) play(c.t)
229
  }, [play])
@@ -238,7 +237,7 @@ export default function JiangnanApp() {
238
  if (!ready) return
239
  let raf = 0
240
  let ema = 16
241
- let lastUi = 0
242
  const loop = () => {
243
  raf = requestAnimationFrame(loop)
244
  const film = filmRef.current
@@ -265,9 +264,10 @@ export default function JiangnanApp() {
265
  ema = ema * 0.9 + dt * 0.1
266
  if (c.playing) {
267
  // adaptive resolution: keep playback smooth on slower devices
268
- if (ema > 42 && scaleRef.current > 0.45) { scaleRef.current *= 0.85; ema = 30; resize() } else if (ema < 14 && scaleRef.current < 1) { scaleRef.current = Math.min(1, scaleRef.current * 1.1); ema = 20; resize() }
 
 
269
  }
270
- if (performance.now() - lastUi > 100) { setTime(t); lastUi = performance.now() }
271
  }
272
  raf = requestAnimationFrame(loop)
273
  return () => cancelAnimationFrame(raf)
@@ -294,10 +294,10 @@ export default function JiangnanApp() {
294
  else el.requestFullscreen?.().catch(() => say('当前浏览器不支持全屏'))
295
  }
296
 
297
- const curShot = shotAt(time)
298
 
299
  // ------------------------------------------------------------ busy wrapper (export / covers / live)
300
- const withBusy = async <T,>(fn: () => Promise<T>) => {
301
  pause()
302
  busyRef.current = true
303
  try { return await fn() } finally {
@@ -305,7 +305,7 @@ export default function JiangnanApp() {
305
  resize()
306
  dirtyRef.current = true
307
  }
308
- }
309
 
310
  return (
311
  <div className="jn">
@@ -337,24 +337,16 @@ export default function JiangnanApp() {
337
 
338
  <div className="jn-controls">
339
  <button className="jn-btn primary" disabled={!ready} onClick={() => (playing ? pause() : play())}>{playing ? '暂停' : '播放'}</button>
340
- <span className="jn-time">{fmt(time)} / {fmt(DURATION)}</span>
341
- <div className="jn-scrub">
342
- <input type="range" min={0} max={DURATION} step={0.05} value={time} onChange={(e) => seek(Number(e.target.value))} disabled={!ready} />
343
- </div>
344
  <button className={`jn-btn ${aspect === 'landscape' ? 'on' : ''}`} onClick={() => setAspect('landscape')}>横屏 16:9</button>
345
  <button className={`jn-btn ${aspect === 'portrait' ? 'on' : ''}`} onClick={() => setAspect('portrait')}>竖屏 9:16</button>
346
  <button className={`jn-btn ghost ${subs ? 'on' : ''}`} onClick={() => setSubs(!subs)}>字幕{subs ? '开' : '关'}</button>
347
  <button className={`jn-btn ghost ${muted ? '' : 'on'}`} onClick={() => setMuted(!muted)}>{muted ? '已静音' : '声音开'}</button>
348
  <button className="jn-btn ghost" onClick={fullscreen}>全屏</button>
 
349
  </div>
350
  {!audioReady && ready && <div className="jn-note">配乐与旁白正在浏览器里合成,稍等几秒后播放会有声音。</div>}
351
- <div className="jn-shots">
352
- {SHOTS.map((s) => (
353
- <button key={s.id} className={`jn-chip ${curShot.id === s.id ? 'active' : ''}`} onClick={() => seek(s.t0 + 0.01)}>
354
- {String(s.id).padStart(2, '0')} {s.name}
355
- </button>
356
- ))}
357
- </div>
358
 
359
  <ExportSection film={filmRef} audio={audioRef} ready={ready && audioReady} withBusy={withBusy} />
360
  <CoverSection film={filmRef} ready={ready} withBusy={withBusy} />
@@ -379,11 +371,67 @@ export default function JiangnanApp() {
379
  )
380
  }
381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
382
  // ====================================================================== export
383
  type FilmRef = React.MutableRefObject<Film | null>
384
  type Busy = <T>(fn: () => Promise<T>) => Promise<T>
385
 
386
- function ExportSection({ film, audio, ready, withBusy }: { film: FilmRef; audio: React.MutableRefObject<{ buf: AudioBuffer | null }>; ready: boolean; withBusy: Busy }) {
387
  const [orient, setOrient] = useState<Aspect>('landscape')
388
  const [res, setRes] = useState<720 | 1080>(1080)
389
  const [fps, setFps] = useState<24 | 30 | 60>(30)
@@ -477,12 +525,12 @@ function ExportSection({ film, audio, ready, withBusy }: { film: FilmRef; audio:
477
  <p className="jn-note">提示:1080p 60fps 共 {Math.round(DURATION * 60)} 帧,独立显卡电脑约 2–4 分钟;手机建议导出 720p。iPhone 上导出后点「保存」→「存储视频」。</p>
478
  </section>
479
  )
480
- }
481
 
482
  // ====================================================================== covers
483
  interface CoverItem { key: string; ratio: Ratio; name: string; url: string; blob: Blob }
484
 
485
- function CoverSection({ film, ready, withBusy }: { film: FilmRef; ready: boolean; withBusy: Busy }) {
486
  const [ratios, setRatios] = useState<Ratio[]>(['16:9', '4:3', '3:4'])
487
  const [designs, setDesigns] = useState<string[]>(COVER_DESIGNS.map((d) => d.key))
488
  const [items, setItems] = useState<CoverItem[]>([])
@@ -554,10 +602,10 @@ function CoverSection({ film, ready, withBusy }: { film: FilmRef; ready: boolean
554
  </div>
555
  </section>
556
  )
557
- }
558
 
559
  // ====================================================================== copy
560
- function CopySection({ say }: { say: (m: string) => void }) {
561
  const [tab, setTab] = useState(PLATFORMS[0].id)
562
  const [pick, setPick] = useState<Record<string, number>>({})
563
  const p = PLATFORMS.find((x) => x.id === tab)!
@@ -600,10 +648,10 @@ function CopySection({ say }: { say: (m: string) => void }) {
600
  </div>
601
  </section>
602
  )
603
- }
604
 
605
  // ====================================================================== live photos
606
- function LiveSection({ film, ready, withBusy, say }: { film: FilmRef; ready: boolean; withBusy: Busy; say: (m: string) => void }) {
607
  const [prog, setProg] = useState<{ p: number; label: string } | null>(null)
608
  const [res, setRes] = useState<LiveResult | null>(null)
609
  const [err, setErr] = useState('')
@@ -668,7 +716,7 @@ function LiveSection({ film, ready, withBusy, say }: { film: FilmRef; ready: boo
668
  <TextDownload />
669
  </section>
670
  )
671
- }
672
 
673
  function TextDownload() {
674
  const all = () => {
 
1
+ import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
2
  import './jiangnan.css'
3
  import { buildMix } from './audio/mixer'
4
  import blenderScript from './blender/jiangnan_village.py?raw'
 
69
  const [load, setLoad] = useState({ p: 0, label: '准备中' })
70
  const [audioReady, setAudioReady] = useState(false)
71
  const [playing, setPlaying] = useState(false)
72
+ const nowRef = useRef<() => number>(() => 0)
73
  const [aspect, setAspect] = useState<Aspect>(() => (typeof window !== 'undefined' && window.innerHeight > window.innerWidth && isMobile() ? 'portrait' : 'landscape'))
74
  const [subs, setSubs] = useState(true)
75
  const [muted, setMuted] = useState(false)
 
223
  const seek = useCallback((t: number) => {
224
  const c = clockRef.current
225
  c.t = Math.max(0, Math.min(DURATION, t))
 
226
  dirtyRef.current = true
227
  if (c.playing) play(c.t)
228
  }, [play])
 
237
  if (!ready) return
238
  let raf = 0
239
  let ema = 16
240
+ let lastScale = performance.now()
241
  const loop = () => {
242
  raf = requestAnimationFrame(loop)
243
  const film = filmRef.current
 
264
  ema = ema * 0.9 + dt * 0.1
265
  if (c.playing) {
266
  // adaptive resolution: keep playback smooth on slower devices
267
+ // with hysteresis + cooldown so the resolution never oscillates (that reads as flicker)
268
+ const since = performance.now() - lastScale
269
+ if (ema > 34 && scaleRef.current > 0.45 && since > 1500) { scaleRef.current *= 0.85; ema = 24; lastScale = performance.now(); resize() } else if (ema < 13 && scaleRef.current < 1 && since > 6000) { scaleRef.current = Math.min(1, scaleRef.current * 1.08); ema = 18; lastScale = performance.now(); resize() }
270
  }
 
271
  }
272
  raf = requestAnimationFrame(loop)
273
  return () => cancelAnimationFrame(raf)
 
294
  else el.requestFullscreen?.().catch(() => say('当前浏览器不支持全屏'))
295
  }
296
 
297
+ nowRef.current = now
298
 
299
  // ------------------------------------------------------------ busy wrapper (export / covers / live)
300
+ const withBusy = useCallback(async <T,>(fn: () => Promise<T>) => {
301
  pause()
302
  busyRef.current = true
303
  try { return await fn() } finally {
 
305
  resize()
306
  dirtyRef.current = true
307
  }
308
+ }, [pause, resize]) as Busy
309
 
310
  return (
311
  <div className="jn">
 
337
 
338
  <div className="jn-controls">
339
  <button className="jn-btn primary" disabled={!ready} onClick={() => (playing ? pause() : play())}>{playing ? '暂停' : '播放'}</button>
340
+ <TimeReadout nowRef={nowRef} seek={seek} ready={ready} />
 
 
 
341
  <button className={`jn-btn ${aspect === 'landscape' ? 'on' : ''}`} onClick={() => setAspect('landscape')}>横屏 16:9</button>
342
  <button className={`jn-btn ${aspect === 'portrait' ? 'on' : ''}`} onClick={() => setAspect('portrait')}>竖屏 9:16</button>
343
  <button className={`jn-btn ghost ${subs ? 'on' : ''}`} onClick={() => setSubs(!subs)}>字幕{subs ? '开' : '关'}</button>
344
  <button className={`jn-btn ghost ${muted ? '' : 'on'}`} onClick={() => setMuted(!muted)}>{muted ? '已静音' : '声音开'}</button>
345
  <button className="jn-btn ghost" onClick={fullscreen}>全屏</button>
346
+ <QualityPicker />
347
  </div>
348
  {!audioReady && ready && <div className="jn-note">配乐与旁白正在浏览器里合成,稍等几秒后播放会有声音。</div>}
349
+ <ShotChips nowRef={nowRef} seek={seek} />
 
 
 
 
 
 
350
 
351
  <ExportSection film={filmRef} audio={audioRef} ready={ready && audioReady} withBusy={withBusy} />
352
  <CoverSection film={filmRef} ready={ready} withBusy={withBusy} />
 
371
  )
372
  }
373
 
374
+ function QualityPicker() {
375
+ const cur = (new URLSearchParams(location.search).get('q') as Quality) || (isMobile() ? 'medium' : 'high')
376
+ const set = (q: Quality) => {
377
+ const u = new URL(location.href)
378
+ u.searchParams.set('q', q)
379
+ location.href = u.toString()
380
+ }
381
+ return (
382
+ <select className="jn-btn ghost" value={cur} onChange={(e) => set(e.target.value as Quality)} aria-label="画质" style={{ paddingRight: 8 }}>
383
+ <option value="high">画质:高</option>
384
+ <option value="medium">画质:中(手机)</option>
385
+ <option value="low">画质:流畅</option>
386
+ </select>
387
+ )
388
+ }
389
+
390
+ // ====================================================================== transport (own render cycle)
391
+ function useFilmTime(nowRef: React.MutableRefObject<() => number>, hz = 8) {
392
+ const [t, setT] = useState(0)
393
+ useEffect(() => {
394
+ let last = -1
395
+ const id = window.setInterval(() => {
396
+ const v = Math.round(nowRef.current() * 10) / 10
397
+ if (v !== last) { last = v; setT(v) }
398
+ }, 1000 / hz)
399
+ return () => window.clearInterval(id)
400
+ }, [nowRef, hz])
401
+ return t
402
+ }
403
+
404
+ function TimeReadout({ nowRef, seek, ready }: { nowRef: React.MutableRefObject<() => number>; seek: (t: number) => void; ready: boolean }) {
405
+ const time = useFilmTime(nowRef)
406
+ return (
407
+ <>
408
+ <span className="jn-time">{fmt(time)} / {fmt(DURATION)}</span>
409
+ <div className="jn-scrub">
410
+ <input type="range" min={0} max={DURATION} step={0.05} value={time} onChange={(e) => seek(Number(e.target.value))} disabled={!ready} />
411
+ </div>
412
+ </>
413
+ )
414
+ }
415
+
416
+ function ShotChips({ nowRef, seek }: { nowRef: React.MutableRefObject<() => number>; seek: (t: number) => void }) {
417
+ const time = useFilmTime(nowRef, 4)
418
+ const cur = shotAt(time)
419
+ return (
420
+ <div className="jn-shots">
421
+ {SHOTS.map((s) => (
422
+ <button key={s.id} className={`jn-chip ${cur.id === s.id ? 'active' : ''}`} onClick={() => seek(s.t0 + 0.01)}>
423
+ {String(s.id).padStart(2, '0')} {s.name}
424
+ </button>
425
+ ))}
426
+ </div>
427
+ )
428
+ }
429
+
430
  // ====================================================================== export
431
  type FilmRef = React.MutableRefObject<Film | null>
432
  type Busy = <T>(fn: () => Promise<T>) => Promise<T>
433
 
434
+ const ExportSection = memo(function ExportSection({ film, audio, ready, withBusy }: { film: FilmRef; audio: React.MutableRefObject<{ buf: AudioBuffer | null }>; ready: boolean; withBusy: Busy }) {
435
  const [orient, setOrient] = useState<Aspect>('landscape')
436
  const [res, setRes] = useState<720 | 1080>(1080)
437
  const [fps, setFps] = useState<24 | 30 | 60>(30)
 
525
  <p className="jn-note">提示:1080p 60fps 共 {Math.round(DURATION * 60)} 帧,独立显卡电脑约 2–4 分钟;手机建议导出 720p。iPhone 上导出后点「保存」→「存储视频」。</p>
526
  </section>
527
  )
528
+ })
529
 
530
  // ====================================================================== covers
531
  interface CoverItem { key: string; ratio: Ratio; name: string; url: string; blob: Blob }
532
 
533
+ const CoverSection = memo(function CoverSection({ film, ready, withBusy }: { film: FilmRef; ready: boolean; withBusy: Busy }) {
534
  const [ratios, setRatios] = useState<Ratio[]>(['16:9', '4:3', '3:4'])
535
  const [designs, setDesigns] = useState<string[]>(COVER_DESIGNS.map((d) => d.key))
536
  const [items, setItems] = useState<CoverItem[]>([])
 
602
  </div>
603
  </section>
604
  )
605
+ })
606
 
607
  // ====================================================================== copy
608
+ const CopySection = memo(function CopySection({ say }: { say: (m: string) => void }) {
609
  const [tab, setTab] = useState(PLATFORMS[0].id)
610
  const [pick, setPick] = useState<Record<string, number>>({})
611
  const p = PLATFORMS.find((x) => x.id === tab)!
 
648
  </div>
649
  </section>
650
  )
651
+ })
652
 
653
  // ====================================================================== live photos
654
+ const LiveSection = memo(function LiveSection({ film, ready, withBusy, say }: { film: FilmRef; ready: boolean; withBusy: Busy; say: (m: string) => void }) {
655
  const [prog, setProg] = useState<{ p: number; label: string } | null>(null)
656
  const [res, setRes] = useState<LiveResult | null>(null)
657
  const [err, setErr] = useState('')
 
716
  <TextDownload />
717
  </section>
718
  )
719
+ })
720
 
721
  function TextDownload() {
722
  const all = () => {
src/jiangnan/assets/fonts/title.woff2 CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:8a0e19db8353edace27893e2bdd4572a167ed6492c5247363582b65a43843e62
3
- size 233272
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:75a02dc6da583ac655d671552f3c5945dbf1ff63cff1ecda40438a71a7f19e0c
3
+ size 248288
src/jiangnan/assets/fonts/wenkai.woff2 CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:bc282ef76d0be3bc574df1397041696fbcf13c37cb1a1af64ce15a23adc9f6e8
3
- size 143264
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6fec6cc3ef086bad9f6d65bb8199459345c55779ef648bcfaa225b20762f9745
3
+ size 151272
src/jiangnan/engine/Film.ts CHANGED
@@ -22,7 +22,7 @@ const tick = () => new Promise<void>((r) => setTimeout(r, 0))
22
  export class Film {
23
  renderer: THREE.WebGLRenderer
24
  scene = new THREE.Scene()
25
- camera = new THREE.PerspectiveCamera(40, 16 / 9, 0.3, 14000)
26
  post!: Post
27
  water!: Water
28
  sky!: ReturnType<typeof createSky>
@@ -39,14 +39,24 @@ export class Film {
39
  envSky!: THREE.Mesh
40
  envRT: THREE.WebGLRenderTarget | null = null
41
  envKey = -1
 
 
 
 
 
 
42
  width = 1280
43
  height = 720
44
  quality: Quality
45
  ready = false
 
 
46
 
47
  constructor(canvas: HTMLCanvasElement, quality: Quality = 'high') {
48
  this.quality = quality
49
- this.renderer = new THREE.WebGLRenderer({ canvas, antialias: false, powerPreference: 'high-performance', preserveDrawingBuffer: true, alpha: false })
 
 
50
  this.renderer.setPixelRatio(1)
51
  this.renderer.toneMapping = THREE.ACESFilmicToneMapping
52
  this.renderer.toneMappingExposure = 1
@@ -66,7 +76,7 @@ export class Film {
66
  getTextures()
67
  progress(0.12, '生成天空与山谷')
68
  await tick()
69
- this.sky = createSky()
70
  s.add(this.sky.mesh)
71
  s.add(createTerrain())
72
  progress(0.3, '开垦梯田')
@@ -80,7 +90,7 @@ export class Film {
80
  s.add(createEmbankments())
81
  progress(0.5, '修建粉墙黛瓦')
82
  await tick()
83
- this.village = createVillage()
84
  s.add(this.village.group)
85
  progress(0.62, '搭石桥、架水车、摆集市')
86
  await tick()
@@ -88,7 +98,7 @@ export class Film {
88
  s.add(this.props.group)
89
  progress(0.72, '种下古樟与竹林')
90
  await tick()
91
- const trees = createTrees()
92
  s.add(trees.group)
93
  progress(0.86, '村民、牛车、白鹭与灯笼')
94
  await tick()
@@ -119,11 +129,27 @@ export class Film {
119
  ground.position.y = -6
120
  this.envScene.add(ground)
121
  this.post = createPost(this.renderer, this.scene, this.camera, this.width, this.height, this.quality === 'low' ? 0 : 4)
 
 
 
122
  progress(0.95, '预热着色器')
123
  await tick()
124
- this.setSize(this.width, this.height)
125
- this.renderFrame(1)
126
- this.renderFrame(60)
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  progress(1, '完成')
128
  this.ready = true
129
  }
@@ -139,19 +165,47 @@ export class Film {
139
  this.water?.setSize(w * rs, h * rs)
140
  }
141
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  private updateEnv(t: number, state: ReturnType<typeof skyState>) {
143
- const key = Math.floor(t * 2)
144
  if (key === this.envKey && this.envRT) return
145
  this.envKey = key
146
- // the env map uses the sky at quantised time so preview & export match
147
- const prevStar = this.sky.uniforms.uStarBoost.value
148
- this.sky.uniforms.uStarBoost.value = 0
149
- const old = this.envRT
150
- this.envRT = this.pmrem.fromScene(this.envScene, 0.04, 0.1, 400)
151
- this.sky.uniforms.uStarBoost.value = prevStar
 
152
  this.scene.environment = this.envRT.texture
153
  this.scene.environmentIntensity = lerp(1.6, 1.1, state.night)
154
- old?.dispose()
155
  }
156
 
157
  /** Update every animated thing for film time t (seconds). */
@@ -193,45 +247,77 @@ export class Film {
193
  }
194
 
195
  private placeLights(t: number, st: ReturnType<typeof skyState>) {
196
- // shadow frustum follows the subject of the current shot
197
  const shot = shotAt(t)
198
  const cam = this.camera
199
  const fwd = new THREE.Vector3()
200
  cam.getWorldDirection(fwd)
201
- let center: THREE.Vector3, size: number
202
- if (shot.id === 1 || shot.id === 10) { center = new THREE.Vector3(-20, 0, -10); size = 380 } else if (shot.id === 7) { center = new THREE.Vector3(TERRACE.cx - 60, 80, TERRACE.cz + 80); size = 320 } else if (shot.id === 6) { center = new THREE.Vector3(TREE_POS.x + 6, 2, TREE_POS.z + 4); size = 70 } else {
203
- center = cam.position.clone().addScaledVector(fwd, 30)
204
- center.y = 2
205
- size = 90
 
 
 
 
 
 
 
 
 
 
206
  }
 
207
  const sc = this.sun.shadow.camera as THREE.OrthographicCamera
208
- sc.left = -size; sc.right = size; sc.top = size; sc.bottom = -size
209
- sc.near = 1
210
- sc.far = 2400
211
- sc.updateProjectionMatrix()
212
- // snap to texels to avoid shimmering
 
 
213
  const texel = (size * 2) / this.sun.shadow.mapSize.x
214
- center.x = Math.round(center.x / texel) * texel
215
- center.z = Math.round(center.z / texel) * texel
216
- this.sun.target.position.copy(center)
217
- this.sun.position.copy(center).addScaledVector(st.sunDir, 1000)
 
 
 
 
218
  this.sun.target.updateMatrixWorld()
219
- this.moon.target.position.copy(center)
220
  this.moon.target.updateMatrixWorld()
221
- // nearest lit lanterns become real point lights
 
222
  const cp = cam.position
223
- const cands = this.lanterns.list
224
- .filter((l) => t > l.on)
225
- .map((l) => ({ l, d: l.p.distanceToSquared(cp) + (l.p.clone().sub(cp).dot(fwd) < -4 ? 4000 : 0) }))
226
- .sort((a, b) => a.d - b.d)
227
- this.lamps.forEach((lamp, i) => {
228
- const c = cands[i]
229
- if (!c || c.d > 90 * 90) { lamp.intensity = 0; return }
230
- const lt = t - c.l.on
 
 
 
 
 
 
 
 
 
 
 
 
 
231
  const on = smoothstep(0, 0.4, lt)
232
- const flick = 0.92 + 0.08 * Math.sin(t * 11 + c.l.seed * 50)
233
- lamp.position.copy(c.l.p).add(new THREE.Vector3(0, -0.45, 0))
234
- lamp.intensity = 26 * on * flick
 
 
235
  })
236
  }
237
 
@@ -239,7 +325,8 @@ export class Film {
239
  renderFrame(t: number) {
240
  if (!this.sky || !this.water || !this.life) return
241
  const st = this.update(t)
242
- const pose = cameraAt(t, this.width / this.height)
 
243
  applyPose(this.camera, pose)
244
  this.sky.mesh.position.copy(this.camera.position)
245
  this.updateEnv(t, st)
@@ -259,7 +346,10 @@ export class Film {
259
  this.post.grade.uniforms.uNight.value = st.night
260
  this.post.grade.uniforms.uFade.value = fadeBlack(t)
261
  this.renderer.shadowMap.needsUpdate = true
262
- this.water.renderReflection(this.renderer, this.scene, this.camera)
 
 
 
263
  this.post.composer.render()
264
  }
265
  }
 
22
  export class Film {
23
  renderer: THREE.WebGLRenderer
24
  scene = new THREE.Scene()
25
+ camera = new THREE.PerspectiveCamera(40, 16 / 9, 0.4, 12000)
26
  post!: Post
27
  water!: Water
28
  sky!: ReturnType<typeof createSky>
 
39
  envSky!: THREE.Mesh
40
  envRT: THREE.WebGLRenderTarget | null = null
41
  envKey = -1
42
+ envCache = new Map<number, THREE.WebGLRenderTarget>()
43
+ shadowShot = -1
44
+ shadowCenter = new THREE.Vector3()
45
+ shadowDir = new THREE.Vector3(0, 1, 0)
46
+ shadowSize = 90
47
+ lampLevel = new Map<number, number>()
48
  width = 1280
49
  height = 720
50
  quality: Quality
51
  ready = false
52
+ /** QA: freeze the camera at this film time (everything else keeps animating) */
53
+ freezeCam: number | null = null
54
 
55
  constructor(canvas: HTMLCanvasElement, quality: Quality = 'high') {
56
  this.quality = quality
57
+ this.renderer = new THREE.WebGLRenderer({ canvas, antialias: false, powerPreference: 'high-performance', preserveDrawingBuffer: false, alpha: false, reversedDepthBuffer: true, stencil: false })
58
+ // see layers: 0 = everything reflected in the water, 1 = main view only
59
+ this.camera.layers.enable(1)
60
  this.renderer.setPixelRatio(1)
61
  this.renderer.toneMapping = THREE.ACESFilmicToneMapping
62
  this.renderer.toneMappingExposure = 1
 
76
  getTextures()
77
  progress(0.12, '生成天空与山谷')
78
  await tick()
79
+ this.sky = createSky(this.renderer.capabilities.reversedDepthBuffer)
80
  s.add(this.sky.mesh)
81
  s.add(createTerrain())
82
  progress(0.3, '开垦梯田')
 
90
  s.add(createEmbankments())
91
  progress(0.5, '修建粉墙黛瓦')
92
  await tick()
93
+ this.village = createVillage(this.quality)
94
  s.add(this.village.group)
95
  progress(0.62, '搭石桥、架水车、摆集市')
96
  await tick()
 
98
  s.add(this.props.group)
99
  progress(0.72, '种下古樟与竹林')
100
  await tick()
101
+ const trees = createTrees(this.quality)
102
  s.add(trees.group)
103
  progress(0.86, '村民、牛车、白鹭与灯笼')
104
  await tick()
 
129
  ground.position.y = -6
130
  this.envScene.add(ground)
131
  this.post = createPost(this.renderer, this.scene, this.camera, this.width, this.height, this.quality === 'low' ? 0 : 4)
132
+ progress(0.9, '烘焙天光')
133
+ await tick()
134
+ await this.bakeEnvironment((p) => progress(0.9 + p * 0.05, '烘焙天光'))
135
  progress(0.95, '预热着色器')
136
  await tick()
137
+ // warm-up: render every shot once (day and night states) at a tiny size so that every
138
+ // shader variant (main, reflection clipping, shadow depth, skinning…) is compiled now,
139
+ // not the first time a shot appears during playback
140
+ const W0 = this.width, H0 = this.height
141
+ this.setSize(96, 54)
142
+ const warm = [0.5, 12, 20, 28, 36, 44, 51, 58.6, 60, 62, 68, 80]
143
+ for (let i = 0; i < warm.length; i++) {
144
+ this.renderFrame(warm[i])
145
+ this.setSize(54, 96) // portrait framing variants
146
+ this.renderFrame(warm[i])
147
+ this.setSize(96, 54)
148
+ progress(0.95 + (i / warm.length) * 0.05, '预热着色器')
149
+ await tick()
150
+ }
151
+ this.shadowShot = -1
152
+ this.setSize(W0, H0)
153
  progress(1, '完成')
154
  this.ready = true
155
  }
 
165
  this.water?.setSize(w * rs, h * rs)
166
  }
167
 
168
+ /** Environment light from the sky. Pre-baked every 0.5 s of film time (no runtime hitches). */
169
+ private envFor(t: number) {
170
+ const key = Math.max(0, Math.min(Math.round(t * 2), 9999))
171
+ let rt = this.envCache.get(key)
172
+ if (!rt) {
173
+ // bake the sky as it is at the quantised time
174
+ const st = skyState(key / 2)
175
+ U.uSunDir.value.copy(st.sunDir)
176
+ U.uNight.value = st.night
177
+ this.sky.update(st)
178
+ const prevStar = this.sky.uniforms.uStarBoost.value
179
+ this.sky.uniforms.uStarBoost.value = 0
180
+ rt = this.pmrem.fromScene(this.envScene, 0.04, 0.1, 400, { size: 64 })
181
+ this.sky.uniforms.uStarBoost.value = prevStar
182
+ this.envCache.set(key, rt)
183
+ }
184
+ return rt
185
+ }
186
+
187
+ /** Bake all environment maps up-front (called during loading). */
188
+ async bakeEnvironment(progress?: (p: number) => void) {
189
+ const n = Math.ceil(86 * 2) + 1
190
+ for (let k = 0; k <= n; k++) {
191
+ this.envFor(k / 2)
192
+ if (k % 12 === 0) { progress?.(k / n); await tick() }
193
+ }
194
+ }
195
+
196
  private updateEnv(t: number, state: ReturnType<typeof skyState>) {
197
+ const key = Math.round(t * 2)
198
  if (key === this.envKey && this.envRT) return
199
  this.envKey = key
200
+ const hit = this.envCache.has(Math.max(0, Math.min(Math.round(t * 2), 9999)))
201
+ this.envRT = this.envFor(t)
202
+ if (!hit) {
203
+ this.sky.update(state)
204
+ U.uSunDir.value.copy(state.sunDir)
205
+ U.uNight.value = state.night
206
+ }
207
  this.scene.environment = this.envRT.texture
208
  this.scene.environmentIntensity = lerp(1.6, 1.1, state.night)
 
209
  }
210
 
211
  /** Update every animated thing for film time t (seconds). */
 
247
  }
248
 
249
  private placeLights(t: number, st: ReturnType<typeof skyState>) {
 
250
  const shot = shotAt(t)
251
  const cam = this.camera
252
  const fwd = new THREE.Vector3()
253
  cam.getWorldDirection(fwd)
254
+ // shadow frustum: fixed for the whole shot (no per-frame re-centering → no shimmering)
255
+ if (this.shadowShot !== shot.id) {
256
+ this.shadowShot = shot.id
257
+ // the sun direction used for shadows is frozen for the shot: a continuously rotating
258
+ // shadow camera re-samples every texel each frame, which reads as crawling / flicker
259
+ this.shadowDir.copy(skyState(shot.t0 + (shot.t1 - shot.t0) * 0.5).sunDir)
260
+ if (this.shadowDir.y < 0.02) this.shadowDir.y = 0.02
261
+ this.shadowDir.normalize()
262
+ const pose = cameraAt(shot.t0 + (shot.t1 - shot.t0) * 0.5, this.width / this.height)
263
+ const dir = pose.target.clone().sub(pose.pos).setY(0).normalize()
264
+ if (shot.id === 1 || shot.id === 10) { this.shadowCenter.set(-20, 0, -10); this.shadowSize = 380 } else if (shot.id === 7) { this.shadowCenter.set(TERRACE.cx - 60, 80, TERRACE.cz + 80); this.shadowSize = 320 } else if (shot.id === 6) { this.shadowCenter.set(TREE_POS.x + 6, 2, TREE_POS.z + 4); this.shadowSize = 60 } else {
265
+ this.shadowCenter.copy(pose.pos).addScaledVector(dir, 34)
266
+ this.shadowCenter.y = 2
267
+ this.shadowSize = shot.id === 5 || shot.id === 8 ? 75 : 70
268
+ }
269
  }
270
+ const size = this.shadowSize
271
  const sc = this.sun.shadow.camera as THREE.OrthographicCamera
272
+ if (sc.right !== size) {
273
+ sc.left = -size; sc.right = size; sc.top = size; sc.bottom = -size
274
+ sc.near = 1
275
+ sc.far = 2400
276
+ sc.updateProjectionMatrix()
277
+ }
278
+ // snap the frustum origin to whole shadow-map texels in light space
279
  const texel = (size * 2) / this.sun.shadow.mapSize.x
280
+ const lightRot = new THREE.Matrix4().lookAt(this.shadowDir, new THREE.Vector3(0, 0, 0), new THREE.Vector3(0, 1, 0))
281
+ const inv = lightRot.clone().invert()
282
+ const c = this.shadowCenter.clone().applyMatrix4(inv)
283
+ c.x = Math.round(c.x / texel) * texel
284
+ c.y = Math.round(c.y / texel) * texel
285
+ c.applyMatrix4(lightRot)
286
+ this.sun.target.position.copy(c)
287
+ this.sun.position.copy(c).addScaledVector(this.shadowDir, 1000)
288
  this.sun.target.updateMatrixWorld()
289
+ this.moon.target.position.copy(c)
290
  this.moon.target.updateMatrixWorld()
291
+ // nearest lit lanterns become real point lights; intensities fade with distance so the
292
+ // set of lights can change without anything visibly popping
293
  const cp = cam.position
294
+ const R = 26, R0 = 15
295
+ const cands: { i: number; d: number }[] = []
296
+ const list = this.lanterns.list
297
+ for (let i = 0; i < list.length; i++) {
298
+ const l = list[i]
299
+ if (t <= l.on) continue
300
+ const dx = l.p.x - cp.x, dy = l.p.y - cp.y, dz = l.p.z - cp.z
301
+ const d = Math.sqrt(dx * dx + dy * dy + dz * dz)
302
+ if (d > R) continue
303
+ const ahead = (dx * fwd.x + dy * fwd.y + dz * fwd.z) > -6
304
+ if (ahead) cands.push({ i, d })
305
+ }
306
+ cands.sort((a, b) => a.d - b.d)
307
+ // the fade-out distance is set by the first lantern that does NOT get a light, so a lantern
308
+ // swapping in or out of the set always does so at ~zero intensity
309
+ const cutoff = Math.min(R, cands[this.lamps.length]?.d ?? R)
310
+ this.lamps.forEach((lamp, k) => {
311
+ const c2 = cands[k]
312
+ if (!c2) { lamp.intensity = 0; return }
313
+ const l = list[c2.i]
314
+ const lt = t - l.on
315
  const on = smoothstep(0, 0.4, lt)
316
+ const flick = 0.92 + 0.08 * Math.sin(t * 11 + l.seed * 50)
317
+ // fade out toward the edge of the radius, and for the last slots of the set
318
+ const edge = 1 - smoothstep(Math.min(R0, cutoff * 0.65), cutoff, c2.d)
319
+ lamp.position.set(l.p.x, l.p.y - 0.45, l.p.z)
320
+ lamp.intensity = 26 * on * flick * edge
321
  })
322
  }
323
 
 
325
  renderFrame(t: number) {
326
  if (!this.sky || !this.water || !this.life) return
327
  const st = this.update(t)
328
+ const shot = shotAt(t)
329
+ const pose = cameraAt(this.freezeCam ?? t, this.width / this.height)
330
  applyPose(this.camera, pose)
331
  this.sky.mesh.position.copy(this.camera.position)
332
  this.updateEnv(t, st)
 
346
  this.post.grade.uniforms.uNight.value = st.night
347
  this.post.grade.uniforms.uFade.value = fadeBlack(t)
348
  this.renderer.shadowMap.needsUpdate = true
349
+ // the river is not in frame in the camphor and terrace shots: skip the whole reflection pass
350
+ const showWater = shot.id !== 6 && shot.id !== 7
351
+ this.water.mesh.visible = showWater
352
+ if (showWater) this.water.renderReflection(this.renderer, this.scene, this.camera)
353
  this.post.composer.render()
354
  }
355
  }
src/jiangnan/engine/figures.ts ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Characters as single skinned meshes (one draw call each): villagers in
2
+ // Jiangnan dress, the ox & cart, egrets. Parts are rigidly bound to bones.
3
+ import * as THREE from 'three'
4
+ import { std } from './materials'
5
+ import { rrange } from './rng'
6
+
7
+ type RGB = [number, number, number]
8
+
9
+ class SkinBuilder {
10
+ pos: number[] = []
11
+ nrm: number[] = []
12
+ col: number[] = []
13
+ idx: number[] = []
14
+ wgt: number[] = []
15
+ private v = new THREE.Vector3()
16
+ private n = new THREE.Vector3()
17
+ /** add geometry (already in bind pose / model space) bound to `bone` with a flat colour */
18
+ add(g: THREE.BufferGeometry, m: THREE.Matrix4, bone: number, color: RGB, shade = true) {
19
+ const geo = g.index ? g.toNonIndexed() : g
20
+ if (!geo.getAttribute('normal')) geo.computeVertexNormals()
21
+ const p = geo.getAttribute('position'), nn = geo.getAttribute('normal')
22
+ const nm = new THREE.Matrix3().getNormalMatrix(m)
23
+ for (let i = 0; i < p.count; i++) {
24
+ this.v.set(p.getX(i), p.getY(i), p.getZ(i)).applyMatrix4(m)
25
+ this.n.set(nn.getX(i), nn.getY(i), nn.getZ(i)).applyMatrix3(nm).normalize()
26
+ this.pos.push(this.v.x, this.v.y, this.v.z)
27
+ this.nrm.push(this.n.x, this.n.y, this.n.z)
28
+ // subtle ambient-occlusion-like darkening toward the bottom of each part
29
+ const k = shade ? 0.85 + 0.15 * Math.min(1, Math.max(0, this.n.y * 0.5 + 0.5)) : 1
30
+ this.col.push(color[0] * k, color[1] * k, color[2] * k)
31
+ this.idx.push(bone, 0, 0, 0)
32
+ this.wgt.push(1, 0, 0, 0)
33
+ }
34
+ }
35
+ build() {
36
+ const g = new THREE.BufferGeometry()
37
+ g.setAttribute('position', new THREE.Float32BufferAttribute(this.pos, 3))
38
+ g.setAttribute('normal', new THREE.Float32BufferAttribute(this.nrm, 3))
39
+ g.setAttribute('color', new THREE.Float32BufferAttribute(this.col, 3))
40
+ g.setAttribute('skinIndex', new THREE.Uint16BufferAttribute(this.idx, 4))
41
+ g.setAttribute('skinWeight', new THREE.Float32BufferAttribute(this.wgt, 4))
42
+ g.computeBoundingSphere()
43
+ return g
44
+ }
45
+ }
46
+
47
+ const M = (x = 0, y = 0, z = 0, rx = 0, ry = 0, rz = 0, sx = 1, sy = 1, sz = 1) =>
48
+ new THREE.Matrix4().compose(new THREE.Vector3(x, y, z), new THREE.Quaternion().setFromEuler(new THREE.Euler(rx, ry, rz)), new THREE.Vector3(sx, sy, sz))
49
+
50
+ function lathe(profile: [number, number][], seg = 14) {
51
+ return new THREE.LatheGeometry(profile.map(([r, y]) => new THREE.Vector2(Math.max(0.001, r), y)), seg)
52
+ }
53
+
54
+ let charMat: THREE.Material | null = null
55
+ export function characterMaterial() {
56
+ if (!charMat) charMat = std({ vertexColors: true, roughness: 0.82, metalness: 0, side: THREE.DoubleSide }, { key: 'char' })
57
+ return charMat
58
+ }
59
+
60
+ function makeSkinned(sb: SkinBuilder, bones: THREE.Bone[]) {
61
+ const mesh = new THREE.SkinnedMesh(sb.build(), characterMaterial())
62
+ mesh.add(bones[0])
63
+ mesh.updateMatrixWorld(true)
64
+ mesh.bind(new THREE.Skeleton(bones))
65
+ mesh.castShadow = true
66
+ mesh.receiveShadow = true
67
+ mesh.frustumCulled = false
68
+ return mesh
69
+ }
70
+
71
+ function bone(parent: THREE.Bone | null, x: number, y: number, z: number) {
72
+ const b = new THREE.Bone()
73
+ b.position.set(x, y, z)
74
+ if (parent) parent.add(b)
75
+ return b
76
+ }
77
+
78
+ // ---------------------------------------------------------------- villager
79
+ const CLOTH: RGB[] = [[0.07, 0.1, 0.22], [0.12, 0.17, 0.3], [0.26, 0.25, 0.23], [0.22, 0.14, 0.08], [0.32, 0.3, 0.27], [0.08, 0.08, 0.09], [0.36, 0.12, 0.08]]
80
+ const SKIN: RGB[] = [[0.62, 0.43, 0.31], [0.55, 0.37, 0.26], [0.68, 0.5, 0.38]]
81
+
82
+ export interface Villager {
83
+ mesh: THREE.SkinnedMesh
84
+ root: THREE.Bone; hips: THREE.Bone; spine: THREE.Bone; head: THREE.Bone
85
+ legL: THREE.Bone; legR: THREE.Bone; armL: THREE.Bone; armR: THREE.Bone; load: THREE.Bone
86
+ hasPole: boolean
87
+ hipY: number
88
+ }
89
+
90
+ export function makeVillager(rng: () => number, opts: { pole?: boolean; hat?: boolean; seated?: boolean; female?: boolean; robe?: boolean }): Villager {
91
+ const female = opts.female ?? rng() < 0.4
92
+ const robe = opts.robe ?? (!female && rng() < 0.25)
93
+ const cloth = CLOTH[Math.floor(rng() * CLOTH.length)]
94
+ const cloth2 = CLOTH[Math.floor(rng() * CLOTH.length)]
95
+ const trouser: RGB = female ? CLOTH[Math.floor(rng() * 3)] : [0.05, 0.05, 0.06]
96
+ const skin = SKIN[Math.floor(rng() * SKIN.length)]
97
+ const hair: RGB = [0.025, 0.022, 0.02]
98
+ const straw: RGB = [0.62, 0.5, 0.28]
99
+ const H = rrange(rng, 0.94, 1.04) * (female ? 0.95 : 1)
100
+
101
+ // bones (bind pose = standing, facing +z)
102
+ const root = bone(null, 0, 0, 0)
103
+ const hips = bone(root, 0, 0.92 * H, 0)
104
+ const spine = bone(hips, 0, 0.02, 0)
105
+ const head = bone(spine, 0, 0.62 * H, 0)
106
+ const legL = bone(hips, -0.09, 0, 0)
107
+ const legR = bone(hips, 0.09, 0, 0)
108
+ const armL = bone(spine, -0.2 * H, 0.54 * H, 0)
109
+ const armR = bone(spine, 0.2 * H, 0.54 * H, 0)
110
+ const load = bone(spine, 0, 0.6 * H, 0.0)
111
+ const bones = [root, hips, spine, head, legL, legR, armL, armR, load]
112
+ const B = { root: 0, hips: 1, spine: 2, head: 3, legL: 4, legR: 5, armL: 6, armR: 7, load: 8 }
113
+ root.updateMatrixWorld(true)
114
+ const sb = new SkinBuilder()
115
+ const hy = 0.92 * H
116
+
117
+ // legs: trouser + cloth shoe
118
+ for (const [sx, b] of [[-0.09, B.legL], [0.09, B.legR]] as const) {
119
+ const leg = lathe([[0.04, 0], [0.05, 0.08], [0.058, 0.4], [0.075, 0.82], [0.07, 0.9]], 10)
120
+ sb.add(leg, M(sx, hy - 0.9 * H, 0, 0, 0, 0, 1, H, 1), b, trouser)
121
+ const shoe = new THREE.SphereGeometry(0.06, 10, 6, 0, Math.PI * 2, 0, Math.PI / 2)
122
+ sb.add(shoe, M(sx, hy - 0.9 * H, 0.03, 0, 0, 0, 0.9, 0.7, 1.9), b, [0.04, 0.035, 0.03])
123
+ }
124
+ // torso (jacket) — flattened lathe with shoulders
125
+ const torso = lathe([[0.14, 0], [0.155, 0.12], [0.175, 0.32], [0.19, 0.48], [0.17, 0.55], [0.07, 0.6], [0.045, 0.62]], 16)
126
+ sb.add(torso, M(0, hy, 0, 0, 0, 0, 1, H, 0.72), B.spine, cloth)
127
+ // jacket hem / robe skirt
128
+ if (robe || female) {
129
+ const len = robe ? 0.82 : 0.32
130
+ const skirt = lathe([[0.15, 0], [0.17, -len * 0.4], [robe ? 0.22 : 0.2, -len]], 16)
131
+ sb.add(skirt, M(0, hy + 0.04, 0, 0, 0, 0, 1, H, 0.8), robe ? B.hips : B.spine, robe ? cloth2 : cloth)
132
+ } else {
133
+ const hem = lathe([[0.15, 0], [0.165, -0.12]], 16)
134
+ sb.add(hem, M(0, hy + 0.03, 0, 0, 0, 0, 1, H, 0.78), B.spine, cloth)
135
+ }
136
+ // sash
137
+ sb.add(new THREE.CylinderGeometry(0.152, 0.152, 0.05, 16, 1, true), M(0, hy + 0.06, 0, 0, 0, 0, 1, 1, 0.74), B.spine, [0.12, 0.09, 0.06])
138
+ // arms: sleeve + forearm + hand
139
+ for (const [sx, b] of [[-1, B.armL], [1, B.armR]] as const) {
140
+ const sx0 = sx * 0.2 * H
141
+ const sleeve = lathe([[0.062, 0], [0.06, -0.25], [0.07, -0.42], [0.072, -0.45]], 10)
142
+ sb.add(sleeve, M(sx0, hy + 0.54 * H, 0, 0, 0, sx * 0.06, 1, H, 1), b, cloth)
143
+ const fore = lathe([[0.035, -0.4], [0.032, -0.55]], 8)
144
+ sb.add(fore, M(sx0 + sx * 0.03, hy + 0.54 * H, 0, 0, 0, sx * 0.06, 1, H, 1), b, skin)
145
+ sb.add(new THREE.SphereGeometry(0.04, 8, 6), M(sx0 + sx * 0.04, hy + 0.54 * H - 0.6 * H, 0.01, 0, 0, 0, 0.8, 1.15, 0.6), b, skin)
146
+ }
147
+ // head & neck
148
+ const hyH = hy + 0.62 * H
149
+ sb.add(new THREE.CylinderGeometry(0.035, 0.04, 0.08, 8), M(0, hyH + 0.02, 0), B.head, skin)
150
+ sb.add(new THREE.SphereGeometry(0.1, 16, 12), M(0, hyH + 0.15, 0.005, 0, 0, 0, 0.92, 1.12, 1), B.head, skin)
151
+ sb.add(new THREE.SphereGeometry(0.03, 6, 4), M(0, hyH + 0.14, 0.095, 0, 0, 0, 0.6, 0.9, 0.5), B.head, skin) // nose
152
+ for (const ex of [-0.093, 0.093]) sb.add(new THREE.SphereGeometry(0.022, 6, 4), M(ex, hyH + 0.15, 0, 0, 0, 0, 0.5, 1, 0.8), B.head, skin) // ears
153
+ if (female) {
154
+ sb.add(new THREE.SphereGeometry(0.106, 14, 10, 0, Math.PI * 2, 0, Math.PI * 0.62), M(0, hyH + 0.16, -0.008, -0.25, 0, 0, 1, 1.05, 1.02), B.head, hair)
155
+ sb.add(new THREE.SphereGeometry(0.05, 10, 8), M(0, hyH + 0.17, -0.11), B.head, hair) // bun
156
+ if (rng() < 0.6) sb.add(new THREE.SphereGeometry(0.112, 14, 8, 0, Math.PI * 2, 0, Math.PI * 0.42), M(0, hyH + 0.165, -0.01, -0.35, 0, 0, 1.02, 1, 1.05), B.head, [0.15, 0.22, 0.42]) // indigo headscarf
157
+ } else {
158
+ sb.add(new THREE.SphereGeometry(0.104, 14, 10, 0, Math.PI * 2, 0, Math.PI * 0.5), M(0, hyH + 0.16, -0.01, -0.2, 0, 0, 0.96, 1.02, 1.02), B.head, hair)
159
+ }
160
+ if (opts.hat) {
161
+ // conical bamboo hat (斗笠) with a slightly concave profile + chin strap rim
162
+ const hat = lathe([[0.4, 0], [0.33, 0.035], [0.2, 0.09], [0.06, 0.15], [0.0, 0.17]], 22)
163
+ sb.add(hat, M(0, hyH + 0.21, 0), B.head, straw)
164
+ const under = lathe([[0.0, 0.16], [0.06, 0.14], [0.2, 0.08], [0.33, 0.025], [0.4, -0.005]], 22)
165
+ sb.add(under, M(0, hyH + 0.21, 0), B.head, [0.42, 0.34, 0.18])
166
+ }
167
+ let hasPole = false
168
+ if (opts.pole) {
169
+ hasPole = true
170
+ // shoulder pole across the right shoulder with two baskets
171
+ const ly = hy + 0.6 * H
172
+ const poleG = new THREE.CylinderGeometry(0.022, 0.022, 1.9, 6)
173
+ poleG.rotateX(Math.PI / 2)
174
+ sb.add(poleG, M(0.12, ly + 0.02, 0), B.load, [0.5, 0.45, 0.24])
175
+ for (const z of [-0.85, 0.85]) {
176
+ for (const dx of [-0.13, 0.13]) {
177
+ const rope = new THREE.CylinderGeometry(0.004, 0.004, 0.72, 3)
178
+ sb.add(rope, M(0.12 + dx * 0.6, ly - 0.36, z + dx * 0.2, 0, 0, dx * 0.35), B.load, [0.3, 0.25, 0.15], false)
179
+ }
180
+ const basket = lathe([[0.16, 0], [0.24, 0.08], [0.26, 0.26], [0.25, 0.28], [0.0, 0.28]], 14)
181
+ sb.add(basket, M(0.12, ly - 0.98, z), B.load, [0.55, 0.42, 0.22])
182
+ const fill = new THREE.SphereGeometry(0.23, 10, 6, 0, Math.PI * 2, 0, Math.PI / 2)
183
+ const c: RGB = rng() < 0.5 ? [0.2, 0.36, 0.08] : [0.72, 0.32, 0.06]
184
+ sb.add(fill, M(0.12, ly - 0.71, z, 0, 0, 0, 1, 0.5, 1), B.load, c)
185
+ }
186
+ }
187
+ const mesh = makeSkinned(sb, bones)
188
+ const v: Villager = { mesh, root, hips, spine, head, legL, legR, armL, armR, load, hasPole, hipY: hy }
189
+ if (opts.pole) {
190
+ armR.rotation.set(-2.5, 0, 0.35) // hand up on the pole
191
+ load.rotation.y = 0.25
192
+ }
193
+ if (opts.seated) {
194
+ hips.position.y = 0.55
195
+ legL.rotation.x = legR.rotation.x = -1.45
196
+ armL.rotation.x = armR.rotation.x = -0.6
197
+ spine.rotation.x = 0.12
198
+ }
199
+ return v
200
+ }
201
+
202
+ export function walkVillager(v: Villager, phase: number, amp = 1) {
203
+ const s = Math.sin(phase)
204
+ v.legL.rotation.x = s * 0.46 * amp
205
+ v.legR.rotation.x = -s * 0.46 * amp
206
+ v.armL.rotation.x = -s * 0.36 * amp
207
+ if (!v.hasPole) v.armR.rotation.x = s * 0.36 * amp
208
+ v.hips.position.y = v.hipY + Math.abs(Math.cos(phase)) * 0.03 * amp
209
+ v.hips.rotation.y = s * 0.06 * amp
210
+ v.spine.rotation.y = -s * 0.08 * amp
211
+ v.spine.rotation.x = v.hasPole ? 0.08 : 0.03
212
+ v.head.rotation.y = s * 0.03
213
+ if (v.hasPole) v.load.rotation.z = Math.sin(phase * 2) * 0.04
214
+ }
215
+
216
+ // ---------------------------------------------------------------- ox & cart
217
+ export interface OxCart {
218
+ mesh: THREE.SkinnedMesh
219
+ legs: THREE.Bone[]; head: THREE.Bone; tail: THREE.Bone; wheels: THREE.Bone[]
220
+ }
221
+
222
+ export function makeOxCart(): OxCart {
223
+ const hide: RGB = [0.17, 0.11, 0.075], dark: RGB = [0.06, 0.045, 0.035], horn: RGB = [0.62, 0.56, 0.45]
224
+ const wood: RGB = [0.3, 0.2, 0.12], hay: RGB = [0.6, 0.48, 0.24]
225
+ const root = bone(null, 0, 0, 0)
226
+ const body = bone(root, 0, 1.15, 0)
227
+ const head = bone(body, 0, 0.12, 0.95)
228
+ const tail = bone(body, 0, 0.15, -0.95)
229
+ const legs = [[-0.24, 0.62], [0.24, 0.62], [-0.24, -0.62], [0.24, -0.62]].map(([x, z]) => bone(body, x, -0.15, z))
230
+ const wheels = [-0.82, 0.82].map((x) => bone(root, x, 0.62, -2.4))
231
+ const bones = [root, body, head, tail, ...legs, ...wheels]
232
+ root.updateMatrixWorld(true)
233
+ const sb = new SkinBuilder()
234
+ // barrel body: lathe along z
235
+ const barrel = lathe([[0.0, -0.95], [0.3, -0.88], [0.42, -0.5], [0.45, 0.1], [0.43, 0.6], [0.34, 0.9], [0.0, 1.0]], 18)
236
+ sb.add(barrel, M(0, 1.15, 0, Math.PI / 2, 0, 0, 1, 1, 0.92), 1, hide)
237
+ sb.add(new THREE.SphereGeometry(0.28, 12, 8), M(0, 1.42, 0.55, 0, 0, 0, 1, 0.8, 1.2), 1, hide) // hump
238
+ sb.add(new THREE.SphereGeometry(0.2, 10, 8), M(0, 0.95, 0.75, 0, 0, 0, 1.3, 1, 1.4), 1, hide) // dewlap/chest
239
+ // head with muzzle, horns, ears
240
+ sb.add(new THREE.SphereGeometry(0.2, 14, 10), M(0, 1.3, 1.12, 0.3, 0, 0, 0.9, 1, 1.25), 2, hide)
241
+ sb.add(new THREE.SphereGeometry(0.13, 12, 8), M(0, 1.14, 1.36, 0.3, 0, 0, 1.05, 0.85, 1), 2, dark)
242
+ for (const sx of [-1, 1]) {
243
+ const hornC = new THREE.TorusGeometry(0.16, 0.035, 6, 10, Math.PI * 0.7)
244
+ sb.add(hornC, M(sx * 0.14, 1.48, 1.04, 0, Math.PI / 2, sx > 0 ? 0.2 : Math.PI - 0.2, 1, 1, 1), 2, horn)
245
+ sb.add(new THREE.SphereGeometry(0.07, 8, 6), M(sx * 0.24, 1.38, 1.0, 0, 0, sx * 0.5, 1.4, 0.6, 0.5), 2, hide)
246
+ sb.add(new THREE.SphereGeometry(0.03, 6, 4), M(sx * 0.12, 1.36, 1.27), 2, [0.02, 0.02, 0.02])
247
+ }
248
+ // tail
249
+ sb.add(new THREE.CylinderGeometry(0.02, 0.03, 0.7, 5), M(0, 0.95, -1.0, 0.15, 0, 0), 3, hide)
250
+ sb.add(new THREE.SphereGeometry(0.05, 6, 6), M(0, 0.6, -1.05, 0, 0, 0, 1, 1.8, 1), 3, dark)
251
+ // legs with hooves
252
+ legs.forEach((_, i) => {
253
+ const x = i % 2 ? 0.24 : -0.24, z = i < 2 ? 0.62 : -0.62
254
+ const leg = lathe([[0.05, -1.0], [0.06, -0.62], [0.075, -0.4], [0.11, -0.1], [0.12, 0.05]], 10)
255
+ sb.add(leg, M(x, 1.0, z), 4 + i, hide)
256
+ sb.add(new THREE.CylinderGeometry(0.06, 0.065, 0.08, 8), M(x, 0.04, z + 0.01), 4 + i, dark)
257
+ })
258
+ // yoke + shafts + cart bed + hay + wheels
259
+ sb.add(new THREE.CylinderGeometry(0.04, 0.04, 0.9, 6), M(0, 1.45, 0.75, 0, 0, Math.PI / 2), 1, wood)
260
+ for (const sx of [-0.45, 0.45]) sb.add(new THREE.BoxGeometry(0.07, 0.07, 2.6), M(sx, 1.0, -1.0, -0.08, 0, 0), 0, wood)
261
+ sb.add(new THREE.BoxGeometry(1.45, 0.1, 2.1), M(0, 0.98, -2.4), 0, wood)
262
+ for (const sx of [-0.7, 0.7]) sb.add(new THREE.BoxGeometry(0.06, 0.32, 2.1), M(sx, 1.18, -2.4), 0, wood)
263
+ sb.add(new THREE.SphereGeometry(0.75, 12, 8, 0, Math.PI * 2, 0, Math.PI / 2), M(0, 1.02, -2.4, 0, 0, 0, 0.88, 0.72, 1.25), 0, hay)
264
+ ;[6, 7].forEach((bi, k) => {
265
+ const sx = k ? 0.82 : -0.82
266
+ const rim = new THREE.TorusGeometry(0.6, 0.05, 6, 22)
267
+ sb.add(rim, M(sx, 0.62, -2.4, 0, Math.PI / 2, 0), bi, wood)
268
+ sb.add(new THREE.CylinderGeometry(0.1, 0.1, 0.16, 10), M(sx, 0.62, -2.4, 0, 0, Math.PI / 2), bi, wood)
269
+ for (let s = 0; s < 8; s++) sb.add(new THREE.BoxGeometry(0.05, 1.15, 0.05), M(sx, 0.62, -2.4, (s / 8) * Math.PI, 0, 0), bi, [0.45, 0.35, 0.22])
270
+ })
271
+ const mesh = makeSkinned(sb, bones)
272
+ return { mesh, legs, head, tail, wheels }
273
+ }
274
+
275
+ export function animateOx(o: OxCart, dist: number, t: number) {
276
+ const ph = dist * 2.6
277
+ o.legs.forEach((l, i) => { l.rotation.x = Math.sin(ph + (i === 0 || i === 3 ? 0 : Math.PI)) * 0.32 })
278
+ o.head.rotation.x = Math.sin(ph * 2) * 0.04 + 0.05
279
+ o.head.rotation.y = Math.sin(t * 0.4) * 0.08
280
+ o.tail.rotation.z = Math.sin(t * 1.7) * 0.25
281
+ o.wheels.forEach((w) => { w.rotation.x = dist / 0.62 })
282
+ }
283
+
284
+ // ---------------------------------------------------------------- egret
285
+ export interface Egret { mesh: THREE.SkinnedMesh; root: THREE.Bone; wl: THREE.Bone; wr: THREE.Bone }
286
+
287
+ export function makeEgret(): Egret {
288
+ const white: RGB = [0.93, 0.93, 0.91], beak: RGB = [0.78, 0.62, 0.16], legC: RGB = [0.05, 0.05, 0.05]
289
+ const root = bone(null, 0, 0, 0)
290
+ const wl = bone(root, -0.06, 0.02, 0.02)
291
+ const wr = bone(root, 0.06, 0.02, 0.02)
292
+ root.updateMatrixWorld(true)
293
+ const sb = new SkinBuilder()
294
+ sb.add(new THREE.SphereGeometry(0.12, 14, 10), M(0, 0, 0, 0, 0, 0, 0.95, 0.85, 2.3), 0, white)
295
+ // S-curved neck tucked back in flight, head, beak
296
+ sb.add(new THREE.CylinderGeometry(0.035, 0.05, 0.22, 8), M(0, 0.07, 0.3, 1.0, 0, 0), 0, white)
297
+ sb.add(new THREE.SphereGeometry(0.055, 10, 8), M(0, 0.12, 0.4, 0, 0, 0, 0.9, 0.9, 1.3), 0, white)
298
+ sb.add(new THREE.ConeGeometry(0.018, 0.17, 6), M(0, 0.11, 0.53, Math.PI / 2, 0, 0), 0, beak)
299
+ sb.add(new THREE.CylinderGeometry(0.01, 0.01, 0.5, 4), M(-0.025, -0.02, -0.5, Math.PI / 2, 0, 0), 0, legC)
300
+ sb.add(new THREE.CylinderGeometry(0.01, 0.01, 0.5, 4), M(0.025, -0.02, -0.5, Math.PI / 2, 0, 0), 0, legC)
301
+ // wings: curved feathered shape (extruded thin) for each side
302
+ const shape = new THREE.Shape()
303
+ shape.moveTo(0, 0.12)
304
+ shape.bezierCurveTo(0.35, 0.22, 0.8, 0.2, 1.12, 0.02)
305
+ shape.lineTo(1.0, -0.04)
306
+ for (let k = 0; k < 6; k++) shape.lineTo(0.95 - k * 0.15, -0.1 - (k % 2) * 0.05) // primary feathers
307
+ shape.lineTo(0, -0.14)
308
+ const wg = new THREE.ExtrudeGeometry(shape, { depth: 0.012, bevelEnabled: false, curveSegments: 10 })
309
+ wg.rotateX(-Math.PI / 2)
310
+ sb.add(wg, M(0.06, 0.02, 0.02), 2, white)
311
+ sb.add(wg.clone(), M(-0.06, 0.02, 0.02, 0, 0, 0, -1, 1, 1), 1, white)
312
+ const mesh = makeSkinned(sb, [root, wl, wr])
313
+ mesh.castShadow = true
314
+ return { mesh, root, wl, wr }
315
+ }
src/jiangnan/engine/geom.ts CHANGED
@@ -49,6 +49,28 @@ export class Builder {
49
  this.pushVertex(c.x, c.y, c.z, nx, ny, nz, t[4], t[5])
50
  this.pushVertex(d.x, d.y, d.z, nx, ny, nz, t[6], t[7])
51
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  tri(a: THREE.Vector3Like, b: THREE.Vector3Like, c: THREE.Vector3Like, uvs?: number[]) {
53
  const e1 = new THREE.Vector3(b.x - a.x, b.y - a.y, b.z - a.z)
54
  const e2 = new THREE.Vector3(c.x - a.x, c.y - a.y, c.z - a.z)
 
49
  this.pushVertex(c.x, c.y, c.z, nx, ny, nz, t[4], t[5])
50
  this.pushVertex(d.x, d.y, d.z, nx, ny, nz, t[6], t[7])
51
  }
52
+ /** quad whose 4 corners carry a relief height (aRH) and a relief slope across x (aRS) */
53
+ quadRelief(a: THREE.Vector3Like, b: THREE.Vector3Like, c: THREE.Vector3Like, d: THREE.Vector3Like, hs: number[], uvs: number[]) {
54
+ const dx = Math.abs(b.x - a.x) || 1
55
+ const slope = (hs[1] - hs[0]) / dx * Math.sign(b.x - a.x || 1)
56
+ const corners = [a, b, c, a, c, d]
57
+ const hIdx = [0, 1, 2, 0, 2, 3]
58
+ const uvIdx = [0, 1, 2, 0, 2, 3]
59
+ const e1 = new THREE.Vector3(b.x - a.x, b.y - a.y, b.z - a.z)
60
+ const e2 = new THREE.Vector3(d.x - a.x, d.y - a.y, d.z - a.z)
61
+ const n = e1.cross(e2).normalize()
62
+ for (let k = 0; k < 6; k++) {
63
+ this.current['aRH'] = hs[hIdx[k]]
64
+ this.current['aRS'] = slope
65
+ const p = corners[k]
66
+ this.pushVertexPublic(p.x, p.y, p.z, n.x, n.y, n.z, uvs[uvIdx[k] * 2], uvs[uvIdx[k] * 2 + 1])
67
+ }
68
+ this.current['aRH'] = 0
69
+ this.current['aRS'] = 0
70
+ }
71
+ pushVertexPublic(x: number, y: number, z: number, nx: number, ny: number, nz: number, u: number, w: number) {
72
+ this.pushVertex(x, y, z, nx, ny, nz, u, w)
73
+ }
74
  tri(a: THREE.Vector3Like, b: THREE.Vector3Like, c: THREE.Vector3Like, uvs?: number[]) {
75
  const e1 = new THREE.Vector3(b.x - a.x, b.y - a.y, b.z - a.z)
76
  const e2 = new THREE.Vector3(c.x - a.x, c.y - a.y, c.z - a.z)
src/jiangnan/engine/life.ts CHANGED
@@ -3,6 +3,7 @@
3
  import * as THREE from 'three'
4
  import { Builder, V3 } from './geom'
5
  import { BRIDGE_S, GROUND_Y, MARKET_S0, MARKET_S1, quayPoint, riverAt, riverHalfWidth, riverPoint, riverSAtX, TREE_POS, VILLAGE_S0, VILLAGE_S1 } from './layout'
 
6
  import { patch, std, U } from './materials'
7
  import type { PropsOut } from './props'
8
  import { clamp, hash1, lerp, mulberry32, smoothstep } from './rng'
@@ -44,7 +45,7 @@ export function createLanterns(village: VillageOut, props: PropsOut): LanternSet
44
  // body: ribbed ellipsoid + caps + tassel
45
  const b = new Builder()
46
  b.set('aPart', 0)
47
- const body = new THREE.SphereGeometry(0.3, 16, 12)
48
  body.scale(1, 1.25, 1)
49
  b.geometry(body, new THREE.Matrix4().makeTranslation(0, -0.42, 0))
50
  b.set('aPart', 1)
@@ -124,95 +125,10 @@ export function createLanterns(village: VillageOut, props: PropsOut): LanternSet
124
  return { mesh, glow, list }
125
  }
126
 
127
- // ------------------------------------------------------------------ villagers
128
- interface Figure { root: THREE.Group; legL: THREE.Object3D; legR: THREE.Object3D; armL: THREE.Object3D; armR: THREE.Object3D; load?: THREE.Object3D }
129
-
130
- function makeFigure(rng: () => number, mats: Record<string, THREE.Material>, opts: { pole?: boolean; hat?: boolean; seated?: boolean }): Figure {
131
- const root = new THREE.Group()
132
- const cloth = [mats.indigo, mats.grey, mats.brown, mats.indigo2][Math.floor(rng() * 4)]
133
- const mk = (g: THREE.BufferGeometry, m: THREE.Material) => { const o = new THREE.Mesh(g, m); o.castShadow = true; return o }
134
- const hip = new THREE.Group()
135
- hip.position.y = 0.92
136
- root.add(hip)
137
- const torso = mk(new THREE.CylinderGeometry(0.17, 0.22, 0.62, 10), cloth)
138
- torso.position.y = 0.32
139
- hip.add(torso)
140
- const head = mk(new THREE.SphereGeometry(0.11, 12, 10), mats.skin)
141
- head.position.y = 0.78
142
- hip.add(head)
143
- const hair = mk(new THREE.SphereGeometry(0.112, 12, 8, 0, Math.PI * 2, 0, Math.PI * 0.55), mats.hair)
144
- hair.position.y = 0.79
145
- hip.add(hair)
146
- if (opts.hat) {
147
- const hat = mk(new THREE.ConeGeometry(0.38, 0.17, 18, 1, true), mats.straw)
148
- hat.position.y = 0.92
149
- hip.add(hat)
150
- }
151
- const leg = (x: number) => {
152
- const g = new THREE.Group()
153
- g.position.set(x, 0, 0)
154
- const l = mk(new THREE.CylinderGeometry(0.065, 0.075, 0.9, 8), opts.seated ? cloth : mats.trouser)
155
- l.position.y = -0.45
156
- g.add(l)
157
- const f = mk(new THREE.BoxGeometry(0.1, 0.06, 0.22), mats.hair)
158
- f.position.set(0, -0.9, 0.05)
159
- g.add(f)
160
- hip.add(g)
161
- return g
162
- }
163
- const arm = (x: number) => {
164
- const g = new THREE.Group()
165
- g.position.set(x, 0.58, 0)
166
- const a = mk(new THREE.CylinderGeometry(0.05, 0.045, 0.62, 8), cloth)
167
- a.position.y = -0.31
168
- g.add(a)
169
- hip.add(g)
170
- return g
171
- }
172
- const legL = leg(-0.09), legR = leg(0.09)
173
- const armL = arm(-0.23), armR = arm(0.23)
174
- let load: THREE.Object3D | undefined
175
- if (opts.pole) {
176
- // shoulder pole (扁担) with two baskets hung on ropes
177
- const p = new THREE.Group()
178
- p.position.set(0, 0.62, 0.02)
179
- const pole = mk(new THREE.BoxGeometry(0.05, 0.04, 1.8), mats.bamboo)
180
- pole.rotation.y = 0
181
- p.add(pole)
182
- for (const z of [-0.82, 0.82]) {
183
- const rope = mk(new THREE.CylinderGeometry(0.006, 0.006, 0.7, 3), mats.hair)
184
- rope.position.set(0, -0.35, z)
185
- p.add(rope)
186
- const bsk = mk(new THREE.CylinderGeometry(0.24, 0.19, 0.3, 12), mats.basket)
187
- bsk.position.set(0, -0.82, z)
188
- p.add(bsk)
189
- const veg = mk(new THREE.SphereGeometry(0.2, 8, 6, 0, Math.PI * 2, 0, Math.PI / 2), z > 0 ? mats.green : mats.orange)
190
- veg.position.set(0, -0.68, z)
191
- p.add(veg)
192
- }
193
- p.rotation.y = Math.PI / 2 + 0.25
194
- hip.add(p)
195
- load = p
196
- armR.rotation.x = -2.4
197
- armR.rotation.z = 0.2
198
- }
199
- if (opts.seated) {
200
- hip.position.y = 0.55
201
- legL.rotation.x = legR.rotation.x = -1.45
202
- }
203
- return { root, legL, legR, armL, armR, load }
204
- }
205
-
206
- function animateWalk(f: Figure, phase: number, amp = 1) {
207
- const s = Math.sin(phase)
208
- f.legL.rotation.x = s * 0.45 * amp
209
- f.legR.rotation.x = -s * 0.45 * amp
210
- f.armL.rotation.x = -s * 0.35 * amp
211
- if (!f.load) f.armR.rotation.x = s * 0.35 * amp
212
- const hip = f.root.children[0]
213
- hip.position.y = 0.92 + Math.abs(Math.cos(phase)) * 0.035 * amp
214
- if (f.load) f.load.position.y = 0.62 + Math.sin(phase * 2) * 0.03
215
- }
216
 
217
  interface Walker { fig: Figure; path: (t: number) => { p: THREE.Vector3; dir: THREE.Vector3; dist: number } | null }
218
 
@@ -244,7 +160,7 @@ export function createLife(village: VillageOut, props: PropsOut): LifeOut {
244
  // porter crossing the bridge (north → south) during the bridge shot
245
  {
246
  const fig = makeFigure(rng, mats, { pole: true, hat: true })
247
- group.add(fig.root)
248
  walkers.push({
249
  fig,
250
  path: (t) => {
@@ -267,7 +183,7 @@ export function createLife(village: VillageOut, props: PropsOut): LifeOut {
267
  ]
268
  for (const [x0, speed, lane, pole, dir] of streetPeople) {
269
  const fig = makeFigure(rng, mats, { pole, hat: pole || rng() < 0.4 })
270
- group.add(fig.root)
271
  const s0 = riverSAtX(x0)
272
  walkers.push({
273
  fig,
@@ -284,7 +200,7 @@ export function createLife(village: VillageOut, props: PropsOut): LifeOut {
284
  const tp = TREE_POS
285
  for (const [a0, dir, spd] of [[2.6, 1, 1.0], [0.4, -1, 0.85]] as [number, number, number][]) {
286
  const fig = makeFigure(rng, mats, { pole: true, hat: true })
287
- group.add(fig.root)
288
  walkers.push({
289
  fig,
290
  path: (t) => {
@@ -298,98 +214,33 @@ export function createLife(village: VillageOut, props: PropsOut): LifeOut {
298
  })
299
  }
300
  // seated elders & vendors
301
- const statics: THREE.Group[] = []
302
  {
303
  const elder = makeFigure(rng, mats, { seated: true })
304
  const a = 0.3
305
- elder.root.position.set(tp.x + Math.cos(a) * 5.2, GROUND_Y, tp.z + Math.sin(a) * 5.2)
306
- elder.root.rotation.y = -a - Math.PI / 2
307
- group.add(elder.root)
308
- statics.push(elder.root)
309
  for (let k = 0; k < 5; k++) {
310
  const s = MARKET_S0 + 12 + k * 24
311
  const p = riverPoint(s, -8.9)
312
  const v = makeFigure(rng, mats, { hat: rng() < 0.3 })
313
- v.root.position.set(p.x, GROUND_Y + 0.03, p.z)
314
- v.root.rotation.y = Math.atan2(-p.nx, -p.nz) + Math.PI
315
  v.armL.rotation.x = -0.6
316
  v.armR.rotation.x = -0.5
317
- group.add(v.root)
318
- statics.push(v.root)
319
  }
320
  }
321
 
322
  // ---------------------------------------------------------------- ox cart
323
- const ox = new THREE.Group()
324
- const cartWheels: THREE.Object3D[] = []
325
- const oxLegs: THREE.Object3D[] = []
326
- {
327
- const mk = (g: THREE.BufferGeometry, mm: THREE.Material) => { const o = new THREE.Mesh(g, mm); o.castShadow = true; return o }
328
- const bodyG = new THREE.CapsuleGeometry(0.42, 1.3, 6, 12)
329
- bodyG.rotateX(Math.PI / 2)
330
- const body = mk(bodyG, mats.ox)
331
- body.position.set(0, 1.15, 0)
332
- ox.add(body)
333
- const hump = mk(new THREE.SphereGeometry(0.3, 10, 8), mats.ox)
334
- hump.position.set(0, 1.45, 0.55)
335
- ox.add(hump)
336
- const head = mk(new THREE.BoxGeometry(0.34, 0.36, 0.55), mats.ox)
337
- head.position.set(0, 1.25, 1.2)
338
- head.rotation.x = 0.5
339
- ox.add(head)
340
- for (const sx of [-1, 1]) {
341
- const horn = mk(new THREE.ConeGeometry(0.05, 0.38, 6), mats.horn)
342
- horn.position.set(sx * 0.2, 1.5, 1.1)
343
- horn.rotation.z = -sx * 1.0
344
- ox.add(horn)
345
- }
346
- for (const [lx, lz] of [[-0.22, 0.6], [0.22, 0.6], [-0.22, -0.6], [0.22, -0.6]]) {
347
- const g = new THREE.Group()
348
- g.position.set(lx, 0.95, lz)
349
- const l = mk(new THREE.CylinderGeometry(0.08, 0.06, 0.95, 6), mats.ox)
350
- l.position.y = -0.47
351
- g.add(l)
352
- ox.add(g)
353
- oxLegs.push(g)
354
- }
355
- // cart behind (−z)
356
- const cart = new THREE.Group()
357
- cart.position.set(0, 0, -2.4)
358
- const bed = mk(new THREE.BoxGeometry(1.4, 0.12, 2.0), mats.wood)
359
- bed.position.y = 0.95
360
- cart.add(bed)
361
- for (const sx of [-0.68, 0.68]) {
362
- const rail = mk(new THREE.BoxGeometry(0.06, 0.3, 2.0), mats.wood)
363
- rail.position.set(sx, 1.12, 0)
364
- cart.add(rail)
365
- const shaft = mk(new THREE.BoxGeometry(0.07, 0.07, 2.4), mats.wood)
366
- shaft.position.set(sx * 0.5, 1.0, 1.9)
367
- cart.add(shaft)
368
- }
369
- // load: hay & baskets
370
- const hay = mk(new THREE.SphereGeometry(0.75, 10, 8, 0, Math.PI * 2, 0, Math.PI / 2), mats.straw)
371
- hay.scale.set(0.9, 0.7, 1.2)
372
- hay.position.y = 1.0
373
- cart.add(hay)
374
- for (const sx of [-0.78, 0.78]) {
375
- const wg = new THREE.Group()
376
- wg.position.set(sx, 0.62, 0)
377
- const wheel = mk(new THREE.CylinderGeometry(0.62, 0.62, 0.08, 18), mats.wood)
378
- wheel.rotation.z = Math.PI / 2
379
- wg.add(wheel)
380
- for (let k = 0; k < 6; k++) {
381
- const sp = mk(new THREE.BoxGeometry(0.1, 1.1, 0.06), mats.horn)
382
- sp.rotation.x = (k / 6) * Math.PI
383
- wg.add(sp)
384
- }
385
- cart.add(wg)
386
- cartWheels.push(wg)
387
- }
388
- ox.add(cart)
389
- group.add(ox)
390
- }
391
  const driver = makeFigure(rng, mats, { hat: true })
392
- group.add(driver.root)
393
  const oxS0 = riverSAtX(-175)
394
  const oxPath = (t: number) => {
395
  const s = oxS0 + (t - 28) * 0.95
@@ -399,44 +250,12 @@ export function createLife(village: VillageOut, props: PropsOut): LifeOut {
399
  }
400
 
401
  // ---------------------------------------------------------------- egrets
402
- const egrets: { g: THREE.Group; wl: THREE.Object3D; wr: THREE.Object3D; seed: number }[] = []
403
- {
404
- const wingShape = new THREE.Shape()
405
- wingShape.moveTo(0, 0)
406
- wingShape.bezierCurveTo(0.3, 0.25, 0.8, 0.22, 1.05, 0.05)
407
- wingShape.bezierCurveTo(0.8, -0.05, 0.4, -0.12, 0, -0.18)
408
- const wingG = new THREE.ShapeGeometry(wingShape, 8)
409
- wingG.rotateX(-Math.PI / 2)
410
- for (let k = 0; k < 7; k++) {
411
- const g = new THREE.Group()
412
- const bodyG = new THREE.SphereGeometry(0.12, 10, 8)
413
- bodyG.scale(1, 0.9, 2.4)
414
- const body = new THREE.Mesh(bodyG, mats.egret)
415
- g.add(body)
416
- const neck = new THREE.Mesh(new THREE.CylinderGeometry(0.035, 0.05, 0.3, 6), mats.egret)
417
- neck.position.set(0, 0.06, 0.34)
418
- neck.rotation.x = 1.1
419
- g.add(neck)
420
- const beak = new THREE.Mesh(new THREE.ConeGeometry(0.02, 0.16, 5), mats.beak)
421
- beak.rotation.x = Math.PI / 2
422
- beak.position.set(0, 0.12, 0.55)
423
- g.add(beak)
424
- const legs = new THREE.Mesh(new THREE.CylinderGeometry(0.012, 0.012, 0.45, 4), mats.hair)
425
- legs.rotation.x = Math.PI / 2
426
- legs.position.set(0, -0.02, -0.5)
427
- g.add(legs)
428
- const wl = new THREE.Mesh(wingG, mats.egret)
429
- const wr = new THREE.Mesh(wingG, mats.egret)
430
- ;(wl.material as THREE.Material).side = THREE.DoubleSide
431
- wl.scale.set(-1, 1, 1)
432
- wl.position.x = -0.06
433
- wr.position.x = 0.06
434
- g.add(wl, wr)
435
- g.traverse((o) => { o.castShadow = true })
436
- g.scale.setScalar(1.25)
437
- group.add(g)
438
- egrets.push({ g, wl, wr, seed: k })
439
- }
440
  }
441
  const egretPos = (t: number) => {
442
  // two passes: low over the river by the bridge, then flying up toward the bamboo hills
@@ -475,6 +294,7 @@ export function createLife(village: VillageOut, props: PropsOut): LifeOut {
475
  })
476
  const flock = new THREE.InstancedMesh(flockGeo, flockMat, flockN)
477
  flock.frustumCulled = false
 
478
  group.add(flock)
479
  const flockOff = Array.from({ length: flockN }, (_, i) => V3((hash1(i, 1) - 0.5) * 22, (hash1(i, 2) - 0.5) * 7, (hash1(i, 3) - 0.5) * 22))
480
  const flockCenter = (t: number) => {
@@ -558,6 +378,7 @@ export function createLife(village: VillageOut, props: PropsOut): LifeOut {
558
  const smoke = new THREE.Mesh(smokeGeo, smokeMat)
559
  smoke.frustumCulled = false
560
  smoke.renderOrder = 5
 
561
  group.add(smoke)
562
 
563
  // ---------------------------------------------------------------- water-wheel splashes
@@ -612,6 +433,7 @@ export function createLife(village: VillageOut, props: PropsOut): LifeOut {
612
  })
613
  const splash = new THREE.Points(g, m)
614
  splash.frustumCulled = false
 
615
  group.add(splash)
616
  }
617
 
@@ -661,8 +483,8 @@ export function createLife(village: VillageOut, props: PropsOut): LifeOut {
661
  // ---------------------------------------------------------------- night boat + boatman + bow lantern
662
  const boat = props.movingBoat
663
  const boatman = makeFigure(rng, mats, { hat: true })
664
- boatman.root.position.set(0, 0.45, -2.9)
665
- boat.add(boatman.root)
666
  const oar = new THREE.Mesh(new THREE.BoxGeometry(0.06, 0.06, 3.6), mats.wood)
667
  oar.position.set(0.25, 1.1, -3.6)
668
  oar.rotation.x = 0.55
@@ -681,10 +503,10 @@ export function createLife(village: VillageOut, props: PropsOut): LifeOut {
681
  // walkers
682
  for (const w of walkers) {
683
  const r = w.path(t)
684
- if (!r) { w.fig.root.visible = false; continue }
685
- w.fig.root.visible = true
686
- w.fig.root.position.copy(r.p)
687
- w.fig.root.rotation.y = Math.atan2(r.dir.x, r.dir.z)
688
  animateWalk(w.fig, r.dist * 3.2)
689
  }
690
  // ox cart
@@ -692,11 +514,10 @@ export function createLife(village: VillageOut, props: PropsOut): LifeOut {
692
  ox.position.copy(o.p)
693
  ox.rotation.y = Math.atan2(o.dir.x, o.dir.z)
694
  const dist = (t - 28) * 0.95
695
- oxLegs.forEach((l, i) => { l.rotation.x = Math.sin(dist * 2.6 + (i % 2 ? Math.PI : 0) + (i > 1 ? 1.2 : 0)) * 0.35 })
696
- cartWheels.forEach((wg) => { wg.rotation.x = dist / 0.62 })
697
  const side = V3(o.dir.z, 0, -o.dir.x)
698
- driver.root.position.copy(o.p).addScaledVector(o.dir, 0.4).addScaledVector(side, -1.0)
699
- driver.root.rotation.y = ox.rotation.y
700
  animateWalk(driver, dist * 3.2)
701
  // egrets
702
  egrets.forEach((e, i) => {
 
3
  import * as THREE from 'three'
4
  import { Builder, V3 } from './geom'
5
  import { BRIDGE_S, GROUND_Y, MARKET_S0, MARKET_S1, quayPoint, riverAt, riverHalfWidth, riverPoint, riverSAtX, TREE_POS, VILLAGE_S0, VILLAGE_S1 } from './layout'
6
+ import { makeEgret, makeOxCart, makeVillager, animateOx, Villager, walkVillager } from './figures'
7
  import { patch, std, U } from './materials'
8
  import type { PropsOut } from './props'
9
  import { clamp, hash1, lerp, mulberry32, smoothstep } from './rng'
 
45
  // body: ribbed ellipsoid + caps + tassel
46
  const b = new Builder()
47
  b.set('aPart', 0)
48
+ const body = new THREE.SphereGeometry(0.3, 12, 8)
49
  body.scale(1, 1.25, 1)
50
  b.geometry(body, new THREE.Matrix4().makeTranslation(0, -0.42, 0))
51
  b.set('aPart', 1)
 
125
  return { mesh, glow, list }
126
  }
127
 
128
+ // ------------------------------------------------------------------ villagers (skinned, see figures.ts)
129
+ type Figure = Villager
130
+ const makeFigure = (rng: () => number, _mats: unknown, opts: { pole?: boolean; hat?: boolean; seated?: boolean }) => makeVillager(rng, opts)
131
+ const animateWalk = walkVillager
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
133
  interface Walker { fig: Figure; path: (t: number) => { p: THREE.Vector3; dir: THREE.Vector3; dist: number } | null }
134
 
 
160
  // porter crossing the bridge (north → south) during the bridge shot
161
  {
162
  const fig = makeFigure(rng, mats, { pole: true, hat: true })
163
+ group.add(fig.mesh)
164
  walkers.push({
165
  fig,
166
  path: (t) => {
 
183
  ]
184
  for (const [x0, speed, lane, pole, dir] of streetPeople) {
185
  const fig = makeFigure(rng, mats, { pole, hat: pole || rng() < 0.4 })
186
+ group.add(fig.mesh)
187
  const s0 = riverSAtX(x0)
188
  walkers.push({
189
  fig,
 
200
  const tp = TREE_POS
201
  for (const [a0, dir, spd] of [[2.6, 1, 1.0], [0.4, -1, 0.85]] as [number, number, number][]) {
202
  const fig = makeFigure(rng, mats, { pole: true, hat: true })
203
+ group.add(fig.mesh)
204
  walkers.push({
205
  fig,
206
  path: (t) => {
 
214
  })
215
  }
216
  // seated elders & vendors
217
+ const statics: THREE.Object3D[] = []
218
  {
219
  const elder = makeFigure(rng, mats, { seated: true })
220
  const a = 0.3
221
+ elder.mesh.position.set(tp.x + Math.cos(a) * 5.2, GROUND_Y, tp.z + Math.sin(a) * 5.2)
222
+ elder.mesh.rotation.y = -a - Math.PI / 2
223
+ group.add(elder.mesh)
224
+ statics.push(elder.mesh)
225
  for (let k = 0; k < 5; k++) {
226
  const s = MARKET_S0 + 12 + k * 24
227
  const p = riverPoint(s, -8.9)
228
  const v = makeFigure(rng, mats, { hat: rng() < 0.3 })
229
+ v.mesh.position.set(p.x, GROUND_Y + 0.03, p.z)
230
+ v.mesh.rotation.y = Math.atan2(-p.nx, -p.nz) + Math.PI
231
  v.armL.rotation.x = -0.6
232
  v.armR.rotation.x = -0.5
233
+ group.add(v.mesh)
234
+ statics.push(v.mesh)
235
  }
236
  }
237
 
238
  // ---------------------------------------------------------------- ox cart
239
+ const oxCart = makeOxCart()
240
+ const ox = oxCart.mesh
241
+ group.add(ox)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  const driver = makeFigure(rng, mats, { hat: true })
243
+ group.add(driver.mesh)
244
  const oxS0 = riverSAtX(-175)
245
  const oxPath = (t: number) => {
246
  const s = oxS0 + (t - 28) * 0.95
 
250
  }
251
 
252
  // ---------------------------------------------------------------- egrets
253
+ const egrets: { g: THREE.Object3D; wl: THREE.Bone; wr: THREE.Bone; seed: number }[] = []
254
+ for (let k = 0; k < 7; k++) {
255
+ const e = makeEgret()
256
+ e.mesh.scale.setScalar(1.25)
257
+ group.add(e.mesh)
258
+ egrets.push({ g: e.mesh, wl: e.wl, wr: e.wr, seed: k })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
  }
260
  const egretPos = (t: number) => {
261
  // two passes: low over the river by the bridge, then flying up toward the bamboo hills
 
294
  })
295
  const flock = new THREE.InstancedMesh(flockGeo, flockMat, flockN)
296
  flock.frustumCulled = false
297
+ flock.layers.set(1)
298
  group.add(flock)
299
  const flockOff = Array.from({ length: flockN }, (_, i) => V3((hash1(i, 1) - 0.5) * 22, (hash1(i, 2) - 0.5) * 7, (hash1(i, 3) - 0.5) * 22))
300
  const flockCenter = (t: number) => {
 
378
  const smoke = new THREE.Mesh(smokeGeo, smokeMat)
379
  smoke.frustumCulled = false
380
  smoke.renderOrder = 5
381
+ smoke.layers.set(1)
382
  group.add(smoke)
383
 
384
  // ---------------------------------------------------------------- water-wheel splashes
 
433
  })
434
  const splash = new THREE.Points(g, m)
435
  splash.frustumCulled = false
436
+ splash.layers.set(1)
437
  group.add(splash)
438
  }
439
 
 
483
  // ---------------------------------------------------------------- night boat + boatman + bow lantern
484
  const boat = props.movingBoat
485
  const boatman = makeFigure(rng, mats, { hat: true })
486
+ boatman.mesh.position.set(0, 0.45, -2.9)
487
+ boat.add(boatman.mesh)
488
  const oar = new THREE.Mesh(new THREE.BoxGeometry(0.06, 0.06, 3.6), mats.wood)
489
  oar.position.set(0.25, 1.1, -3.6)
490
  oar.rotation.x = 0.55
 
503
  // walkers
504
  for (const w of walkers) {
505
  const r = w.path(t)
506
+ if (!r) { w.fig.mesh.visible = false; continue }
507
+ w.fig.mesh.visible = true
508
+ w.fig.mesh.position.copy(r.p)
509
+ w.fig.mesh.rotation.y = Math.atan2(r.dir.x, r.dir.z)
510
  animateWalk(w.fig, r.dist * 3.2)
511
  }
512
  // ox cart
 
514
  ox.position.copy(o.p)
515
  ox.rotation.y = Math.atan2(o.dir.x, o.dir.z)
516
  const dist = (t - 28) * 0.95
517
+ animateOx(oxCart, dist, t)
 
518
  const side = V3(o.dir.z, 0, -o.dir.x)
519
+ driver.mesh.position.copy(o.p).addScaledVector(o.dir, 0.4).addScaledVector(side, -1.0)
520
+ driver.mesh.rotation.y = ox.rotation.y
521
  animateWalk(driver, dist * 3.2)
522
  // egrets
523
  egrets.forEach((e, i) => {
src/jiangnan/engine/post.ts CHANGED
@@ -62,7 +62,7 @@ const GradeShader = {
62
  tDiffuse: { value: null as THREE.Texture | null },
63
  uTime: { value: 0 },
64
  uVignette: { value: 0.32 },
65
- uGrain: { value: 0.035 },
66
  uFade: { value: 0 },
67
  uNight: { value: 0 },
68
  uRes: { value: new THREE.Vector2(1920, 1080) },
@@ -109,6 +109,7 @@ export interface Post {
109
 
110
  export function createPost(renderer: THREE.WebGLRenderer, scene: THREE.Scene, camera: THREE.Camera, w: number, h: number, samples = 4): Post {
111
  const rt = new THREE.WebGLRenderTarget(w, h, { type: THREE.HalfFloatType, samples })
 
112
  const composer = new EffectComposer(renderer, rt)
113
  composer.addPass(new RenderPass(scene, camera))
114
  const rays = new ShaderPass(GodRaysShader)
 
62
  tDiffuse: { value: null as THREE.Texture | null },
63
  uTime: { value: 0 },
64
  uVignette: { value: 0.32 },
65
+ uGrain: { value: 0.016 },
66
  uFade: { value: 0 },
67
  uNight: { value: 0 },
68
  uRes: { value: new THREE.Vector2(1920, 1080) },
 
109
 
110
  export function createPost(renderer: THREE.WebGLRenderer, scene: THREE.Scene, camera: THREE.Camera, w: number, h: number, samples = 4): Post {
111
  const rt = new THREE.WebGLRenderTarget(w, h, { type: THREE.HalfFloatType, samples })
112
+ rt.depthTexture = new THREE.DepthTexture(w, h, THREE.FloatType)
113
  const composer = new EffectComposer(renderer, rt)
114
  composer.addPass(new RenderPass(scene, camera))
115
  const rays = new ShaderPass(GodRaysShader)
src/jiangnan/engine/props.ts CHANGED
@@ -261,7 +261,7 @@ export function createProps(): PropsOut {
261
  }
262
  const jarGeos = [jarProfile(0.28, 0.7), jarProfile(0.4, 0.9), jarProfile(0.2, 0.45)]
263
  const basketGeo = new THREE.CylinderGeometry(0.42, 0.32, 0.35, 16, 1, true)
264
- const fruitGeo = new THREE.IcosahedronGeometry(0.075, 1)
265
  for (let s = MARKET_S0; s < MARKET_S1; s += rrange(rng, 5.5, 8)) {
266
  if (Math.abs(s - BRIDGE_S) < 12) continue
267
  const p = riverPoint(s, -9.6)
@@ -455,11 +455,12 @@ export function createProps(): PropsOut {
455
  lanternSpots.push({ p: V3(0, 3.3, 0).applyMatrix4(m), on: 58.5 })
456
  }
457
 
458
- const add = (b: Builder, mat: THREE.Material, cast = true) => {
459
  if (!b.count) return
460
  const mesh = new THREE.Mesh(b.build(), mat)
461
  mesh.castShadow = cast
462
  mesh.receiveShadow = true
 
463
  group.add(mesh)
464
  }
465
  add(stone, stoneMat)
@@ -467,11 +468,12 @@ export function createProps(): PropsOut {
467
  add(dark, darkMat)
468
  add(red, redMat)
469
  add(roof, roofMat)
470
- add(goods, fruitMat)
471
- add(basket, basketMat)
472
- add(jars, jarMat)
473
- add(meat, meatMat)
474
- add(awning, awningMat)
 
475
 
476
  return {
477
  group, wheel,
 
261
  }
262
  const jarGeos = [jarProfile(0.28, 0.7), jarProfile(0.4, 0.9), jarProfile(0.2, 0.45)]
263
  const basketGeo = new THREE.CylinderGeometry(0.42, 0.32, 0.35, 16, 1, true)
264
+ const fruitGeo = new THREE.IcosahedronGeometry(0.075, 0)
265
  for (let s = MARKET_S0; s < MARKET_S1; s += rrange(rng, 5.5, 8)) {
266
  if (Math.abs(s - BRIDGE_S) < 12) continue
267
  const p = riverPoint(s, -9.6)
 
455
  lanternSpots.push({ p: V3(0, 3.3, 0).applyMatrix4(m), on: 58.5 })
456
  }
457
 
458
+ const add = (b: Builder, mat: THREE.Material, cast = true, reflect = true) => {
459
  if (!b.count) return
460
  const mesh = new THREE.Mesh(b.build(), mat)
461
  mesh.castShadow = cast
462
  mesh.receiveShadow = true
463
+ if (!reflect) mesh.layers.set(1)
464
  group.add(mesh)
465
  }
466
  add(stone, stoneMat)
 
468
  add(dark, darkMat)
469
  add(red, redMat)
470
  add(roof, roofMat)
471
+ // market goods: small, main view only
472
+ add(goods, fruitMat, false, false)
473
+ add(basket, basketMat, false, false)
474
+ add(jars, jarMat, false, false)
475
+ add(meat, meatMat, true, false)
476
+ add(awning, awningMat, true, false)
477
 
478
  return {
479
  group, wheel,
src/jiangnan/engine/sky.ts CHANGED
@@ -55,7 +55,11 @@ void main() {
55
  vDir = normalize(position);
56
  vec4 p = modelViewMatrix * vec4(position, 1.0);
57
  gl_Position = projectionMatrix * p;
 
 
 
58
  gl_Position.z = gl_Position.w * 0.99999;
 
59
  }
60
  `
61
 
@@ -168,7 +172,7 @@ void main() {
168
  }
169
  `
170
 
171
- export function createSky() {
172
  const uniforms = {
173
  uSunDir: U.uSunDir,
174
  uMoonDir: { value: new THREE.Vector3(0, 0.4, 1).normalize() },
@@ -180,6 +184,7 @@ export function createSky() {
180
  const mat = new THREE.ShaderMaterial({
181
  vertexShader: SKY_VS, fragmentShader: SKY_FS, uniforms,
182
  side: THREE.BackSide, depthWrite: false, fog: false,
 
183
  })
184
  const mesh = new THREE.Mesh(new THREE.SphereGeometry(5000, 64, 32), mat)
185
  mesh.frustumCulled = false
 
55
  vDir = normalize(position);
56
  vec4 p = modelViewMatrix * vec4(position, 1.0);
57
  gl_Position = projectionMatrix * p;
58
+ #ifdef REVERSED_DEPTH
59
+ gl_Position.z = gl_Position.w * 1e-6;
60
+ #else
61
  gl_Position.z = gl_Position.w * 0.99999;
62
+ #endif
63
  }
64
  `
65
 
 
172
  }
173
  `
174
 
175
+ export function createSky(reversed = false) {
176
  const uniforms = {
177
  uSunDir: U.uSunDir,
178
  uMoonDir: { value: new THREE.Vector3(0, 0.4, 1).normalize() },
 
184
  const mat = new THREE.ShaderMaterial({
185
  vertexShader: SKY_VS, fragmentShader: SKY_FS, uniforms,
186
  side: THREE.BackSide, depthWrite: false, fog: false,
187
+ defines: reversed ? { REVERSED_DEPTH: 1 } : {},
188
  })
189
  const mesh = new THREE.Mesh(new THREE.SphereGeometry(5000, 64, 32), mat)
190
  mesh.frustumCulled = false
src/jiangnan/engine/terrain.ts CHANGED
@@ -75,8 +75,8 @@ function groundColor(x: number, z: number, h: number, slope: number): RGB {
75
 
76
  export function createTerrain() {
77
  const T = getTextures()
78
- const xs = axis(NEAR.x0, NEAR.x1, 2.2, 7, 280, 700)
79
- const zs = axis(NEAR.z0, NEAR.z1, 2.2, 7, 200, 640)
80
  const nx = xs.length, nz = zs.length
81
  const pos = new Float32Array(nx * nz * 3)
82
  const col = new Float32Array(nx * nz * 3)
@@ -113,7 +113,7 @@ export function createTerrain() {
113
  const mat = std({ vertexColors: true, roughness: 0.95, metalness: 0, map: T.ground }, { key: 'terrain' })
114
  const mesh = new THREE.Mesh(geo, mat)
115
  mesh.receiveShadow = true
116
- mesh.castShadow = true
117
  return mesh
118
  }
119
 
 
75
 
76
  export function createTerrain() {
77
  const T = getTextures()
78
+ const xs = axis(NEAR.x0, NEAR.x1, 2.5, 9, 280, 700)
79
+ const zs = axis(NEAR.z0, NEAR.z1, 2.5, 9, 200, 640)
80
  const nx = xs.length, nz = zs.length
81
  const pos = new Float32Array(nx * nz * 3)
82
  const col = new Float32Array(nx * nz * 3)
 
113
  const mat = std({ vertexColors: true, roughness: 0.95, metalness: 0, map: T.ground }, { key: 'terrain' })
114
  const mesh = new THREE.Mesh(geo, mat)
115
  mesh.receiveShadow = true
116
+ mesh.castShadow = false
117
  return mesh
118
  }
119
 
src/jiangnan/engine/trees.ts CHANGED
@@ -14,7 +14,7 @@ const UP = new THREE.Vector3(0, 1, 0)
14
 
15
  function leafMaterial(map: THREE.Texture, opts: { center?: THREE.Vector3; sway?: number; key: string }) {
16
  const center = opts.center || new THREE.Vector3()
17
- const mat = patch(new THREE.MeshStandardMaterial({ map, alphaTest: 0.45, side: THREE.DoubleSide, roughness: 0.82, metalness: 0 }), {
18
  key: opts.key,
19
  vertexPars: 'uniform vec3 uCrown; uniform float uSway; attribute vec3 instanceTint; varying vec3 vTint;',
20
  vertex: `
@@ -132,7 +132,8 @@ function growTree(rng: Rng, base: THREE.Vector3, height: number, radius: number,
132
 
133
  export interface TreesOut { group: THREE.Group; camphorTop: THREE.Vector3 }
134
 
135
- export function createTrees(): TreesOut {
 
136
  const T = getTextures()
137
  const group = new THREE.Group()
138
  const rng = mulberry32(777)
@@ -239,10 +240,10 @@ export function createTrees(): TreesOut {
239
  }
240
 
241
  // ------------------------------------------------ bamboo groves
242
- group.add(createBamboo(rng))
243
 
244
  // ------------------------------------------------ hillside forest
245
- group.add(createForest(rng))
246
 
247
  // ------------------------------------------------ reeds
248
  group.add(createReeds(rng))
@@ -274,7 +275,7 @@ function instancedClusters(geo: THREE.BufferGeometry, mat: THREE.Material, list:
274
  return inst
275
  }
276
 
277
- function createBamboo(rng: Rng) {
278
  const T = getTextures()
279
  const group = new THREE.Group()
280
  // one clump: culms + leaf cards
@@ -286,13 +287,13 @@ function createBamboo(rng: Rng) {
286
  const h = 9 + clumpRng() * 5
287
  const lean = new THREE.Vector3(Math.cos(a), 0, Math.sin(a)).multiplyScalar(0.06 + clumpRng() * 0.1)
288
  const base = new THREE.Vector3(Math.cos(a) * r, 0, Math.sin(a) * r)
289
- const segs = 7
290
  for (let i = 0; i < segs; i++) {
291
  const f0 = i / segs, f1 = (i + 1) / segs
292
  const p0 = base.clone().add(new THREE.Vector3(lean.x * h * f0 * f0 * 2, h * f0, lean.z * h * f0 * f0 * 2))
293
  const p1 = base.clone().add(new THREE.Vector3(lean.x * h * f1 * f1 * 2, h * f1, lean.z * h * f1 * f1 * 2))
294
  const d = p1.clone().sub(p0)
295
- const g = new THREE.CylinderGeometry(0.045 * (1 - f1 * 0.6), 0.05 * (1 - f0 * 0.6), d.length(), 5, 1, true)
296
  culms.geometry(g, new THREE.Matrix4().compose(p0.clone().addScaledVector(d, 0.5), new THREE.Quaternion().setFromUnitVectors(UP, d.clone().normalize()), new THREE.Vector3(1, 1, 1)))
297
  if (f0 > 0.45) {
298
  for (let k = 0; k < 2; k++) {
@@ -313,7 +314,7 @@ function createBamboo(rng: Rng) {
313
  const houses = buildHouses()
314
  const spots: THREE.Matrix4[] = []
315
  const tints: number[] = []
316
- for (let tries = 0; tries < 9000 && spots.length < 900; tries++) {
317
  const x = rrange(rng, -520, 560), z = rrange(rng, -420, 380)
318
  const q = riverQuery(x, z)
319
  if (q.d < 22) continue
@@ -362,18 +363,21 @@ function createBamboo(rng: Rng) {
362
  const leafInst = new THREE.InstancedMesh(leafGeo, leafMat, spots.length)
363
  spots.forEach((m, i) => { culmInst.setMatrixAt(i, m); leafInst.setMatrixAt(i, m) })
364
  leafGeo.setAttribute('instanceTint', new THREE.InstancedBufferAttribute(new Float32Array(tints), 3))
365
- culmInst.castShadow = leafInst.castShadow = true
 
366
  leafInst.receiveShadow = true
 
 
367
  culmInst.computeBoundingSphere()
368
  leafInst.computeBoundingSphere()
369
  group.add(culmInst, leafInst)
370
  return group
371
  }
372
 
373
- function createForest(rng: Rng) {
374
  const group = new THREE.Group()
375
  // broadleaf blob + fir cone, vertex-noise deformed
376
- const blob = new THREE.IcosahedronGeometry(1, 2)
377
  {
378
  const p = blob.getAttribute('position') as THREE.BufferAttribute
379
  for (let i = 0; i < p.count; i++) {
@@ -407,7 +411,7 @@ function createForest(rng: Rng) {
407
  const lists: THREE.Matrix4[][] = [[], []]
408
  const tints: number[][] = [[], []]
409
  const area = { x0: -1500, x1: 1500, z0: -1300, z1: 1200 }
410
- for (let tries = 0; tries < 60000 && lists[0].length + lists[1].length < 9000; tries++) {
411
  const x = rrange(rng, area.x0, area.x1), z = rrange(rng, area.z0, area.z1)
412
  const q = riverQuery(x, z)
413
  if (q.d < 70) continue
@@ -430,8 +434,10 @@ function createForest(rng: Rng) {
430
  const inst = new THREE.InstancedMesh(g, mats[gi], lists[gi].length)
431
  lists[gi].forEach((m, i) => inst.setMatrixAt(i, m))
432
  g.setAttribute('instanceTint', new THREE.InstancedBufferAttribute(new Float32Array(tints[gi]), 3))
433
- inst.castShadow = true
434
- inst.receiveShadow = true
 
 
435
  inst.computeBoundingSphere()
436
  group.add(inst)
437
  })
 
14
 
15
  function leafMaterial(map: THREE.Texture, opts: { center?: THREE.Vector3; sway?: number; key: string }) {
16
  const center = opts.center || new THREE.Vector3()
17
+ const mat = patch(new THREE.MeshStandardMaterial({ map, alphaTest: 0.3, alphaToCoverage: true, side: THREE.DoubleSide, roughness: 0.82, metalness: 0 }), {
18
  key: opts.key,
19
  vertexPars: 'uniform vec3 uCrown; uniform float uSway; attribute vec3 instanceTint; varying vec3 vTint;',
20
  vertex: `
 
132
 
133
  export interface TreesOut { group: THREE.Group; camphorTop: THREE.Vector3 }
134
 
135
+ export function createTrees(quality: 'low' | 'medium' | 'high' = 'high'): TreesOut {
136
+ const density = quality === 'high' ? 1 : quality === 'medium' ? 0.55 : 0.32
137
  const T = getTextures()
138
  const group = new THREE.Group()
139
  const rng = mulberry32(777)
 
240
  }
241
 
242
  // ------------------------------------------------ bamboo groves
243
+ group.add(createBamboo(rng, density))
244
 
245
  // ------------------------------------------------ hillside forest
246
+ group.add(createForest(rng, density))
247
 
248
  // ------------------------------------------------ reeds
249
  group.add(createReeds(rng))
 
275
  return inst
276
  }
277
 
278
+ function createBamboo(rng: Rng, density = 1) {
279
  const T = getTextures()
280
  const group = new THREE.Group()
281
  // one clump: culms + leaf cards
 
287
  const h = 9 + clumpRng() * 5
288
  const lean = new THREE.Vector3(Math.cos(a), 0, Math.sin(a)).multiplyScalar(0.06 + clumpRng() * 0.1)
289
  const base = new THREE.Vector3(Math.cos(a) * r, 0, Math.sin(a) * r)
290
+ const segs = 4
291
  for (let i = 0; i < segs; i++) {
292
  const f0 = i / segs, f1 = (i + 1) / segs
293
  const p0 = base.clone().add(new THREE.Vector3(lean.x * h * f0 * f0 * 2, h * f0, lean.z * h * f0 * f0 * 2))
294
  const p1 = base.clone().add(new THREE.Vector3(lean.x * h * f1 * f1 * 2, h * f1, lean.z * h * f1 * f1 * 2))
295
  const d = p1.clone().sub(p0)
296
+ const g = new THREE.CylinderGeometry(0.045 * (1 - f1 * 0.6), 0.05 * (1 - f0 * 0.6), d.length(), 4, 1, true)
297
  culms.geometry(g, new THREE.Matrix4().compose(p0.clone().addScaledVector(d, 0.5), new THREE.Quaternion().setFromUnitVectors(UP, d.clone().normalize()), new THREE.Vector3(1, 1, 1)))
298
  if (f0 > 0.45) {
299
  for (let k = 0; k < 2; k++) {
 
314
  const houses = buildHouses()
315
  const spots: THREE.Matrix4[] = []
316
  const tints: number[] = []
317
+ for (let tries = 0; tries < 9000 && spots.length < Math.round(650 * density); tries++) {
318
  const x = rrange(rng, -520, 560), z = rrange(rng, -420, 380)
319
  const q = riverQuery(x, z)
320
  if (q.d < 22) continue
 
363
  const leafInst = new THREE.InstancedMesh(leafGeo, leafMat, spots.length)
364
  spots.forEach((m, i) => { culmInst.setMatrixAt(i, m); leafInst.setMatrixAt(i, m) })
365
  leafGeo.setAttribute('instanceTint', new THREE.InstancedBufferAttribute(new Float32Array(tints), 3))
366
+ culmInst.castShadow = false
367
+ leafInst.castShadow = true
368
  leafInst.receiveShadow = true
369
+ culmInst.layers.set(1)
370
+ leafInst.layers.set(1)
371
  culmInst.computeBoundingSphere()
372
  leafInst.computeBoundingSphere()
373
  group.add(culmInst, leafInst)
374
  return group
375
  }
376
 
377
+ function createForest(rng: Rng, density = 1) {
378
  const group = new THREE.Group()
379
  // broadleaf blob + fir cone, vertex-noise deformed
380
+ const blob = new THREE.IcosahedronGeometry(1, 1)
381
  {
382
  const p = blob.getAttribute('position') as THREE.BufferAttribute
383
  for (let i = 0; i < p.count; i++) {
 
411
  const lists: THREE.Matrix4[][] = [[], []]
412
  const tints: number[][] = [[], []]
413
  const area = { x0: -1500, x1: 1500, z0: -1300, z1: 1200 }
414
+ for (let tries = 0; tries < 60000 && lists[0].length + lists[1].length < Math.round(9000 * density); tries++) {
415
  const x = rrange(rng, area.x0, area.x1), z = rrange(rng, area.z0, area.z1)
416
  const q = riverQuery(x, z)
417
  if (q.d < 70) continue
 
434
  const inst = new THREE.InstancedMesh(g, mats[gi], lists[gi].length)
435
  lists[gi].forEach((m, i) => inst.setMatrixAt(i, m))
436
  g.setAttribute('instanceTint', new THREE.InstancedBufferAttribute(new Float32Array(tints[gi]), 3))
437
+ // distant hillside forest: main view only (no shadow / reflection passes)
438
+ inst.castShadow = false
439
+ inst.receiveShadow = false
440
+ inst.layers.set(1)
441
  inst.computeBoundingSphere()
442
  group.add(inst)
443
  })
src/jiangnan/engine/village.ts CHANGED
@@ -20,7 +20,7 @@ export interface VillageOut {
20
 
21
  const FLOOR_H = 3.3
22
 
23
- export function createVillage(): VillageOut {
24
  const T = getTextures()
25
  const houses = buildHouses()
26
  const wall = new Builder(), roof = new Builder(), dark = new Builder(), wood = new Builder(), stone = new Builder(), glow = new Builder()
@@ -29,6 +29,22 @@ export function createVillage(): VillageOut {
29
  const eaveAnchors: VillageOut['eaveAnchors'] = []
30
  const shopFronts: VillageOut['shopFronts'] = []
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  for (const h of houses) buildHouse(h)
33
 
34
  function windowOn(h: HouseSpec, k: number) {
@@ -67,6 +83,7 @@ export function createVillage(): VillageOut {
67
  const base = Math.max(GROUND_Y, gy)
68
  const m = trs(h.x, base, h.z, h.rot)
69
  const H = floors * FLOOR_H + 0.5
 
70
  const rise = d * 0.27
71
  const ridge = H + rise
72
  const n = h.gableSteps
@@ -193,7 +210,21 @@ export function createVillage(): VillageOut {
193
  const y0 = slopeY(u0), y1 = slopeY(u1)
194
  const L = eaveZ * Math.hypot(1, (ridge - eaveY) / eaveZ)
195
  const v0 = (u0 * L) / 1.2, v1 = (u1 * L) / 1.2
196
- if (zsgn > 0) roof.quad(V3(rx0, y0, z0), V3(rx1, y0, z0), V3(rx1, y1, z1), V3(rx0, y1, z1), [rx0 / 1.2, v0, rx1 / 1.2, v0, rx1 / 1.2, v1, rx0 / 1.2, v1])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  else roof.quad(V3(rx1, y0, z0), V3(rx0, y0, z0), V3(rx0, y1, z1), V3(rx1, y1, z1), [rx1 / 1.2, v0, rx0 / 1.2, v0, rx0 / 1.2, v1, rx1 / 1.2, v1])
198
  // soffit underside
199
  dark.setMatrix(m)
@@ -203,6 +234,14 @@ export function createVillage(): VillageOut {
203
  // eave fascia board
204
  wood.setMatrix(m)
205
  wood.box(0, eaveY - 0.08, zsgn * eaveZ, rx1 - rx0, 0.16, 0.08)
 
 
 
 
 
 
 
 
206
  }
207
  // ridge with upturned ends
208
  dark.setMatrix(m)
@@ -237,6 +276,15 @@ export function createVillage(): VillageOut {
237
  // warm interior light (lights up with the windows)
238
  addWindow(m, (xa + xb) / 2, (sh - 0.3 + 1.0) / 2 + 0.1, hd - 0.58, xb - xa - 0.35, sh - 1.5, windowOn(h, 50 + b) - 1.5, h.seed + b, 1)
239
  shopFronts.push({ p: new THREE.Vector3((xa + xb) / 2, 0, hd + 0.6).applyMatrix4(m), rot: h.rot, w: xb - xa, s: h.s })
 
 
 
 
 
 
 
 
 
240
  } else {
241
  for (let p = 0; p < 4; p++) {
242
  const x0 = xa + 0.1 + ((xb - xa - 0.2) * p) / 4
@@ -280,6 +328,26 @@ export function createVillage(): VillageOut {
280
  dark.setMatrix(m)
281
  dark.box(doorX, 3.38, hd + 0.05, 2.7, 0.12, 0.16)
282
  dark.quad(V3(doorX - 1.3, 3.25, hd), V3(doorX + 1.3, 3.25, hd), V3(doorX + 1.3, 2.9, hd + 0.75), V3(doorX - 1.3, 2.9, hd + 0.75))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283
  if (h.lantern) {
284
  eaveAnchors.push({ p: new THREE.Vector3(doorX - 0.95, 2.85, hd + 0.5).applyMatrix4(m), s: h.s, side: h.side, facing: h.rot })
285
  eaveAnchors.push({ p: new THREE.Vector3(doorX + 0.95, 2.85, hd + 0.5).applyMatrix4(m), s: h.s, side: h.side, facing: h.rot })
@@ -347,18 +415,36 @@ export function createVillage(): VillageOut {
347
  }
348
 
349
  const group = new THREE.Group()
 
 
 
 
 
 
350
  const wallMat = std({ map: T.wall, normalMap: T.wallN, normalScale: new THREE.Vector2(0.5, 0.5), roughness: 0.93, color: new THREE.Color(0.95, 0.94, 0.9) }, { key: 'wall' })
351
- const roofMat = std({ map: T.roof, normalMap: T.roofN, roughness: 0.62, metalness: 0.05, color: new THREE.Color(0.95, 0.95, 1.0) }, { key: 'roof' })
 
 
 
 
 
 
 
 
 
 
 
352
  const darkMat = std({ color: new THREE.Color(0.045, 0.045, 0.05), roughness: 0.7 }, { key: 'dark' })
353
  const woodMat = std({ map: T.wood, roughness: 0.78, color: new THREE.Color(0.8, 0.75, 0.7) }, { key: 'wood' })
354
  const stoneMat = std({ map: T.stone, normalMap: T.stoneN, roughness: 0.88, color: new THREE.Color(0.75, 0.76, 0.74) }, { key: 'stone' })
355
  const paveMat = std({ map: T.slab, normalMap: T.slabN, roughness: 0.55, color: new THREE.Color(0.85, 0.88, 0.92) }, { key: 'pave' })
356
  const glowMat = windowMaterial(T.lattice)
357
- const add = (b: Builder, mat: THREE.Material, cast = true) => {
358
  if (!b.count) return
359
  const mesh = new THREE.Mesh(b.build(), mat)
360
  mesh.castShadow = cast
361
  mesh.receiveShadow = true
 
362
  group.add(mesh)
363
  }
364
  add(wall, wallMat)
@@ -368,9 +454,67 @@ export function createVillage(): VillageOut {
368
  add(stone, stoneMat)
369
  add(pave, paveMat, false)
370
  add(glow, glowMat, false)
 
 
 
 
371
  return { group, houses, chimneys, eaveAnchors, shopFronts }
372
  }
373
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374
  function riverPointS(x: number) {
375
  // nearest arc length for an x coordinate (river runs west→east)
376
  let best = 0, bd = 1e9
 
20
 
21
  const FLOOR_H = 3.3
22
 
23
+ export function createVillage(quality: 'low' | 'medium' | 'high' = 'high'): VillageOut {
24
  const T = getTextures()
25
  const houses = buildHouses()
26
  const wall = new Builder(), roof = new Builder(), dark = new Builder(), wood = new Builder(), stone = new Builder(), glow = new Builder()
 
29
  const eaveAnchors: VillageOut['eaveAnchors'] = []
30
  const shopFronts: VillageOut['shopFronts'] = []
31
 
32
+ roof.set('aRelief', 0).set('aRH', 0).set('aRS', 0)
33
+ const tileEnds = new Builder()
34
+ const endCap = new THREE.CylinderGeometry(0.075, 0.075, 0.05, 7)
35
+ endCap.rotateX(Math.PI / 2)
36
+ const dripShape = new THREE.Shape()
37
+ dripShape.moveTo(-0.1, 0.03); dripShape.lineTo(0.1, 0.03); dripShape.lineTo(0, -0.07); dripShape.closePath()
38
+ const dripTile = new THREE.ExtrudeGeometry(dripShape, { depth: 0.04, bevelEnabled: false })
39
+ const tileRelief = (x: number) => {
40
+ const f = Math.sin((Math.PI * x) / 0.2)
41
+ return f > 0 ? f * 0.07 : f * 0.022
42
+ }
43
+ const couplets = new Builder() // red door couplets (uv into the sign atlas)
44
+ const signs = new Builder() // shop signboards (uv into the sign atlas)
45
+ const clutter = new Builder() // water jars, firewood, potted plants (vertex-coloured)
46
+ clutter.set('aTint', 0)
47
+
48
  for (const h of houses) buildHouse(h)
49
 
50
  function windowOn(h: HouseSpec, k: number) {
 
83
  const base = Math.max(GROUND_Y, gy)
84
  const m = trs(h.x, base, h.z, h.rot)
85
  const H = floors * FLOOR_H + 0.5
86
+ const detailed = quality === 'high' ? h.lantern : quality === 'medium' ? h.shop : false // street/river fronts get full roof relief
87
  const rise = d * 0.27
88
  const ridge = H + rise
89
  const n = h.gableSteps
 
210
  const y0 = slopeY(u0), y1 = slopeY(u1)
211
  const L = eaveZ * Math.hypot(1, (ridge - eaveY) / eaveZ)
212
  const v0 = (u0 * L) / 1.2, v1 = (u1 * L) / 1.2
213
+ if (detailed) {
214
+ // real 阴阳瓦 relief: convex cover tiles over concave pan tiles (0.4 m period,
215
+ // aligned with the tile texture), so ridges catch the low sun and cast tiny shadows
216
+ const nx = Math.max(2, Math.round((rx1 - rx0) / 0.1))
217
+ for (let c = 0; c < nx; c++) {
218
+ const xa = rx0 + ((rx1 - rx0) * c) / nx, xb = rx0 + ((rx1 - rx0) * (c + 1)) / nx
219
+ const ha = tileRelief(xa), hb = tileRelief(xb)
220
+ const ua = xa / 1.2, ub = xb / 1.2
221
+ // relief is applied in the vertex shader (and faded out with distance → no shimmer)
222
+ roof.set('aRelief', 1)
223
+ if (zsgn > 0) roof.quadRelief(V3(xa, y0, z0), V3(xb, y0, z0), V3(xb, y1, z1), V3(xa, y1, z1), [ha, hb, hb, ha], [ua, v0, ub, v0, ub, v1, ua, v1])
224
+ else roof.quadRelief(V3(xb, y0, z0), V3(xa, y0, z0), V3(xa, y1, z1), V3(xb, y1, z1), [hb, ha, ha, hb], [ub, v0, ua, v0, ua, v1, ub, v1])
225
+ roof.set('aRelief', 0)
226
+ }
227
+ } else if (zsgn > 0) roof.quad(V3(rx0, y0, z0), V3(rx1, y0, z0), V3(rx1, y1, z1), V3(rx0, y1, z1), [rx0 / 1.2, v0, rx1 / 1.2, v0, rx1 / 1.2, v1, rx0 / 1.2, v1])
228
  else roof.quad(V3(rx1, y0, z0), V3(rx0, y0, z0), V3(rx0, y1, z1), V3(rx1, y1, z1), [rx1 / 1.2, v0, rx0 / 1.2, v0, rx0 / 1.2, v1, rx1 / 1.2, v1])
229
  // soffit underside
230
  dark.setMatrix(m)
 
234
  // eave fascia board
235
  wood.setMatrix(m)
236
  wood.box(0, eaveY - 0.08, zsgn * eaveZ, rx1 - rx0, 0.16, 0.08)
237
+ if (detailed) {
238
+ // round tile ends (瓦当) on every cover row and pointed drip tiles (滴水) on the pans
239
+ tileEnds.setMatrix(m)
240
+ for (let x = Math.ceil((rx0 - 0.1) / 0.4) * 0.4 + 0.1; x < rx1 - 0.05; x += 0.4) {
241
+ tileEnds.geometry(endCap, new THREE.Matrix4().compose(V3(x, eaveY + 0.04, zsgn * (eaveZ + 0.02)), new THREE.Quaternion().setFromAxisAngle(V3(0, 1, 0), zsgn > 0 ? 0 : Math.PI), V3(1, 1, 1)))
242
+ if (x + 0.2 < rx1) tileEnds.geometry(dripTile, new THREE.Matrix4().compose(V3(x + 0.2, eaveY - 0.03, zsgn * (eaveZ + 0.02)), new THREE.Quaternion().setFromAxisAngle(V3(0, 1, 0), zsgn > 0 ? 0 : Math.PI), V3(1, 1, 1)))
243
+ }
244
+ }
245
  }
246
  // ridge with upturned ends
247
  dark.setMatrix(m)
 
276
  // warm interior light (lights up with the windows)
277
  addWindow(m, (xa + xb) / 2, (sh - 0.3 + 1.0) / 2 + 0.1, hd - 0.58, xb - xa - 0.35, sh - 1.5, windowOn(h, 50 + b) - 1.5, h.seed + b, 1)
278
  shopFronts.push({ p: new THREE.Vector3((xa + xb) / 2, 0, hd + 0.6).applyMatrix4(m), rot: h.rot, w: xb - xa, s: h.s })
279
+ if (b === Math.floor(bays / 2)) {
280
+ // black lacquer signboard with gilded characters (店招)
281
+ const si = Math.floor(rng() * 8)
282
+ const cx = (xa + xb) / 2, sw = Math.min(2.2, xb - xa - 0.1)
283
+ dark.setMatrix(m)
284
+ dark.box(cx, sh + 0.1, hd + 0.06, sw + 0.12, 0.62, 0.06)
285
+ signs.setMatrix(m)
286
+ signs.quad(V3(cx - sw / 2, sh - 0.17, hd + 0.1), V3(cx + sw / 2, sh - 0.17, hd + 0.1), V3(cx + sw / 2, sh + 0.37, hd + 0.1), V3(cx - sw / 2, sh + 0.37, hd + 0.1), [(si % 4) / 4, (si < 4 ? 0 : 0.125), ((si % 4) + 1) / 4, (si < 4 ? 0 : 0.125), ((si % 4) + 1) / 4, (si < 4 ? 0.125 : 0.25), (si % 4) / 4, (si < 4 ? 0.125 : 0.25)])
287
+ }
288
  } else {
289
  for (let p = 0; p < 4; p++) {
290
  const x0 = xa + 0.1 + ((xb - xa - 0.2) * p) / 4
 
328
  dark.setMatrix(m)
329
  dark.box(doorX, 3.38, hd + 0.05, 2.7, 0.12, 0.16)
330
  dark.quad(V3(doorX - 1.3, 3.25, hd), V3(doorX + 1.3, 3.25, hd), V3(doorX + 1.3, 2.9, hd + 0.75), V3(doorX - 1.3, 2.9, hd + 0.75))
331
+ // red couplets either side of the door and a horizontal scroll above it
332
+ couplets.setMatrix(m)
333
+ const cs = Math.floor(rng() * 3)
334
+ const cu = (i: number) => [i * 0.125, 0.5, (i + 1) * 0.125, 0.5, (i + 1) * 0.125, 1, i * 0.125, 1]
335
+ const zc = hd + 0.015
336
+ couplets.quad(V3(doorX - 1.24, 0.75, zc), V3(doorX - 0.98, 0.75, zc), V3(doorX - 0.98, 2.45, zc), V3(doorX - 1.24, 2.45, zc), cu(cs * 2 + 1))
337
+ couplets.quad(V3(doorX + 0.98, 0.75, zc), V3(doorX + 1.24, 0.75, zc), V3(doorX + 1.24, 2.45, zc), V3(doorX + 0.98, 2.45, zc), cu(cs * 2))
338
+ const bu = [cs / 3, 0.25, (cs + 1) / 3, 0.25, (cs + 1) / 3, 0.5, cs / 3, 0.5]
339
+ couplets.quad(V3(doorX - 0.75, 2.78, zc), V3(doorX + 0.75, 2.78, zc), V3(doorX + 0.75, 3.0, zc), V3(doorX - 0.75, 3.0, zc), bu)
340
+ // clutter by the door: glazed water jar, firewood stack or a potted plant
341
+ clutter.setMatrix(m)
342
+ const side = doorX > 0 ? -1 : 1
343
+ const kind = Math.floor(rng() * 3)
344
+ if (kind === 0) { clutter.set('aTint', 0); clutter.geometry(jarGeo, new THREE.Matrix4().makeTranslation(doorX + side * 1.75, 0, hd + 0.55)) } else if (kind === 1) {
345
+ clutter.set('aTint', 1)
346
+ for (let k = 0; k < 9; k++) clutter.geometry(logGeo, new THREE.Matrix4().compose(V3(doorX + side * (1.9 + (k % 3) * 0.02), 0.1 + Math.floor(k / 3) * 0.17, hd + 0.35 + (k % 3) * 0.17), new THREE.Quaternion().setFromAxisAngle(V3(0, 0, 1), Math.PI / 2), V3(1, 1, 1)))
347
+ } else {
348
+ clutter.set('aTint', 2); clutter.geometry(potGeo, new THREE.Matrix4().makeTranslation(doorX + side * 1.6, 0, hd + 0.5))
349
+ clutter.set('aTint', 3); clutter.geometry(shrubGeo, new THREE.Matrix4().makeTranslation(doorX + side * 1.6, 0.62, hd + 0.5))
350
+ }
351
  if (h.lantern) {
352
  eaveAnchors.push({ p: new THREE.Vector3(doorX - 0.95, 2.85, hd + 0.5).applyMatrix4(m), s: h.s, side: h.side, facing: h.rot })
353
  eaveAnchors.push({ p: new THREE.Vector3(doorX + 0.95, 2.85, hd + 0.5).applyMatrix4(m), s: h.s, side: h.side, facing: h.rot })
 
415
  }
416
 
417
  const group = new THREE.Group()
418
+ const atlas = signAtlas()
419
+ const signMat = std({ map: atlas, roughness: 0.55, metalness: 0.0 }, { key: 'sign' })
420
+ const clutterMat = std({ roughness: 0.6 }, {
421
+ key: 'clutter', vertexPars: 'attribute float aTint; varying float vTint;', vertex: 'vTint = aTint;', fragmentPars: 'varying float vTint;',
422
+ colorFrag: 'diffuseColor.rgb = vTint < 0.5 ? vec3(0.09, 0.06, 0.04) : vTint < 1.5 ? vec3(0.34, 0.22, 0.12) : vTint < 2.5 ? vec3(0.42, 0.2, 0.1) : vec3(0.1, 0.22, 0.06);',
423
+ })
424
  const wallMat = std({ map: T.wall, normalMap: T.wallN, normalScale: new THREE.Vector2(0.5, 0.5), roughness: 0.93, color: new THREE.Color(0.95, 0.94, 0.9) }, { key: 'wall' })
425
+ const roofMat = std({ map: T.roof, normalMap: T.roofN, normalScale: new THREE.Vector2(0.8, 0.8), roughness: 0.66, metalness: 0.05, color: new THREE.Color(0.95, 0.95, 1.0) }, {
426
+ key: 'roof',
427
+ vertexPars: 'attribute float aRelief; attribute float aRH;',
428
+ vertex: `
429
+ {
430
+ // tile relief: full near the camera, flattened beyond ~45 m (keeps far roofs from aliasing)
431
+ vec3 wp0 = (modelMatrix * vec4(position, 1.0)).xyz;
432
+ float fade = 1.0 - smoothstep(22.0, 48.0, distance(wp0, cameraPosition));
433
+ transformed.y += aRH * aRelief * fade;
434
+ }
435
+ `,
436
+ })
437
  const darkMat = std({ color: new THREE.Color(0.045, 0.045, 0.05), roughness: 0.7 }, { key: 'dark' })
438
  const woodMat = std({ map: T.wood, roughness: 0.78, color: new THREE.Color(0.8, 0.75, 0.7) }, { key: 'wood' })
439
  const stoneMat = std({ map: T.stone, normalMap: T.stoneN, roughness: 0.88, color: new THREE.Color(0.75, 0.76, 0.74) }, { key: 'stone' })
440
  const paveMat = std({ map: T.slab, normalMap: T.slabN, roughness: 0.55, color: new THREE.Color(0.85, 0.88, 0.92) }, { key: 'pave' })
441
  const glowMat = windowMaterial(T.lattice)
442
+ const add = (b: Builder, mat: THREE.Material, cast = true, reflect = true) => {
443
  if (!b.count) return
444
  const mesh = new THREE.Mesh(b.build(), mat)
445
  mesh.castShadow = cast
446
  mesh.receiveShadow = true
447
+ if (!reflect) mesh.layers.set(1)
448
  group.add(mesh)
449
  }
450
  add(wall, wallMat)
 
454
  add(stone, stoneMat)
455
  add(pave, paveMat, false)
456
  add(glow, glowMat, false)
457
+ add(couplets, signMat, false, false)
458
+ add(signs, signMat, false, false)
459
+ add(tileEnds, darkMat, false, false)
460
+ add(clutter, clutterMat, false, false)
461
  return { group, houses, chimneys, eaveAnchors, shopFronts }
462
  }
463
 
464
+ const jarGeo = new THREE.LatheGeometry([[0.05, 0], [0.32, 0.08], [0.4, 0.35], [0.36, 0.62], [0.3, 0.7], [0.32, 0.72], [0.26, 0.72]].map(([r, y]) => new THREE.Vector2(r, y)), 14)
465
+ const logGeo = new THREE.CylinderGeometry(0.08, 0.08, 0.9, 6)
466
+ const potGeo = new THREE.LatheGeometry([[0.05, 0], [0.18, 0.02], [0.24, 0.4], [0.26, 0.45], [0.2, 0.45]].map(([r, y]) => new THREE.Vector2(r, y)), 12)
467
+ const shrubGeo = new THREE.IcosahedronGeometry(0.34, 1)
468
+
469
+ /** Atlas: row 0-1 = 8 shop signs, row 2 = 3 horizontal scrolls, row 3 = 6 couplet strips. */
470
+ function signAtlas() {
471
+ const W = 1024, H = 1024
472
+ const c = document.createElement('canvas')
473
+ c.width = W
474
+ c.height = H
475
+ const g = c.getContext('2d')!
476
+ const font = (px: number) => `${px}px JNTitle, "STKaiti", "KaiTi", serif`
477
+ g.textAlign = 'center'
478
+ g.textBaseline = 'middle'
479
+ // shop signs: black lacquer with gold characters (v 0 – 0.25 → canvas bottom quarter... flipY)
480
+ const SIGNS = ['米铺', '茶馆', '酱园', '布庄', '药铺', '豆腐坊', '酒坊', '竹器']
481
+ SIGNS.forEach((t, i) => {
482
+ const x = (i % 4) * 256, y = H - (Math.floor(i / 4) + 1) * 128
483
+ g.fillStyle = '#120c08'
484
+ g.fillRect(x, y, 256, 128)
485
+ g.strokeStyle = '#8a6a2a'
486
+ g.lineWidth = 6
487
+ g.strokeRect(x + 8, y + 8, 240, 112)
488
+ g.fillStyle = '#d8b25a'
489
+ g.font = font(t.length > 2 ? 64 : 80)
490
+ g.fillText(t, x + 128, y + 68)
491
+ })
492
+ // horizontal scrolls (横批)
493
+ const BANNERS = ['福满江南', '人寿年丰', '耕读传家']
494
+ BANNERS.forEach((t, i) => {
495
+ const x = (i * W) / 3, y = H * 0.5
496
+ g.fillStyle = '#b3241b'
497
+ g.fillRect(x + 4, y, W / 3 - 8, H * 0.25)
498
+ g.fillStyle = '#1a0a05'
499
+ g.font = font(70)
500
+ g.fillText(t, x + W / 6, y + H * 0.125)
501
+ })
502
+ // couplet strips (vertical), 6 strips = 3 pairs
503
+ const PAIRS = [['一溪春水绕门过', '两岸灯花照客来'], ['小桥流水千家月', '古巷炊烟万户春'], ['白墙黛瓦藏诗意', '细雨斜阳入画中']]
504
+ PAIRS.flat().forEach((t, i) => {
505
+ const x = i * 128, y = 0
506
+ g.fillStyle = '#b8261c'
507
+ g.fillRect(x + 6, y, 116, H * 0.5)
508
+ g.fillStyle = '#1a0a05'
509
+ g.font = font(54)
510
+ Array.from(t).forEach((ch, k) => g.fillText(ch, x + 64, y + 40 + k * 68))
511
+ })
512
+ const tex = new THREE.CanvasTexture(c)
513
+ tex.colorSpace = THREE.SRGBColorSpace
514
+ tex.anisotropy = 8
515
+ return tex
516
+ }
517
+
518
  function riverPointS(x: number) {
519
  // nearest arc length for an x coordinate (river runs west→east)
520
  let best = 0, bd = 1e9
src/jiangnan/engine/water.ts CHANGED
@@ -39,24 +39,26 @@ float vn(vec2 p) {
39
  return mix(mix(h21(i), h21(i + vec2(1, 0)), u.x), mix(h21(i + vec2(0, 1)), h21(i + vec2(1, 1)), u.x), u.y);
40
  }
41
  // height of the water surface ripples
42
- float wave(vec2 p) {
43
  float t = uTime;
44
  float h = 0.0;
45
  h += sin(dot(p, vec2(0.62, 0.21)) * 1.1 + t * 1.3) * 0.5;
46
  h += sin(dot(p, vec2(-0.35, 0.78)) * 1.7 + t * 1.7) * 0.32;
47
  h += sin(dot(p, vec2(0.9, -0.5)) * 2.9 + t * 2.3) * 0.18;
48
  h += vn(p * 1.3 + vec2(t * 0.35, t * 0.12)) * 0.6;
49
- h += vn(p * 3.7 - vec2(t * 0.6, -t * 0.2)) * 0.25;
50
- h += vn(p * 9.0 + vec2(t * 0.9, t * 0.4)) * 0.1;
51
  return h;
52
  }
53
 
54
  void main() {
55
  vec2 p = vWorld.xz;
56
- float e = 0.08;
57
- float h0 = wave(p);
58
- vec2 grad = vec2(wave(p + vec2(e, 0.0)) - h0, wave(p + vec2(0.0, e)) - h0) / e;
59
- float amp = mix(0.09, 0.022, vCalm);
 
 
60
  vec3 N = normalize(vec3(-grad.x * amp, 1.0, -grad.y * amp));
61
 
62
  vec3 V = normalize(cameraPosition - vWorld);
@@ -75,7 +77,7 @@ void main() {
75
  // sun glitter
76
  vec3 R = reflect(-V, N);
77
  float sd = max(dot(R, uSunDir), 0.0);
78
- col += uSunCol * (pow(sd, 900.0) * 5.0 + pow(sd, 120.0) * 0.45) * uSunI * smoothstep(-0.01, 0.03, uSunDir.y);
79
  col = applyWorldFog(col, vWorld);
80
  if (uDebug > 1.5) col = vec3(uv, 0.0);
81
  else if (uDebug > 0.5) col = refl;
@@ -120,6 +122,8 @@ export function createWater(): Water {
120
  geo.computeBoundingSphere()
121
 
122
  const rt = new THREE.WebGLRenderTarget(512, 512, { type: THREE.HalfFloatType, samples: 0 })
 
 
123
  const textureMatrix = new THREE.Matrix4()
124
  const uniforms: Record<string, THREE.IUniform> = {
125
  tReflect: { value: rt.texture },
@@ -136,12 +140,13 @@ export function createWater(): Water {
136
  mesh.receiveShadow = false
137
 
138
  const mirror = new THREE.PerspectiveCamera()
 
139
  const normal = new THREE.Vector3(0, 1, 0)
140
- const plane = new THREE.Plane()
141
- const clip = new THREE.Vector4()
142
- const q = new THREE.Vector4()
143
  const camPos = new THREE.Vector3(), look = new THREE.Vector3(), target = new THREE.Vector3(), rot = new THREE.Matrix4()
144
  const origin = new THREE.Vector3(0, 0, 0)
 
 
 
145
 
146
  const renderReflection = (renderer: THREE.WebGLRenderer, scene: THREE.Scene, camera: THREE.PerspectiveCamera) => {
147
  camPos.setFromMatrixPosition(camera.matrixWorld)
@@ -154,34 +159,25 @@ export function createWater(): Water {
154
  mirror.position.copy(view)
155
  mirror.up.set(0, 1, 0).applyMatrix4(rot).reflect(normal)
156
  mirror.lookAt(target)
157
- mirror.far = camera.far
 
158
  mirror.near = camera.near
 
 
159
  mirror.updateMatrixWorld()
160
- mirror.projectionMatrix.copy(camera.projectionMatrix)
161
  textureMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1)
162
  textureMatrix.multiply(mirror.projectionMatrix).multiply(mirror.matrixWorldInverse)
163
- plane.setFromNormalAndCoplanarPoint(normal, new THREE.Vector3(0, -0.05, 0))
164
- plane.applyMatrix4(mirror.matrixWorldInverse)
165
- clip.set(plane.normal.x, plane.normal.y, plane.normal.z, plane.constant)
166
- const pm = mirror.projectionMatrix
167
- q.x = (Math.sign(clip.x) + pm.elements[8]) / pm.elements[0]
168
- q.y = (Math.sign(clip.y) + pm.elements[9]) / pm.elements[5]
169
- q.z = -1
170
- q.w = (1 + pm.elements[10]) / pm.elements[14]
171
- clip.multiplyScalar(2 / clip.dot(q))
172
- pm.elements[2] = clip.x
173
- pm.elements[6] = clip.y
174
- pm.elements[10] = clip.z + 1
175
- pm.elements[14] = clip.w
176
- mirror.projectionMatrixInverse.copy(pm).invert()
177
  mesh.visible = false
178
  const prevRT = renderer.getRenderTarget()
179
  const prevShadow = renderer.shadowMap.autoUpdate
180
  renderer.shadowMap.autoUpdate = false
 
181
  renderer.setRenderTarget(rt)
182
  renderer.clear()
183
  renderer.render(scene, mirror)
184
  renderer.setRenderTarget(prevRT)
 
185
  renderer.shadowMap.autoUpdate = prevShadow
186
  mesh.visible = true
187
  }
 
39
  return mix(mix(h21(i), h21(i + vec2(1, 0)), u.x), mix(h21(i + vec2(0, 1)), h21(i + vec2(1, 1)), u.x), u.y);
40
  }
41
  // height of the water surface ripples
42
+ float wave(vec2 p, float detail) {
43
  float t = uTime;
44
  float h = 0.0;
45
  h += sin(dot(p, vec2(0.62, 0.21)) * 1.1 + t * 1.3) * 0.5;
46
  h += sin(dot(p, vec2(-0.35, 0.78)) * 1.7 + t * 1.7) * 0.32;
47
  h += sin(dot(p, vec2(0.9, -0.5)) * 2.9 + t * 2.3) * 0.18;
48
  h += vn(p * 1.3 + vec2(t * 0.35, t * 0.12)) * 0.6;
49
+ h += vn(p * 3.7 - vec2(t * 0.6, -t * 0.2)) * 0.25 * detail;
50
+ h += vn(p * 9.0 + vec2(t * 0.9, t * 0.4)) * 0.1 * detail * detail;
51
  return h;
52
  }
53
 
54
  void main() {
55
  vec2 p = vWorld.xz;
56
+ float camDist = length(cameraPosition - vWorld);
57
+ float detail = 1.0 - smoothstep(25.0, 140.0, camDist);
58
+ float e = mix(0.08, 0.6, smoothstep(20.0, 200.0, camDist));
59
+ float h0 = wave(p, detail);
60
+ vec2 grad = vec2(wave(p + vec2(e, 0.0), detail) - h0, wave(p + vec2(0.0, e), detail) - h0) / e;
61
+ float amp = mix(0.09, 0.022, vCalm) * mix(1.0, 0.45, smoothstep(40.0, 300.0, camDist));
62
  vec3 N = normalize(vec3(-grad.x * amp, 1.0, -grad.y * amp));
63
 
64
  vec3 V = normalize(cameraPosition - vWorld);
 
77
  // sun glitter
78
  vec3 R = reflect(-V, N);
79
  float sd = max(dot(R, uSunDir), 0.0);
80
+ col += uSunCol * (pow(sd, 900.0) * 5.0 * detail + pow(sd, 120.0) * 0.45) * uSunI * smoothstep(-0.01, 0.03, uSunDir.y);
81
  col = applyWorldFog(col, vWorld);
82
  if (uDebug > 1.5) col = vec3(uv, 0.0);
83
  else if (uDebug > 0.5) col = refl;
 
122
  geo.computeBoundingSphere()
123
 
124
  const rt = new THREE.WebGLRenderTarget(512, 512, { type: THREE.HalfFloatType, samples: 0 })
125
+ // float depth: together with the reversed depth buffer this removes distant z-fighting
126
+ rt.depthTexture = new THREE.DepthTexture(512, 512, THREE.FloatType)
127
  const textureMatrix = new THREE.Matrix4()
128
  const uniforms: Record<string, THREE.IUniform> = {
129
  tReflect: { value: rt.texture },
 
140
  mesh.receiveShadow = false
141
 
142
  const mirror = new THREE.PerspectiveCamera()
143
+ mirror.layers.set(0) // objects on layer 1 (vegetation, people, small props…) are not reflected
144
  const normal = new THREE.Vector3(0, 1, 0)
 
 
 
145
  const camPos = new THREE.Vector3(), look = new THREE.Vector3(), target = new THREE.Vector3(), rot = new THREE.Matrix4()
146
  const origin = new THREE.Vector3(0, 0, 0)
147
+ // clip everything below the water surface (works with any depth convention)
148
+ const clipPlanes = [new THREE.Plane(new THREE.Vector3(0, 1, 0), 0.05)]
149
+ const noClip: THREE.Plane[] = []
150
 
151
  const renderReflection = (renderer: THREE.WebGLRenderer, scene: THREE.Scene, camera: THREE.PerspectiveCamera) => {
152
  camPos.setFromMatrixPosition(camera.matrixWorld)
 
159
  mirror.position.copy(view)
160
  mirror.up.set(0, 1, 0).applyMatrix4(rot).reflect(normal)
161
  mirror.lookAt(target)
162
+ mirror.fov = camera.fov
163
+ mirror.aspect = camera.aspect
164
  mirror.near = camera.near
165
+ mirror.far = camera.far
166
+ mirror.updateProjectionMatrix()
167
  mirror.updateMatrixWorld()
168
+ // x/y rows of the projection are identical for standard and reversed depth
169
  textureMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1)
170
  textureMatrix.multiply(mirror.projectionMatrix).multiply(mirror.matrixWorldInverse)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  mesh.visible = false
172
  const prevRT = renderer.getRenderTarget()
173
  const prevShadow = renderer.shadowMap.autoUpdate
174
  renderer.shadowMap.autoUpdate = false
175
+ renderer.clippingPlanes = clipPlanes
176
  renderer.setRenderTarget(rt)
177
  renderer.clear()
178
  renderer.render(scene, mirror)
179
  renderer.setRenderTarget(prevRT)
180
+ renderer.clippingPlanes = noClip
181
  renderer.shadowMap.autoUpdate = prevShadow
182
  mesh.visible = true
183
  }
src/jiangnan/export/covers.ts CHANGED
@@ -26,12 +26,13 @@ export function renderCover(film: Film, d: CoverDesign, ratio: Ratio): HTMLCanva
26
  const R = RATIOS.find((r) => r.id === ratio)!
27
  const W = R.w, H = R.h
28
  const prevW = film.width, prevH = film.height
29
- film.setSize(W, H)
30
  film.renderFrame(d.t)
31
  const c = document.createElement('canvas')
32
  c.width = W
33
  c.height = H
34
  const g = c.getContext('2d')!
 
35
  g.drawImage(film.renderer.domElement, 0, 0, W, H)
36
  film.setSize(prevW, prevH)
37
  const u = Math.min(W, H)
 
26
  const R = RATIOS.find((r) => r.id === ratio)!
27
  const W = R.w, H = R.h
28
  const prevW = film.width, prevH = film.height
29
+ film.setSize(Math.round(W * 1.5), Math.round(H * 1.5)) // supersampled
30
  film.renderFrame(d.t)
31
  const c = document.createElement('canvas')
32
  c.width = W
33
  c.height = H
34
  const g = c.getContext('2d')!
35
+ g.imageSmoothingQuality = 'high'
36
  g.drawImage(film.renderer.domElement, 0, 0, W, H)
37
  film.setSize(prevW, prevH)
38
  const u = Math.min(W, H)
src/jiangnan/export/livegen.ts CHANGED
@@ -66,7 +66,8 @@ export async function generateLivePhotos(film: Film, onProgress: (p: number, lab
66
  comp.height = H
67
  const g = comp.getContext('2d')!
68
  const prevW = film.width, prevH = film.height
69
- film.setSize(W, H)
 
70
  try {
71
  for (let ci = 0; ci < clips.length; ci++) {
72
  const clip = clips[ci]
 
66
  comp.height = H
67
  const g = comp.getContext('2d')!
68
  const prevW = film.width, prevH = film.height
69
+ film.setSize(Math.round(W * 1.4), Math.round(H * 1.4)) // supersampled
70
+ g.imageSmoothingQuality = 'high'
71
  try {
72
  for (let ci = 0; ci < clips.length; ci++) {
73
  const clip = clips[ci]
src/jiangnan/export/mp4.ts CHANGED
@@ -106,7 +106,11 @@ export async function exportMp4(film: Film, o: ExportOptions): Promise<{ blob: B
106
  comp.height = H
107
  const g = comp.getContext('2d')!
108
  const prevW = film.width, prevH = film.height
109
- film.setSize(W, H)
 
 
 
 
110
  const t0 = performance.now()
111
  try {
112
  for (let i = 0; i < total; i++) {
 
106
  comp.height = H
107
  const g = comp.getContext('2d')!
108
  const prevW = film.width, prevH = film.height
109
+ // supersampling: render larger, then filter down → crisp edges, no crawling on fine detail
110
+ const ss = W * H <= 1280 * 720 ? 2 : 1.5
111
+ film.setSize(Math.round(W * ss), Math.round(H * ss))
112
+ g.imageSmoothingEnabled = true
113
+ g.imageSmoothingQuality = 'high'
114
  const t0 = performance.now()
115
  try {
116
  for (let i = 0; i < total; i++) {
tools/jiangnan/analyze.py CHANGED
@@ -77,21 +77,19 @@ def main():
77
  pg.on('console', lambda m: logs.append(m.type + ': ' + m.text) if m.type in ('error', 'warning') else None)
78
  pg.on('pageerror', lambda e: logs.append('PAGEERROR: ' + str(e)))
79
  t0 = time.time()
80
- pg.goto(f'{BASE}?w={w}&h={h}&t={times[0]}', timeout=180000)
81
  pg.wait_for_function("document.title === 'ready' || document.title === 'error'", timeout=900000)
82
  print('init', round(time.time() - t0, 1), 's', pg.title())
83
  for t in times:
84
  print(f'\n===== t={t} =====')
85
  if mode in ('both', 'final'):
86
- pg.evaluate(f"window.__film.renderFrame({t})")
87
- data = pg.evaluate("document.querySelector('canvas').toDataURL('image/jpeg', 0.9)")
88
  img = Image.open(io.BytesIO(base64.b64decode(data.split(',')[1])))
89
  img.save(f'{out}/t{t:05.1f}.jpg')
90
  print(stats(img))
91
  print(ascii_lum(img))
92
  if mode in ('both', 'ids'):
93
- pg.evaluate(f"window.__ids({t})")
94
- data = pg.evaluate("document.querySelector('canvas').toDataURL('image/png')")
95
  img = Image.open(io.BytesIO(base64.b64decode(data.split(',')[1])))
96
  img.save(f'{out}/ids{t:05.1f}.png')
97
  print(ascii_ids(img))
 
77
  pg.on('console', lambda m: logs.append(m.type + ': ' + m.text) if m.type in ('error', 'warning') else None)
78
  pg.on('pageerror', lambda e: logs.append('PAGEERROR: ' + str(e)))
79
  t0 = time.time()
80
+ pg.goto(f'{BASE}?w={w}&h={h}&noaudio=1&t={times[0]}', timeout=180000)
81
  pg.wait_for_function("document.title === 'ready' || document.title === 'error'", timeout=900000)
82
  print('init', round(time.time() - t0, 1), 's', pg.title())
83
  for t in times:
84
  print(f'\n===== t={t} =====')
85
  if mode in ('both', 'final'):
86
+ data = pg.evaluate(f"(() => {{ window.__film.renderFrame({t}); return window.__film.renderer.domElement.toDataURL('image/jpeg', 0.9) }})()")
 
87
  img = Image.open(io.BytesIO(base64.b64decode(data.split(',')[1])))
88
  img.save(f'{out}/t{t:05.1f}.jpg')
89
  print(stats(img))
90
  print(ascii_lum(img))
91
  if mode in ('both', 'ids'):
92
+ data = pg.evaluate(f"(() => {{ window.__ids({t}); return window.__film.renderer.domElement.toDataURL('image/png') }})()")
 
93
  img = Image.open(io.BytesIO(base64.b64decode(data.split(',')[1])))
94
  img.save(f'{out}/ids{t:05.1f}.png')
95
  print(ascii_ids(img))
tools/jiangnan/t_flick4.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys, io, base64
2
+ sys.path.insert(0, '/workspaces/space/tools')
3
+ from analyze import *
4
+ times = [float(x) for x in sys.argv[1].split(',')]
5
+ with sync_playwright() as p:
6
+ b = p.chromium.launch(args=['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist', '--disable-dev-shm-usage'])
7
+ pg = b.new_page(viewport={'width': 1000, 'height': 600})
8
+ pg.goto(BASE + '?w=960&h=540&noaudio=1', timeout=180000)
9
+ pg.wait_for_function("document.title === 'ready' || document.title === 'error'", timeout=900000)
10
+ pg.evaluate("window.__film.post.grade.uniforms.uGrain.value = 0")
11
+ for t0 in times:
12
+ pg.evaluate(f"window.__film.freezeCam = {t0}")
13
+ fr = []
14
+ for k in range(3):
15
+ d = pg.evaluate(f"(() => {{ window.__film.renderFrame({t0 + k / 30}); return window.__film.renderer.domElement.toDataURL('image/png') }})()")
16
+ fr.append(list(Image.open(io.BytesIO(base64.b64decode(d.split(',')[1]))).convert('L').getdata()))
17
+ d = pg.evaluate(f"(() => {{ window.__ids({t0 + 1 / 30}); return window.__film.renderer.domElement.toDataURL('image/png') }})()")
18
+ ids = list(Image.open(io.BytesIO(base64.b64decode(d.split(',')[1]))).convert('RGB').getdata())
19
+ cnt, tot, n = {}, {}, 0
20
+ for i in range(len(ids)):
21
+ c = classify(ids[i]); tot[c] = tot.get(c, 0) + 1
22
+ x, y, z = fr[0][i], fr[1][i], fr[2][i]
23
+ if abs(y - x) > 12 and abs(y - z) > 12 and (y - x) * (y - z) > 0:
24
+ cnt[c] = cnt.get(c, 0) + 1; n += 1
25
+ print(f't={t0} static-camera flicker pixels {n / len(ids) * 100:.3f}% ' + ' '.join(f'{c}:{cnt[c] / tot[c] * 100:.2f}%' for c in sorted(cnt, key=lambda k: -cnt[k])[:8]), flush=True)
26
+ b.close()
tools/jiangnan/t_perf.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys, time, json
2
+ sys.path.insert(0, '/workspaces/space/tools')
3
+ from analyze import *
4
+ times = [float(x) for x in sys.argv[1].split(',')]
5
+ with sync_playwright() as p:
6
+ b = p.chromium.launch(args=['--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist', '--disable-dev-shm-usage'])
7
+ pg = b.new_page(viewport={'width': 400, 'height': 300})
8
+ pg.goto(BASE + '?w=320&h=180&noaudio=1', timeout=180000)
9
+ pg.wait_for_function("document.title === 'ready' || document.title === 'error'", timeout=900000)
10
+ for t in times:
11
+ r = pg.evaluate(f"""(() => {{ const f = window.__film; const i = f.renderer.info; i.autoReset = false; i.reset();
12
+ const t0 = performance.now(); f.renderFrame({t}); const dt = performance.now() - t0;
13
+ const o = {{ calls: i.render.calls, tris: i.render.triangles, points: i.render.points, ms: Math.round(dt), progs: i.programs.length, tex: i.memory.textures, geo: i.memory.geometries }};
14
+ i.autoReset = true; return JSON.stringify(o) }})()""")
15
+ print(t, r, flush=True)
16
+ b.close()