roamwright 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CONTRIBUTING.md +39 -8
  2. package/README.md +53 -24
  3. package/examples/viaduct-camera.js +40 -0
  4. package/examples/viaduct-landscape.js +81 -0
  5. package/examples/viaduct.css +75 -0
  6. package/examples/viaduct.html +47 -0
  7. package/examples/viaduct.js +332 -0
  8. package/geometry/builder.js +11 -14
  9. package/geometry/creased-sheet.js +127 -0
  10. package/geometry/ear.js +97 -0
  11. package/geometry/erosion.js +106 -0
  12. package/geometry/face-grid.js +143 -0
  13. package/geometry/garment-tags.js +11 -0
  14. package/geometry/hair-gathers.js +174 -0
  15. package/geometry/hair-locks.js +156 -0
  16. package/geometry/hair-patch.js +42 -0
  17. package/geometry/hair-shell.js +186 -0
  18. package/geometry/hair-tags.js +6 -0
  19. package/geometry/head-profile.js +138 -0
  20. package/geometry/head-shape.js +499 -0
  21. package/geometry/heightfield.js +68 -0
  22. package/geometry/outline-grid.js +46 -0
  23. package/geometry/path-field.js +65 -0
  24. package/geometry/sagging-tube.js +58 -0
  25. package/geometry/sampled-surface.js +101 -0
  26. package/geometry/scatter-grid.js +32 -0
  27. package/geometry/sculpt.js +263 -0
  28. package/geometry/shore-grid.js +67 -0
  29. package/geometry/strata-field.js +339 -0
  30. package/geometry/strata-tiles.js +215 -0
  31. package/geometry/stream.js +94 -0
  32. package/geometry/terrain-chunks.js +300 -0
  33. package/geometry/terrain-extension.js +44 -0
  34. package/math/cell-edge.js +44 -0
  35. package/math/cloth-textures.js +83 -0
  36. package/math/cloud-textures.js +112 -0
  37. package/math/color.js +29 -0
  38. package/math/curve.js +3 -4
  39. package/math/mountain-ranges.js +463 -0
  40. package/math/particle-noise.js +48 -0
  41. package/math/periodic.js +20 -0
  42. package/math/rock-texture.js +56 -0
  43. package/math/surface-textures.js +241 -0
  44. package/motion/arm-reach.js +74 -0
  45. package/motion/biped-stride.js +276 -0
  46. package/motion/crowd-alarms.js +127 -0
  47. package/motion/crowd-routine.js +183 -0
  48. package/motion/daily-clock.js +59 -0
  49. package/motion/instance-sight.js +84 -0
  50. package/motion/quadruped.js +332 -0
  51. package/motion/weather.js +59 -0
  52. package/motion/wind.js +27 -0
  53. package/package.json +6 -4
  54. package/rendering/caster-motion.js +79 -0
  55. package/rendering/cell-lod.js +175 -0
  56. package/rendering/cloud-dome.js +371 -0
  57. package/rendering/cloud-field.js +83 -0
  58. package/rendering/compilation-schedule.js +34 -0
  59. package/rendering/contact-shadows.js +79 -0
  60. package/rendering/crowd-skinning.js +133 -0
  61. package/rendering/crust.js +28 -0
  62. package/rendering/daylight.js +50 -0
  63. package/rendering/far-shadow.js +186 -0
  64. package/rendering/flocks.js +323 -0
  65. package/rendering/garment-material.js +110 -0
  66. package/rendering/glow-lines.js +74 -0
  67. package/rendering/glow-shell.js +90 -0
  68. package/rendering/hair-strands.js +67 -0
  69. package/rendering/height-haze.js +129 -0
  70. package/rendering/height-probe.js +91 -0
  71. package/rendering/interior-mapping.js +19 -0
  72. package/rendering/light-budget.js +222 -0
  73. package/rendering/light-points.js +51 -0
  74. package/rendering/light-shafts.js +131 -0
  75. package/rendering/local-lights.js +28 -0
  76. package/rendering/low-light.js +13 -0
  77. package/rendering/material-lod.js +110 -0
  78. package/rendering/particle-emitters.js +223 -0
  79. package/rendering/particles.js +297 -0
  80. package/rendering/planar-reflection.js +175 -0
  81. package/rendering/post-shaders.js +21 -1
  82. package/rendering/post.js +8 -5
  83. package/rendering/rain-rings.js +22 -0
  84. package/rendering/road-surface.js +63 -0
  85. package/rendering/sea-shaders.js +230 -0
  86. package/rendering/shader-warmup.js +197 -0
  87. package/rendering/shadow-alignment.js +28 -0
  88. package/rendering/shadow-depth.js +129 -0
  89. package/rendering/sky-occlusion.js +187 -0
  90. package/rendering/sky.js +169 -0
  91. package/rendering/stage-lights.js +209 -0
  92. package/rendering/static-point-shadow.js +119 -0
  93. package/rendering/still-casters.js +6 -11
  94. package/rendering/strata-material.js +93 -0
  95. package/rendering/stream-flow.js +36 -0
  96. package/rendering/surface-light.js +22 -0
  97. package/rendering/surface-projection.js +69 -0
  98. package/rendering/talus.js +26 -0
  99. package/rendering/terrain-rock.js +48 -0
  100. package/rendering/texture-fills.js +68 -0
  101. package/rendering/viewport.js +9 -0
  102. package/rendering/wakes.js +99 -0
  103. package/rendering/water-material.js +288 -0
  104. package/rendering/world-matrices.js +4 -6
  105. package/runtime/device-quality.js +27 -0
  106. package/runtime/diagnostic-log.js +80 -0
  107. package/runtime/events.js +14 -0
  108. package/runtime/first-use.js +3 -1
  109. package/runtime/frame-yield.js +14 -0
  110. package/runtime/grid-cache.js +88 -0
  111. package/runtime/grid-rows.js +9 -0
  112. package/runtime/module-preload.js +15 -0
  113. package/runtime/quality-fit.js +5 -9
  114. package/runtime/search.js +69 -0
  115. package/runtime/spatial-audio.js +57 -0
  116. package/scripts/serve.py +26 -0
