threejs-towers

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Three.js Towers

Three.js 塔楼

Architecture is the one subject where procedural generation pays immediately: buildings are made of repeated, parameterised parts, and once you have the vocabulary a second style costs a parameter set rather than a model.
Stand it in
threejs-landscape
and weather it with
threejs-weather
.
建筑是程序化生成能立刻见效的领域:建筑由重复的参数化部件构成,一旦拥有了这套几何词汇表,生成另一种风格只需一套参数集,而非重新建模。
可将其置于
threejs-landscape
场景中,并通过
threejs-weather
实现风化效果。

Build the vocabulary before the building

先构建几何词汇表,再搭建建筑

Write ten small builders that all append into shared vertex/normal/UV/index arrays, then never write raw geometry again:
txt
face(P, uv)                     quad with a computed normal
box(cx,cy,cz, sx,sy,sz, ry, uvScale, rz)
prism(y0,y1, R0,R1, uv, capTop, capBot)          square on plan
prismN(y0,y1, R0,R1, n, uv, capTop, capBot)      any n-gon
sweepPlan(plan, y0,y1, steps, profile)           an outline scaled up a curve
lathe(cx,cy,cz, y0,y1, profile, steps, seg)      surface of revolution
ring / arc                                        annulus on a face plane
fan(points, z, ry, cx, cy)                        filled polygon on a face
tube(points, r, sides)                            swept tube
That set covers a Japanese keep, a Chinese pagoda, an Ottoman dome, a Khmer prasat and a Vietnamese tháp. Each style becomes one assembly function plus a table of levels.
Merge by material, not by part. Six buildings drawn in 11–18 draw calls is the difference between 120fps and 30.
Winding is the bug you will hit most. A prism whose side faces are wound inward gets back-face culled and you find yourself looking at the inside of the far wall. Get one prism right, then copy its vertex order everywhere. When a surface goes missing, suspect winding before you suspect anything else.
编写十个小型构建函数,所有函数都将数据追加到共享的顶点/法线/UV/索引数组中,从此无需再编写原始几何代码:
txt
face(P, uv)                     带计算法线的四边形
box(cx,cy,cz, sx,sy,sz, ry, uvScale, rz)
prism(y0,y1, R0,R1, uv, capTop, capBot)          平面正方形棱柱
prismN(y0,y1, R0,R1, n, uv, capTop, capBot)      任意n边形棱柱
sweepPlan(plan, y0,y1, steps, profile)           沿曲线缩放轮廓生成模型
lathe(cx,cy,cz, y0,y1, profile, steps, seg)      旋转曲面
ring / arc                                        面平面上的圆环/圆弧
fan(points, z, ry, cx, cy)                        面平面上的填充多边形
tube(points, r, sides)                            扫掠生成管道
这套函数可生成日式城堡、中式宝塔、奥斯曼穹顶、高棉 prasat(寺庙)和越南 tháp(塔)。每种风格只需一个组装函数加上一组层级参数表即可实现。
按材质合并模型,而非按部件合并。绘制6栋建筑只需11-18次绘制调用,这正是120fps和30fps的区别所在。
绕序问题是你最常遇到的bug。如果棱柱的侧面是向内绕序的,会被背面剔除,你会发现自己看到的是远端墙体的内侧。先把一个棱柱的绕序弄对,然后将其顶点顺序复制到所有地方。当某个面消失时,首先怀疑绕序问题,再排查其他原因。

Roofs are a function of position along the eave

屋顶形态由屋檐位置决定

