@jgengine/core 0.4.0 → 0.6.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 (51) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/dist/game/defineGame.d.ts +3 -0
  3. package/dist/game/feed.d.ts +2 -0
  4. package/dist/game/feed.js +10 -8
  5. package/dist/game/playableGame.d.ts +10 -1
  6. package/dist/game/progression.d.ts +61 -0
  7. package/dist/game/progression.js +96 -0
  8. package/dist/game/quest.d.ts +39 -0
  9. package/dist/game/quest.js +195 -0
  10. package/dist/game/trade.d.ts +23 -0
  11. package/dist/game/trade.js +50 -8
  12. package/dist/game/unlocks.d.ts +9 -0
  13. package/dist/game/unlocks.js +19 -1
  14. package/dist/inventory/slotModel.d.ts +19 -0
  15. package/dist/inventory/slotModel.js +76 -0
  16. package/dist/meta/changelog.d.ts +8 -0
  17. package/dist/meta/changelog.js +43 -0
  18. package/dist/physics/physicsWorld.d.ts +136 -0
  19. package/dist/physics/physicsWorld.js +489 -0
  20. package/dist/runtime/gameContext.d.ts +2 -0
  21. package/dist/runtime/gameContext.js +3 -0
  22. package/dist/scene/assetCatalog.d.ts +13 -0
  23. package/dist/scene/entityStore.d.ts +6 -0
  24. package/dist/scene/entityStore.js +15 -1
  25. package/dist/time/simClock.d.ts +62 -0
  26. package/dist/time/simClock.js +132 -0
  27. package/dist/world/buildingIndex.d.ts +16 -0
  28. package/dist/world/buildingIndex.js +63 -0
  29. package/dist/world/buildings.d.ts +98 -0
  30. package/dist/world/buildings.js +320 -0
  31. package/dist/world/features.d.ts +105 -1
  32. package/dist/world/features.js +95 -0
  33. package/dist/world/geometry.d.ts +23 -0
  34. package/dist/world/geometry.js +75 -0
  35. package/dist/world/interiors.d.ts +35 -0
  36. package/dist/world/interiors.js +66 -0
  37. package/dist/world/placement.d.ts +30 -0
  38. package/dist/world/placement.js +20 -0
  39. package/dist/world/regions.d.ts +66 -0
  40. package/dist/world/regions.js +158 -0
  41. package/dist/world/scatter.d.ts +24 -0
  42. package/dist/world/scatter.js +126 -0
  43. package/dist/world/scatterItems.d.ts +38 -0
  44. package/dist/world/scatterItems.js +85 -0
  45. package/dist/world/terrain.d.ts +54 -0
  46. package/dist/world/terrain.js +181 -0
  47. package/dist/world/water.d.ts +27 -0
  48. package/dist/world/water.js +125 -0
  49. package/dist/world/wind.d.ts +17 -0
  50. package/dist/world/wind.js +40 -0
  51. package/package.json +5 -2
