Prompt specification
Build or customize the Three.js 3D scene "Loess Plateau terraced slope and village scene" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Loess Plateau terraced slope and village scene
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/loess-plateau-terraced-slope-and-village-scene-x3059
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring gullies and terraces on China's Loess Plateau. Build a bounded referenced landscape with rounded uplands, branching gullies, terraces, and a modest settlement. Avoid replacing the complex terrain with identical stair-step blocks. Low-poly.
Working Three.js Starter (loess-plateau-terraced-slope-and-village-scene-x3059):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Loess Plateau — Terraces & Gullies</title>
<style>
:root {
color-scheme: light;
--ink: #2f3028;
--paper: rgba(245, 239, 220, 0.88);
--line: rgba(68, 59, 42, 0.25);
--olive: #707c46;
--ochre: #ad8750;
--umber: #765a3d;
}
* { box-sizing: border-box; }
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 72% 18%, rgba(255, 249, 222, 0.9), transparent 28%),
linear-gradient(180deg, #cbd6d2 0%, #ddd5bd 52%, #b4a185 100%);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--ink);
}
#stage {
position: fixed;
inset: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
canvas:active { cursor: grabbing; }
.panel {
position: fixed;
z-index: 5;
pointer-events: none;
background: var(--paper);
border: 1px solid var(--line);
box-shadow: 0 12px 36px rgba(73, 59, 36, 0.12);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
#title-card {
top: 24px;
left: 24px;
width: min(390px, calc(100vw - 48px));
padding: 19px 21px 17px;
border-radius: 3px;
}
.eyebrow {
margin-bottom: 8px;
color: #76684f;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.19em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(27px, 4vw, 39px);
font-weight: 500;
line-height: 0.98;
letter-spacing: -0.025em;
}
#title-card p {
margin: 12px 0 16px;
max-width: 330px;
color: #5e5a4e;
font-size: 12px;
line-height: 1.55;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 8px 15px;
padding-top: 13px;
border-top: 1px solid var(--line);
}
.legend span {
display: inline-flex;
align-items: center;
gap: 7px;
color: #625d50;
font-size: 10px;
letter-spacing: 0.055em;
text-transform: uppercase;
}
.legend i {
width: 9px;
height: 9px;
border-radius: 2px;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.08);
}
.legend .terrace { background: var(--olive); }
.legend .gully { background: var(--umber); }
.legend .village { background: #625347; }
#compass {
top: 24px;
right: 24px;
width: 72px;
height: 72px;
display: grid;
place-items: center;
border-radius: 50%;
}
#needle {
position: relative;
width: 30px;
height: 43px;
transform-origin: 50% 58%;
transition: transform 80ms linear;
}
#needle::before {
content: "";
position: absolute;
left: 10px;
top: 13px;
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 18px solid #3c4634;
}
#needle::after {
content: "";
position: absolute;
left: 10px;
top: 22px;
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 14px solid #a58b64;
}
#north {
position: absolute;
top: 7px;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
}
#meta {
right: 24px;
bottom: 24px;
padding: 11px 14px;
color: #686253;
font-size: 9px;
line-height: 1.65;
letter-spacing: 0.08em;
text-align: right;
text-transform: uppercase;
}
#controls {
left: 24px;
bottom: 24px;
padding: 10px 13px;
color: #665f50;
font-size: 10px;
letter-spacing: 0.025em;
}
.annotation {
position: fixed;
z-index: 4;
display: flex;
align-items: center;
gap: 7px;
pointer-events: none;
transform: translate(-50%, -50%);
opacity: 0;
transition: opacity 160ms ease;
white-space: nowrap;
}
.annotation i {
width: 7px;
height: 7px;
border: 2px solid rgba(248, 242, 223, 0.95);
border-radius: 50%;
background: #66503a;
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.3);
}
.annotation span {
padding: 4px 7px 3px;
border: 1px solid rgba(248, 242, 223, 0.45);
background: rgba(66, 57, 43, 0.73);
color: #f7f0dc;
font-size: 8px;
font-weight: 750;
letter-spacing: 0.12em;
text-transform: uppercase;
backdrop-filter: blur(4px);
}
#loading {
position: fixed;
z-index: 10;
inset: 0;
display: grid;
place-items: center;
background: #d5d0bd;
color: #665a45;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.18em;
text-transform: uppercase;
transition: opacity 400ms ease;
}
@media (max-width: 720px) {
#title-card {
top: 14px;
left: 14px;
width: calc(100vw - 28px);
padding: 14px 16px;
}
#title-card p { display: none; }
.legend { margin-top: 12px; }
#compass { top: auto; right: 14px; bottom: 58px; width: 58px; height: 58px; }
#controls { left: 14px; bottom: 14px; }
#meta { display: none; }
.annotation span { font-size: 7px; }
}
</style>
</head>
<body>
<main id="stage" aria-label="Interactive low-poly Loess Plateau landscape"></main>
<section id="title-card" class="panel">
<div class="eyebrow">Central Loess Plateau · China</div>
<h1>Terraces<br />& Gullies</h1>
<p>
An interpretive reconstruction of the rounded loess uplands, branching
erosion channels, contour fields, and small settlements characteristic
of the Loess Plateau.
</p>
<div class="legend" aria-label="Scene legend">
<span><i class="terrace"></i>Contour terraces</span>
<span><i class="gully"></i>Erosion gullies</span>
<span><i class="village"></i>Settlement</span>
</div>
</section>
<aside id="compass" class="panel" aria-label="North indicator">
<div id="north">N</div>
<div id="needle"></div>
</aside>
<div id="controls" class="panel">
Drag to orbit · Shift/right-drag to pan · Scroll to zoom
</div>
<div id="meta" class="panel">
120 × 100 m interpretive study<br />
Not survey geometry
</div>
<div id="label-terrace" class="annotation">
<i></i><span>Contour fields</span>
</div>
<div id="label-gully" class="annotation">
<i></i><span>Branching gully</span>
</div>
<div id="label-village" class="annotation">
<i></i><span>Settlement</span>
</div>
<div id="loading">Building loess landscape…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const stage = document.querySelector("#stage");
const loading = document.querySelector("#loading");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.75));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x000000, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Low-poly Loess Plateau landscape with branching gullies, terraces, and a village"
);
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0xd7cdb5, 145, 270);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
420
);
const hemisphere = new THREE.HemisphereLight(0xe9e4d2, 0x705638, 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffe2aa, 3.15);
sun.position.set(-58, 86, 43);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -84;
sun.shadow.camera.right = 84;
sun.shadow.camera.top = 72;
sun.shadow.camera.bottom = -72;
sun.shadow.camera.near = 4;
sun.shadow.camera.far = 190;
sun.shadow.bias = -0.00025;
sun.shadow.normalBias = 0.035;
scene.add(sun);
scene.add(sun.target);
const ambient = new THREE.AmbientLight(0xfff0d3, 0.24);
scene.add(ambient);
const WIDTH = 120;
const DEPTH = 100;
const NX = 97;
const NZ = 81;
const DX = WIDTH / (NX - 1);
const DZ = DEPTH / (NZ - 1);
const BASE_Y = -4.8;
// ---------------------------------------------------------------------
// Deterministic terrain functions
// ---------------------------------------------------------------------
function hash2(x, z) {
const n = Math.sin(x * 127.1 + z * 311.7 + 19.19) * 43758.5453123;
return n - Math.floor(n);
}
function smooth(t) {
return t * t * (3 - 2 * t);
}
function valueNoise(x, z) {
const ix = Math.floor(x);
const iz = Math.floor(z);
const fx = smooth(x - ix);
const fz = smooth(z - iz);
const a = hash2(ix, iz);
const b = hash2(ix + 1, iz);
const c = hash2(ix, iz + 1);
const d = hash2(ix + 1, iz + 1);
return (
a * (1 - fx) * (1 - fz) +
b * fx * (1 - fz) +
c * (1 - fx) * fz +
d * fx * fz
);
}
function fbm(x, z) {
let sum = 0;
let amplitude = 0.55;
let frequency = 1;
for (let i = 0; i < 4; i++) {
sum += valueNoise(x * frequency, z * frequency) * amplitude;
frequency *= 2.03;
amplitude *= 0.49;
}
return sum / 1.02;
}
function gaussianHill(x, z, cx, cz, rx, rz) {
const dx = (x - cx) / rx;
const dz = (z - cz) / rz;
return Math.exp(-(dx * dx + dz * dz));
}
const gullies = [
{
width: 3.65,
depth: 6.9,
points: [
[-6, -49], [-7, -35], [-4, -25], [-3, -17],
[1, -7], [6, 8], [4, 21], [8, 34], [7, 49]
]
},
{
width: 2.35,
depth: 4.9,
points: [
[-47, -31], [-36, -28], [-25, -21], [-13, -18], [-3, -17]
]
},
{
width: 2.2,
depth: 4.7,
points: [
[-37, -10], [-28, -6], [-18, -6], [-8, -8], [-3, -17]
]
},
{
width: 2.5,
depth: 5.1,
points: [
[42, -30], [33, -23], [22, -18], [12, -14], [-3, -17]
]
},
{
width: 2.35,
depth: 4.9,
points: [
[45, 18], [36, 14], [28, 7], [17, 1], [6, 8]
]
},
{
width: 2.2,
depth: 4.6,
points: [
[32, 38], [24, 32], [16, 25], [8, 20], [6, 8]
]
}
];
function nearestOnPath(x, z, points) {
let bestDistanceSq = Infinity;
let bestT = 0;
for (let i = 0; i < points.length - 1; i++) {
const ax = points[i][0];
const az = points[i][1];
const bx = points[i + 1][0];
const bz = points[i + 1][1];
const vx = bx - ax;
const vz = bz - az;
const lengthSq = vx * vx + vz * vz;
let t = ((x - ax) * vx + (z - az) * vz) / lengthSq;
t = THREE.MathUtils.clamp(t, 0, 1);
const qx = ax + vx * t;
const qz = az + vz * t;
const distanceSq = (x - qx) ** 2 + (z - qz) ** 2;
if (distanceSq < bestDistanceSq) {
bestDistanceSq = distanceSq;
bestT = (i + t) / (points.length - 1);
}
}
return { distance: Math.sqrt(bestDistanceSq), t: bestT };
}
function gullyInfo(x, z) {
let carve = 0;
let influence = 0;
for (const gully of gullies) {
const nearest = nearestOnPath(x, z, gully.points);
const shape = Math.exp(-Math.pow(nearest.distance / gully.width, 1.65));
const taper = 0.48 + 0.52 * nearest.t;
carve += gully.depth * shape * taper;
influence = Math.max(influence, shape);
}
return {
carve: Math.min(carve, 8.25),
influence
};
}
function heightAt(x, z) {
let h = 11.5;
h += 13.5 * gaussianHill(x, z, -31, -21, 19, 14);
h += 11.5 * gaussianHill(x, z, 34, -22, 15, 13);
h += 10.0 * gaussianHill(x, z, 29, 22, 17, 14);
h += 4.1 * gaussianHill(x, z, -44, 20, 14, 18);
h += (fbm(x * 0.035 + 4.2, z * 0.035 - 7.4) - 0.5) * 4.5;
h += (fbm(x * 0.105 - 11.0, z * 0.105 + 5.0) - 0.5) * 1.25;
h -= gullyInfo(x, z).carve;
return h;
}
function terrainSlope(x, z) {
const e = 0.7;
const dx = (heightAt(x + e, z) - heightAt(x - e, z)) / (2 * e);
const dz = (heightAt(x, z + e) - heightAt(x, z - e)) / (2 * e);
return Math.hypot(dx, dz);
}
// ---------------------------------------------------------------------
// Low-poly terrain surface
// ---------------------------------------------------------------------
const heights = new Float32Array(NX * NZ);
for (let iz = 0; iz < NZ; iz++) {
const z = -DEPTH / 2 + iz * DZ;
for (let ix = 0; ix < NX; ix++) {
const x = -WIDTH / 2 + ix * DX;
heights[iz * NX + ix] = heightAt(x, z);
}
}
const terrainPositions = [];
const terrainColors = [];
const lowEarth = new THREE.Color(0x947349);
const midEarth = new THREE.Color(0xc3a468);
const highEarth = new THREE.Color(0xd3b77b);
const gullyEarth = new THREE.Color(0x76563a);
const colorScratch = new THREE.Color();
function terrainColor(height, influence, variation, out) {
if (height < 18) {
out.lerpColors(lowEarth, midEarth, THREE.MathUtils.clamp((height - 5) / 13, 0, 1));
} else {
out.lerpColors(
midEarth,
highEarth,
THREE.MathUtils.clamp((height - 18) / 17, 0, 1)
);
}
out.lerp(gullyEarth, THREE.MathUtils.clamp(influence * 0.74, 0, 0.82));
out.multiplyScalar(0.95 + variation * 0.09);
return out;
}
function pushTerrainTriangle(a, b, c, color) {
terrainPositions.push(...a, ...b, ...c);
for (let i = 0; i < 3; i++) terrainColors.push(color.r, color.g, color.b);
}
let faceIndex = 0;
for (let iz = 0; iz < NZ - 1; iz++) {
const z0 = -DEPTH / 2 + iz * DZ;
const z1 = z0 + DZ;
for (let ix = 0; ix < NX - 1; ix++) {
const x0 = -WIDTH / 2 + ix * DX;
const x1 = x0 + DX;
const a = [x0, heights[iz * NX + ix], z0];
const b = [x1, heights[iz * NX + ix + 1], z0];
const c = [x1, heights[(iz + 1) * NX + ix + 1], z1];
const d = [x0, heights[(iz + 1) * NX + ix], z1];
const centerX = (x0 + x1) * 0.5;
const centerZ = (z0 + z1) * 0.5;
const averageHeight = (a[1] + b[1] + c[1] + d[1]) * 0.25;
const influence = gullyInfo(centerX, centerZ).influence;
const variation = hash2(ix * 0.71, iz * 0.63);
const color = terrainColor(
averageHeight,
influence,
variation,
colorScratch.clone()
);
pushTerrainTriangle(a, c, b, color);
pushTerrainTriangle(a, d, c, color);
faceIndex += 2;
}
}
const terrainGeometry = new THREE.BufferGeometry();
terrainGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(terrainPositions, 3)
);
terrainGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(terrainColors, 3)
);
terrainGeometry.computeVertexNormals();
terrainGeometry.computeBoundingSphere();
const terrainMaterial = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 1,
metalness: 0,
flatShading: true
});
const terrain = new THREE.Mesh(terrainGeometry, terrainMaterial);
terrain.receiveShadow = true;
scene.add(terrain);
// ---------------------------------------------------------------------
// Earth-colored skirt and bounded plinth
// ---------------------------------------------------------------------
const edgeSegments = [];
for (let ix = 0; ix < NX - 1; ix++) {
edgeSegments.push([
[-WIDTH / 2 + ix * DX, heights[ix]],
[-WIDTH / 2 + (ix + 1) * DX, heights[ix + 1]]
]);
}
for (let iz = 0; iz < NZ - 1; iz++) {
edgeSegments.push([
[WIDTH / 2, heights[iz * NX + NX - 1]],
[WIDTH / 2, heights[(iz + 1) * NX + NX - 1]]
]);
}
for (let ix = NX - 1; ix > 0; ix--) {
edgeSegments.push([
[-WIDTH / 2 + ix * DX, heights[(NZ - 1) * NX + ix]],
[-WIDTH / 2 + (ix - 1) * DX, heights[(NZ - 1) * NX + ix - 1]]
]);
}
for (let iz = NZ - 1; iz > 0; iz--) {
edgeSegments.push([
[-WIDTH / 2, heights[iz * NX]],
[-WIDTH / 2, heights[(iz - 1) * NX]]
]);
}
const skirtPositions = [];
const skirtColors = [];
const strata = [
new THREE.Color(0x9a7448),
new THREE.Color(0x815d39),
new THREE.Color(0x62442d)
];
const fractions = [0.72, 0.38, 0];
function pushSkirtTriangle(a, b, c, color) {
skirtPositions.push(...a, ...b, ...c);
for (let i = 0; i < 3; i++) skirtColors.push(color.r, color.g, color.b);
}
for (const segment of edgeSegments) {
const [a, b] = segment;
for (let layer = 0; layer < fractions.length; layer++) {
const aTopY = BASE_Y + (a[1] - BASE_Y) * fractions[layer];
const bTopY = BASE_Y + (b[1] - BASE_Y) * fractions[layer];
const aBottomY =
BASE_Y + (a[1] - BASE_Y) * (layer + 1 < fractions.length
? fractions[layer + 1]
: 0);
const bBottomY =
BASE_Y + (b[1] - BASE_Y) * (layer + 1 < fractions.length
? fractions[layer + 1]
: 0);
const aTop = [a[0], aTopY, 0];
const bTop = [b[0], bTopY, 0];
const aBottom = [a[0], aBottomY, 0];
const bBottom = [b[0], bBottomY, 0];
const color = strata[layer].clone().multiplyScalar(
0.94 + hash2(a[0], b[0]) * 0.09
);
pushSkirtTriangle(aTop, aBottom, bBottom, color);
pushSkirtTriangle(aTop, bBottom, bTop, color);
}
}
const skirtGeometry = new THREE.BufferGeometry();
skirtGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(skirtPositions, 3)
);
skirtGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(skirtColors, 3)
);
skirtGeometry.computeVertexNormals();
const skirt = new THREE.Mesh(
skirtGeometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 1,
flatShading: true,
side: THREE.DoubleSide
})
);
skirt.castShadow = true;
skirt.receiveShadow = true;
scene.add(skirt);
const plinth = new THREE.Mesh(
new THREE.BoxGeometry(WIDTH + 1.6, 1.25, DEPTH + 1.6),
new THREE.MeshStandardMaterial({ color: 0x65492f, roughness: 1 })
);
plinth.position.y = BASE_Y - 0.57;
plinth.castShadow = true;
plinth.receiveShadow = true;
scene.add(plinth);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(480, 480),
new THREE.MeshStandardMaterial({ color: 0xb8aa8e, roughness: 1 })
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = BASE_Y - 1.22;
floor.receiveShadow = true;
scene.add(floor);
// ---------------------------------------------------------------------
// Contour extraction for irregular terrace ribbons
// ---------------------------------------------------------------------
function contourLinesAtLevel(level) {
const segments = [];
const adjacency = new Map();
const pointMap = new Map();
const keyOf = (p) => `${Math.round(p.x * 1000)},${Math.round(p.z * 1000)}`;
function addSegment(a, b) {
const index = segments.length;
const aKey = keyOf(a);
const bKey = keyOf(b);
segments.push({ a: aKey, b: bKey });
pointMap.set(aKey, a);
pointMap.set(bKey, b);
if (!adjacency.has(aKey)) adjacency.set(aKey, []);
if (!adjacency.has(bKey)) adjacency.set(bKey, []);
adjacency.get(aKey).push(index);
adjacency.get(bKey).push(index);
}
for (let iz = 0; iz < NZ - 1; iz++) {
const z0 = -DEPTH / 2 + iz * DZ;
const z1 = z0 + DZ;
for (let ix = 0; ix < NX - 1; ix++) {
const x0 = -WIDTH / 2 + ix * DX;
const x1 = x0 + DX;
const p0 = { x: x0, z: z0, h: heights[iz * NX + ix] };
const p1 = { x: x1, z: z0, h: heights[iz * NX + ix + 1] };
const p2 = { x: x1, z: z1, h: heights[(iz + 1) * NX + ix + 1] };
const p3 = { x: x0, z: z1, h: heights[(iz + 1) * NX + ix] };
const edges = [
[p0, p1],
[p1, p2],
[p2, p3],
[p3, p0]
];
const crossings = [];
for (const [pa, pb] of edges) {
if ((pa.h >= level) === (pb.h >= level)) continue;
const t = (level - pa.h) / (pb.h - pa.h);
crossings.push({
x: pa.x + (pb.x - pa.x) * t,
z: pa.z + (pb.z - pa.z) * t
});
}
if (crossings.length === 2) {
addSegment(crossings[0], crossings[1]);
} else if (crossings.length === 4) {
addSegment(crossings[0], crossings[1]);
addSegment(crossings[2], crossings[3]);
}
}
}
const visited = new Uint8Array(segments.length);
const lines = [];
function walk(startIndex, startKey) {
const points = [];
let segmentIndex = startIndex;
let currentKey = startKey;
while (segmentIndex !== null) {
visited[segmentIndex] = 1;
const segment = segments[segmentIndex];
const otherKey = segment.a === currentKey ? segment.b : segment.a;
const otherPoint = pointMap.get(otherKey);
if (!otherPoint) break;
if (!points.length) {
points.push({ ...pointMap.get(currentKey) });
}
const last = points[points.length - 1];
if (Math.hypot(last.x - otherPoint.x, last.z - otherPoint.z) > 0.001) {
points.push({ ...otherPoint });
}
const nextCandidates = (adjacency.get(otherKey) || []).filter(
(index) => !visited[index]
);
if (!nextCandidates.length) break;
segmentIndex = nextCandidates[0];
currentKey = otherKey;
}
return points;
}
for (let i = 0; i < segments.length; i++) {
if (visited[i]) continue;
const segment = segments[i];
const aDegree = adjacency.get(segment.a)?.length || 0;
const bDegree = adjacency.get(segment.b)?.length || 0;
let startKey = segment.a;
if (bDegree === 1 && aDegree !== 1) startKey = segment.b;
const line = walk(i, startKey);
if (line.length > 2) lines.push(line);
}
return lines;
}
function terraceRuns(line, zone) {
const runs = [];
let current = [];
for (let i = 0; i < line.length - 1; i++) {
const a = line[i];
const b = line[i + 1];
const x = (a.x + b.x) * 0.5;
const z = (a.z + b.z) * 0.5;
const dx = (x - zone.cx) / zone.rx;
const dz = (z - zone.cz) / zone.rz;
const inside = dx * dx + dz * dz < 1.04;
const gully = gullyInfo(x, z).influence;
const brokenEdge = fbm(x * 0.16 + zone.phase, z * 0.16 - zone.phase) > 0.27;
if (inside && gully < 0.52 && brokenEdge) {
if (!current.length) current.push(a);
current.push(b);
} else if (current.length >= 3) {
runs.push(current);
current = [];
} else {
current = [];
}
}
if (current.length >= 3) runs.push(current);
return runs;
}
const terraceZones = [
{
cx: -31,
cz: -21,
rx: 18,
rz: 13,
phase: 2.1,
levels: [16, 19, 22, 25],
palette: [0x839052, 0x9b995b, 0xb1a064, 0x77874e]
},
{
cx: 34,
cz: -22,
rx: 14,
rz: 11,
phase: 8.4,
levels: [16, 19, 22],
palette: [0x7d8b4c, 0x96945a, 0xaaa064]
},
{
cx: 29,
cz: 22,
rx: 15,
rz: 12,
phase: 14.7,
levels: [15, 18, 21],
palette: [0x8b9255, 0xa29b5f, 0xb5a365]
}
];
const terracePositions = [];
const terraceColors = [];
const riserPositions = [];
const riserColors = [];
function pushColoredTriangle(positionArray, colorArray, a, b, c, color) {
positionArray.push(...a, ...b, ...c);
for (let i = 0; i < 3; i++) {
colorArray.push(color.r, color.g, color.b);
}
}
for (const zone of terraceZones) {
zone.levels.forEach((level, levelIndex) => {
const lines = contourLinesAtLevel(level);
for (const line of lines) {
const runs = terraceRuns(line, zone);
for (const run of runs) {
const midpoint = run[Math.floor(run.length / 2)];
const before = run[Math.max(0, Math.floor(run.length / 2) - 1)];
const after = run[Math.min(run.length - 1, Math.floor(run.length / 2) + 1)];
const tangent = new THREE.Vector2(
after.x - before.x,
after.z - before.z
).normalize();
const normal = new THREE.Vector2(-tangent.y, tangent.x);
const hPositive = heightAt(midpoint.x + normal.x, midpoint.z + normal.y);
const hNegative = heightAt(midpoint.x - normal.x, midpoint.z - normal.y);
const downhill = hPositive < hNegative ? normal.clone() : normal.clone().negate();
const baseColor = new THREE.Color(zone.palette[levelIndex]);
const topY = level + 0.13;
for (let i = 0; i < run.length - 1; i++) {
const p0 = run[i];
const p1 = run[i + 1];
const t0 = new THREE.Vector2(
p1.x - p0.x,
p1.z - p0.z
).normalize();
const t1 = new THREE.Vector2(
run[Math.min(i + 2, run.length - 1)].x - p0.x,
run[Math.min(i + 2, run.length - 1)].z - p0.z
).normalize();
const n0 = new THREE.Vector2(-t0.y, t0.x);
const n1 = new THREE.Vector2(-t1.y, t1.x);
if (n0.dot(downhill) < 0) n0.negate();
if (n1.dot(downhill) < 0) n1.negate();
const width0 = 2.15 + Math.sin(i * 0.71 + level) * 0.3;
const width1 = 2.15 + Math.sin((i + 1) * 0.71 + level) * 0.3;
const down0 = new THREE.Vector2(
p0.x + n0.x * width0 * 0.5,
p0.z + n0.y * width0 * 0.5
);
const down1 = new THREE.Vector2(
p1.x + n1.x * width1 * 0.5,
p1.z + n1.y * width1 * 0.5
);
const up0 = new THREE.Vector2(
p0.x - n0.x * width0 * 0.5,
p0.z - n0.y * width0 * 0.5
);
const up1 = new THREE.Vector2(
p1.x - n1.x * width1 * 0.5,
p1.z - n1.y * width1 * 0.5
);
const fieldColor = baseColor.clone().multiplyScalar(
0.92 + hash2(i, levelIndex + zone.cx) * 0.13
);
const a = [up0.x, topY, up0.y];
const b = [down0.x, topY, down0.y];
const c = [down1.x, topY, down1.y];
const d = [up1.x, topY, up1.y];
pushColoredTriangle(
terracePositions, terraceColors, a, b, c, fieldColor
);
pushColoredTriangle(
terracePositions, terraceColors, a, c, d, fieldColor
);
const foot0 = new THREE.Vector2(
down0.x + downhill.x * 0.14,
down0.y + downhill.y * 0.14
);
const foot1 = new THREE.Vector2(
down1.x + downhill.x * 0.14,
down1.y + downhill.y * 0.14
);
const bottomY0 = Math.min(
topY - 0.25,
heightAt(foot0.x, foot0.y) - 0.08
);
const bottomY1 = Math.min(
topY - 0.25,
heightAt(foot1.x, foot1.y) - 0.08
);
const soilColor = new THREE.Color(0x8f6d43).multiplyScalar(
0.94 + hash2(i + 17, level) * 0.1
);
pushColoredTriangle(
riserPositions,
riserColors,
[down0.x, topY, down0.y],
[foot0.x, bottomY0, foot0.y],
[foot1.x, bottomY1, foot1.y],
soilColor
);
pushColoredTriangle(
riserPositions,
riserColors,
[down0.x, topY, down0.y],
[foot1.x, bottomY1, foot1.y],
[down1.x, topY, down1.y],
soilColor
);
}
}
}
});
}
const terraceGeometry = new THREE.BufferGeometry();
terraceGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(terracePositions, 3)
);
terraceGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(terraceColors, 3)
);
terraceGeometry.computeVertexNormals();
const terraceMesh = new THREE.Mesh(
terraceGeometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 1,
flatShading: true,
side: THREE.DoubleSide
})
);
terraceMesh.castShadow = true;
terraceMesh.receiveShadow = true;
scene.add(terraceMesh);
const riserGeometry = new THREE.BufferGeometry();
riserGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(riserPositions, 3)
);
riserGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(riserColors, 3)
);
riserGeometry.computeVertexNormals();
const riserMesh = new THREE.Mesh(
riserGeometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 1,
flatShading: true,
side: THREE.DoubleSide
})
);
riserMesh.castShadow = true;
riserMesh.receiveShadow = true;
scene.add(riserMesh);
// ---------------------------------------------------------------------
// Village paths and low-poly houses
// ---------------------------------------------------------------------
function mulberry32(seed) {
return function () {
let t = seed += 0x6D2B79F5;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const random = mulberry32(82731);
function createGroundRibbon(points, width, color, lift = 0.075) {
const positions = [];
for (let i = 0; i < points.length - 1; i++) {
const a = points[i];
const b = points[i + 1];
const dx = b[0] - a[0];
const dz = b[1] - a[1];
const length = Math.hypot(dx, dz);
const nx = -dz / length * width * 0.5;
const nz = dx / length * width * 0.5;
const p0 = [a[0] - nx, heightAt(a[0] - nx, a[1] - nz) + lift, a[1] - nz];
const p1 = [a[0] + nx, heightAt(a[0] + nx, a[1] + nz) + lift, a[1] + nz];
const p2 = [b[0] + nx, heightAt(b[0] + nx, b[1] + nz) + lift, b[1] + nz];
const p3 = [b[0] - nx, heightAt(b[0] - nx, b[1] - nz) + lift, b[1] - nz];
positions.push(...p0, ...p1, ...p2, ...p0, ...p2, ...p3);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.computeVertexNormals();
const mesh = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
color,
roughness: 1,
side: THREE.DoubleSide
})
);
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
createGroundRibbon(
[[49, -7], [44, -3], [39, 0], [33, 4], [28, 9]],
0.72,
0xb99b68
);
createGroundRibbon(
[[39, -5], [38, -1], [36, 3], [33, 6]],
0.48,
0xb89a67
);
createGroundRibbon(
[[43, 3], [40, 4], [36, 7]],
0.46,
0xb89a67
);
const wallMaterials = [
new THREE.MeshStandardMaterial({ color: 0xc8b181, roughness: 1 }),
new THREE.MeshStandardMaterial({ color: 0xbca16e, roughness: 1 }),
new THREE.MeshStandardMaterial({ color: 0xd0bb8e, roughness: 1 })
];
const foundationMaterial = new THREE.MeshStandardMaterial({
color: 0x81705b,
roughness: 1
});
const roofMaterial = new THREE.MeshStandardMaterial({
color: 0x51463a,
roughness: 1,
flatShading: true,
side: THREE.DoubleSide
});
const doorMaterial = new THREE.MeshStandardMaterial({
color: 0x493b2d,
roughness: 1
});
const windowMaterial = new THREE.MeshStandardMaterial({
color: 0x424b43,
roughness: 0.85
});
const courtyardMaterial = new THREE.MeshStandardMaterial({
color: 0xb59c70,
roughness: 1
});
function roofGeometry(width, depth, base, rise) {
const w = width * 0.57;
const d = depth * 0.58;
const vertices = [
[-w, base, -d], [w, base, -d], [w, base + rise, 0],
[-w, base + rise, 0], [-w, base, d], [w, base, d]
];
const triangles = [
[4, 5, 2], [4, 2, 3],
[1, 0, 3], [1, 3, 2],
[0, 4, 3], [5, 1, 2]
];
const positions = [];
for (const triangle of triangles) {
for (const index of triangle) positions.push(...vertices[index]);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.computeVertexNormals();
return geometry;
}
const houses = [];
const villageCenter = { x: 39.5, z: -1.0 };
for (let attempt = 0; attempt < 700 && houses.length < 14; attempt++) {
const angle = random() * Math.PI * 2;
const radius = Math.sqrt(random());
const x = villageCenter.x + Math.cos(angle) * radius * 10.8;
const z = villageCenter.z + Math.sin(angle) * radius * 7.3;
if (terrainSlope(x, z) > 0.48) continue;
if (gullyInfo(x, z).influence > 0.17) continue;
let tooClose = false;
for (const house of houses) {
if (Math.hypot(house.x - x, house.z - z) < 3.45) {
tooClose = true;
break;
}
}
if (tooClose) continue;
houses.push({
x,
z,
width: 2.25 + random() * 1.35,
depth: 2.0 + random() * 1.05,
wallHeight: 1.55 + random() * 0.65,
angle: random() * Math.PI * 2
});
}
houses.forEach((house, index) => {
const group = new THREE.Group();
group.position.set(house.x, heightAt(house.x, house.z) + 0.06, house.z);
group.rotation.y = house.angle;
const foundation = new THREE.Mesh(
new THREE.BoxGeometry(house.width + 0.3, 0.52, house.depth + 0.3),
foundationMaterial
);
foundation.position.y = 0.04;
foundation.castShadow = true;
foundation.receiveShadow = true;
group.add(foundation);
const walls = new THREE.Mesh(
new THREE.BoxGeometry(house.width, house.wallHeight, house.depth),
wallMaterials[index % wallMaterials.length]
);
walls.position.y = 0.26 + house.wallHeight * 0.5;
walls.castShadow = true;
walls.receiveShadow = true;
group.add(walls);
const roof = new THREE.Mesh(
roofGeometry(
house.width + 0.35,
house.depth + 0.35,
0.26 + house.wallHeight,
0.72 + random() * 0.32
),
roofMaterial
);
roof.castShadow = true;
group.add(roof);
const door = new THREE.Mesh(
new THREE.BoxGeometry(0.56, 1.05, 0.08),
doorMaterial
);
door.position.set(-house.width * 0.12, 0.78, house.depth * 0.5 + 0.045);
door.castShadow = true;
group.add(door);
const window = new THREE.Mesh(
new THREE.BoxGeometry(0.48, 0.38, 0.065),
windowMaterial
);
window.position.set(
house.width * 0.25,
0.26 + house.wallHeight * 0.66,
house.depth * 0.5 + 0.04
);
group.add(window);
if ([0, 4, 8].includes(index)) {
const backWall = new THREE.Mesh(
new THREE.BoxGeometry(house.width + 2.2, 0.65, 0.18),
courtyardMaterial
);
backWall.position.set(0, 0.34, -house.depth * 0.5 - 0.95);
backWall.castShadow = true;
group.add(backWall);
const sideWall = new THREE.Mesh(
new THREE.BoxGeometry(0.18, 0.65, house.depth + 1.7),
courtyardMaterial
);
sideWall.position.set(-house.width * 0.5 - 1.05, 0.34, -0.08);
sideWall.castShadow = true;
group.add(sideWall);
}
scene.add(group);
});
// ---------------------------------------------------------------------
// Sparse poplars and angular stones
// ---------------------------------------------------------------------
const treePositions = [];
for (let attempt = 0; attempt < 1600 && treePositions.length < 28; attempt++) {
const angle = random() * Math.PI * 2;
const radius = Math.sqrt(random());
const x = villageCenter.x + Math.cos(angle) * radius * 15.5;
const z = villageCenter.z + Math.sin(angle) * radius * 11.0;
if (terrainSlope(x, z) > 0.66) continue;
if (gullyInfo(x, z).influence > 0.22) continue;
let tooClose = false;
for (const house of houses) {
if (Math.hypot(house.x - x, house.z - z) < 2.8) {
tooClose = true;
break;
}
}
if (tooClose) continue;
treePositions.push({
x,
z,
scale: 0.72 + random() * 0.58,
rotation: random() * Math.PI * 2
});
}
const trunkMesh = new THREE.InstancedMesh(
new THREE.CylinderGeometry(0.12, 0.17, 1.8, 5),
new THREE.MeshStandardMaterial({ color: 0x6a5238, roughness: 1, flatShading: true }),
treePositions.length
);
const foliageMesh = new THREE.InstancedMesh(
new THREE.ConeGeometry(0.66, 2.85, 6),
new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 1, flatShading: true }),
treePositions.length
);
const dummy = new THREE.Object3D();
const foliageColors = [0x59683c, 0x687447, 0x71804e, 0x53613a];
treePositions.forEach((tree, index) => {
const ground = heightAt(tree.x, tree.z);
dummy.position.set(tree.x, ground + 0.9 * tree.scale, tree.z);
dummy.rotation.set(0, tree.rotation, 0);
dummy.scale.setScalar(tree.scale);
dummy.updateMatrix();
trunkMesh.setMatrixAt(index, dummy.matrix);
dummy.position.set(tree.x, ground + 2.12 * tree.scale, tree.z);
dummy.rotation.set(0, tree.rotation + 0.4, 0);
dummy.updateMatrix();
foliageMesh.setMatrixAt(index, dummy.matrix);
foliageMesh.setColorAt(index, new THREE.Color(foliageColors[index % foliageColors.length]));
});
trunkMesh.instanceMatrix.needsUpdate = true;
foliageMesh.instanceMatrix.needsUpdate = true;
if (foliageMesh.instanceColor) foliageMesh.instanceColor.needsUpdate = true;
trunkMesh.castShadow = true;
foliageMesh.castShadow = true;
scene.add(trunkMesh, foliageMesh);
const rockPositions = [];
for (let attempt = 0; attempt < 1800 && rockPositions.length < 18; attempt++) {
const x = -WIDTH / 2 + random() * WIDTH;
const z = -DEPTH / 2 + random() * DEPTH;
const influence = gullyInfo(x, z).influence;
if (influence < 0.16 || influence > 0.74) continue;
if (terrainSlope(x, z) > 1.0) continue;
rockPositions.push({
x,
z,
scale: 0.28 + random() * 0.55,
rotation: random() * Math.PI * 2
});
}
const rockMesh = new THREE.InstancedMesh(
new THREE.IcosahedronGeometry(0.75, 0),
new THREE.MeshStandardMaterial({
color: 0x806e53,
roughness: 1,
flatShading: true
}),
rockPositions.length
);
rockPositions.forEach((rock, index) => {
const ground = heightAt(rock.x, rock.z);
dummy.position.set(rock.x, ground + rock.scale * 0.34, rock.z);
dummy.rotation.set(random() * 0.4, rock.rotation, random() * 0.25);
dummy.scale.set(
rock.scale * (0.75 + random() * 0.35),
rock.scale * 0.65,
rock.scale * (0.75 + random() * 0.35)
);
dummy.updateMatrix();
rockMesh.setMatrixAt(index, dummy.matrix);
});
rockMesh.instanceMatrix.needsUpdate = true;
rockMesh.castShadow = true;
rockMesh.receiveShadow = true;
scene.add(rockMesh);
// ---------------------------------------------------------------------
// Custom camera controls — no addons
// ---------------------------------------------------------------------
const controls = {
theta: 0.74,
phi: 0.91,
radius: window.innerWidth < 720 ? 182 : 139,
target: new THREE.Vector3(0, 11.5, 0)
};
const desired = {
theta: controls.theta,
phi: controls.phi,
radius: controls.radius,
target: controls.target.clone()
};
const pointers = new Map();
let pinchDistance = 0;
let panMode = false;
function updatePointerMode(event) {
panMode = event.button === 2 || event.shiftKey;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
updatePointerMode(event);
if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
pinchDistance = Math.hypot(a.x - b.x, a.y - b.y);
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
const previous = pointers.get(event.pointerId);
if (!previous) return;
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
previous.x = event.clientX;
previous.y = event.clientY;
if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
const distance = Math.hypot(a.x - b.x, a.y - b.y);
if (pinchDistance > 0 && distance > 0) {
desired.radius = THREE.MathUtils.clamp(
desired.radius * (pinchDistance / distance),
55,
230
);
}
pinchDistance = distance;
return;
}
if (panMode) {
const right = new THREE.Vector3(
Math.cos(desired.theta),
0,
-Math.sin(desired.theta)
);
const forward = new THREE.Vector3(
-Math.sin(desired.theta),
0,
-Math.cos(desired.theta)
);
const panScale = desired.radius * 0.00115;
desired.target.addScaledVector(right, -dx * panScale);
desired.target.addScaledVector(forward, dy * panScale);
desired.target.x = THREE.MathUtils.clamp(desired.target.x, -48, 48);
desired.target.z = THREE.MathUtils.clamp(desired.target.z, -40, 40);
} else {
desired.theta -= dx * 0.005;
desired.phi = THREE.MathUtils.clamp(desired.phi - dy * 0.0045, 0.34, 1.37);
}
});
function endPointer(event) {
pointers.delete(event.pointerId);
if (pointers.size < 2) pinchDistance = 0;
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener("contextmenu", (event) => event.preventDefault());
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
desired.radius = THREE.MathUtils.clamp(
desired.radius * Math.exp(event.deltaY * 0.001),
55,
230
);
},
{ passive: false }
);
window.addEventListener("keydown", (event) => {
if (event.key === "ArrowLeft") desired.theta += 0.08;
if (event.key === "ArrowRight") desired.theta -= 0.08;
if (event.key === "ArrowUp") {
desired.phi = THREE.MathUtils.clamp(desired.phi - 0.06, 0.34, 1.37);
}
if (event.key === "ArrowDown") {
desired.phi = THREE.MathUtils.clamp(desired.phi + 0.06, 0.34, 1.37);
}
if (event.key === "+" || event.key === "=") {
desired.radius = Math.max(55, desired.radius * 0.9);
}
if (event.key === "-") {
desired.radius = Math.min(230, desired.radius * 1.1);
}
});
// ---------------------------------------------------------------------
// Projected landscape labels
// ---------------------------------------------------------------------
const annotations = [
{
element: document.querySelector("#label-terrace"),
position: new THREE.Vector3(-30, heightAt(-30, -21) + 3.2, -21)
},
{
element: document.querySelector("#label-gully"),
position: new THREE.Vector3(1, heightAt(1, -7) + 2.0, -7)
},
{
element: document.querySelector("#label-village"),
position: new THREE.Vector3(39.5, heightAt(39.5, -1) + 5.0, -1)
}
];
const projected = new THREE.Vector3();
function updateAnnotations() {
const width = window.innerWidth;
const height = window.innerHeight;
for (const annotation of annotations) {
projected.copy(annotation.position).project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.15 &&
projected.x < 1.15 &&
projected.y > -1.15 &&
projected.y < 1.15;
annotation.element.style.opacity = visible ? "1" : "0";
if (visible) {
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
annotation.element.style.left = `${x}px`;
annotation.element.style.top = `${y}px`;
}
}
}
// ---------------------------------------------------------------------
// Render loop
// ---------------------------------------------------------------------
const compassNeedle = document.querySelector("#needle");
const spherical = new THREE.Spherical();
let previousTime = performance.now();
function animate(time) {
const delta = Math.min((time - previousTime) / 1000, 0.05);
previousTime = time;
const damping = 1 - Math.exp(-delta * 8.5);
controls.theta += (desired.theta - controls.theta) * damping;
controls.phi += (desired.phi - controls.phi) * damping;
controls.radius += (desired.radius - controls.radius) * damping;
controls.target.lerp(desired.target, damping);
spherical.set(controls.radius, controls.phi, controls.theta);
camera.position.setFromSpherical(spherical).add(controls.target);
camera.lookAt(controls.target);
compassNeedle.style.transform =
`rotate(${-controls.theta * 180 / Math.PI}deg)`;
updateAnnotations();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.75));
}
window.addEventListener("resize", resize);
resize();
renderer.render(scene, camera);
loading.style.opacity = "0";
setTimeout(() => loading.remove(), 450);
requestAnimationFrame(animate);
</script>
</body>
</html>
```