The whole character of an East Asian roof — flat near the ridge, steepening, then curling up at the corners — comes from one function that maps (panel, position across, position down) to a point:
js
function roofPoint(o, p, u, t) {
  const tc = Math.min(1, t);
  const g = 1 - Math.pow(1 - tc, o.pow);              // the sag of the slope
  const corner = Math.pow(Math.abs(u), 2.0);          // 0 mid-eave, 1 at hips
  const flare = 1 + o.flare * corner * Math.pow(tc, 3.2);
  const y = o.yT - (o.yT - o.yE) * g
          + o.lift * corner * Math.pow(tc, 2.6);      // corners lift
  return [ /* lerp inner edge → outer edge × flare */ ];
}
Six numbers give you every roof in the set:
lift
,
tip
,
flare
,
pow
,
trunc
,
ridge
.
trunc
is the one that is easy to miss — it lets a lower roof die cleanly behind the wall above it instead of poking through.
Math.pow(negative, 2.35)
is NaN.
Tiles that overshoot the eave push
t
past 1, and the whole roof silently disappears. Clamp
tc = Math.min(1, t)
and handle the overshoot as a separate linear term.
东亚屋顶的整体特征——屋脊附近平缓,逐渐变陡,边角向上翘起——都来自一个函数,该函数将*(面板、横向位置、纵向位置)*映射为一个点:
js
function roofPoint(o, p, u, t) {
  const tc = Math.min(1, t);
  const g = 1 - Math.pow(1 - tc, o.pow);              // 坡度的弧度
  const corner = Math.pow(Math.abs(u), 2.0);          // 屋檐中间为0,屋脊处为1
  const flare = 1 + o.flare * corner * Math.pow(tc, 3.2);
  const y = o.yT - (o.yT - o.yE) * g
          + o.lift * corner * Math.pow(tc, 2.6);      // 边角上翘
  return [ /* 内边缘 → 外边缘 × flare 的线性插值 */ ];
}
六个参数即可生成这套系统中的所有屋顶:
lift
tip
flare
pow
trunc
ridge
trunc
是最容易被忽略的参数——它能让下层屋顶干净地收于上层墙体之后,而非穿透墙体。
Math.pow(负数, 2.35)
会返回NaN
。如果瓦片超出屋檐,会导致
t
超过1,整个屋顶会无声无息地消失。将
tc = Math.min(1, t)
进行钳位处理,并将超出部分作为单独的线性项处理。

Non-square plans

非正方形平面

prismN
handles octagons and sixteen-sided drums. For anything with re-entrant corners — a Khmer prasat is a square pushed out on each axis and stepped back twice before the corner — build the outline once and sweep it:
js
const oct = [[1+P,0],[1+P,0.30],[1.0,0.30],[1.0,0.45],[0.90,0.45], ... ];
const half = oct.concat(oct.slice(0,-1).reverse().map(q => [q[1], q[0]]));
// mirror across the diagonal, then rotate four times
Then every storey is the same outline at a smaller scale, and the silhouette is coherent for free.
Deck the ledges. Where a storey steps back onto the one above, the gap between the two outlines is open. Fill it with a flat annulus on the plan or the tower reads as a stack of floating shelves with daylight between them.
prismN
可处理八边形和十六边形鼓形结构。对于带有凹角的建筑——比如高棉 prasat 是一个正方形,每条边向外突出,在转角处两次后退——只需先构建轮廓,再进行扫掠:
js
const oct = [[1+P,0],[1+P,0.30],[1.0,0.30],[1.0,0.45],[0.90,0.45], ... ];
const half = oct.concat(oct.slice(0,-1).reverse().map(q => [q[1], q[0]]));
// 沿对角线镜像,然后旋转四次
这样每个楼层都是同一轮廓按比例缩小,轮廓会自然保持连贯。
填充边缘空隙。当某个楼层退到上层结构之后时,两个轮廓之间的空隙是开放的。用平面圆环填充这个空隙,否则塔楼会看起来像一堆悬浮的架子,层与层之间透进光线。

Size detail to the surface it sits on

根据表面尺寸调整细节比例