@@ -0,0 +1,158 @@
1
+ import { fractalNoise, withNormal, } from "./terrain.js";
2
+ function toRgb(color, fallback) {
3
+ if (color === undefined)
4
+ return fallback;
5
+ if (typeof color !== "string")
6
+ return color;
7
+ const value = color.startsWith("#") ? color.slice(1) : color;
8
+ const int = Number.parseInt(value, 16);
9
+ return [((int >> 16) & 255) / 255, ((int >> 8) & 255) / 255, (int & 255) / 255];
10
+ }
11
+ function clamp01(value) {
12
+ return value < 0 ? 0 : value > 1 ? 1 : value;
13
+ }
14
+ function selectorNoise(x, z, seed, frequency) {
15
+ const config = { seed, frequency, octaves: 3, lacunarity: 2, persistence: 0.5, ridged: false };
16
+ return clamp01(0.5 + fractalNoise(x, z, config) * 0.9);
17
+ }
18
+ const DEFAULT_SELECTOR_FREQUENCY = 0.004;
19
+ const DEFAULT_SHARPNESS = 6;
20
+ export function createRegionField(config) {
21
+ if (config.regions.length === 0)
22
+ throw new Error("createRegionField: regions must be non-empty");
23
+ const seed = config.seed ?? 1337;
24
+ const regions = config.regions;
25
+ const seaLevel = config.seaLevel ?? 0;
26
+ const axes = regions[0].selector.length;
27
+ const sharpness = config.sharpness ?? DEFAULT_SHARPNESS;
28
+ const warp = config.warp ?? 40;
29
+ const heightConfigs = regions.map((region) => ({
30
+ seed: seed ^ hashId(region.id),
31
+ frequency: region.height.frequency,
32
+ octaves: region.height.octaves ?? 4,
33
+ lacunarity: region.height.lacunarity ?? 2,
34
+ persistence: region.height.persistence ?? 0.5,
35
+ ridged: region.height.ridged ?? false,
36
+ }));
37
+ const tints = regions.map((region) => toRgb(region.tint, [0.4, 0.42, 0.38]));
38
+ const steeps = regions.map((region, index) => toRgb(region.steepTint, tints[index]));
39
+ const waters = regions.map((region) => (region.water !== undefined ? toRgb(region.water, [0, 0, 0]) : null));
40
+ const fogs = regions.map((region) => (region.fog !== undefined ? toRgb(region.fog, [0, 0, 0]) : null));
41
+ const axisSeeds = Array.from({ length: axes }, (_, axis) => seed ^ (0x1111 * (axis + 1)));
42
+ const axisFrequencies = Array.from({ length: axes }, (_, axis) => config.selectorFrequencies?.[axis] ?? DEFAULT_SELECTOR_FREQUENCY);
43
+ const axisWeights = Array.from({ length: axes }, (_, axis) => config.axisWeights?.[axis] ?? 1);
44
+ const warpConfig = { seed: seed ^ 0x9e3779b1, frequency: 0.006, octaves: 2, lacunarity: 2, persistence: 0.5, ridged: false };
45
+ const sampleSelector = (x, z) => {
46
+ const wx = warp === 0 ? x : x + fractalNoise(x, z, warpConfig) * warp;
47
+ const wz = warp === 0 ? z : z + fractalNoise(z, x, warpConfig) * warp;
48
+ const values = new Array(axes);
49
+ for (let axis = 0; axis < axes; axis += 1) {
50
+ values[axis] = selectorNoise(wx, wz, axisSeeds[axis], axisFrequencies[axis]);
51
+ }
52
+ return values;
53
+ };
54
+ const weightsFor = (selector) => {
55
+ const raw = new Array(regions.length);
56
+ let total = 0;
57
+ for (let index = 0; index < regions.length; index += 1) {
58
+ const center = regions[index].selector;
59
+ let distanceSq = 0;
60
+ for (let axis = 0; axis < axes; axis += 1) {
61
+ const delta = (selector[axis] - center[axis]) * axisWeights[axis];
62
+ distanceSq += delta * delta;
63
+ }
64
+ const weight = Math.exp(-distanceSq * sharpness * regions.length);
65
+ raw[index] = weight;
66
+ total += weight;
67
+ }
68
+ if (total > 0)
69
+ for (let index = 0; index < raw.length; index += 1)
70
+ raw[index] /= total;
71
+ return raw;
72
+ };
73
+ const regionHeight = (index, x, z) => regions[index].height.baseHeight + regions[index].height.amplitude * fractalNoise(x, z, heightConfigs[index]);
74
+ const sampleHeight = (x, z) => {
75
+ const weights = weightsFor(sampleSelector(x, z));
76
+ let height = 0;
77
+ for (let index = 0; index < weights.length; index += 1) {
78
+ if (weights[index] < 0.01)
79
+ continue;
80
+ height += weights[index] * regionHeight(index, x, z);
81
+ }
82
+ return height;
83
+ };
84
+ const sampleRegion = (x, z) => {
85
+ const selector = sampleSelector(x, z);
86
+ const weights = weightsFor(selector);
87
+ let dominant = 0;
88
+ const tint = [0, 0, 0];
89
+ const steep = [0, 0, 0];
90
+ const water = [0, 0, 0];
91
+ let waterWeight = 0;
92
+ const fog = [0, 0, 0];
93
+ let fogWeight = 0;
94
+ let fogDensity = 0;
95
+ let speed = 0;
96
+ let speedWeight = 0;
97
+ for (let index = 0; index < weights.length; index += 1) {
98
+ const weight = weights[index];
99
+ if (weight > weights[dominant])
100
+ dominant = index;
101
+ if (weight < 0.01)
102
+ continue;
103
+ for (let channel = 0; channel < 3; channel += 1) {
104
+ tint[channel] += tints[index][channel] * weight;
105
+ steep[channel] += steeps[index][channel] * weight;
106
+ }
107
+ const w = waters[index];
108
+ if (w !== null) {
109
+ for (let channel = 0; channel < 3; channel += 1)
110
+ water[channel] += w[channel] * weight;
111
+ waterWeight += weight;
112
+ }
113
+ const f = fogs[index];
114
+ if (f !== null) {
115
+ for (let channel = 0; channel < 3; channel += 1)
116
+ fog[channel] += f[channel] * weight;
117
+ fogWeight += weight;
118
+ fogDensity += (regions[index].fogDensity ?? 0) * weight;
119
+ }
120
+ speed += (regions[index].speedMultiplier ?? 1) * weight;
121
+ speedWeight += weight;
122
+ }
123
+ const normalize = (rgb, weight) => weight > 0 ? [rgb[0] / weight, rgb[1] / weight, rgb[2] / weight] : rgb;
124
+ return {
125
+ region: regions[dominant],
126
+ weight: weights[dominant],
127
+ selector,
128
+ tint,
129
+ steepTint: steep,
130
+ water: waterWeight > 0.05 ? normalize(water, waterWeight) : null,
131
+ fog: fogWeight > 0.05 ? normalize(fog, fogWeight) : null,
132
+ fogDensity: fogWeight > 0.05 ? fogDensity / fogWeight : 0,
133
+ speedMultiplier: speedWeight > 0 ? speed / speedWeight : 1,
134
+ data: regions[dominant].data,
135
+ };
136
+ };
137
+ return {
138
+ sampleHeight,
139
+ sampleNormal: withNormal(sampleHeight),
140
+ sampleRegion,
141
+ regions,
142
+ seaLevel,
143
+ seed,
144
+ waterLevel: seaLevel,
145
+ bounds: config.bounds,
146
+ };
147
+ }
148
+ function hashId(id) {
149
+ let hash = 2166136261;
150
+ for (let index = 0; index < id.length; index += 1) {
151
+ hash ^= id.charCodeAt(index);
152
+ hash = Math.imul(hash, 16777619);
153
+ }
154
+ return hash | 0;
155
+ }
156
+ export function isRegionField(field) {
157
+ return "sampleRegion" in field;
158
+ }
@@ -0,0 +1,24 @@
1
+ import { type Aabb, type Vec2 } from "./geometry.js";
2
+ export interface ScatterArea {
3
+ w: number;
4
+ d: number;
5
+ center?: Vec2;
6
+ }
7
+ export interface ScatterConfig {
8
+ area: ScatterArea | Aabb;
9
+ count?: number;
10
+ density?: number;
11
+ seed?: string | number;
12
+ minDistance?: number;
13
+ avoid?: readonly Aabb[];
14
+ avoidMargin?: number;
15
+ jitter?: number;
16
+ maxAttempts?: number;
17
+ }
18
+ export interface ScatterPoint {
19
+ x: number;
20
+ z: number;
21
+ index: number;
22
+ }
23
+ export declare function scatterAabb(area: ScatterArea | Aabb): Aabb;
24
+ export declare function scatter(config: ScatterConfig): ScatterPoint[];
@@ -0,0 +1,126 @@
1
+ import { expandAabb, pointInAabb } from "./geometry.js";
2
+ function isAabb(area) {
3
+ return (typeof area.minX === "number" &&
4
+ typeof area.minZ === "number" &&
5
+ typeof area.maxX === "number" &&
6
+ typeof area.maxZ === "number");
7
+ }
8
+ export function scatterAabb(area) {
9
+ if (isAabb(area)) {
10
+ return { minX: area.minX, minZ: area.minZ, maxX: area.maxX, maxZ: area.maxZ };
11
+ }
12
+ const cx = area.center ? area.center[0] : 0;
13
+ const cz = area.center ? area.center[1] : 0;
14
+ const halfW = area.w / 2;
15
+ const halfD = area.d / 2;
16
+ return { minX: cx - halfW, minZ: cz - halfD, maxX: cx + halfW, maxZ: cz + halfD };
17
+ }
18
+ function hashSeed(seed) {
19
+ const text = typeof seed === "number" ? seed.toString() : seed;
20
+ let h = 2166136261 >>> 0;
21
+ for (let i = 0; i < text.length; i++) {
22
+ h ^= text.charCodeAt(i);
23
+ h = Math.imul(h, 16777619);
24
+ }
25
+ return h >>> 0;
26
+ }
27
+ function mulberry32(state) {
28
+ let a = state >>> 0;
29
+ return () => {
30
+ a = (a + 0x6d2b79f5) >>> 0;
31
+ let t = a;
32
+ t = Math.imul(t ^ (t >>> 15), t | 1);
33
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
34
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
35
+ };
36
+ }
37
+ export function scatter(config) {
38
+ const aabb = scatterAabb(config.area);
39
+ const width = aabb.maxX - aabb.minX;
40
+ const depth = aabb.maxZ - aabb.minZ;
41
+ const density = config.density ?? 0.01;
42
+ const target = config.count ?? Math.max(0, Math.floor(width * depth * density));
43
+ if (target <= 0 || width <= 0 || depth <= 0)
44
+ return [];
45
+ const minDistance = config.minDistance ?? 0;
46
+ const avoidMargin = config.avoidMargin ?? 0;
47
+ const jitter = config.jitter ?? 1;
48
+ const maxAttempts = config.maxAttempts ?? target * 30;
49
+ const avoid = (config.avoid ?? []).map((a) => (avoidMargin !== 0 ? expandAabb(a, avoidMargin) : a));
50
+ const rng = mulberry32(hashSeed(config.seed ?? "scatter"));
51
+ const useDistance = minDistance > 0;
52
+ const buckets = new Map();
53
+ const bucketKey = (x, z) => `${Math.floor(x / minDistance)}:${Math.floor(z / minDistance)}`;
54
+ const rejectedByAvoid = (point) => {
55
+ for (const a of avoid)
56
+ if (pointInAabb(point, a))
57
+ return true;
58
+ return false;
59
+ };
60
+ const rejectedByDistance = (point) => {
61
+ if (!useDistance)
62
+ return false;
63
+ const cx = Math.floor(point[0] / minDistance);
64
+ const cz = Math.floor(point[1] / minDistance);
65
+ const minSq = minDistance * minDistance;
66
+ for (let dx = -1; dx <= 1; dx++) {
67
+ for (let dz = -1; dz <= 1; dz++) {
68
+ const nearby = buckets.get(`${cx + dx}:${cz + dz}`);
69
+ if (!nearby)
70
+ continue;
71
+ for (const other of nearby) {
72
+ const ex = other[0] - point[0];
73
+ const ez = other[1] - point[1];
74
+ if (ex * ex + ez * ez < minSq)
75
+ return true;
76
+ }
77
+ }
78
+ }
79
+ return false;
80
+ };
81
+ const accepted = [];
82
+ const commit = (point) => {
83
+ accepted.push({ x: point[0], z: point[1], index: accepted.length });
84
+ if (useDistance) {
85
+ const key = bucketKey(point[0], point[1]);
86
+ const bucket = buckets.get(key);
87
+ if (bucket)
88
+ bucket.push(point);
89
+ else
90
+ buckets.set(key, [point]);
91
+ }
92
+ };
93
+ const cols = Math.max(1, Math.ceil(Math.sqrt(target * (width / depth))));
94
+ const rows = Math.max(1, Math.ceil(target / cols));
95
+ const cellW = width / cols;
96
+ const cellD = depth / rows;
97
+ for (let row = 0; row < rows && accepted.length < target; row++) {
98
+ for (let col = 0; col < cols && accepted.length < target; col++) {
99
+ const baseX = aabb.minX + (col + 0.5) * cellW;
100
+ const baseZ = aabb.minZ + (row + 0.5) * cellD;
101
+ const x = baseX + jitter * (rng() - 0.5) * cellW;
102
+ const z = baseZ + jitter * (rng() - 0.5) * cellD;
103
+ const point = [x, z];
104
+ if (!pointInAabb(point, aabb))
105
+ continue;
106
+ if (rejectedByAvoid(point))
107
+ continue;
108
+ if (rejectedByDistance(point))
109
+ continue;
110
+ commit(point);
111
+ }
112
+ }
113
+ let attempts = 0;
114
+ while (accepted.length < target && attempts < maxAttempts) {
115
+ attempts++;
116
+ const x = aabb.minX + rng() * width;
117
+ const z = aabb.minZ + rng() * depth;
118
+ const point = [x, z];
119
+ if (rejectedByAvoid(point))
120
+ continue;
121
+ if (rejectedByDistance(point))
122
+ continue;
123
+ commit(point);
124
+ }
125
+ return accepted;
126
+ }
@@ -0,0 +1,38 @@
1
+ import type { Aabb } from "./geometry.js";
2
+ import type { RegionField, RegionSample } from "./regions.js";
3
+ /** One placeable class. `item` is an opaque id the caller maps to a mesh/entity. */
4
+ export interface ScatterLayer {
5
+ item: string;
6
+ density: number;
7
+ minScale?: number;
8
+ maxScale?: number;
9
+ maxSlope?: number;
10
+ aboveWaterOnly?: boolean;
11
+ }
12
+ export interface ScatterInstance {
13
+ id: string;
14
+ item: string;
15
+ x: number;
16
+ z: number;
17
+ y: number;
18
+ scale: number;
19
+ rotation: number;
20
+ regionId: string;
21
+ }
22
+ /**
23
+ * Deterministically place opaque items across `area`, grounded on a region field.
24
+ * For each grid cell it asks `layersFor` which items may appear in that region and
25
+ * rolls one against their densities. The engine never interprets `item` — a game
26
+ * maps it to a mesh or entity. Content scatter (region-driven density) as opposed to
27
+ * `scatter` in `./scatter`, which is renderer-free geometric point distribution.
28
+ */
29
+ export declare function scatterItems<T>(field: RegionField<T>, area: Aabb, layersFor: (sample: RegionSample<T>) => readonly ScatterLayer[], options?: {
30
+ cell?: number;
31
+ max?: number;
32
+ saltKey?: number;
33
+ }): ScatterInstance[];
34
+ /** Weighted pick from opaque entries; `roll` in [0, 1). Returns null when empty. */
35
+ export declare function pickWeighted<T>(entries: readonly {
36
+ value: T;
37
+ weight: number;
38
+ }[], roll: number): T | null;
@@ -0,0 +1,85 @@
1
+ function hash(ix, iz, salt) {
2
+ let h = salt | 0;
3
+ h = Math.imul(h ^ (ix | 0), 0x27d4eb2d);
4
+ h = Math.imul(h ^ (iz | 0), 0x85ebca6b);
5
+ h ^= h >>> 15;
6
+ h = Math.imul(h, 0x2c1b3c6d);
7
+ h ^= h >>> 12;
8
+ return (h >>> 0) / 4294967295;
9
+ }
10
+ const DEFAULT_MAX_SLOPE = 0.55;
11
+ /**
12
+ * Deterministically place opaque items across `area`, grounded on a region field.
13
+ * For each grid cell it asks `layersFor` which items may appear in that region and
14
+ * rolls one against their densities. The engine never interprets `item` — a game
15
+ * maps it to a mesh or entity. Content scatter (region-driven density) as opposed to
16
+ * `scatter` in `./scatter`, which is renderer-free geometric point distribution.
17
+ */
18
+ export function scatterItems(field, area, layersFor, options = {}) {
19
+ const cell = options.cell ?? 5;
20
+ const max = options.max ?? 1400;
21
+ const salt = field.seed ^ (options.saltKey ?? 0x5f3a);
22
+ const out = [];
23
+ for (let gx = Math.floor(area.minX / cell); gx <= Math.ceil(area.maxX / cell); gx += 1) {
24
+ for (let gz = Math.floor(area.minZ / cell); gz <= Math.ceil(area.maxZ / cell); gz += 1) {
25
+ const roll = hash(gx, gz, salt);
26
+ const x = (gx + hash(gx, gz, salt ^ 0x11)) * cell;
27
+ const z = (gz + hash(gx, gz, salt ^ 0x22)) * cell;
28
+ const y = field.sampleHeight(x, z);
29
+ const sample = field.sampleRegion(x, z);
30
+ const layers = layersFor(sample);
31
+ if (layers.length === 0)
32
+ continue;
33
+ let total = 0;
34
+ for (const layer of layers)
35
+ total += layer.density;
36
+ if (roll > total)
37
+ continue;
38
+ let acc = 0;
39
+ let chosen = layers[0];
40
+ for (const layer of layers) {
41
+ acc += layer.density;
42
+ if (roll <= acc) {
43
+ chosen = layer;
44
+ break;
45
+ }
46
+ }
47
+ if ((chosen.aboveWaterOnly ?? true) && y < field.seaLevel + 0.1)
48
+ continue;
49
+ if (1 - field.sampleNormal(x, z)[1] > (chosen.maxSlope ?? DEFAULT_MAX_SLOPE))
50
+ continue;
51
+ const scaleRoll = hash(gx, gz, salt ^ 0x99);
52
+ const min = chosen.minScale ?? 0.8;
53
+ const maxScale = chosen.maxScale ?? 1.2;
54
+ out.push({
55
+ id: `${gx}:${gz}`,
56
+ item: chosen.item,
57
+ x,
58
+ z,
59
+ y,
60
+ scale: min + scaleRoll * (maxScale - min),
61
+ rotation: hash(gx, gz, salt ^ 0xabcd) * Math.PI * 2,
62
+ regionId: sample.region.id,
63
+ });
64
+ if (out.length >= max)
65
+ return out;
66
+ }
67
+ }
68
+ return out;
69
+ }
70
+ /** Weighted pick from opaque entries; `roll` in [0, 1). Returns null when empty. */
71
+ export function pickWeighted(entries, roll) {
72
+ if (entries.length === 0)
73
+ return null;
74
+ let total = 0;
75
+ for (const entry of entries)
76
+ total += entry.weight;
77
+ const pick = roll * total;
78
+ let acc = 0;
79
+ for (const entry of entries) {
80
+ acc += entry.weight;
81
+ if (pick <= acc)
82
+ return entry.value;
83
+ }
84
+ return entries[entries.length - 1].value;
85
+ }
@@ -0,0 +1,54 @@
1
+ import type { TerrainEnvironmentDescriptor, WorldBounds } from "./features.js";
2
+ export type TerrainNormal = readonly [number, number, number];
3
+ export interface TerrainField {
4
+ sampleHeight(x: number, z: number): number;
5
+ sampleNormal(x: number, z: number): TerrainNormal;
6
+ readonly bounds?: WorldBounds;
7
+ readonly waterLevel?: number;
8
+ }
9
+ export declare function valueNoise(x: number, z: number, seed: number): number;
10
+ export interface FractalNoiseConfig {
11
+ seed: number;
12
+ frequency: number;
13
+ octaves: number;
14
+ lacunarity: number;
15
+ persistence: number;
16
+ ridged: boolean;
17
+ }
18
+ export declare function fractalNoise(x: number, z: number, config: FractalNoiseConfig): number;
19
+ export declare function seedFrom(value: string | number | undefined, fallback: number): number;
20
+ export declare function withNormal(sampleHeight: (x: number, z: number) => number): TerrainField["sampleNormal"];
21
+ export declare const FLAT_FIELD: TerrainField;
22
+ export declare function flatField(): TerrainField;
23
+ export interface NoiseFieldConfig {
24
+ seed?: string | number;
25
+ amplitude?: number;
26
+ frequency?: number;
27
+ octaves?: number;
28
+ lacunarity?: number;
29
+ persistence?: number;
30
+ baseHeight?: number;
31
+ ridged?: boolean;
32
+ bounds?: WorldBounds;
33
+ waterLevel?: number;
34
+ }
35
+ export declare function noiseField(config?: NoiseFieldConfig): TerrainField;
36
+ export interface RollingFieldConfig {
37
+ seed?: string | number;
38
+ amplitude?: number;
39
+ frequency?: number;
40
+ bounds?: WorldBounds;
41
+ }
42
+ export declare function rollingField(config?: RollingFieldConfig): TerrainField;
43
+ export interface ArenaFieldConfig {
44
+ seed?: string | number;
45
+ bounds?: WorldBounds;
46
+ }
47
+ export declare const ARENA_WATER_LEVEL = -0.9;
48
+ export declare function arenaField(config?: ArenaFieldConfig): TerrainField;
49
+ export declare function resolveTerrainField(descriptor?: TerrainEnvironmentDescriptor): TerrainField;
50
+ export declare const DEFAULT_MAX_WALK_SLOPE = 0.6;
51
+ export declare function resolveGroundStep(field: TerrainField, x: number, z: number, stepX: number, stepZ: number, maxSlope?: number): {
52
+ stepX: number;
53
+ stepZ: number;
54
+ };
@@ -0,0 +1,181 @@
1
+ function clamp01(value) {
2
+ return value < 0 ? 0 : value > 1 ? 1 : value;
3
+ }
4
+ function lerp(a, b, t) {
5
+ return a + (b - a) * t;
6
+ }
7
+ function hash2(ix, iz, seed) {
8
+ let h = seed | 0;
9
+ h = Math.imul(h ^ (ix | 0), 0x27d4eb2d);
10
+ h = Math.imul(h ^ (iz | 0), 0x85ebca6b);
11
+ h ^= h >>> 15;
12
+ h = Math.imul(h, 0x2c1b3c6d);
13
+ h ^= h >>> 12;
14
+ return (h >>> 0) / 4294967295;
15
+ }
16
+ export function valueNoise(x, z, seed) {
17
+ const x0 = Math.floor(x);
18
+ const z0 = Math.floor(z);
19
+ const fx = x - x0;
20
+ const fz = z - z0;
21
+ const v00 = hash2(x0, z0, seed);
22
+ const v10 = hash2(x0 + 1, z0, seed);
23
+ const v01 = hash2(x0, z0 + 1, seed);
24
+ const v11 = hash2(x0 + 1, z0 + 1, seed);
25
+ const sx = fx * fx * (3 - 2 * fx);
26
+ const sz = fz * fz * (3 - 2 * fz);
27
+ const top = lerp(v00, v10, sx);
28
+ const bottom = lerp(v01, v11, sx);
29
+ return lerp(top, bottom, sz) * 2 - 1;
30
+ }
31
+ export function fractalNoise(x, z, config) {
32
+ let amplitude = 1;
33
+ let frequency = config.frequency;
34
+ let sum = 0;
35
+ let norm = 0;
36
+ for (let octave = 0; octave < config.octaves; octave += 1) {
37
+ let sample = valueNoise(x * frequency, z * frequency, config.seed + octave * 1013);
38
+ if (config.ridged)
39
+ sample = 1 - 2 * Math.abs(sample);
40
+ sum += sample * amplitude;
41
+ norm += amplitude;
42
+ amplitude *= config.persistence;
43
+ frequency *= config.lacunarity;
44
+ }
45
+ return norm === 0 ? 0 : sum / norm;
46
+ }
47
+ export function seedFrom(value, fallback) {
48
+ if (typeof value === "number")
49
+ return value | 0;
50
+ if (typeof value === "string") {
51
+ let hash = 2166136261;
52
+ for (let index = 0; index < value.length; index += 1) {
53
+ hash ^= value.charCodeAt(index);
54
+ hash = Math.imul(hash, 16777619);
55
+ }
56
+ return hash | 0;
57
+ }
58
+ return fallback;
59
+ }
60
+ export function withNormal(sampleHeight) {
61
+ const epsilon = 0.75;
62
+ return (x, z) => {
63
+ const hx = sampleHeight(x + epsilon, z) - sampleHeight(x - epsilon, z);
64
+ const hz = sampleHeight(x, z + epsilon) - sampleHeight(x, z - epsilon);
65
+ const nx = -hx;
66
+ const nz = -hz;
67
+ const ny = 2 * epsilon;
68
+ const length = Math.hypot(nx, ny, nz) || 1;
69
+ return [nx / length, ny / length, nz / length];
70
+ };
71
+ }
72
+ function fieldFromHeight(sampleHeight, extra) {
73
+ return {
74
+ sampleHeight,
75
+ sampleNormal: withNormal(sampleHeight),
76
+ ...(extra?.bounds === undefined ? {} : { bounds: extra.bounds }),
77
+ ...(extra?.waterLevel === undefined ? {} : { waterLevel: extra.waterLevel }),
78
+ };
79
+ }
80
+ export const FLAT_FIELD = {
81
+ sampleHeight: () => 0,
82
+ sampleNormal: () => [0, 1, 0],
83
+ };
84
+ export function flatField() {
85
+ return FLAT_FIELD;
86
+ }
87
+ export function noiseField(config = {}) {
88
+ const fractal = {
89
+ seed: seedFrom(config.seed, 1337),
90
+ frequency: config.frequency ?? 0.03,
91
+ octaves: config.octaves ?? 4,
92
+ lacunarity: config.lacunarity ?? 2,
93
+ persistence: config.persistence ?? 0.5,
94
+ ridged: config.ridged ?? false,
95
+ };
96
+ const amplitude = config.amplitude ?? 1;
97
+ const baseHeight = config.baseHeight ?? 0;
98
+ return fieldFromHeight((x, z) => baseHeight + amplitude * fractalNoise(x, z, fractal), {
99
+ bounds: config.bounds,
100
+ waterLevel: config.waterLevel,
101
+ });
102
+ }
103
+ export function rollingField(config = {}) {
104
+ return noiseField({
105
+ seed: config.seed ?? "rolling",
106
+ amplitude: config.amplitude ?? 0.55,
107
+ frequency: config.frequency ?? 0.03,
108
+ octaves: 3,
109
+ persistence: 0.55,
110
+ bounds: config.bounds,
111
+ });
112
+ }
113
+ const ARENA_PLATEAU_HEIGHT = 6;
114
+ const ARENA_HILL_HEIGHT = 4.2;
115
+ const ARENA_BASIN_DEPTH = 2.6;
116
+ export const ARENA_WATER_LEVEL = -0.9;
117
+ function smoothstep(edge0, edge1, value) {
118
+ if (edge0 === edge1)
119
+ return value < edge0 ? 0 : 1;
120
+ const t = clamp01((value - edge0) / (edge1 - edge0));
121
+ return t * t * (3 - 2 * t);
122
+ }
123
+ export function arenaField(config = {}) {
124
+ const seed = seedFrom(config.seed ?? "arena", 7);
125
+ const rolling = {
126
+ seed,
127
+ frequency: 0.03,
128
+ octaves: 3,
129
+ lacunarity: 2,
130
+ persistence: 0.5,
131
+ ridged: false,
132
+ };
133
+ const sampleHeight = (x, z) => {
134
+ const distToSpawn = Math.hypot(x, z);
135
+ const spawn = 1 - smoothstep(14, 24, distToSpawn);
136
+ const undulation = 0.55 * fractalNoise(x, z, rolling);
137
+ const cliff = smoothstep(20, 27, z);
138
+ const ramp = smoothstep(16, 46, z);
139
+ const inRamp = 1 - clamp01(Math.abs(x) / 6);
140
+ const plateauExtent = 1 - smoothstep(30, 42, Math.abs(x));
141
+ const mesa = ARENA_PLATEAU_HEIGHT * plateauExtent * lerp(cliff, ramp, inRamp);
142
+ const hillDist = Math.hypot(x - 34, z + 8) / 18;
143
+ const hillFalloff = smoothstep(0, 1, 1 - hillDist);
144
+ const hill = ARENA_HILL_HEIGHT * hillFalloff;
145
+ const basinDist = Math.hypot(x + 40, z + 20) / 20;
146
+ const basin = -ARENA_BASIN_DEPTH * smoothstep(0, 1, 1 - basinDist);
147
+ return (undulation + mesa + hill + basin) * (1 - spawn);
148
+ };
149
+ return fieldFromHeight(sampleHeight, { bounds: config.bounds, waterLevel: ARENA_WATER_LEVEL });
150
+ }
151
+ export function resolveTerrainField(descriptor) {
152
+ if (descriptor === undefined)
153
+ return flatField();
154
+ return noiseField({
155
+ seed: descriptor.seed,
156
+ amplitude: descriptor.height,
157
+ frequency: descriptor.frequency,
158
+ octaves: descriptor.octaves,
159
+ ridged: descriptor.ridged,
160
+ baseHeight: descriptor.baseHeight,
161
+ waterLevel: descriptor.waterLevel,
162
+ bounds: descriptor.bounds,
163
+ });
164
+ }
165
+ export const DEFAULT_MAX_WALK_SLOPE = 0.6;
166
+ export function resolveGroundStep(field, x, z, stepX, stepZ, maxSlope = DEFAULT_MAX_WALK_SLOPE) {
167
+ const baseHeight = field.sampleHeight(x, z);
168
+ const tooSteep = (dx, dz) => {
169
+ const distance = Math.hypot(dx, dz);
170
+ if (distance < 1e-6)
171
+ return false;
172
+ const rise = field.sampleHeight(x + dx, z + dz) - baseHeight;
173
+ return rise / distance > maxSlope;
174
+ };
175
+ if (!tooSteep(stepX, stepZ))
176
+ return { stepX, stepZ };
177
+ return {
178
+ stepX: tooSteep(stepX, 0) ? 0 : stepX,
179
+ stepZ: tooSteep(0, stepZ) ? 0 : stepZ,
180
+ };
181
+ }