package/CONTRIBUTING.md CHANGED
@@ -1,12 +1,43 @@
1
- # Contributing
1
+ # Contributing to Roamwright
2
2
 
3
- Use a current Node.js LTS release and npm. From a fresh checkout run `npm ci`, then `npm test`. Run `npx playwright install chromium` followed by `npm run test:browser` to exercise the eye adaptation, temporal history, overlay and GPU batch paths in a real WebGL context. The compatibility workflow runs these checks on both supported revisions. Run `npm run demo` and open `/examples/` to check changes to rendering or input. For a change to renderer behavior, test both Three.js revisions listed in the peer dependency. A separate checkout can switch versions with `npm install --no-save --package-lock=false three@0.170.0`.
3
+ Use the [issue tracker](https://github.com/enestaylan/roamwright/issues) for bugs and feature requests. For a rendering bug, a seed, a short reproduction and the Roamwright, Three.js and browser versions help other contributors recreate the scene. Send security-sensitive reports through [GitHub Security Advisories](https://github.com/enestaylan/roamwright/security/advisories/new).
4
4
 
5
- Keep application content in the consumer. A reusable module accepts the world seed, terrain function, camera, materials or callbacks it needs. Show new public behavior with a small example or a focused test, especially when it changes typed-array layouts or shader inputs. Include the source and license of adapted components in `licenses/`.
5
+ ## Set up and test
6
6
 
7
- ## Release process
7
+ Use Node.js 24 to match CI, npm, and Python 3 for the local HTTP server. From the repository root, run the following commands.
8
8
 
9
- 1. Update the package version and lockfile together with `npm version --no-git-tag-version patch` (or choose the appropriate minor or major increment). Update the installation example and compatibility notes.
10
- 2. Run the tests, open the example and inspect `npm pack --dry-run` to check the published file list.
11
- 3. Commit on `main`, tag that commit as `v<version>`, push the commit and tag, and create the matching GitHub release.
12
- 4. Publish the checked package to the public npm registry with `npm publish --access public`, then verify the version and integrity with `npm view roamwright version dist.integrity`. Consumers can pin the release commit and commit their npm lockfile.
9
+ ```sh
10
+ npm ci
11
+ npm test
12
+ npx playwright install chromium
13
+ npm run test:browser
14
+ npm run test:package
15
+ ```
16
+
17
+ | Command | What it checks |
18
+ | --- | --- |
19
+ | `npm test` | Seeded generation, geometry buffers, player motion and worker/runtime behavior. |
20
+ | `npm run test:browser` | GPU batching, post-processing, and both examples rendered with two seeds in Chromium. Set `CHROMIUM_EXECUTABLE` to use an existing Chrome executable. |
21
+ | `npm run test:package` | Packs the working tree, installs the tarball and the selected Three.js revision into a temporary project, and builds geometry through public imports. |
22
+ | `npm run demo` | Starts the local server and prints an address for each [example](README.md#examples). |
23
+
24
+ CI runs the first three checks with Three.js 0.170.0 and 0.187.0. To try the older peer locally, run `npm install --no-save --package-lock=false three@0.170.0` and repeat the checks. Run `npm ci` to restore the locked dependencies.
25
+
26
+ After both compatibility jobs pass on `main`, the same workflow deploys the [live examples](https://enestaylan.github.io/roamwright/) from this repository. The site serves the locked Three.js build alongside the example modules.
27
+
28
+ ## Prepare a pull request
29
+
30
+ - Keep application content in the consumer. Pass in the seed, terrain function, camera, materials or callbacks a reusable module needs.
31
+ - Show new public behavior with a focused test or a small example. For rendering changes, compare the same scene before and after and record draw counts. For motion or geometry, compare deterministic state or buffers.
32
+ - Update the README for public API changes. For a new Three.js revision, update the peer range, lockfile, compatibility notes and CI matrix together.
33
+ - Include the source and license of adapted components in `licenses/`. Review `npm pack --dry-run` when changing the published file list.
34
+
35
+ ## Maintainer releases
36
+
37
+ Push tested changes as they are ready. Batch routine GitHub and npm releases into at most one per day. Check the latest registry version, its publication date and the commits since its tag before preparing a release. To try development code between releases, install a local tarball in a separate consumer checkout or pin a full Git commit SHA.
38
+
39
+ 1. Choose an unused semantic version. Update the manifest and lockfile together with `npm version --no-git-tag-version patch` (or use `minor` or `major`).
40
+ 2. Run the compatibility checks above, inspect `npm pack --dry-run`, and exercise the changed path in a consumer.
41
+ 3. Commit on top of current `main`, create an annotated `v<version>` tag, and push the commit and tag atomically.
42
+ 4. From the tagged checkout, run `npm pack`. Create the GitHub release with that tarball attached and publish the same tarball using `npm publish ./<tarball>.tgz --access public`.
43
+ 5. Verify the release and the exact version's registry integrity with `npm view roamwright@<version> dist.integrity`. In a clean consumer, install that version and exercise the changed path.
package/README.md CHANGED
@@ -1,29 +1,47 @@
1
1
  # Roamwright
2
2
 
3
- Roamwright is a modular Three.js engine for building procedural worlds in the browser. Generate terrain from a seed, combine thousands of colored primitives into meshes, and move a camera through walkable or flyable spaces. The worker pool can prepare geometry while the renderer draws the current frame.
3
+ [![npm version](https://img.shields.io/npm/v/roamwright)](https://www.npmjs.com/package/roamwright)
4
+ [![Compatibility tests](https://github.com/enestaylan/roamwright/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/enestaylan/roamwright/actions/workflows/test.yml)
4
5
 
5
- ## Try the island
6
+ Roamwright is a Three.js library for building procedural worlds you can explore on foot or in flight. Generate terrain from a seed, batch scenery into meshes, and use the same terrain to guide movement through the world in your browser. For larger worlds, a worker pool can build geometry off the main thread.
6
7
 
7
- With Node.js, npm and Python 3 installed, run the following commands.
8
+ ![A red passenger train on a stone viaduct above a winding alpine river, with conifers on the banks and snow on the peaks](https://raw.githubusercontent.com/enestaylan/roamwright/main/docs/alpine-viaduct.jpg)
9
+
10
+ **Alpine viaduct, seed 42.** One height field shapes the riverbed and snowy ridges and determines where the conifers take root. Eight copies of an arch profile form the viaduct. The stonework, rails and overhead wires share one mesh. The four-car electric train moves as a separate mesh. Choose Valley, Trackside or Riverbank and select **Run train** to watch it cross. [Explore the example source](examples/viaduct.js).
11
+
12
+ ## Install
8
13
 
9
14
  ```sh
10
- git clone https://github.com/enestaylan/roamwright.git
11
- cd roamwright
12
- npm ci
13
- npm run demo
15
+ npm install roamwright
14
16
  ```
15
17
 
16
- Open [the island](http://localhost:8080/examples/) and drag to orbit. Change the `seed` query parameter to generate another coastline. The example serves Three.js from the local installation.
18
+ npm resolves the Three.js peer in a new project. If you already use Three.js, the supported versions are **0.170.0** and **0.187.0**. To select one explicitly, run `npm install roamwright three@0.187.0`. The renderer requires WebGL 2.
19
+
20
+ ## Built with Roamwright
17
21
 
18
- ## Use in a project
22
+ [Malazan](https://enestaylan.com/malazan/) is an explorable world built with Roamwright. Fly over Darujhistan, Pale, and the Rhivi Plain from *Malazan Book of the Fallen*.
19
23
 
20
- Install with npm. It resolves the Three.js peer automatically for a new project.
24
+ ## Examples
25
+
26
+ | Live example | What the example shows | Source |
27
+ | --- | --- | --- |
28
+ | [Alpine viaduct](https://enestaylan.github.io/roamwright/examples/viaduct.html?seed=42) | Watch an electric train cross eight stone arches from the valley, trackside or riverbank. Change the seed to generate another landscape. | [viaduct.js](examples/viaduct.js) |
29
+ | [Seeded island](https://enestaylan.github.io/roamwright/examples/?seed=42) | Seeded noise shapes the coastline, and a single mesh holds the rocks scattered along the shore. | [island.js](examples/island.js) |
30
+
31
+ ### Run locally
32
+
33
+ With Node.js, npm and Python 3 installed, run the following commands.
21
34
 
22
35
  ```sh
23
- npm install roamwright
36
+ git clone https://github.com/enestaylan/roamwright.git
37
+ cd roamwright
38
+ npm ci
39
+ npm run demo
24
40
  ```
25
41
 
26
- Version 0.1.0 supports **Three.js 0.187.0** and **0.170.0**. To select a revision explicitly, use `npm install roamwright three@0.187.0`. You can also install the tagged source directly with `npm install github:enestaylan/roamwright#v0.1.0`.
42
+ Open the address printed in the terminal for the example you want to explore. Drag to orbit and scroll or pinch to zoom. Change the integer after `?seed=` to generate a different landscape.
43
+
44
+ ## Render your first mesh
27
45
 
28
46
  Use an ES module bundler, or provide a browser import map as in the example. Supply a canvas with a CSS width and height.
29
47
 
@@ -47,17 +65,28 @@ renderer.render(scene, camera);
47
65
 
48
66
  ## Modules
49
67
 
50
- | Import from `roamwright/` | Use |
51
- | --- | --- |
52
- | `math/noise.js`, `math/random.js`, `math/curve.js` | Create independent seeded noise fields, resumable random streams and evenly spaced spline samples. These modules also run in workers. |
53
- | `geometry/builder.js`, `geometry/primitives.js` | Transform and merge primitives, produce typed vertex buffers, or build a Three.js mesh. Colors passed to the builder are linear RGB. |
54
- | `geometry/instances.js`, `rendering/piece-batch.js` | Draw repeated geometry with instancing or collect changing pieces into a GPU batch. |
55
- | `motion/spaces.js`, `motion/player.js` | Give a space terrain height, decks and colliders. Set the controller's input axes, call `update(deltaSeconds)`, then `applyCamera(camera)`. Distances are in metres. |
56
- | `runtime/pool.js`, `runtime/worker.js` | Register named jobs on a module worker and send work from the page. Typed-array buffers in results transfer back to the caller. |
57
- | `rendering/context.js`, `rendering/world-matrices.js` | Set up WebGL2, a camera, a scene and world group. Optionally track static transforms once per frame before drawing. |
58
- | `rendering/post.js`, `rendering/taa.js`, `rendering/dof.js` | Compose HDR passes, temporal antialiasing, depth of field, exposure and upscaling. The application supplies its camera, effect scene and sky occlusion mask. |
59
- | `runtime/gpu-timing.js`, `runtime/quality-fit.js`, `runtime/quality-store.js` | Measure GPU work, adapt quality and persist a visitor's settings in a storage namespace chosen by the application. |
68
+ Import any module from `roamwright/<folder>/<name>.js`. Each area below names its main modules first. Its other modules are listed after them. See each module’s source for its parameters, and the [tests](test) and browser fixtures for complete setups.
69
+
70
+ | Area | Main modules | Also includes |
71
+ | --- | --- | --- |
72
+ | Foundations | `math/noise.js`, `math/random.js`, `math/curve.js` and `math/color.js` provide seeded noise, resumable random streams, spline samples and colour conversion. They also run in workers. | `math/scalar.js`, `math/cell-edge.js`, `math/periodic.js` |
73
+ | Geometry | `geometry/builder.js` and `geometry/primitives.js` merge primitives into typed buffers or a Three.js mesh. `geometry/sculpt.js` builds lofted, skinned shapes. `geometry/instances.js` and `rendering/piece-batch.js` draw repeated or changing pieces. | `geometry/sampled-surface.js`, `geometry/placement.js`, `geometry/creased-sheet.js`, `geometry/sagging-tube.js`, `rendering/cell-lod.js` |
74
+ | Terrain | `geometry/terrain-chunks.js` refines a height grid in mesh batches. `geometry/heightfield.js` samples and refines it, `math/mountain-ranges.js` raises relief and `geometry/strata-field.js` plans rock outcrops. | `geometry/terrain-extension.js`, `geometry/erosion.js`, `geometry/strata-tiles.js`, `geometry/scatter-grid.js`, `geometry/outline-grid.js`, `geometry/path-field.js`, `math/rock-texture.js`, `rendering/terrain-rock.js`, `rendering/strata-material.js`, `rendering/talus.js`, `rendering/road-surface.js` |
75
+ | Water | `rendering/water-material.js` shades lakes, streams and rivers. `geometry/stream.js` builds stream ribbons and `geometry/shore-grid.js` measures distance to shorelines. | `rendering/sea-shaders.js`, `rendering/wakes.js`, `rendering/stream-flow.js`, `rendering/rain-rings.js`, `rendering/planar-reflection.js` |
76
+ | Sky and weather | `rendering/sky.js` combines `rendering/cloud-field.js` and `rendering/cloud-dome.js` into a volumetric cloud sky ([fixture](test/atmosphere.js)). `motion/weather.js` and `motion/wind.js` drive rain, dust, squalls and gusts. | `math/cloud-textures.js`, `rendering/daylight.js`, `rendering/height-haze.js`, `rendering/particles.js`, `math/particle-noise.js`, `rendering/particle-emitters.js`, `rendering/flocks.js` |
77
+ | Characters | `geometry/head-shape.js` builds parametric heads, `geometry/hair-shell.js` hair and `rendering/garment-material.js` cloth, plate and mail ([fixture](test/garment-material.js)). `motion/biped-stride.js` and `motion/quadruped.js` animate gaits, and `rendering/crowd-skinning.js` draws instanced skinned crowds. | `geometry/ear.js`, `geometry/face-grid.js`, `geometry/head-profile.js`, `geometry/hair-locks.js`, `geometry/hair-gathers.js`, `geometry/hair-patch.js`, `geometry/hair-tags.js`, `geometry/garment-tags.js`, `math/cloth-textures.js`, `rendering/hair-strands.js`, `motion/arm-reach.js`, `motion/crowd-alarms.js`, `motion/crowd-routine.js` |
78
+ | Surfaces | `rendering/surface-projection.js` projects textures in metres onto standard materials and `rendering/surface-light.js` adds wetness and backlighting ([fixture](test/projected-surface.js)). `math/surface-textures.js` fills seeded, tileable masonry, plaster, roof tile, rock, plank, foliage, ground, road, brick and ice textures, in a worker if wanted. | `rendering/interior-mapping.js`, `rendering/crust.js`, `rendering/low-light.js`, `rendering/material-lod.js`, `rendering/textures.js`, `rendering/texture-fills.js` |
79
+ | Lights and shadows | `rendering/far-shadow.js` pairs near and far directional shadows, `rendering/static-point-shadow.js` caches point-light shadows and `rendering/sky-occlusion.js` darkens covered areas. | `rendering/shadow-depth.js`, `rendering/shadow-alignment.js`, `rendering/local-lights.js`, `rendering/caster-motion.js`, `rendering/still-casters.js`, `rendering/contact-shadows.js`, `rendering/light-points.js`, `rendering/light-shafts.js`, `rendering/glow-lines.js`, `rendering/glow-shell.js`, `rendering/light-budget.js`, `rendering/stage-lights.js` |
80
+ | Rendering pipeline | `rendering/context.js` sets up WebGL2, a scene and a camera. `rendering/post.js` and `rendering/taa.js` compose HDR passes and temporal antialiasing, and `rendering/shader-warmup.js` compiles programs ahead of use. | `rendering/dof.js`, `rendering/post-shaders.js`, `rendering/eye-adapt.js`, `rendering/viewport.js`, `rendering/world-matrices.js`, `rendering/compilation-schedule.js`, `rendering/height-probe.js` |
81
+ | Player and world | `motion/spaces.js` and `motion/player.js` move a first-person controller over terrain, decks and colliders. | `motion/instance-sight.js`, `motion/daily-clock.js`, `runtime/spatial-audio.js` |
82
+ | Runtime | `runtime/pool.js` and `runtime/worker.js` run named jobs on module workers. `runtime/quality-fit.js` adapts quality to measured GPU time. | `runtime/device-quality.js`, `runtime/quality-store.js`, `runtime/gpu-timing.js`, `runtime/first-use.js`, `runtime/hand-over.js`, `runtime/seen.js`, `runtime/frame-yield.js`, `runtime/grid-cache.js`, `runtime/grid-rows.js`, `runtime/events.js`, `runtime/diagnostic-log.js`, `runtime/module-preload.js`, `runtime/search.js` |
83
+
84
+ Pass a `revisions` object mapping grid names to input-version strings to `createGridCache` to reuse compatible grids across builds. Saving a grid retires its previous revision. Names without a revision bypass storage. The existing `build` string versions the whole cache when `revisions` is omitted.
85
+
86
+ For geometry generated off the main thread, call `builder.parts(true)` in the worker and `geometryOf(parts)` on the page.
87
+
88
+ ## Contributing and license
60
89
 
61
- For geometry generated off the main thread, call `builder.parts(true)` in the worker and `geometryOf(parts)` on the page. This path frees static CPU-side attributes after upload. Keep the seed or source data if your application needs to regenerate meshes after a context loss.
90
+ See the [contributor guide](CONTRIBUTING.md) for local checks and release instructions. Use [GitHub Issues](https://github.com/enestaylan/roamwright/issues) for bugs and feature requests, or [report a vulnerability privately](https://github.com/enestaylan/roamwright/security/advisories/new).
62
91
 
63
- The [island example](examples/island.js) shows deterministic generation, mesh batching, resize handling and camera input together. See [CONTRIBUTING.md](CONTRIBUTING.md) for testing and releases. Roamwright is distributed under the [MIT license](LICENSE). Notices for adapted components are in [licenses](licenses).
92
+ Roamwright is distributed under the [MIT license](LICENSE). Notices for adapted components are in [licenses](licenses).
@@ -0,0 +1,40 @@
1
+ import { MathUtils } from 'three';
2
+
3
+ // Keep the eye and its entire near plane inside the landscape and above its surface.
4
+ export function createCameraGuard(ground, trees) {
5
+ const { widthSegments: columns, heightSegments: rows } = ground.parameters;
6
+ const positions = ground.attributes.position;
7
+ const x0 = positions.getX(0), z0 = positions.getZ(0);
8
+ const x1 = positions.getX(columns), z1 = positions.getZ(rows * (columns + 1));
9
+ const cellWidth = (x1 - x0) / columns, cellDepth = (z1 - z0) / rows;
10
+
11
+ return camera => {
12
+ const halfHeight = camera.near * Math.tan(MathUtils.degToRad(camera.fov / 2));
13
+ const margin = Math.hypot(camera.near, halfHeight, halfHeight * camera.aspect);
14
+ const eye = camera.position;
15
+ eye.x = MathUtils.clamp(eye.x, x0 + margin, x1 - margin);
16
+ eye.z = MathUtils.clamp(eye.z, z0 + margin, z1 - margin);
17
+
18
+ // Every point on a rendered triangle is at or below its highest corner.
19
+ const left = Math.max(0, Math.floor((eye.x - margin - x0) / cellWidth));
20
+ const right = Math.min(columns, Math.ceil((eye.x + margin - x0) / cellWidth));
21
+ const back = Math.max(0, Math.floor((eye.z - margin - z0) / cellDepth));
22
+ const front = Math.min(rows, Math.ceil((eye.z + margin - z0) / cellDepth));
23
+ let floor = 0; // Water level.
24
+ for (let row = back; row <= front; row++) {
25
+ for (let col = left; col <= right; col++) {
26
+ floor = Math.max(floor, positions.getY(row * (columns + 1) + col));
27
+ }
28
+ }
29
+
30
+ let minimum = floor + margin + 1;
31
+ for (const { x, z, top, radius } of trees) {
32
+ const buffer = radius + margin;
33
+ const dx = eye.x - x, dz = eye.z - z;
34
+ if (Math.abs(dx) > buffer + 2 || Math.abs(dz) > buffer + 2) continue;
35
+ const lift = 1 - MathUtils.smoothstep(Math.hypot(dx, dz), buffer, buffer + 2);
36
+ minimum = Math.max(minimum, MathUtils.lerp(floor + margin + 1, top + margin + 0.35, lift));
37
+ }
38
+ eye.y = Math.max(eye.y, minimum);
39
+ };
40
+ }
@@ -0,0 +1,81 @@
1
+ import * as THREE from 'three';
2
+
3
+ // A directional panorama keeps the cloud banks fixed over the mountains as the camera turns.
4
+ export function valleySky(noise) {
5
+ const width = 768, height = 384;
6
+ const pixels = new Uint8Array(width * height * 4);
7
+ const sun = new THREE.Vector3(-0.78, 0.32, -0.54).normalize();
8
+ for (let y = 0; y < height; y++) {
9
+ const latitude = Math.PI * ((y + 0.5) / height - 0.5);
10
+ const up = Math.sin(latitude), ring = Math.cos(latitude);
11
+ const blue = THREE.MathUtils.smoothstep(up, -0.05, 0.78);
12
+ for (let x = 0; x < width; x++) {
13
+ const longitude = 2 * Math.PI * ((x + 0.5) / width - 0.5);
14
+ const east = ring * Math.cos(longitude), north = ring * Math.sin(longitude);
15
+ const air = Math.max(0.09, up);
16
+ const cloud = noise.fbm(east / air * 1.35, north / air * 2.8, 4, 71);
17
+ const veil = THREE.MathUtils.smoothstep(cloud, 0.53, 0.76) * THREE.MathUtils.smoothstep(up, 0, 0.13);
18
+ const glow = Math.pow(Math.max(0, east * sun.x + up * sun.y + north * sun.z), 32);
19
+ const i = (y * width + x) * 4;
20
+ pixels[i] = Math.min(255, (202 - blue * 116) * (1 - veil) + 249 * veil + 31 * glow);
21
+ pixels[i + 1] = Math.min(255, (218 - blue * 60) * (1 - veil) + 237 * veil + 18 * glow);
22
+ pixels[i + 2] = Math.min(255, (220 - blue * 15) * (1 - veil) + 213 * veil + 5 * glow);
23
+ pixels[i + 3] = 255;
24
+ }
25
+ }
26
+ const sky = new THREE.DataTexture(pixels, width, height);
27
+ sky.colorSpace = THREE.SRGBColorSpace;
28
+ sky.mapping = THREE.EquirectangularReflectionMapping;
29
+ sky.minFilter = sky.magFilter = THREE.LinearFilter;
30
+ sky.needsUpdate = true;
31
+ return sky;
32
+ }
33
+
34
+ // An irregular skirt and an offset apex give each whorl a recognizable branch silhouette.
35
+ export function branchWhorl() {
36
+ const points = [];
37
+ const rim = [];
38
+ for (let i = 0; i < 14; i++) {
39
+ const angle = i * Math.PI / 7;
40
+ const radius = i % 2 ? 0.34 : 0.5;
41
+ rim.push([radius * Math.cos(angle), i % 2 ? 0.16 : 0.03 * Math.sin(3 * angle), radius * Math.sin(angle)]);
42
+ }
43
+ for (let i = 0; i < rim.length; i++) {
44
+ const next = rim[(i + 1) % rim.length];
45
+ points.push(...rim[i], 0.02, 1, -0.02, ...next);
46
+ }
47
+ const geometry = new THREE.BufferGeometry();
48
+ geometry.setAttribute('position', new THREE.Float32BufferAttribute(points, 3));
49
+ geometry.computeVertexNormals();
50
+ return geometry;
51
+ }
52
+
53
+ export function alpineRiver(channel, elevation, noise) {
54
+ const grid = new THREE.PlaneGeometry(38, 385, 36, 385).rotateX(-Math.PI / 2).translate(0, 0, -24.5);
55
+ const position = grid.attributes.position;
56
+ const colors = new Float32Array(position.count * 3);
57
+ const shallows = new THREE.Color(0x83aea1), deep = new THREE.Color(0x236c73);
58
+ const tint = new THREE.Color();
59
+ for (let i = 0; i < position.count; i++) {
60
+ const z = position.getZ(i), x = position.getX(i) + channel(z);
61
+ const depth = THREE.MathUtils.smoothstep(-elevation(x, z), -0.3, 2);
62
+ position.setX(i, x);
63
+ tint.copy(shallows).lerp(deep, depth).multiplyScalar(0.88 + 0.19 * noise.vnoise(x * 0.6, z * 0.21, 92)).toArray(colors, i * 3);
64
+ }
65
+ grid.setAttribute('color', new THREE.BufferAttribute(colors, 3));
66
+ const material = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.4 });
67
+ material.onBeforeCompile = shader => {
68
+ shader.vertexShader = 'varying vec2 vRiver;\n' + shader.vertexShader.replace('#include <begin_vertex>', '#include <begin_vertex>\nvRiver = position.xz;');
69
+ shader.fragmentShader = 'varying vec2 vRiver;\n' + shader.fragmentShader.replace('#include <color_fragment>', `
70
+ #include <color_fragment>
71
+ float eddy = sin(vRiver.x * 0.73 + sin(vRiver.y * 0.47)) + sin(vRiver.y * 0.32 + vRiver.x * 0.31);
72
+ float flow = vRiver.y + 0.72 * eddy;
73
+ float ripple = sin(flow * 8.3 + sin(flow * 2.3)) + 0.45 * sin(vRiver.x * 2.35 - flow * 1.4 + eddy);
74
+ float visible = 1.0 - smoothstep(0.07, 0.55, fwidth(flow));
75
+ diffuseColor.rgb += vec3(0.12, 0.19, 0.18) * smoothstep(0.96, 1.44, ripple) * smoothstep(-0.8, 1.5, eddy) * visible;
76
+ `);
77
+ };
78
+ const river = new THREE.Mesh(grid, material);
79
+ river.receiveShadow = true;
80
+ return river;
81
+ }
@@ -0,0 +1,75 @@
1
+ :root {
2
+ color-scheme: dark;
3
+ font: 15px/1.4 "Avenir Next", "Segoe UI", sans-serif;
4
+ color: #fff6df;
5
+ background: #294347;
6
+ }
7
+ .sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%) }
8
+ * { box-sizing: border-box }
9
+ body { margin: 0 }
10
+ canvas { display: block; width: 100%; height: 100vh; height: 100dvh; touch-action: none }
11
+ header, footer {
12
+ position: absolute;
13
+ left: 0;
14
+ right: 0;
15
+ display: flex;
16
+ align-items: center;
17
+ justify-content: space-between;
18
+ padding: clamp(14px, 2.4vw, 36px);
19
+ pointer-events: none;
20
+ }
21
+ header { top: 0; gap: 1rem; background: linear-gradient(#16302f48, transparent) }
22
+ footer {
23
+ bottom: 0;
24
+ align-items: flex-end;
25
+ gap: 1rem;
26
+ padding-top: 5rem;
27
+ background: linear-gradient(transparent, #112a2bb5);
28
+ }
29
+ a, button, input { font: inherit; color: inherit }
30
+ button { cursor: pointer }
31
+ a:focus-visible, button:focus-visible, input:focus-visible, canvas:focus-visible { outline: 3px solid #ffd577; outline-offset: 2px }
32
+ .back, form, .views, #train {
33
+ pointer-events: auto;
34
+ border: 1px solid #f7edcf65;
35
+ border-radius: .45rem;
36
+ background: #132e2eef;
37
+ }
38
+ .back { padding: .65rem .95rem; font-weight: 600; text-decoration: none }
39
+ .back span { margin-right: .3rem }
40
+ form, .views, .tools, #train { display: flex; align-items: center }
41
+ form { padding-left: .85rem }
42
+ form label { color: #d9ddc9; font-size: .84rem }
43
+ input {
44
+ background: transparent;
45
+ border: 0;
46
+ width: 7ch;
47
+ padding: .5rem .25rem;
48
+ text-align: center;
49
+ appearance: textfield;
50
+ font-variant-numeric: tabular-nums;
51
+ }
52
+ input:focus { width: 13ch }
53
+ input::-webkit-inner-spin-button { -webkit-appearance: none }
54
+ button { min-height: 44px; border: 0; background: transparent; font-weight: 550 }
55
+ form button { width: 44px; border-left: 1px solid #f7edcf38 }
56
+ h1 { margin: 0; font: 500 clamp(2.35rem, 5.3vw, 5.5rem)/1 "Iowan Old Style", "Palatino Linotype", Georgia, serif; letter-spacing: -.045em }
57
+ p { margin: .5rem 0 0; font-size: .9rem }
58
+ .tools { gap: .5rem }
59
+ .views { padding: 3px }
60
+ .views button { border-radius: .28rem; padding: .45rem .8rem }
61
+ .views button[aria-pressed="true"] { background: #f4e8cb; color: #243b36 }
62
+ #train { gap: .55rem; justify-content: center; min-width: 8.2rem; padding: .55rem .85rem; min-height: 52px }
63
+ #train span:first-child { color: #ffcd7a }
64
+ button:hover, .back:hover { background-color: #49625b }
65
+ @media (max-width: 780px) {
66
+ footer { align-items: flex-start; flex-direction: column; padding-top: 2.5rem }
67
+ .tools { max-width: 100%; flex-wrap: wrap }
68
+ .views button { padding-inline: .62rem }
69
+ #train { min-width: 7.1rem }
70
+ }
71
+ @media (max-height: 480px) {
72
+ footer { flex-direction: row; align-items: flex-end; padding-top: 1rem }
73
+ h1 { font-size: 1.9rem }
74
+ .caption p { display: none }
75
+ }
@@ -0,0 +1,47 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <meta name="theme-color" content="#152c2c">
7
+ <title>Alpine viaduct · Roamwright</title>
8
+ <link rel="stylesheet" href="./viaduct.css">
9
+ <script type="importmap">
10
+ {
11
+ "imports": {
12
+ "three": "../node_modules/three/build/three.module.js",
13
+ "three/addons/": "../node_modules/three/examples/jsm/",
14
+ "roamwright": "../index.js",
15
+ "roamwright/": "../"
16
+ }
17
+ }
18
+ </script>
19
+ </head>
20
+ <body>
21
+ <canvas tabindex="0" aria-label="Alpine railway in a forested river valley" aria-describedby="gestures keyboard-help"></canvas>
22
+ <header>
23
+ <a class="back" href="../index.html" aria-label="Back to Roamwright examples"><span aria-hidden="true">←</span> Roamwright</a>
24
+ <form method="get">
25
+ <label for="seed">Seed</label>
26
+ <input id="seed" name="seed" type="number" step="1" min="-2147483648" max="2147483647" value="42" required>
27
+ <button type="submit" title="Explore this seed" aria-label="Explore this seed">→</button>
28
+ </form>
29
+ </header>
30
+ <footer>
31
+ <div class="caption">
32
+ <h1>Alpine viaduct</h1>
33
+ <p id="gestures">Drag to orbit · Scroll or pinch to zoom</p>
34
+ </div>
35
+ <span id="keyboard-help" class="sr-only">With the scene focused, use the arrow keys to orbit and plus or minus to zoom.</span>
36
+ <div class="tools">
37
+ <div class="views" role="group" aria-label="Camera viewpoint">
38
+ <button type="button" data-view="valley" aria-pressed="true">Valley</button>
39
+ <button type="button" data-view="trackside" aria-pressed="false">Trackside</button>
40
+ <button type="button" data-view="riverbank" aria-pressed="false">Riverbank</button>
41
+ </div>
42
+ <button type="button" id="train"><span aria-hidden="true">▶</span> <span id="train-label">Run train</span></button>
43
+ </div>
44
+ </footer>
45
+ <script type="module" src="./viaduct.js"></script>
46
+ </body>
47
+ </html>