The most common modelling mistake is not the geometry, it is the proportion. A doorway sized for a face that turns out to be a third as wide spills onto the returns and reads as noise. Measure the face first, then size the door, the colonnettes and the pediment as fractions of it — and check that the pediment finishes under the cornice rather than through it.
最常见的建模错误不是几何问题,而是比例问题。如果为某个面设计的门洞最终发现该面宽度只有预期的三分之一,门洞会延伸到侧面,看起来像噪音。应先测量面的尺寸,然后将门、小柱和山墙按该尺寸的比例进行调整——还要确保山墙收尾在檐口下方,而非穿透檐口。

The build animation is one clipping plane

构建动画仅需一个裁剪平面

Everything exists from the first frame. A plane facing down travels up, and every structural material clips against it:
js
renderer.localClippingEnabled = true;
const CLIP = new THREE.Plane(new THREE.Vector3(0, -1, 0), 0);
['stone','plaster','tile','timber', ...].forEach(k => {
  MAT[k].clippingPlanes = [CLIP];
  MAT[k].clipShadows = true;                     // or the shadow builds early
});
CLIP.constant = heightAt(t);
A clipped shell is hollow, so add a cap mesh at the plane's height, scaled to the footprint. That is what turns a see-through section into what reads as a solid course of masonry.
The cap has to match the plan it is capping. A square cap dropped into an octagonal tower leaves four wedges open to the sky. Let each style declare the plan of its own section — four sides through a hall, eight through a drum, sixteen through a dome — and rebuild the cap geometry as the plane passes from one into the next:
js
caps: [[0, 4.74, 2.56], [4.74, 5.42, 2.02, 8], [5.42, 6.46, 1.86, 16]]
//      y0    y1   radius  sides
For interiors, a capped inner volume on a
DoubleSide
dark material reads as solid stone from any angle, and costs almost nothing.
所有物体从第一帧就已存在。一个向下的平面向上移动,所有结构材质都将被该平面裁剪:
js
renderer.localClippingEnabled = true;
const CLIP = new THREE.Plane(new THREE.Vector3(0, -1, 0), 0);
['stone','plaster','tile','timber', ...].forEach(k => {
  MAT[k].clippingPlanes = [CLIP];
  MAT[k].clipShadows = true;                     // 否则阴影会提前生成
});
CLIP.constant = heightAt(t);
被裁剪的外壳是中空的,因此需要在平面高度处添加一个与建筑占地面积匹配的顶盖网格。这样就能将透明截面转化为看起来是实心砖石层的效果。
顶盖必须与它所覆盖的平面形状匹配。将正方形顶盖放入八边形塔楼中,会留下四个楔形空隙暴露在外。让每种风格都声明其自身截面的平面形状——大厅为四边形,鼓形结构为八边形,穹顶为十六边形——并在平面从一种形状过渡到另一种形状时重新构建顶盖几何:
js
caps: [[0, 4.74, 2.56], [4.74, 5.42, 2.02, 8], [5.42, 6.46, 1.86, 16]]
//      y0    y1   半径  边数
对于内部空间,使用
DoubleSide
深色材质的带顶盖内部体积,从任何角度看都像实心石材,且几乎不增加性能开销。

Scaffolding is the exception to the plane

脚手架是不受裁剪平面限制的例外

It ignores the clip, so it always stands one step ahead of the finished work. That single relationship is what makes the animation read as construction rather than as a wipe.
BoxGeometry
gives every face UVs of 0..1 regardless of size.
A three-metre pole and a fifteen-centimetre brace therefore get the same grain, and both read as plastic. Rewrite the UVs in world units before upload:
js
const dims = [[sz,sy],[sz,sy],[sx,sz],[sx,sz],[sx,sy],[sx,sy]];
for (let f = 0; f < 6; f++) {
  const du = dims[f][0], dv = dims[f][1], swap = dv > du;
  for (let i = 0; i < 4; i++) { /* scale by real size, offset randomly */ }
}
Grow each tier in with a short eased scale — verticals scale in Y, horizontals in X — and let it fall away just before the next stage lands.
脚手架不受裁剪影响,因此始终比已完成的建筑超前一步。正是这种单一关系让动画看起来像是在建造,而非简单的擦除效果。
BoxGeometry
会为每个面赋予0..1的UV坐标,无论尺寸大小
。三米长的柱子和十五厘米的支撑会得到相同的纹理,看起来都像塑料。在上传前按世界单位重写UV坐标:
js
const dims = [[sz,sy],[sz,sy],[sx,sz],[sx,sz],[sx,sy],[sx,sy]];
for (let f = 0; f < 6; f++) {
  const du = dims[f][0], dv = dims[f][1], swap = dv > du;
  for (let i = 0; i < 4; i++) { /* 按实际尺寸缩放,随机偏移 */ }
}
让每一层脚手架通过短时间的缓动缩放进入场景——垂直构件沿Y轴缩放,水平构件沿X轴缩放——并在下一阶段建筑落地前让脚手架消失。

Stages carry the timeline

阶段划分承载时间线

Give each style a list of
[local caption, ENGLISH, target height]
and ease the plane between targets. The caption names what is happening, which is most of what makes a construction study legible:
js
stages: [['準備','READY',0.00], ['石垣普請','STONEWORK',3.36],
         ['柱梁組立','TIMBER',6.24], ['白壁塗籠','PLASTER',8.80], ...]
Fire a one-shot sound on each stage change and a bell on the last. Keep the whole build short — four to five seconds — and put a large percentage somewhere quiet in the frame. People will rebuild it repeatedly if it is fast.
为每种风格提供一个
[本地标题, 英文标题, 目标高度]
的列表,让裁剪平面在目标高度之间缓动过渡。标题说明当前正在进行的操作,这是让建筑研究清晰易懂的关键:
js
stages: [['準備','READY',0.00], ['石垣普請','STONEWORK',3.36],
         ['柱梁組立','TIMBER',6.24], ['白壁塗籠','PLASTER',8.80], ...]
每个阶段切换时播放一次音效,最后一个阶段播放钟声。整个构建过程要短——4到5秒——并在画面的某个安静区域显示较大的进度百分比。如果过程很快,人们会反复观看。

Emissive light leaks

自发光材质漏光问题

If you light windows at night with an emissive material, that glow escapes through every opening you did not deck: under eaves, through truncated roofs, out of hollow storeys. Deck the truncated roofs and split enclosed volumes onto a non-emissive material. The symptom is a building that glows along its silhouette like a lantern.
如果在夜间用自发光材质照亮窗户,光线会从所有未填充的开口漏出:屋檐下、被截断的屋顶处、中空楼层。填充被截断的屋顶,并将封闭体积设置为非自发光材质。漏光的表现是建筑轮廓像灯笼一样发光。

What to check before you call it done

完成前需要检查的事项

  • Orbit a full turn at ground level. Missing walls are inverted winding; long bars flying out of faces are a rotation sign error on face-mounted boxes.
  • Scrub the timeline slowly through every stage. The cap should stay inside the walls at every height, and never poke out at the corners.
  • Look at the roof from directly above once. Overshooting tiles and NaN panels only show from there.
  • Switch styles ten times. If memory climbs, you are not disposing the previous group's geometries.
  • Count draw calls per style. If one style is triple the others, a material is not shared.
  • 在地面高度完整旋转一周查看。缺失的墙体是因为绕序反转;从墙面伸出的长条是因为面挂载盒子时旋转符号错误。
  • 缓慢拖动时间线查看每个阶段。顶盖在任何高度都应保持在墙体内部,绝不能在边角处突出。
  • 从正上方查看屋顶一次。超出屋檐的瓦片和NaN面板只有从这个角度才能看到。
  • 切换十种风格。如果内存占用上升,说明你没有释放之前模型组的几何资源。
  • 统计每种风格的绘制调用次数。如果某一种风格的调用次数是其他风格的三倍,说明材质没有共享。