diff --git a/README.md b/README.md index 5bbf41f..7727624 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,8 @@ Desktop: On touch devices, the game displays a wide steering surface on the left and large throttle/brake controls on the right, plus **AUTO** and **RESET** buttons. Landscape orientation is recommended but portrait remains usable. +Standard-mapped Xbox and PlayStation-style gamepads are supported. The left stick steers, RT/R2 accelerates, LT/L2 brakes, A/Cross applies the handbrake channel, Y/Triangle changes camera, B/Circle resets the car, the D-pad adjusts cruise speed or changes music, Start/Options opens settings, and the right stick orbits the camera. Deadzones, vibration, and connection status are available under **CONTROLS** in the settings panel. + Steering takes over from autopilot immediately, while braking disengages both autopilot and cruise control. The accelerator remains available as a temporary speed override. The instrument-style cruise panel sets a shared target from 5 to 375 km/h for both manual driving and autopilot. In manual mode cruise controls the pedals while the player steers. Holding the accelerator temporarily overrides the target for a smooth boost; releasing it returns to the selected speed. Braking disengages both cruise control and autopilot. Steering takes over from autopilot without dropping the active cruise target. @@ -85,7 +87,7 @@ Landscape detail is split into near (88 m), mid (280 m), and far (820 m) zones. - `src/game` — main loop, renderer, scene, resize handling, damped cameras - `src/world` — deterministic road function, chunk pool, terrain, procedural vegetation factory, instancing, shader wind, and LOD - `src/vehicle` — original lofted muscle-coupe model, lightweight vehicle dynamics, autopilot -- `src/input` — keyboard and Pointer Events input +- `src/input` — unified keyboard, Pointer Events, and standard Gamepad API input - `src/audio` — synthesized engine and band-limited tire rumble, plus a very low-level oscillator airflow layer without looping white-noise wind - `src/ui` — start screen and responsive HUD - `src/config` — centralized tuning values diff --git a/package.json b/package.json index 19638f6..47930ec 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,7 @@ "prebuild": "npm run music:manifest", "build": "tsc -b && vite build", "typecheck": "tsc -b --pretty false", + "test:regions": "node scripts/run-region-probes.mjs", "preview": "vite preview" }, "dependencies": { diff --git a/scripts/run-region-probes.mjs b/scripts/run-region-probes.mjs new file mode 100644 index 0000000..5a689f0 --- /dev/null +++ b/scripts/run-region-probes.mjs @@ -0,0 +1,56 @@ +import { build } from 'esbuild'; + +globalThis.matchMedia ??= () => ({ matches: false }); +globalThis.navigator ??= { maxTouchPoints: 0, userAgent: 'region-probe' }; +globalThis.requestIdleCallback ??= () => 1; +globalThis.cancelIdleCallback ??= () => undefined; +globalThis.window ??= globalThis; + +const source = ` + import { CONFIG } from './src/config/gameConfig.ts'; + import { InfiniteWorld } from './src/world/InfiniteWorld.ts'; + import { RoadGenerator } from './src/world/RoadGenerator.ts'; + import { runRegionScheduleProbe } from './src/world/WorldRegionDirector.ts'; + export function run() { + const road = new RoadGenerator(CONFIG.seed); + const world = new InfiniteWorld(); + const schedule = runRegionScheduleProbe(CONFIG.seed, 1_000_000); + const continuity = road.runRegionContinuityProbe(1_000_000); + const bridgeSurface = road.runBridgeSurfaceProbe(); + const riverCorridor = road.runRiverCorridorProbe(); + const fieldParcels = road.fieldParcels.runProbe(); + const firstFields = world.road.regions.nextSpecial(0, 'fields'); + world.update(firstFields.startDistance + firstFields.transitionDistance + 500, true); + const fieldRender = world.getDebugStats(); + const lifecycle = world.runRegionLifecycleProbe(500_000); + const fieldPerformance = fieldRender.chunks === fieldRender.expectedActiveChunks && fieldRender.sceneObjects < 3500; + return { schedule, continuity, bridgeSurface, riverCorridor, fieldParcels, + fieldRender: { chunks: fieldRender.chunks, sceneObjects: fieldRender.sceneObjects, + vegetationInstances: fieldRender.vegetationInstances, trees: fieldRender.treesNear + fieldRender.treesMid + fieldRender.treesFar, + shrubs: fieldRender.shrubs, grassPlants: fieldRender.grassPlants }, lifecycle, + passed: schedule.passed && continuity && bridgeSurface && riverCorridor && fieldParcels.passed && fieldPerformance && lifecycle.passed }; + } +`; + +const bundle = await build({ + stdin: { contents: source, resolveDir: process.cwd(), loader: 'ts' }, + bundle: true, + platform: 'node', + format: 'esm', + write: false, + logLevel: 'silent', + define: { + 'import.meta.env.DEV': 'false', + 'import.meta.env.PROD': 'true' + } +}); +const encoded = Buffer.from(bundle.outputFiles[0].text).toString('base64'); +try { + const module = await import(`data:text/javascript;base64,${encoded}`); + const result = module.run(); + console.log(JSON.stringify(result, null, 2)); + if (!result.passed) process.exitCode = 1; +} catch (error) { + console.error(error instanceof Error ? `${error.name}: ${error.message}` : String(error)); + process.exitCode = 1; +} diff --git a/src/audio/MusicPlayer.ts b/src/audio/MusicPlayer.ts index 5e12eb8..c433d41 100644 --- a/src/audio/MusicPlayer.ts +++ b/src/audio/MusicPlayer.ts @@ -265,6 +265,9 @@ export class MusicPlayer { if (play) void this.play().catch(() => this.renderPlayback()); } + previousTrack(): void { this.previous(); } + nextTrack(): void { this.next(true); } + private async togglePlay(): Promise { if (this.tracks.length === 0) return; if (this.audio.paused) await this.play().catch(() => undefined); diff --git a/src/config/GraphicsSettings.ts b/src/config/GraphicsSettings.ts index c884107..e61257e 100644 --- a/src/config/GraphicsSettings.ts +++ b/src/config/GraphicsSettings.ts @@ -1,7 +1,10 @@ +import { DEFAULT_VEHICLE_COLOR, isVehicleColor } from './VehicleColors'; + export type TimeMode = 'day' | 'night' | 'auto'; export type CloudQuality = 'low' | 'medium' | 'high'; export interface GraphicsSettings { + vehicleColor: string; renderScale: number; drawDistance: number; terrainDistance: number; treeNearDistance: number; treeMidDistance: number; treeFarDistance: number; bushDistance: number; grassDistance: number; vegetationDensity: number; grassDensity: number; bushDensity: number; treeDensity: number; objectDensity: number; @@ -15,6 +18,7 @@ export interface GraphicsSettings { } export const DEFAULT_GRAPHICS_SETTINGS: Readonly = { + vehicleColor: DEFAULT_VEHICLE_COLOR, renderScale: 1, drawDistance: 700, terrainDistance: 800, treeNearDistance: 95, treeMidDistance: 260, treeFarDistance: 600, bushDistance: 200, grassDistance: 65, vegetationDensity: 100, grassDensity: 100, bushDensity: 100, treeDensity: 100, objectDensity: 100, @@ -32,7 +36,9 @@ const STORAGE_KEY = 'quiet-mile.graphics.v2'; export function loadGraphicsSettings(): GraphicsSettings { try { const parsed = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}') as Partial; - return { ...DEFAULT_GRAPHICS_SETTINGS, ...parsed }; + const settings = { ...DEFAULT_GRAPHICS_SETTINGS, ...parsed }; + settings.vehicleColor = isVehicleColor(parsed.vehicleColor) ? parsed.vehicleColor.toLowerCase() : DEFAULT_VEHICLE_COLOR; + return settings; } catch { return { ...DEFAULT_GRAPHICS_SETTINGS }; } } diff --git a/src/config/VehicleColors.ts b/src/config/VehicleColors.ts new file mode 100644 index 0000000..9ec1fd9 --- /dev/null +++ b/src/config/VehicleColors.ts @@ -0,0 +1,29 @@ +export interface VehicleColorOption { + readonly name: string; + readonly value: string; +} + +export const VEHICLE_COLORS: readonly VehicleColorOption[] = [ + { name: 'Black', value: '#101315' }, + { name: 'Graphite', value: '#343a3d' }, + { name: 'Silver', value: '#a5aaad' }, + { name: 'White', value: '#d7d6d0' }, + { name: 'Dark Red', value: '#8e1f17' }, + { name: 'Classic Red', value: '#b52a20' }, + { name: 'Burgundy', value: '#5d1720' }, + { name: 'Orange', value: '#b8511e' }, + { name: 'Yellow', value: '#c3a52f' }, + { name: 'British Green', value: '#193f2f' }, + { name: 'Dark Green', value: '#173027' }, + { name: 'Teal', value: '#1d5a5b' }, + { name: 'Dark Blue', value: '#172b49' }, + { name: 'Classic Blue', value: '#245486' }, + { name: 'Purple', value: '#4b315f' }, + { name: 'Bronze / Copper', value: '#8a5639' } +]; + +export const DEFAULT_VEHICLE_COLOR = '#8e1f17'; + +export function isVehicleColor(value: unknown): value is string { + return typeof value === 'string' && VEHICLE_COLORS.some((option) => option.value === value.toLowerCase()); +} diff --git a/src/game/CameraController.ts b/src/game/CameraController.ts index 3fa670e..e0ed112 100644 --- a/src/game/CameraController.ts +++ b/src/game/CameraController.ts @@ -143,6 +143,19 @@ export class CameraController { setEffects(settings: GraphicsSettings): void { this.settings = settings; } + applyGamepadOrbit(x: number, y: number, dt: number): void { + if (x === 0 && y === 0) { + if (this.orbitPointer === null) this.isUserOrbiting = false; + return; + } + if (this.mode === 2) return; + this.targetOrbitYaw = this.wrapAngle(this.targetOrbitYaw - x * 2.25 * dt); + this.targetOrbitPitch = MathUtils.clamp(this.targetOrbitPitch - y * 1.7 * dt, + CONFIG.camera.orbitMinPitch, CONFIG.camera.orbitMaxPitch); + this.lastUserCameraInputTime = performance.now() * .001; + this.isUserOrbiting = true; + } + update(dt: number, vehicle: Vehicle, bass?: BassAnalysis): void { this.elapsed += dt; // Remove last frame's presentation-only kick before calculating the diff --git a/src/game/Game.ts b/src/game/Game.ts index cf362b8..49876d2 100644 --- a/src/game/Game.ts +++ b/src/game/Game.ts @@ -12,9 +12,10 @@ import { MusicPlayer, type BassAnalysis } from '../audio/MusicPlayer'; import { CONFIG, GRAPHICS_PROFILES } from '../config/gameConfig'; import { loadGraphicsSettings, type GraphicsSettings } from '../config/GraphicsSettings'; import { mpsToKmh } from '../config/speedUnits'; -import { InputManager } from '../input/InputManager'; +import { InputManager, runGamepadInputProbe, type GameAction } from '../input/InputManager'; import { UI } from '../ui/UI'; import { GraphicsMenu } from '../ui/GraphicsMenu'; +import { MenuNavigator } from '../ui/MenuNavigator'; import { AutopilotController } from '../vehicle/AutopilotController'; import { CruiseController, runCruiseControllerProbe } from '../vehicle/CruiseController'; import { Vehicle } from '../vehicle/Vehicle'; @@ -25,6 +26,8 @@ import { runTransmissionProbe } from '../vehicle/Transmission'; import { InfiniteWorld } from '../world/InfiniteWorld'; import { Atmosphere } from '../world/Atmosphere'; import { proceduralVegetationFactory } from '../world/ProceduralVegetationFactory'; +import { updateWaterTime } from '../world/WorldMaterials'; +import { runRegionScheduleProbe, type SpecialWorldRegionType } from '../world/WorldRegionDirector'; import { CameraController } from './CameraController'; import { createVehicleEnvironment } from './VehicleEnvironment'; import { getNormalizedSpeedEffect, runSpeedEffectsProbe, SpeedStreakPass } from './SpeedEffects'; @@ -45,6 +48,7 @@ export class Game { private readonly ui: UI; private readonly music: MusicPlayer; private readonly graphicsMenu: GraphicsMenu; + private readonly menuNavigation: MenuNavigator; private readonly input: InputManager; private readonly composer = new EffectComposer(this.renderer); private readonly renderPass = new RenderPass(this.scene, this.camera); @@ -66,6 +70,7 @@ export class Game { private physicsStepsSinceDiagnostics = 0; private physicsFps = 60; private chunkGenerationMs = 0; + private wasOnRoad = true; private maxFrameTimeMs = 0; private lastMaxFrameTimeMs = 0; private readonly lastBass: BassAnalysis = { @@ -84,24 +89,18 @@ export class Game { else this.vehicle.reset(debugDistance); } this.odometer.sync(this.vehicle.position); - this.ui = new UI(root, { - start: () => this.start(), toggleAuto: () => this.toggleAuto(), reset: () => this.reset(), - toggleMute: () => this.toggleMute(), toggleCamera: () => this.cameraController.toggle(this.vehicle), - toggleGraphics: () => this.graphicsMenu.toggle(), toggleCruise: () => this.toggleCruise(), - adjustCruise: (deltaKph) => this.cruise.adjustTargetKph(deltaKph), - setCruiseTarget: (targetKph) => this.cruise.setTargetKph(targetKph) - }); + this.ui = new UI(root, { dispatch: (action, value) => this.handleGameAction(action, value) }); this.music = new MusicPlayer(root); - this.graphicsMenu = new GraphicsMenu(root, (settings, heavy) => this.applyGraphics(settings, heavy)); - this.settings = this.graphicsMenu.settings; this.input = new InputManager({ - toggleAutopilot: () => this.toggleAuto(), reset: () => this.reset(), toggleMute: () => this.toggleMute(), - toggleCamera: () => this.cameraController.toggle(this.vehicle), toggleDebug: () => this.toggleDebug(), - toggleVegetationDebug: () => this.toggleVegetationDebug(), - toggleFreeCamera: () => this.cameraController.toggleFreeCamera(this.vehicle), - toggleVehicleWireframe: () => this.toggleVehicleWireframe(), - toggleCruise: () => this.toggleCruise(), adjustCruise: (deltaKph) => this.cruise.adjustTargetKph(deltaKph) + dispatch: (action, value, valueY, dt) => this.handleGameAction(action, value, valueY, dt), + isMenuOpen: () => this.isMenuOpen() }); + this.graphicsMenu = new GraphicsMenu(root, (settings, heavy) => this.applyGraphics(settings, heavy), + (gamepadSettings) => this.input.setGamepadSettings(gamepadSettings)); + this.input.setGamepadSettings(this.graphicsMenu.gamepadSettings); + this.settings = this.graphicsMenu.settings; + this.menuNavigation = new MenuNavigator(() => this.graphicsMenu.isOpen() + ? this.graphicsMenu.element : this.ui.isStartScreenOpen() ? this.ui.getStartMenuRoot() : null); this.input.bindTouch(this.ui.steering, this.ui.throttle, this.ui.brake); this.setupScene(); if (import.meta.env.DEV && query.has('vehicleSilhouette')) this.vehicle.setVehicleSilhouette(true); @@ -152,6 +151,20 @@ export class Game { const speedEffectsProbe = runSpeedEffectsProbe(); this.renderer.domElement.dataset.speedEffectsProbe = speedEffectsProbe.passed ? 'passed' : 'failed'; this.renderer.domElement.dataset.speedEffectsResults = JSON.stringify(speedEffectsProbe); + const regionProbe = runRegionScheduleProbe(CONFIG.seed); + this.renderer.domElement.dataset.regionScheduleProbe = regionProbe.passed ? 'passed' : 'failed'; + this.renderer.domElement.dataset.regionScheduleResults = JSON.stringify(regionProbe); + this.renderer.domElement.dataset.bridgeSurfaceProbe = this.world.road.runBridgeSurfaceProbe() ? 'passed' : 'failed'; + this.renderer.domElement.dataset.riverCorridorProbe = this.world.road.runRiverCorridorProbe() ? 'passed' : 'failed'; + this.renderer.domElement.dataset.regionContinuityProbe = this.world.road.runRegionContinuityProbe() ? 'passed' : 'failed'; + const gamepadProbe = runGamepadInputProbe(); + this.renderer.domElement.dataset.gamepadInputProbe = gamepadProbe.passed ? 'passed' : 'failed'; + this.renderer.domElement.dataset.gamepadInputResults = JSON.stringify(gamepadProbe); + } + if (import.meta.env.DEV && query.has('regionTest')) { + const lifecycle = this.world.runRegionLifecycleProbe(); + this.renderer.domElement.dataset.regionLifecycleProbe = lifecycle.passed ? 'passed' : 'failed'; + this.renderer.domElement.dataset.regionLifecycleResults = JSON.stringify(lifecycle); } addEventListener('resize', this.onResize); addEventListener('pagehide', () => this.odometer.flush()); @@ -172,6 +185,7 @@ export class Game { private applyGraphics(settings: GraphicsSettings, heavy: boolean): void { this.settings = settings; + this.vehicle.setBodyColor(settings.vehicleColor); this.renderer.shadowMap.enabled = settings.shadows; this.camera.far = settings.drawDistance + 220; this.camera.updateProjectionMatrix(); @@ -187,6 +201,52 @@ export class Game { this.onResize(); } + private isMenuOpen(): boolean { return this.ui.isStartScreenOpen() || this.graphicsMenu.isOpen(); } + + private handleGameAction(action: GameAction, value = 0, valueY = 0, dt = 0): void { + if (action === 'menuConfirm' || action === 'menuUp' || action === 'menuDown' + || action === 'menuLeft' || action === 'menuRight') { this.menuNavigation.handle(action); return; } + if (action === 'menuBack') { + if (this.graphicsMenu.isOpen()) { this.graphicsMenu.close(); this.blurFocusedUi(); this.accumulator = 0; } + return; + } + if (action === 'pause') { + if (this.ui.isStartScreenOpen()) { this.startFromMenu(); return; } + if (this.graphicsMenu.isOpen()) { this.graphicsMenu.close(); this.blurFocusedUi(); } + else { this.graphicsMenu.open(); requestAnimationFrame(() => this.menuNavigation.focusFirst()); } + this.accumulator = 0; return; + } + if (action === 'start') { this.startFromMenu(); return; } + if (action === 'autopilot') this.toggleAuto(); + else if (action === 'recover') this.reset(); + else if (action === 'mute') this.toggleMute(); + else if (action === 'camera') this.cameraController.toggle(this.vehicle); + else if (action === 'cruiseToggle') this.toggleCruise(); + else if (action === 'cruiseUp') this.cruise.adjustTargetKph(CONFIG.cruise.stepKph); + else if (action === 'cruiseDown') this.cruise.adjustTargetKph(-CONFIG.cruise.stepKph); + else if (action === 'cruiseSet') this.cruise.setTargetKph(value); + else if (action === 'musicPrevious') this.music.previousTrack(); + else if (action === 'musicNext') this.music.nextTrack(); + else if (action === 'orbitCamera') this.cameraController.applyGamepadOrbit(value, valueY, dt); + else if (action === 'toggleDebug') this.toggleDebug(); + else if (action === 'toggleVegetationDebug') this.toggleVegetationDebug(); + else if (action === 'toggleFreeCamera') this.cameraController.toggleFreeCamera(this.vehicle); + else if (action === 'toggleVehicleWireframe') this.toggleVehicleWireframe(); + else if (action === 'jumpFields') this.jumpToRegion('fields'); + else if (action === 'jumpCoast') this.jumpToRegion('coast'); + else if (action === 'jumpRiver') this.jumpToRegion('river_bridge'); + } + + private startFromMenu(): void { + this.ui.hideStartScreen(); this.blurFocusedUi(); this.accumulator = 0; + if (!this.started) void this.start(); + } + + private blurFocusedUi(): void { + if (document.activeElement instanceof HTMLElement) document.activeElement.blur(); + document.querySelectorAll('.gamepad-focus').forEach((element) => element.classList.remove('gamepad-focus')); + } + private async start(): Promise { this.started = true; this.autopilot.enabled = !this.debugInspection; @@ -214,6 +274,19 @@ export class Game { } } private toggleMute(): void { this.ui.setMuted(this.audio.toggleMute()); } + private jumpToRegion(type: SpecialWorldRegionType): void { + if (!import.meta.env.DEV) return; + const region = this.world.road.regions.nextSpecial(this.vehicle.roadDistance, type); + const target = type === 'river_bridge' + ? Math.max(region.startDistance, region.bridgeStart - 220) + : region.startDistance + region.transitionDistance + 120; + this.vehicle.reset(target); + this.odometer.sync(this.vehicle.position); + this.world.update(target, true); + this.cameraController.snapTo(this.vehicle); + this.world.updateCameraLods(this.camera.position, true); + this.accumulator = 0; + } private toggleDebug(): void { this.debugEnabled = !this.debugEnabled; this.ui.setDebug(this.debugEnabled || this.vegetationDebugEnabled); @@ -245,15 +318,20 @@ export class Game { this.lastTime = time; this.maxFrameTimeMs = Math.max(this.maxFrameTimeMs, rawDelta * 1000); this.smoothedFps += ((rawDelta > 0 ? 1 / rawDelta : 60) - this.smoothedFps) * 0.08; + this.input.pollGamepad(frameDelta); + const gamepad = this.input.getGamepadDebugState(); + this.ui.setInputDevice(gamepad.lastInputDevice, gamepad.family); + this.ui.setControlHints(this.graphicsMenu.gamepadSettings.controlHints); + this.graphicsMenu.updateGamepadStatus(gamepad); - if (this.started) { + if (this.started && !this.graphicsMenu.isOpen()) { this.accumulator += frameDelta; while (this.accumulator >= CONFIG.physics.fixedDt) { this.physicsStep(CONFIG.physics.fixedDt); this.accumulator -= CONFIG.physics.fixedDt; } } - this.vehicle.updateRender(this.started ? this.accumulator / CONFIG.physics.fixedDt : 1); + this.vehicle.updateRender(this.started && !this.graphicsMenu.isOpen() ? this.accumulator / CONFIG.physics.fixedDt : 1); const worldStart = performance.now(); this.world.update(this.vehicle.roadDistance); const worldElapsed = performance.now() - worldStart; @@ -268,6 +346,7 @@ export class Game { this.renderer.toneMappingExposure = this.atmosphere.exposure; this.vehicle.updateLighting(this.atmosphere.getNightFactor(), this.settings); proceduralVegetationFactory.updateWind(time * 0.001); + updateWaterTime(time * 0.001); this.audio.update(this.vehicle.speed, !this.vehicle.onRoad, this.vehicle.rpm); const odometer = this.odometer.state; this.ui.update(this.vehicle.speed, this.autopilot.enabled, this.cruise.state, this.vehicle.gear, this.vehicle.rpm, @@ -302,6 +381,8 @@ export class Game { control = this.cruise.update(this.vehicle, manual); } this.vehicle.update(dt, control); + if (this.wasOnRoad && !this.vehicle.onRoad) this.input.pulseHaptic(.24, 85); + this.wasOnRoad = this.vehicle.onRoad; this.odometer.record(this.vehicle.position); const backfire = this.vehicle.consumeBackfire(); if (backfire > 0) this.audio.triggerBackfire(backfire); @@ -325,6 +406,7 @@ export class Game { this.lastMaxFrameTimeMs = this.maxFrameTimeMs; this.maxFrameTimeMs = 0; const cameraState = this.cameraController.getDebugState(); + const gamepad = this.input.getGamepadDebugState(); const streakState = this.speedStreakPass.getDebugState(); this.renderer.domElement.dataset.fps = this.smoothedFps.toFixed(1); this.renderer.domElement.dataset.frameTime = (1000 / Math.max(1, this.smoothedFps)).toFixed(2); @@ -340,6 +422,17 @@ export class Game { this.renderer.domElement.dataset.bassSecondsSinceHit = this.lastBass.secondsSinceHit.toFixed(3); this.renderer.domElement.dataset.bassPulseStrength = cameraState.bassPulseStrength.toFixed(4); this.renderer.domElement.dataset.bassCameraOffset = cameraState.bassCameraOffset.toFixed(4); + this.renderer.domElement.dataset.gamepadConnected = gamepad.connected ? 'true' : 'false'; + this.renderer.domElement.dataset.gamepadId = gamepad.id; + this.renderer.domElement.dataset.gamepadLeftStickX = gamepad.leftStickX.toFixed(3); + this.renderer.domElement.dataset.gamepadRightStickX = gamepad.rightStickX.toFixed(3); + this.renderer.domElement.dataset.gamepadRightStickY = gamepad.rightStickY.toFixed(3); + this.renderer.domElement.dataset.gamepadThrottle = gamepad.throttle.toFixed(3); + this.renderer.domElement.dataset.gamepadBrake = gamepad.brake.toFixed(3); + this.renderer.domElement.dataset.gamepadSteering = gamepad.steering.toFixed(3); + this.renderer.domElement.dataset.lastInputDevice = gamepad.lastInputDevice; + this.renderer.domElement.dataset.gameAction = gamepad.lastAction; + this.renderer.domElement.dataset.focusedUiElement = this.menuNavigation.getFocusedLabel(); this.renderer.domElement.dataset.audioContextState = this.lastBass.audioContextState; this.renderer.domElement.dataset.speedEffect = cameraState.speedEffect.toFixed(4); this.renderer.domElement.dataset.speedEffectsMaster = cameraState.speedMaster.toFixed(4); @@ -359,6 +452,11 @@ export class Game { if (!this.debugEnabled && !this.vegetationDebugEnabled && !this.stabilityDiagnostics) return; const stats = this.world.getDebugStats(); const shadowState = this.atmosphere.getDebugState(); + const region = this.world.road.regions.sample(this.vehicle.roadDistance); + const nextRegion = this.world.road.regions.nextSpecial(this.vehicle.roadDistance); + const nextFields = this.world.road.regions.nextSpecial(this.vehicle.roadDistance, 'fields'); + const nextCoast = this.world.road.regions.nextSpecial(this.vehicle.roadDistance, 'coast'); + const nextRiverBridge = this.world.road.regions.nextSpecial(this.vehicle.roadDistance, 'river_bridge'); if (!this.world.hasChunk(this.vehicle.currentChunkIndex)) this.worldInvariantFailures++; const cameraDistance = this.camera.position.distanceTo(this.vehicle.renderPosition); this.renderer.domElement.dataset.progress = this.vehicle.roadDistance.toFixed(1); @@ -409,6 +507,17 @@ export class Game { this.renderer.domElement.dataset.geometries = this.renderer.info.memory.geometries.toString(); this.renderer.domElement.dataset.textures = this.renderer.info.memory.textures.toString(); this.renderer.domElement.dataset.roadsideFeatures = stats.roadsideFeatures.toString(); + this.renderer.domElement.dataset.currentRegion = region.type; + this.renderer.domElement.dataset.regionId = region.regionId.toString(); + this.renderer.domElement.dataset.regionStart = region.startDistance.toFixed(1); + this.renderer.domElement.dataset.regionEnd = region.endDistance.toFixed(1); + this.renderer.domElement.dataset.regionProgress = region.localT.toFixed(4); + this.renderer.domElement.dataset.nextSpecialRegion = nextRegion.type; + this.renderer.domElement.dataset.distanceToNextRegion = Math.max(0, nextRegion.startDistance - this.vehicle.roadDistance).toFixed(1); + this.renderer.domElement.dataset.distanceToNextFields = Math.max(0, nextFields.startDistance - this.vehicle.roadDistance).toFixed(1); + this.renderer.domElement.dataset.distanceToNextCoast = Math.max(0, nextCoast.startDistance - this.vehicle.roadDistance).toFixed(1); + this.renderer.domElement.dataset.distanceToNextRiverBridge = Math.max(0, nextRiverBridge.startDistance - this.vehicle.roadDistance).toFixed(1); + this.renderer.domElement.dataset.bridgeSections = stats.bridgeSections.toString(); this.renderer.domElement.dataset.cruiseEnabled = this.cruise.enabled ? 'true' : 'false'; this.renderer.domElement.dataset.cruiseTargetKph = this.cruise.targetKph.toString(); this.renderer.domElement.dataset.cruiseAccelerating = this.cruise.accelerating ? 'true' : 'false'; @@ -448,6 +557,9 @@ export class Game { `CHUNK GENERATION ${this.chunkGenerationMs.toFixed(2)} ms SPEED ${mpsToKmh(this.vehicle.speed).toFixed(1)} km/h`, `POS ${this.vehicle.position.x.toFixed(1)}, ${this.vehicle.position.y.toFixed(1)}, ${this.vehicle.position.z.toFixed(1)}`, `ROAD ${this.vehicle.roadDistance.toFixed(1)} CHUNK ${this.vehicle.currentChunkIndex}`, + `REGION ${region.type.toUpperCase()} #${region.regionId} ${(region.startDistance/1000).toFixed(1)}..${Number.isFinite(region.endDistance) ? (region.endDistance/1000).toFixed(1) : '∞'} km ${(region.localT*100).toFixed(1)}%`, + `NEXT ${nextRegion.type.toUpperCase()} IN ${(Math.max(0,nextRegion.startDistance-this.vehicle.roadDistance)/1000).toFixed(1)} km BRIDGE SECTIONS ${stats.bridgeSections}`, + `TO FIELDS ${(Math.max(0,nextFields.startDistance-this.vehicle.roadDistance)/1000).toFixed(1)} km COAST ${(Math.max(0,nextCoast.startDistance-this.vehicle.roadDistance)/1000).toFixed(1)} km RIVER ${(Math.max(0,nextRiverBridge.startDistance-this.vehicle.roadDistance)/1000).toFixed(1)} km`, `LATERAL ${this.vehicle.lateralDistance.toFixed(2)} HEADING ${this.vehicle.heading.toFixed(3)}`, `STEER ${(this.vehicle.steeringAngle * 180 / Math.PI).toFixed(1)}° YAW RATE ${this.vehicle.yawRate.toFixed(3)}`, `ACTIVE ROAD/TERRAIN/VEGETATION ${stats.chunks}/${stats.chunks}/${stats.chunks}`, @@ -458,8 +570,12 @@ export class Game { `GEAR ${this.vehicle.gear}/6 RPM ${this.vehicle.rpm.toFixed(0)}`, `CAM ${this.camera.position.x.toFixed(1)}, ${this.camera.position.y.toFixed(1)}, ${this.camera.position.z.toFixed(1)} D ${cameraDistance.toFixed(1)}`, `ORBIT yaw ${(cameraState.orbitYaw * 180 / Math.PI).toFixed(1)}° pitch ${(cameraState.orbitPitch * 180 / Math.PI).toFixed(1)}° d ${cameraState.orbitDistance.toFixed(1)}${cameraState.isUserOrbiting ? ' DRAG' : ''}`, + `GAMEPAD ${gamepad.connected ? 'CONNECTED' : 'NOT CONNECTED'} ${gamepad.id || '—'} MAP ${gamepad.standardMapping ? 'STANDARD' : '—'}`, + `PAD LX ${gamepad.leftStickX.toFixed(3)} RX/RY ${gamepad.rightStickX.toFixed(3)}/${gamepad.rightStickY.toFixed(3)} THR ${gamepad.throttle.toFixed(3)} BRK ${gamepad.brake.toFixed(3)} STEER ${gamepad.steering.toFixed(3)}`, + `LAST INPUT ${gamepad.lastInputDevice.toUpperCase()} ACTION ${gamepad.lastAction.toUpperCase()} FOCUS ${this.menuNavigation.getFocusedLabel()} HAPTICS ${gamepad.hapticsSupported ? 'YES' : 'NO'}`, `SUN ${shadowState.sun.x.toFixed(1)}, ${shadowState.sun.y.toFixed(1)}, ${shadowState.sun.z.toFixed(1)} TARGET ${shadowState.target.x.toFixed(1)}, ${shadowState.target.y.toFixed(1)}, ${shadowState.target.z.toFixed(1)}`, `SHADOW ${shadowState.bounds} INSPECT ${this.cameraController.isFreeCameraEnabled() ? 'ON' : 'OFF'} (F4) WIREFRAME F6`, + `DEV REGION JUMPS F8 FIELDS / F9 COAST / F10 RIVER_BRIDGE`, `DRAWS ${this.renderer.info.render.calls} TRIANGLES ${this.renderer.info.render.triangles}`, `SCENE OBJECTS ${stats.sceneObjects} GEOMETRIES ${this.renderer.info.memory.geometries} TEXTURES ${this.renderer.info.memory.textures}`, `RENDER ${(this.settings.renderScale*100).toFixed(0)}% DRAW ${this.settings.drawDistance}m SHADOW ${this.settings.shadowResolution}`, diff --git a/src/input/GamepadSettings.ts b/src/input/GamepadSettings.ts new file mode 100644 index 0000000..5c3541a --- /dev/null +++ b/src/input/GamepadSettings.ts @@ -0,0 +1,34 @@ +export interface GamepadSettings { + enabled: boolean; + steeringDeadzone: number; + cameraDeadzone: number; + vibration: boolean; + controlHints: boolean; +} + +export const DEFAULT_GAMEPAD_SETTINGS: Readonly = { + enabled: true, + steeringDeadzone: .12, + cameraDeadzone: .15, + vibration: true, + controlHints: true +}; + +const STORAGE_KEY = 'quiet-mile.gamepad.v1'; + +export function loadGamepadSettings(): GamepadSettings { + try { + const stored = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}') as Partial; + return { ...DEFAULT_GAMEPAD_SETTINGS, ...stored }; + } catch { return { ...DEFAULT_GAMEPAD_SETTINGS }; } +} + +export function saveGamepadSettings(settings: GamepadSettings): void { + localStorage.setItem(STORAGE_KEY, JSON.stringify(settings)); +} + +export function resetGamepadSettings(): GamepadSettings { + const settings = { ...DEFAULT_GAMEPAD_SETTINGS }; + saveGamepadSettings(settings); + return settings; +} diff --git a/src/input/InputManager.ts b/src/input/InputManager.ts index cd24bfd..0064985 100644 --- a/src/input/InputManager.ts +++ b/src/input/InputManager.ts @@ -1,25 +1,94 @@ import type { VehicleControls } from '../vehicle/VehicleControls'; +import { loadGamepadSettings, type GamepadSettings } from './GamepadSettings'; + +export type InputDevice = 'keyboard' | 'touch' | 'gamepad'; +export type GamepadFamily = 'xbox' | 'playstation' | 'generic'; +export type GameAction = 'accelerate' | 'brake' | 'steer' | 'handbrake' | 'camera' | 'recover' + | 'cruiseUp' | 'cruiseDown' | 'musicNext' | 'musicPrevious' | 'pause' + | 'menuConfirm' | 'menuBack' | 'menuUp' | 'menuDown' | 'menuLeft' | 'menuRight' + | 'start' | 'autopilot' | 'mute' | 'cruiseToggle' | 'cruiseSet' | 'toggleDebug' + | 'toggleVegetationDebug' | 'toggleFreeCamera' | 'toggleVehicleWireframe' + | 'jumpFields' | 'jumpCoast' | 'jumpRiver' | 'orbitCamera'; + +export interface VehicleInputState { steering: number; throttle: number; brake: number; handbrake: number } +export interface GamepadDebugState { + connected: boolean; id: string; standardMapping: boolean; family: GamepadFamily; + leftStickX: number; rightStickX: number; rightStickY: number; + throttle: number; brake: number; steering: number; handbrake: number; + lastInputDevice: InputDevice; hapticsSupported: boolean; lastAction: GameAction | 'none'; +} export interface InputActions { - toggleAutopilot: () => void; - reset: () => void; - toggleMute: () => void; - toggleCamera: () => void; - toggleDebug: () => void; - toggleVegetationDebug: () => void; - toggleFreeCamera: () => void; - toggleVehicleWireframe: () => void; - toggleCruise: () => void; - adjustCruise: (deltaKph: number) => void; + dispatch: (action: GameAction, value?: number, valueY?: number, dt?: number) => void; + isMenuOpen: () => boolean; } const blockedKeys = new Set(['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Space']); +const STANDARD_GAMEPAD_BUTTON = { + confirm: 0, back: 1, camera: 3, brake: 6, throttle: 7, menu: 9, + cruiseToggle: 10, autopilotToggle: 11, + dpadUp: 12, dpadDown: 13, dpadLeft: 14, dpadRight: 15 +} as const; + +export function normalizeGamepadAxis(value: number, deadzone: number): number { + const magnitude = Math.abs(value); if (magnitude <= deadzone) return 0; + return Math.sign(value) * Math.min(1, (magnitude - deadzone) / Math.max(.001, 1 - deadzone)); +} + +export function detectGamepadFamily(id: string): GamepadFamily { + const value = id.toLowerCase(); + // Xbox names can also contain "Wireless Controller", so test the explicit family first. + if (/xbox|xinput|microsoft/.test(value)) return 'xbox'; + if (/dualsense|dualshock|playstation|wireless controller|sony/.test(value)) return 'playstation'; + return 'generic'; +} + +export function runGamepadInputProbe(): { passed: boolean; deadzone: boolean; analogRange: boolean; edgeDetection: boolean; + stickClickEdgeDetection: boolean; frameRateIndependent: boolean; menuRepeatIndependent: boolean; familyDetection: boolean } { + const deadzone = normalizeGamepadAxis(.12, .12) === 0 && normalizeGamepadAxis(-.08, .12) === 0; + const analogRange = Math.abs(normalizeGamepadAxis(1, .12) - 1) < 1e-9 + && normalizeGamepadAxis(.5, .12) > 0 && normalizeGamepadAxis(.5, .12) < 1; + let previous = false; let edges = 0; + for (const pressed of [false, true, true, false, true, true, false]) { if (pressed && !previous) edges++; previous = pressed; } + const countSinglePress = (states: readonly boolean[]): number => { + let wasPressed = false; let actions = 0; + for (const pressed of states) { if (pressed && !wasPressed) actions++; wasPressed = pressed; } + return actions; + }; + const stickClickEdgeDetection = countSinglePress([false, true, true, true, false]) === 1 + && countSinglePress([false, true, true, false]) === 1; + const integrate = (hz: number): number => { let yaw = 0; for (let i = 0; i < hz * 4; i++) yaw += .7 * 2.25 / hz; return yaw; }; + const yaw60 = integrate(60); const frameRateIndependent = [integrate(120), integrate(144)] + .every((value) => Math.abs(value - yaw60) < 1e-9); + const repeatCount = (hz: number): number => { let timer = .3; let count = 1; + for (let frame = 1; frame < hz; frame++) { timer -= 1 / hz; if (timer <= 0) { timer += .085; count++; } } return count; }; + const menuRepeatIndependent = Math.max(repeatCount(60), repeatCount(120), repeatCount(144)) + - Math.min(repeatCount(60), repeatCount(120), repeatCount(144)) <= 1; + const familyDetection = detectGamepadFamily('Xbox Wireless Controller') === 'xbox' + && detectGamepadFamily('DualSense Wireless Controller') === 'playstation' + && detectGamepadFamily('USB Standard Pad') === 'generic'; + return { passed: deadzone && analogRange && edges === 2 && stickClickEdgeDetection + && frameRateIndependent && menuRepeatIndependent && familyDetection, + deadzone, analogRange, edgeDetection: edges === 2, stickClickEdgeDetection, + frameRateIndependent, menuRepeatIndependent, familyDetection }; +} export class InputManager { readonly control: VehicleControls = { throttle: 0, brake: 0, steering: 0 }; + readonly unified: VehicleInputState = { steering: 0, throttle: 0, brake: 0, handbrake: 0 }; private readonly keys = new Set(); - private touchSteer = 0; - private touchThrottle = 0; - private touchBrake = 0; + private touchSteer = 0; private touchThrottle = 0; private touchBrake = 0; + private settings = loadGamepadSettings(); + private readonly gamepadButtons = new Uint8Array(16); + private readonly menuRepeatHeld = new Uint8Array(4); + private readonly menuRepeatTimers = new Float32Array(4); + private gamepadIndex = -1; + private gamepadSteer = 0; private gamepadThrottle = 0; private gamepadBrake = 0; private gamepadHandbrake = 0; + private gamepadRightX = 0; private gamepadRightY = 0; + private connected = false; private gamepadId = ''; private standardMapping = false; private hapticsSupported = false; + private gamepadFamily: GamepadFamily = 'generic'; + private suppressGamepadDriveUntilNeutral = false; + private lastActiveInputDevice: InputDevice = 'keyboard'; + private lastAction: GameAction | 'none' = 'none'; constructor(private readonly actions: InputActions) { addEventListener('keydown', this.onKeyDown, { passive: false }); @@ -27,58 +96,183 @@ export class InputManager { addEventListener('blur', () => this.keys.clear()); } + setGamepadSettings(settings: GamepadSettings): void { this.settings = { ...settings }; if (!settings.enabled) this.setDisconnected(); } + + pollGamepad(dt: number): void { + if (!this.settings.enabled || typeof navigator.getGamepads !== 'function') { this.setDisconnected(); return; } + const pads = navigator.getGamepads(); + let pad: Gamepad | null = this.gamepadIndex >= 0 ? pads[this.gamepadIndex] ?? null : null; + if (!pad?.connected) { + pad = null; + for (let i = 0; i < pads.length; i++) { const candidate = pads[i]; if (candidate?.connected && candidate.mapping === 'standard') { pad = candidate; break; } } + if (!pad) for (let i = 0; i < pads.length; i++) if (pads[i]?.connected) { pad = pads[i]; break; } + } + if (!pad) { this.setDisconnected(); return; } + if (pad.index !== this.gamepadIndex) this.gamepadButtons.fill(0); + this.connected = true; this.gamepadIndex = pad.index; this.gamepadId = pad.id || 'Gamepad'; + this.gamepadFamily = detectGamepadFamily(this.gamepadId); this.standardMapping = pad.mapping === 'standard'; + this.hapticsSupported = Boolean(this.getVibrationActuator(pad)); + if (!this.standardMapping) { this.clearGamepadValues(); return; } + const rawSteer = pad.axes[0] ?? 0; + this.gamepadSteer = this.curvedAxis(rawSteer, this.settings.steeringDeadzone, 1.4); + this.gamepadRightX = normalizeGamepadAxis(pad.axes[2] ?? 0, this.settings.cameraDeadzone); + this.gamepadRightY = normalizeGamepadAxis(pad.axes[3] ?? 0, this.settings.cameraDeadzone); + this.gamepadBrake = this.buttonValue(pad, STANDARD_GAMEPAD_BUTTON.brake); + this.gamepadThrottle = this.buttonValue(pad, STANDARD_GAMEPAD_BUTTON.throttle); + this.gamepadHandbrake = this.buttonValue(pad, STANDARD_GAMEPAD_BUTTON.confirm); + const active = Math.abs(rawSteer) > this.settings.steeringDeadzone + || Math.abs(pad.axes[1] ?? 0) > this.settings.steeringDeadzone + || Math.abs(pad.axes[2] ?? 0) > this.settings.cameraDeadzone || Math.abs(pad.axes[3] ?? 0) > this.settings.cameraDeadzone + || this.gamepadThrottle > .02 || this.gamepadBrake > .02 || this.anyButtonPressed(pad); + if (active) this.lastActiveInputDevice = 'gamepad'; + if (this.actions.isMenuOpen()) { this.suppressGamepadDriveUntilNeutral = true; this.pollGamepadMenu(pad, dt); } + else { + const orbitX = this.suppressGamepadDriveUntilNeutral ? 0 : this.gamepadRightX; + const orbitY = this.suppressGamepadDriveUntilNeutral ? 0 : this.gamepadRightY; + this.actions.dispatch('orbitCamera', orbitX, orbitY, dt); + if (orbitX !== 0 || orbitY !== 0) this.lastAction = 'orbitCamera'; + this.edge(pad, STANDARD_GAMEPAD_BUTTON.camera, () => this.fire('camera')); + this.edge(pad, STANDARD_GAMEPAD_BUTTON.back, () => this.fire('recover')); + this.edge(pad, STANDARD_GAMEPAD_BUTTON.cruiseToggle, () => this.fire('cruiseToggle')); + this.edge(pad, STANDARD_GAMEPAD_BUTTON.autopilotToggle, () => this.fire('autopilot')); + this.edge(pad, STANDARD_GAMEPAD_BUTTON.dpadUp, () => this.fire('cruiseUp')); + this.edge(pad, STANDARD_GAMEPAD_BUTTON.dpadDown, () => this.fire('cruiseDown')); + this.edge(pad, STANDARD_GAMEPAD_BUTTON.dpadLeft, () => this.fire('musicPrevious')); + this.edge(pad, STANDARD_GAMEPAD_BUTTON.dpadRight, () => this.fire('musicNext')); + this.edge(pad, STANDARD_GAMEPAD_BUTTON.menu, () => this.fire('pause')); + } + } + update(dt: number): VehicleControls { + if (this.actions.isMenuOpen()) { + this.unified.steering = this.unified.throttle = this.unified.brake = this.unified.handbrake = 0; + this.control.steering = 0; this.control.throttle = this.damp(this.control.throttle, 0, 12, dt); + this.control.brake = this.damp(this.control.brake, 0, 15, dt); return this.control; + } + if (this.suppressGamepadDriveUntilNeutral && Math.abs(this.gamepadSteer) < .001 && this.gamepadThrottle < .02 + && this.gamepadBrake < .02 && this.gamepadHandbrake < .02) this.suppressGamepadDriveUntilNeutral = false; + const padSteer = this.suppressGamepadDriveUntilNeutral ? 0 : this.gamepadSteer; + const padThrottle = this.suppressGamepadDriveUntilNeutral ? 0 : this.gamepadThrottle; + const padBrake = this.suppressGamepadDriveUntilNeutral ? 0 : this.gamepadBrake; + const padHandbrake = this.suppressGamepadDriveUntilNeutral ? 0 : this.gamepadHandbrake; const keySteer = (this.keys.has('KeyD') || this.keys.has('ArrowRight') ? 1 : 0) - (this.keys.has('KeyA') || this.keys.has('ArrowLeft') ? 1 : 0); - const targetSteer = Math.abs(this.touchSteer) > 0.01 ? this.touchSteer : keySteer; - const targetThrottle = Math.max(this.touchThrottle, this.keys.has('KeyW') || this.keys.has('ArrowUp') ? 1 : 0); - const targetBrake = Math.max(this.touchBrake, this.keys.has('KeyS') || this.keys.has('ArrowDown') || this.keys.has('Space') ? 1 : 0); - this.control.steering = targetSteer; - this.control.throttle = this.damp(this.control.throttle, targetThrottle, 9, dt); - this.control.brake = this.damp(this.control.brake, targetBrake, 12, dt); + this.unified.steering = this.strongestAxis(keySteer, this.touchSteer, padSteer); + this.unified.throttle = Math.max(this.touchThrottle, padThrottle, this.keys.has('KeyW') || this.keys.has('ArrowUp') ? 1 : 0); + this.unified.brake = Math.max(this.touchBrake, padBrake, + this.keys.has('KeyS') || this.keys.has('ArrowDown') || this.keys.has('Space') ? 1 : 0); + this.unified.handbrake = padHandbrake; + this.control.steering = this.unified.steering; + this.control.throttle = this.damp(this.control.throttle, this.unified.throttle, 9, dt); + this.control.brake = this.damp(this.control.brake, Math.max(this.unified.brake, this.unified.handbrake), 12, dt); return this.control; } + getGamepadDebugState(): GamepadDebugState { + return { connected: this.connected, id: this.gamepadId, standardMapping: this.standardMapping, family: this.gamepadFamily, + leftStickX: this.gamepadSteer, rightStickX: this.gamepadRightX, rightStickY: this.gamepadRightY, + throttle: this.gamepadThrottle, brake: this.gamepadBrake, steering: this.control.steering, handbrake: this.gamepadHandbrake, + lastInputDevice: this.lastActiveInputDevice, hapticsSupported: this.hapticsSupported, lastAction: this.lastAction }; + } + + pulseHaptic(strength: number, durationMs: number): void { + if (!this.settings.enabled || !this.settings.vibration || this.gamepadIndex < 0) return; + const pad = navigator.getGamepads?.()[this.gamepadIndex]; const actuator = pad ? this.getVibrationActuator(pad) : null; + if (!actuator || typeof actuator.playEffect !== 'function') return; + void actuator.playEffect('dual-rumble', { duration: durationMs, startDelay: 0, + weakMagnitude: Math.max(0, Math.min(1, strength * .7)), strongMagnitude: Math.max(0, Math.min(1, strength)) }).catch(() => undefined); + } + bindTouch(steering: HTMLElement, throttle: HTMLElement, brake: HTMLElement): void { let steerPointer: number | null = null; - const steer = (event: PointerEvent): void => { - const rect = steering.getBoundingClientRect(); - this.touchSteer = Math.max(-1, Math.min(1, ((event.clientX - rect.left) / rect.width - 0.5) * 2.3)); - }; + const steer = (event: PointerEvent): void => { this.lastActiveInputDevice = 'touch'; const rect = steering.getBoundingClientRect(); + this.touchSteer = Math.max(-1, Math.min(1, ((event.clientX - rect.left) / rect.width - .5) * 2.3)); }; steering.addEventListener('pointerdown', (event) => { steerPointer = event.pointerId; steering.setPointerCapture(event.pointerId); steer(event); }); steering.addEventListener('pointermove', (event) => { if (event.pointerId === steerPointer) steer(event); }); const endSteer = (event: PointerEvent): void => { if (event.pointerId === steerPointer) { steerPointer = null; this.touchSteer = 0; } }; steering.addEventListener('pointerup', endSteer); steering.addEventListener('pointercancel', endSteer); - this.bindButton(throttle, (value) => { this.touchThrottle = value; }); - this.bindButton(brake, (value) => { this.touchBrake = value; }); + this.bindButton(throttle, (value) => { this.lastActiveInputDevice = 'touch'; this.touchThrottle = value; }); + this.bindButton(brake, (value) => { this.lastActiveInputDevice = 'touch'; this.touchBrake = value; }); } - hasManualInput(): boolean { return this.control.throttle > 0.15 || this.control.brake > 0.15 || Math.abs(this.control.steering) > 0.15; } + hasManualInput(): boolean { return this.control.throttle > .15 || this.control.brake > .15 || Math.abs(this.control.steering) > .15; } - private damp(current: number, target: number, lambda: number, dt: number): number { - return current + (target - current) * (1 - Math.exp(-lambda * dt)); + private pollGamepadMenu(pad: Gamepad, dt: number): void { + this.actions.dispatch('orbitCamera', 0, 0, dt); + this.edge(pad, STANDARD_GAMEPAD_BUTTON.confirm, () => this.fire('menuConfirm')); + this.edge(pad, STANDARD_GAMEPAD_BUTTON.back, () => this.fire('menuBack')); + this.edge(pad, STANDARD_GAMEPAD_BUTTON.menu, () => this.fire('pause')); + const vertical = pad.axes[1] ?? 0; const horizontal = pad.axes[0] ?? 0; + this.repeatMenu(0, Boolean(pad.buttons[STANDARD_GAMEPAD_BUTTON.dpadUp]?.pressed) || vertical < -.58, 'menuUp', dt); + this.repeatMenu(1, Boolean(pad.buttons[STANDARD_GAMEPAD_BUTTON.dpadDown]?.pressed) || vertical > .58, 'menuDown', dt); + this.repeatMenu(2, Boolean(pad.buttons[STANDARD_GAMEPAD_BUTTON.dpadLeft]?.pressed) || horizontal < -.58, 'menuLeft', dt); + this.repeatMenu(3, Boolean(pad.buttons[STANDARD_GAMEPAD_BUTTON.dpadRight]?.pressed) || horizontal > .58, 'menuRight', dt); + for (let index = 0; index < this.gamepadButtons.length; index++) this.gamepadButtons[index] = pad.buttons[index]?.pressed ? 1 : 0; + } + private repeatMenu(index: number, pressed: boolean, action: GameAction, dt: number): void { + if (!pressed) { this.menuRepeatHeld[index] = 0; this.menuRepeatTimers[index] = 0; return; } + if (this.menuRepeatHeld[index] === 0) { this.menuRepeatHeld[index] = 1; this.menuRepeatTimers[index] = .3; this.fire(action); return; } + this.menuRepeatTimers[index] -= dt; + if (this.menuRepeatTimers[index] <= 0) { this.menuRepeatTimers[index] += .085; this.fire(action); } + } + private fire(action: GameAction, value?: number, valueY?: number, dt?: number): void { this.lastAction = action; this.actions.dispatch(action, value, valueY, dt); } + private edge(pad: Gamepad, index: number, action: () => void): void { + const down = Boolean(pad.buttons[index]?.pressed || (pad.buttons[index]?.value ?? 0) > .5); + if (down && this.gamepadButtons[index] === 0) action(); this.gamepadButtons[index] = down ? 1 : 0; } + private damp(current: number, target: number, lambda: number, dt: number): number { return current + (target - current) * (1 - Math.exp(-lambda * dt)); } + private curvedAxis(value: number, deadzone: number, exponent: number): number { const normalized = normalizeGamepadAxis(value, deadzone); + return Math.sign(normalized) * Math.pow(Math.abs(normalized), exponent); } + private strongestAxis(a: number, b: number, c: number): number { let result = Math.abs(a) >= Math.abs(b) ? a : b; if (Math.abs(c) > Math.abs(result)) result = c; return result; } + private buttonValue(pad: Gamepad, index: number): number { const button = pad.buttons[index]; return button ? Math.max(0, Math.min(1, button.value)) : 0; } + private anyButtonPressed(pad: Gamepad): boolean { for (let i = 0; i < pad.buttons.length; i++) if (pad.buttons[i]?.pressed || pad.buttons[i]?.value > .02) return true; return false; } + private clearGamepadValues(): void { this.gamepadSteer = this.gamepadThrottle = this.gamepadBrake = this.gamepadHandbrake = 0; + this.gamepadRightX = this.gamepadRightY = 0; this.gamepadButtons.fill(0); } + private clearGamepadState(): void { this.clearGamepadValues(); this.gamepadIndex = -1; } + private setDisconnected(): void { + const wasConnected = this.connected; this.clearGamepadState(); this.connected = false; this.gamepadId = ''; + this.standardMapping = false; this.hapticsSupported = false; this.gamepadFamily = 'generic'; + this.suppressGamepadDriveUntilNeutral = false; + this.menuRepeatHeld.fill(0); this.menuRepeatTimers.fill(0); + if (wasConnected) { this.control.steering = this.control.throttle = this.control.brake = 0; + this.unified.steering = this.unified.throttle = this.unified.brake = this.unified.handbrake = 0; } + } + private getVibrationActuator(pad: Gamepad): GamepadHapticActuator | null { return pad.vibrationActuator ?? null; } private bindButton(element: HTMLElement, set: (value: number) => void): void { element.addEventListener('pointerdown', (event) => { element.setPointerCapture(event.pointerId); set(1); }); - const end = (): void => set(0); - element.addEventListener('pointerup', end); element.addEventListener('pointercancel', end); element.addEventListener('lostpointercapture', end); + const end = (): void => set(0); element.addEventListener('pointerup', end); element.addEventListener('pointercancel', end); element.addEventListener('lostpointercapture', end); } private onKeyDown = (event: KeyboardEvent): void => { + this.lastActiveInputDevice = 'keyboard'; + if (this.actions.isMenuOpen()) { + const action = this.keyboardMenuAction(event.code); + if (action) { event.preventDefault(); if (!event.repeat || action === 'menuUp' || action === 'menuDown' || action === 'menuLeft' || action === 'menuRight') this.fire(action); return; } + } if (blockedKeys.has(event.code)) event.preventDefault(); if (!event.repeat) { - if (event.code === 'KeyP') this.actions.toggleAutopilot(); - if (event.code === 'KeyR') this.actions.reset(); - if (event.code === 'KeyM') this.actions.toggleMute(); - if (event.code === 'KeyC') this.actions.toggleCamera(); - if (event.code === 'KeyV') this.actions.toggleCruise(); - if (event.code === 'Equal' || event.code === 'NumpadAdd') this.actions.adjustCruise(5); - if (event.code === 'Minus' || event.code === 'NumpadSubtract') this.actions.adjustCruise(-5); - if (event.code === 'F3') { event.preventDefault(); this.actions.toggleDebug(); } - if (event.code === 'F4') { event.preventDefault(); this.actions.toggleFreeCamera(); } - if (event.code === 'F6') { event.preventDefault(); this.actions.toggleVehicleWireframe(); } - if (event.code === 'F7') { event.preventDefault(); this.actions.toggleVegetationDebug(); } + if (event.code === 'KeyP') this.fire('autopilot'); if (event.code === 'KeyR') this.fire('recover'); + if (event.code === 'KeyM') this.fire('mute'); if (event.code === 'KeyC') this.fire('camera'); + if (event.code === 'KeyV') this.fire('cruiseToggle'); + if (event.code === 'Equal' || event.code === 'NumpadAdd') this.fire('cruiseUp'); + if (event.code === 'Minus' || event.code === 'NumpadSubtract') this.fire('cruiseDown'); + if (event.code === 'BracketLeft') this.fire('musicPrevious'); + if (event.code === 'BracketRight') this.fire('musicNext'); + if (event.code === 'Escape') { event.preventDefault(); this.fire('pause'); } + if (event.code === 'F3') { event.preventDefault(); this.fire('toggleDebug'); } + if (event.code === 'F4') { event.preventDefault(); this.fire('toggleFreeCamera'); } + if (event.code === 'F6') { event.preventDefault(); this.fire('toggleVehicleWireframe'); } + if (event.code === 'F7') { event.preventDefault(); this.fire('toggleVegetationDebug'); } + if (import.meta.env.DEV && event.code === 'F8') { event.preventDefault(); this.fire('jumpFields'); } + if (import.meta.env.DEV && event.code === 'F9') { event.preventDefault(); this.fire('jumpCoast'); } + if (import.meta.env.DEV && event.code === 'F10') { event.preventDefault(); this.fire('jumpRiver'); } } this.keys.add(event.code); }; + private keyboardMenuAction(code: string): GameAction | null { + if (code === 'ArrowUp') return 'menuUp'; if (code === 'ArrowDown') return 'menuDown'; + if (code === 'ArrowLeft') return 'menuLeft'; if (code === 'ArrowRight') return 'menuRight'; + if (code === 'Enter' || code === 'Space') return 'menuConfirm'; + if (code === 'Escape' || code === 'Backspace') return 'menuBack'; return null; + } private onKeyUp = (event: KeyboardEvent): void => { if (blockedKeys.has(event.code)) event.preventDefault(); this.keys.delete(event.code); }; } diff --git a/src/style.css b/src/style.css index f73b82d..85e5c20 100644 --- a/src/style.css +++ b/src/style.css @@ -134,4 +134,20 @@ h1 { margin: 12px 0 15px; font-size: clamp(3.4rem, 11vw, 6.6rem); line-height: . @media (min-width: 900px) { .top-actions, .music-player { transition: right .2s ease; }.graphics-open .top-actions, .graphics-open .music-player { right: max(446px, calc(env(safe-area-inset-right) + 430px)); } } @media (pointer: coarse) { .music-player { right: max(18px, env(safe-area-inset-right)); bottom: max(142px, calc(env(safe-area-inset-bottom) + 122px)); width: min(320px, calc(100vw - 36px)); } } @media (pointer: coarse) and (orientation: portrait) { .music-player { right: 50%; bottom: max(274px, calc(env(safe-area-inset-bottom) + 254px)); transform: translateX(50%); } } +.gamepad-status { display: grid; gap: 3px; margin: 0 0 12px; padding: 10px 11px; border: 1px solid #ffffff14; border-radius: 10px; background: #ffffff08; } +.gamepad-status strong { color: #d7ef8a; font-size: .62rem; letter-spacing: .12em; } +.gamepad-status span { overflow: hidden; color: #aab9b6; font-size: .62rem; text-overflow: ellipsis; white-space: nowrap; } +.gamepad-status span.connected { color: #edf4ee; } +.vehicle-color-heading { display: flex; align-items: center; justify-content: space-between; margin-bottom: 9px; color: #b7c6c3; font-size: .62rem; letter-spacing: .07em; }.vehicle-color-heading output { color: #d7ef8a; letter-spacing: .02em; } +.vehicle-color-palette { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; } +.vehicle-color-swatch { position: relative; height: 38px; padding: 0; border: 2px solid #ffffff18; border-radius: 10px; background: var(--vehicle-color); box-shadow: inset 0 1px #ffffff2b, inset 0 -6px 12px #00000026; } +.vehicle-color-swatch::after { content: ''; position: absolute; inset: 4px; border: 1px solid #ffffff13; border-radius: 6px; }.vehicle-color-swatch:hover { border-color: #ffffff75; transform: translateY(-1px); } +.vehicle-color-swatch.selected { border-color: #d7ef8a; box-shadow: 0 0 0 2px #d7ef8a32, inset 0 1px #ffffff42, inset 0 -6px 12px #00000026; }.vehicle-color-swatch.selected::before { content: '✓'; position: absolute; z-index: 1; right: 5px; bottom: 3px; color: white; font-size: .7rem; font-weight: 900; text-shadow: 0 1px 4px black; } +.control-hints { position: absolute; z-index: 4; top: 38%; right: max(24px, env(safe-area-inset-right)); width: 174px; padding: 11px 12px; color: #edf4eec7; border: 1px solid #ffffff22; border-radius: 14px; background: #10262959; box-shadow: 0 10px 28px #071a2024; backdrop-filter: blur(8px); transform: translateY(-50%); pointer-events: none; transition: opacity .18s; } +.control-hints[hidden] { display: none; }.control-hints > strong { display: block; margin-bottom: 7px; color: #d7ef8abf; font-size: .52rem; letter-spacing: .15em; } +.control-hints > div { display: grid; grid-template-columns: 58px 1fr; align-items: center; gap: 7px; min-height: 21px; font-size: .56rem; } +.control-hints kbd { min-width: 27px; padding: 3px 5px; color: #f8f5e8d9; border: 1px solid #ffffff2b; border-radius: 6px; background: #ffffff0d; box-shadow: inset 0 -1px #0000002e; text-align: center; font: 750 .52rem/1 system-ui, sans-serif; } +.graphics-open .control-hints { opacity: 0; } +.gamepad-focus, .graphics-menu .gamepad-focus + i { outline: 2px solid #d7ef8a !important; outline-offset: 3px; } +@media (max-height: 620px) { .control-hints { top: 35%; transform: translateY(-50%) scale(.78); transform-origin: right center; } } @media (max-height: 520px) and (pointer: coarse) { .music-player { right: 50%; bottom: max(125px, calc(env(safe-area-inset-bottom) + 105px)); width: min(300px, 42vw); transform: translateX(50%); } } diff --git a/src/ui/GraphicsMenu.ts b/src/ui/GraphicsMenu.ts index 5efd293..1c40ebd 100644 --- a/src/ui/GraphicsMenu.ts +++ b/src/ui/GraphicsMenu.ts @@ -2,6 +2,9 @@ import { loadGraphicsSettings, resetGraphicsSettings, saveGraphicsSettings, type GraphicsSettings } from '../config/GraphicsSettings'; +import { VEHICLE_COLORS } from '../config/VehicleColors'; +import { loadGamepadSettings, resetGamepadSettings, saveGamepadSettings, type GamepadSettings } from '../input/GamepadSettings'; +import type { GamepadDebugState } from '../input/InputManager'; type Key = keyof GraphicsSettings; interface RangeSpec { key: Key; label: string; min: number; max: number; step: number; suffix?: string; heavy?: boolean } @@ -65,11 +68,15 @@ const toggles: readonly [Key, string, string][] = [ export class GraphicsMenu { readonly element = document.createElement('aside'); settings = loadGraphicsSettings(); + gamepadSettings = loadGamepadSettings(); private heavyTimer = 0; + private gamepadStatus: HTMLElement | null = null; + private lastGamepadStatus = ''; - constructor(private readonly root: HTMLElement, private readonly onChange: (settings: GraphicsSettings, heavy: boolean) => void) { + constructor(private readonly root: HTMLElement, private readonly onChange: (settings: GraphicsSettings, heavy: boolean) => void, + private readonly onGamepadChange: (settings: GamepadSettings) => void = () => undefined) { this.element.className = 'graphics-menu'; this.element.hidden = true; - this.element.innerHTML = '
RENDER CONTROLGRAPHICS
'; + this.element.innerHTML = '
CONTROL CENTERSETTINGS
'; root.appendChild(this.element); const scroll = this.required('.graphics-scroll'); for (const [title, ranges] of sections) { @@ -84,25 +91,28 @@ export class GraphicsMenu { } ranges.filter((spec) => spec.key !== 'renderScale').forEach((spec) => this.addRange(section, spec)); } + this.addVehicleColorSection(scroll); + this.addGamepadSection(scroll); const reset = document.createElement('button'); reset.className = 'graphics-reset'; reset.type = 'button'; reset.textContent = 'RESET GRAPHICS TO DEFAULT'; reset.addEventListener('click', () => { this.settings = resetGraphicsSettings(); this.refresh(); this.onChange(this.settings, true); }); scroll.appendChild(reset); - this.required('[data-close]').addEventListener('click', () => this.setOpen(false)); + this.required('[data-close]').addEventListener('click', () => this.close()); this.element.addEventListener('pointerdown', (event) => event.stopPropagation()); this.element.addEventListener('wheel', (event) => event.stopPropagation()); - this.element.addEventListener('keydown', (event) => { - if (event.key === 'Escape') this.setOpen(false); - event.stopPropagation(); - }); - this.element.addEventListener('keyup', (event) => event.stopPropagation()); - addEventListener('keydown', (event) => { - if (event.key === 'Escape' && !this.element.hidden) { - event.preventDefault(); - this.setOpen(false); - } - }, { capture: true }); } toggle(force?: boolean): void { this.setOpen(force ?? this.element.hidden); } + open(): void { this.setOpen(true); } + close(): void { this.setOpen(false); } + isOpen(): boolean { return !this.element.hidden; } + + updateGamepadStatus(state: GamepadDebugState): void { + const text = state.connected + ? `Connected · ${state.id}${state.standardMapping ? '' : ' · non-standard mapping'}` + : 'Not Connected'; + if (text === this.lastGamepadStatus) return; + this.lastGamepadStatus = text; + if (this.gamepadStatus) { this.gamepadStatus.textContent = text; this.gamepadStatus.classList.toggle('connected', state.connected); } + } private setOpen(open: boolean): void { this.element.hidden = !open; @@ -140,11 +150,85 @@ export class GraphicsMenu { if (!heavy) return; clearTimeout(this.heavyTimer); this.heavyTimer = window.setTimeout(() => this.onChange(this.settings, true), 280); } + private addVehicleColorSection(parent: HTMLElement): void { + const section = document.createElement('section'); section.dataset.section = 'VEHICLE COLOR'; + section.innerHTML = '

VEHICLE COLOR

BODY PAINT
'; + const output = section.querySelector('output') as HTMLOutputElement; + const palette = document.createElement('div'); palette.className = 'vehicle-color-palette'; + palette.setAttribute('role', 'radiogroup'); palette.setAttribute('aria-label', 'Vehicle color'); + const showSelectedName = (): void => { + output.value = VEHICLE_COLORS.find((option) => option.value === this.settings.vehicleColor)?.name ?? 'Dark Red'; + }; + for (const option of VEHICLE_COLORS) { + const swatch = document.createElement('button'); swatch.type = 'button'; swatch.className = 'vehicle-color-swatch'; + swatch.dataset.vehicleColor = option.value; swatch.title = option.name; + swatch.setAttribute('aria-label', option.name); swatch.setAttribute('role', 'radio'); + swatch.style.setProperty('--vehicle-color', option.value); + swatch.addEventListener('pointerenter', () => { output.value = option.name; }); + swatch.addEventListener('focus', () => { output.value = option.name; }); + swatch.addEventListener('pointerleave', showSelectedName); + swatch.addEventListener('click', () => { + this.settings.vehicleColor = option.value; this.refreshVehicleColor(); this.changed(false); + }); + palette.appendChild(swatch); + } + section.appendChild(palette); parent.appendChild(section); this.refreshVehicleColor(); + } + + private refreshVehicleColor(): void { + const option = VEHICLE_COLORS.find((candidate) => candidate.value === this.settings.vehicleColor) ?? VEHICLE_COLORS[4]; + this.element.querySelectorAll('[data-vehicle-color]').forEach((swatch) => { + const selected = swatch.dataset.vehicleColor === option.value; + swatch.classList.toggle('selected', selected); swatch.setAttribute('aria-checked', String(selected)); + }); + const output = this.element.querySelector('[data-section="VEHICLE COLOR"] output'); + if (output) output.value = option.name; + } + + private addGamepadSection(parent: HTMLElement): void { + const section = document.createElement('section'); section.dataset.section = 'CONTROLS'; + section.innerHTML = '

CONTROLS

GAMEPADNot Connected
'; + this.gamepadStatus = section.querySelector('.gamepad-status span'); + const addToggle = (key: 'enabled' | 'vibration' | 'controlHints', labelText: string): void => { + const label = document.createElement('label'); label.className = 'graphics-toggle'; + label.innerHTML = `${labelText}`; + const input = label.querySelector('input') as HTMLInputElement; input.checked = this.gamepadSettings[key]; input.dataset.gamepadKey = key; + input.addEventListener('change', () => { this.gamepadSettings[key] = input.checked; this.gamepadChanged(); }); + section.appendChild(label); + }; + const addRange = (key: 'steeringDeadzone' | 'cameraDeadzone', labelText: string): void => { + const label = document.createElement('label'); label.className = 'graphics-control'; + label.innerHTML = `${labelText}`; + const input = label.querySelector('input') as HTMLInputElement; const output = label.querySelector('output') as HTMLOutputElement; + input.value = String(this.gamepadSettings[key]); input.dataset.gamepadKey = key; + const render = (): void => { output.value = `${Math.round(Number(input.value) * 100)}%`; }; render(); + input.addEventListener('input', () => { this.gamepadSettings[key] = Number(input.value); render(); this.gamepadChanged(); }); + section.appendChild(label); + }; + addToggle('enabled', 'Gamepad Enabled'); addRange('steeringDeadzone', 'Steering Deadzone'); + addRange('cameraDeadzone', 'Camera Deadzone'); addToggle('vibration', 'Vibration'); + addToggle('controlHints', 'Control Hints'); + const reset = document.createElement('button'); reset.type = 'button'; reset.className = 'graphics-reset'; reset.textContent = 'RESET GAMEPAD TO DEFAULT'; + reset.addEventListener('click', () => { this.gamepadSettings = resetGamepadSettings(); this.refreshGamepad(); this.onGamepadChange(this.gamepadSettings); }); + section.appendChild(reset); parent.appendChild(section); + } + + private refreshGamepad(): void { + this.element.querySelectorAll('[data-gamepad-key]').forEach((input) => { + const key = input.dataset.gamepadKey as keyof GamepadSettings; + if (input.type === 'checkbox') input.checked = Boolean(this.gamepadSettings[key]); + else { input.value = String(this.gamepadSettings[key]); input.dispatchEvent(new Event('input')); } + }); + } + + private gamepadChanged(): void { saveGamepadSettings(this.gamepadSettings); this.onGamepadChange(this.gamepadSettings); } + private refresh(): void { this.element.querySelectorAll('[data-key]').forEach((input) => { const key = input.dataset.key as Key; if (input instanceof HTMLInputElement && input.type === 'checkbox') input.checked = Boolean(this.settings[key]); else input.value = String(this.settings[key]); input.dispatchEvent(new Event('input')); }); + this.refreshVehicleColor(); } private required(selector: string): T { const el = this.element.querySelector(selector); if (!el) throw new Error(`Missing graphics menu ${selector}`); return el; } diff --git a/src/ui/MenuNavigator.ts b/src/ui/MenuNavigator.ts new file mode 100644 index 0000000..392afa5 --- /dev/null +++ b/src/ui/MenuNavigator.ts @@ -0,0 +1,63 @@ +import type { GameAction } from '../input/InputManager'; + +const FOCUSABLE = 'button:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])'; + +/** Native-control menu navigation shared by keyboard and gamepad actions. */ +export class MenuNavigator { + constructor(private readonly getActiveRoot: () => HTMLElement | null) {} + + handle(action: GameAction): void { + const root = this.getActiveRoot(); if (!root) return; + const elements = this.elements(root); if (elements.length === 0) return; + const current = document.activeElement instanceof HTMLElement && root.contains(document.activeElement) ? document.activeElement : null; + if (current?.matches('[data-vehicle-color]') && this.moveWithinColorPalette(root, current, action)) return; + if (action === 'menuUp' || action === 'menuDown') { + const index = current ? elements.indexOf(current) : -1; const delta = action === 'menuUp' ? -1 : 1; + this.focus(elements[(index + delta + elements.length) % elements.length]); return; + } + if (action === 'menuLeft' || action === 'menuRight') { + const target = current ?? elements[0]; const direction = action === 'menuLeft' ? -1 : 1; + if (target instanceof HTMLInputElement && target.type === 'range') { + direction < 0 ? target.stepDown() : target.stepUp(); + target.dispatchEvent(new Event('input', { bubbles: true })); target.dispatchEvent(new Event('change', { bubbles: true })); + } else if (target instanceof HTMLSelectElement) { + target.selectedIndex = Math.max(0, Math.min(target.options.length - 1, target.selectedIndex + direction)); + target.dispatchEvent(new Event('change', { bubbles: true })); + } else if (target instanceof HTMLInputElement && target.type === 'checkbox') { + target.checked = direction > 0; target.dispatchEvent(new Event('change', { bubbles: true })); + } + return; + } + if (action === 'menuConfirm') { const target = current ?? elements[0]; this.focus(target); target.click(); } + } + + focusFirst(): void { + const root = this.getActiveRoot(); const elements = root ? this.elements(root) : []; + const first = elements.find((element) => !element.hasAttribute('data-close')) ?? elements[0]; + if (first) this.focus(first); + } + getFocusedLabel(): string { + const element = document.activeElement; + return element instanceof HTMLElement + ? element.getAttribute('aria-label') || element.textContent?.trim().slice(0, 48) || element.tagName.toLowerCase() : 'none'; + } + private elements(root: HTMLElement): HTMLElement[] { + return [...root.querySelectorAll(FOCUSABLE)].filter((element) => !element.hidden && element.offsetParent !== null); + } + private moveWithinColorPalette(root: HTMLElement, current: HTMLElement, action: GameAction): boolean { + if (action !== 'menuUp' && action !== 'menuDown' && action !== 'menuLeft' && action !== 'menuRight') return false; + const swatches = [...root.querySelectorAll('[data-vehicle-color]')]; + const index = swatches.indexOf(current); if (index < 0) return false; + const columns = 4; let next = index; + if (action === 'menuLeft') next = index % columns > 0 ? index - 1 : index; + else if (action === 'menuRight') next = index % columns < columns - 1 && index + 1 < swatches.length ? index + 1 : index; + else if (action === 'menuUp' && index >= columns) next = index - columns; + else if (action === 'menuDown' && index + columns < swatches.length) next = index + columns; + else return false; + this.focus(swatches[next]); return true; + } + private focus(element: HTMLElement): void { + document.querySelectorAll('.gamepad-focus').forEach((item) => item.classList.remove('gamepad-focus')); + element.focus({ preventScroll: false }); element.classList.add('gamepad-focus'); element.scrollIntoView({ block: 'nearest' }); + } +} diff --git a/src/ui/UI.ts b/src/ui/UI.ts index 577890f..2aa6e7b 100644 --- a/src/ui/UI.ts +++ b/src/ui/UI.ts @@ -1,17 +1,10 @@ import { CONFIG, IS_COARSE_POINTER } from '../config/gameConfig'; import { mpsToKmh } from '../config/speedUnits'; import type { CruiseState } from '../vehicle/CruiseController'; +import type { GameAction, GamepadFamily, InputDevice } from '../input/InputManager'; export interface UIActions { - start: () => void | Promise; - toggleAuto: () => void; - reset: () => void; - toggleMute: () => void; - toggleCamera: () => void; - toggleGraphics: () => void; - toggleCruise: () => void; - adjustCruise: (deltaKph: number) => void; - setCruiseTarget: (targetKph: number) => void; + dispatch: (action: GameAction, value?: number) => void; } export class UI { @@ -33,8 +26,15 @@ export class UI { private readonly cruiseTarget: HTMLElement; private readonly cruiseMode: HTMLElement; private readonly cruiseRange: HTMLInputElement; + private readonly controlsCopy: HTMLElement; + private readonly controlHints: HTMLElement; + private inputDevice: InputDevice = IS_COARSE_POINTER ? 'touch' : 'keyboard'; + private gamepadFamily: GamepadFamily = 'generic'; + private controlHintsEnabled = true; + private cruiseActive = false; + private autopilotActive = false; - constructor(root: HTMLElement, actions: UIActions) { + constructor(private readonly root: HTMLElement, actions: UIActions) { root.innerHTML = `
@@ -58,6 +58,7 @@ export class UI {
+
‹РУЛЬ›
@@ -72,7 +73,7 @@ export class UI {
ПРОЦЕДУРНАЯ ПОЕЗДКА

Quiet Mile

Дорога без финиша. Езжайте в своём ритме или доверьте путь автопилоту.

-
${IS_COARSE_POINTER +
${IS_COARSE_POINTER ? 'Касайтесь руля слеваГаз и тормоз — справа · круиз 5–375 км/ч на панели' : 'WASD / стрелки — управлениеГаз временно ускоряет круиз · тормоз отключает его · P — автопилот'}
@@ -91,17 +92,20 @@ export class UI { this.cruiseTarget = this.required('cruise-target'); this.cruiseMode = this.required('cruise-mode'); this.cruiseRange = this.required('cruise-range') as HTMLInputElement; - this.required('start').addEventListener('click', async () => { await actions.start(); this.startScreen.classList.add('hidden'); }); - this.required('auto-touch').addEventListener('click', actions.toggleAuto); - this.required('reset-touch').addEventListener('click', actions.reset); - this.required('reset').addEventListener('click', actions.reset); - this.soundButton.addEventListener('click', actions.toggleMute); - this.required('camera').addEventListener('click', actions.toggleCamera); - this.required('graphics').addEventListener('click', actions.toggleGraphics); - this.cruiseToggle.addEventListener('click', actions.toggleCruise); - this.bindRepeatButton(this.required('cruise-minus'), () => actions.adjustCruise(-CONFIG.cruise.stepKph)); - this.bindRepeatButton(this.required('cruise-plus'), () => actions.adjustCruise(CONFIG.cruise.stepKph)); - this.cruiseRange.addEventListener('input', () => actions.setCruiseTarget(Number(this.cruiseRange.value))); + this.controlsCopy = this.required('controls-copy'); + this.controlHints = this.required('control-hints'); + this.required('start').addEventListener('click', () => actions.dispatch('start')); + this.required('auto-touch').addEventListener('click', () => actions.dispatch('autopilot')); + this.required('reset-touch').addEventListener('click', () => actions.dispatch('recover')); + this.required('reset').addEventListener('click', () => actions.dispatch('recover')); + this.soundButton.addEventListener('click', () => actions.dispatch('mute')); + this.required('camera').addEventListener('click', () => actions.dispatch('camera')); + this.required('graphics').addEventListener('click', () => actions.dispatch('pause')); + this.cruiseToggle.addEventListener('click', () => actions.dispatch('cruiseToggle')); + this.bindRepeatButton(this.required('cruise-minus'), () => actions.dispatch('cruiseDown')); + this.bindRepeatButton(this.required('cruise-plus'), () => actions.dispatch('cruiseUp')); + this.cruiseRange.addEventListener('input', () => actions.dispatch('cruiseSet', Number(this.cruiseRange.value))); + this.renderControlHints(); this.onResize(); addEventListener('resize', this.onResize); } @@ -125,10 +129,45 @@ export class UI { this.cruiseRange.value = cruise.targetKph.toString(); const progress = (cruise.targetKph - CONFIG.cruise.minimumKph) / (CONFIG.cruise.maximumKph - CONFIG.cruise.minimumKph) * 100; this.cruisePanel.style.setProperty('--cruise-progress', `${progress}%`); + if (this.cruiseActive !== cruise.enabled || this.autopilotActive !== auto) { + this.cruiseActive = cruise.enabled; this.autopilotActive = auto; + if (this.inputDevice === 'gamepad') this.renderControlHints(); + } } setMuted(muted: boolean): void { this.soundButton.textContent = muted ? 'ЗВУК OFF' : 'ЗВУК ON'; } + setInputDevice(device: InputDevice, family: GamepadFamily = this.gamepadFamily): void { + if (device === this.inputDevice && family === this.gamepadFamily) return; + this.inputDevice = device; this.gamepadFamily = family; this.root.dataset.inputDevice = device; + this.controlsCopy.innerHTML = device === 'gamepad' + ? 'Левый стик — руль · RT газ · LT тормозL3 — круиз · R3 — автопилот · правый стик — камера · D-pad круиз и музыка' + : device === 'touch' + ? 'Касайтесь руля слеваГаз и тормоз — справа · круиз 5–375 км/ч на панели' + : 'WASD / стрелки — управлениеГаз временно ускоряет круиз · тормоз отключает его · P — автопилот'; + this.renderControlHints(); + } + setControlHints(enabled: boolean): void { + if (enabled === this.controlHintsEnabled) return; + this.controlHintsEnabled = enabled; + this.renderControlHints(); + } + isStartScreenOpen(): boolean { return !this.startScreen.classList.contains('hidden'); } + hideStartScreen(): void { this.startScreen.classList.add('hidden'); } + getStartMenuRoot(): HTMLElement { return this.startScreen; } setDebug(enabled: boolean): void { this.debugPanel.classList.toggle('visible', enabled); } updateDebug(text: string): void { this.debugPanel.textContent = text; } + private renderControlHints(): void { + const visible = this.controlHintsEnabled && this.inputDevice !== 'touch'; + this.controlHints.hidden = !visible; if (!visible) return; + const keys = this.inputDevice === 'gamepad' + ? this.gamepadFamily === 'playstation' + ? [['R2','Accelerate'],['L2','Brake'],['LS','Steer'],['L3',`Cruise${this.cruiseActive ? ' ON' : ''}`],['R3',`Autopilot${this.autopilotActive ? ' ON' : ''}`],['Triangle','Camera'],['Circle','Recover'],['D↑ D↓','Cruise speed'],['D← D→','Music'],['Options','Menu']] + : this.gamepadFamily === 'xbox' + ? [['RT','Accelerate'],['LT','Brake'],['LS','Steer'],['L3',`Cruise${this.cruiseActive ? ' ON' : ''}`],['R3',`Autopilot${this.autopilotActive ? ' ON' : ''}`],['Y','Camera'],['B','Recover'],['D↑ D↓','Cruise speed'],['D← D→','Music'],['START','Menu']] + : [['B7','Accelerate'],['B6','Brake'],['LS','Steer'],['B10',`Cruise${this.cruiseActive ? ' ON' : ''}`],['B11',`Autopilot${this.autopilotActive ? ' ON' : ''}`],['B3','Camera'],['B1','Recover'],['D↑ D↓','Cruise speed'],['D← D→','Music'],['B9','Menu']] + : [['W / ↑','Accelerate'],['S / ↓','Brake'],['A D / ← →','Steer'],['V','Cruise'],['P','Autopilot'],['C','Camera'],['R','Recover'],['+ / −','Cruise speed'],['[ / ]','Music'],['ESC','Menu']]; + this.controlHints.innerHTML = `${this.inputDevice === 'gamepad' ? 'GAMEPAD' : 'KEYBOARD'}${keys + .map(([key, label]) => `
${key}${label}
`).join('')}`; + } private bindRepeatButton(element: HTMLElement, action: () => void): void { let delayTimer = 0; let repeatTimer = 0; diff --git a/src/vehicle/Vehicle.ts b/src/vehicle/Vehicle.ts index b4e09b8..529fcdd 100644 --- a/src/vehicle/Vehicle.ts +++ b/src/vehicle/Vehicle.ts @@ -85,6 +85,8 @@ export class Vehicle implements VehicleState { this.placeAtStartParking(); } + setBodyColor(color: string): void { this.vehicleModel.setBodyColor(color); } + update(dt: number, control: VehicleControls): void { this.previousPhysicsPosition.copy(this.position); this.previousPhysicsHeading = this.heading; diff --git a/src/vehicle/VehicleModel.ts b/src/vehicle/VehicleModel.ts index d7ce391..d462fc0 100644 --- a/src/vehicle/VehicleModel.ts +++ b/src/vehicle/VehicleModel.ts @@ -328,6 +328,8 @@ export class VehicleModel { tailLensMaterial.emissiveIntensity = .45 + nightFactor * 2.2 + braking * 3.5; } + setBodyColor(color: string): void { paintMaterial.color.set(color); } + private buildBody(): void { this.bodyShell.add(mesh(buildBodyGeometry(), paintMaterial, 'MainBody')); const roof = parametricGeometry(64, 24, (u, v, target) => { diff --git a/src/world/FieldParcelSystem.ts b/src/world/FieldParcelSystem.ts new file mode 100644 index 0000000..e371e57 --- /dev/null +++ b/src/world/FieldParcelSystem.ts @@ -0,0 +1,95 @@ +import { hash01 } from './SeededRandom'; + +export type FieldCoverType = 'wheat' | 'meadow' | 'stubble' | 'fallow'; + +export interface FieldParcelSample { + type: FieldCoverType; + parcelId: number; + alongIndex: number; + lateralIndex: number; + distanceToBoundary: number; + boundaryStrength: number; + interiorStrength: number; +} + +const PARCEL_LENGTH = 340; +const PARCEL_WIDTH = 145; +const BORDER_WIDTH = 11; + +const positiveModulo = (value: number, divisor: number): number => ((value % divisor) + divisor) % divisor; +const smoothstep = (value: number): number => { + const t = Math.max(0, Math.min(1, value)); + return t * t * (3 - 2 * t); +}; + +/** Deterministic road-local agricultural parcel layout shared by terrain and vegetation. */ +export class FieldParcelSystem { + private readonly alongPhase: number; + private readonly lateralPhase: number; + private readonly warpPhaseA: number; + private readonly warpPhaseB: number; + + constructor(readonly seed: number) { + this.alongPhase = hash01(seed + 1901, 0, 0) * PARCEL_LENGTH; + this.lateralPhase = hash01(seed + 1903, 0, 0) * PARCEL_WIDTH; + this.warpPhaseA = hash01(seed + 1907, 0, 0) * Math.PI * 2; + this.warpPhaseB = hash01(seed + 1913, 0, 0) * Math.PI * 2; + } + + createSample(): FieldParcelSample { + return { type: 'meadow', parcelId: 0, alongIndex: 0, lateralIndex: 0, + distanceToBoundary: 0, boundaryStrength: 0, interiorStrength: 0 }; + } + + sample(roadDistance: number, lateral: number, target = this.createSample()): FieldParcelSample { + const warpedAlong = roadDistance + this.alongPhase + + Math.sin(lateral * 0.012 + this.warpPhaseA) * 17; + const warpedLateral = lateral + this.lateralPhase + + Math.sin(roadDistance * 0.0062 + this.warpPhaseB) * 13; + const alongIndex = Math.floor(warpedAlong / PARCEL_LENGTH); + const lateralIndex = Math.floor(warpedLateral / PARCEL_WIDTH); + const localAlong = positiveModulo(warpedAlong, PARCEL_LENGTH); + const localLateral = positiveModulo(warpedLateral, PARCEL_WIDTH); + const distanceToBoundary = Math.min(localAlong, PARCEL_LENGTH - localAlong, + localLateral, PARCEL_WIDTH - localLateral); + const roll = hash01(this.seed + 1921, alongIndex, lateralIndex); + target.type = roll < 0.38 ? 'wheat' : roll < 0.65 ? 'meadow' : roll < 0.86 ? 'stubble' : 'fallow'; + target.alongIndex = alongIndex; + target.lateralIndex = lateralIndex; + target.parcelId = (Math.imul(alongIndex, 73856093) ^ Math.imul(lateralIndex, 19349663)) >>> 0; + target.distanceToBoundary = distanceToBoundary; + target.boundaryStrength = 1 - smoothstep(distanceToBoundary / BORDER_WIDTH); + target.interiorStrength = smoothstep((distanceToBoundary - BORDER_WIDTH * 0.65) / 14); + return target; + } + + /** Snaps scenery to a long parcel edge, creating continuous roadside-visible shelterbelts. */ + snapLateralToBoundary(roadDistance: number, lateral: number): number { + const wave = Math.sin(roadDistance * 0.0062 + this.warpPhaseB) * 13; + const warped = lateral + this.lateralPhase + wave; + return Math.round(warped / PARCEL_WIDTH) * PARCEL_WIDTH - this.lateralPhase - wave; + } + + runProbe(maxDistance = 250_000): { passed: boolean; deterministic: boolean; differentSeed: boolean; allCovers: boolean; borderSnap: boolean; coverCounts: Record } { + const same = new FieldParcelSystem(this.seed); const different = new FieldParcelSystem(this.seed + 1); + const a = this.createSample(); const b = same.createSample(); const c = different.createSample(); + const coverCounts: Record = { wheat: 0, meadow: 0, stubble: 0, fallow: 0 }; + let deterministic = true; let differentSeed = false; let borderSnap = true; + for (let s = 0; s <= maxDistance; s += 173) { + for (let lateral = -430; lateral <= 430; lateral += 71) { + this.sample(s, lateral, a); same.sample(s, lateral, b); different.sample(s, lateral, c); + deterministic &&= a.type === b.type && a.parcelId === b.parcelId + && Math.abs(a.distanceToBoundary - b.distanceToBoundary) < 1e-9; + differentSeed ||= a.type !== c.type || a.parcelId !== c.parcelId + || Math.abs(a.distanceToBoundary - c.distanceToBoundary) > 1e-6; + coverCounts[a.type]++; + const snapped = this.snapLateralToBoundary(s, lateral); + this.sample(s, snapped, b); + borderSnap &&= b.distanceToBoundary < 0.0001; + } + } + const allCovers = Object.values(coverCounts).every((count) => count > 0); + return { passed: deterministic && differentSeed && allCovers && borderSnap, + deterministic, differentSeed, allCovers, borderSnap, coverCounts }; + } +} diff --git a/src/world/InfiniteWorld.ts b/src/world/InfiniteWorld.ts index cf80897..0773305 100644 --- a/src/world/InfiniteWorld.ts +++ b/src/world/InfiniteWorld.ts @@ -26,6 +26,7 @@ export interface WorldDebugStats { oldestActiveChunk: number; newestActiveChunk: number; expectedActiveChunks: number; + bridgeSections: number; } export interface ChunkLeakSnapshot { @@ -39,6 +40,15 @@ export interface ChunkLeakProbeResult { passed: boolean; } +export interface RegionLifecycleProbeResult { + passed: boolean; + distanceTested: number; + regionsSeen: string[]; + maximumActiveChunks: number; + maximumSceneObjects: number; + maximumBridgeSections: number; +} + /** Transactional streaming keyed by stable logical chunk indices. */ export class InfiniteWorld { readonly group = new Group(); @@ -233,11 +243,47 @@ export class InfiniteWorld { return { afterTwoMinutes, afterThirtyMinutes, passed }; } + runRegionLifecycleProbe(maxDistance = 1_000_000): RegionLifecycleProbeResult { + const originalDistance = this.lastRoadDistance; + const originalOrigin = this.road.getOriginOffsetZ(); + const regionsSeen = new Set(); + let maximumActiveChunks = 0; + let maximumSceneObjects = 0; + let maximumBridgeSections = 0; + let passed = true; + const step = CONFIG.road.chunkLength * 12; + for (let distance = 0; distance <= maxDistance; distance += step) { + const originDistance = distance - this.road.getOriginOffsetZ(); + if (originDistance > CONFIG.world.floatingOriginThreshold) this.shiftOrigin(originDistance, distance); + this.update(distance); + const region = this.road.regions.sample(distance); + regionsSeen.add(region.type); + const stats = this.getDebugStats(); + maximumActiveChunks = Math.max(maximumActiveChunks, stats.chunks); + maximumSceneObjects = Math.max(maximumSceneObjects, stats.sceneObjects); + maximumBridgeSections = Math.max(maximumBridgeSections, stats.bridgeSections); + if (stats.chunks !== stats.expectedActiveChunks || stats.bridgeSections > 14 || + stats.oldestActiveChunk < stats.activeStart || stats.newestActiveChunk > stats.activeEnd) { + passed = false; + break; + } + } + passed = passed && ['forest', 'fields', 'coast', 'river_bridge'].every((type) => regionsSeen.has(type)) && + maximumBridgeSections > 0; + this.shiftOrigin(originalOrigin - this.road.getOriginOffsetZ(), originalDistance); + this.update(originalDistance, true); + return { + passed, distanceTested: maxDistance, regionsSeen: [...regionsSeen], maximumActiveChunks, + maximumSceneObjects, maximumBridgeSections + }; + } + getDebugStats(): WorldDebugStats { let sceneObjects = 0; let vegetationInstances = 0; let vegetationLayoutFingerprint = 2166136261; let roadsideFeatures = 0; + let bridgeSections = 0; let treesNear = 0; let treesMid = 0; let treesFar = 0; let shrubs = 0; let grassPlants = 0; let ferns = 0; let oldestActiveChunk = Number.POSITIVE_INFINITY; @@ -248,6 +294,7 @@ export class InfiniteWorld { newestActiveChunk = Math.max(newestActiveChunk, index); vegetationInstances += chunk.getVegetationInstanceCount(); roadsideFeatures += chunk.getRoadsideFeatureCount(); + bridgeSections += chunk.getBridgeSectionCount(); const vegetation = chunk.getVegetationStats(); treesNear += vegetation.treesNear; treesMid += vegetation.treesMid; treesFar += vegetation.treesFar; shrubs += vegetation.shrubs; grassPlants += vegetation.grass; ferns += vegetation.ferns; @@ -268,7 +315,7 @@ export class InfiniteWorld { originOffsetZ: this.road.getOriginOffsetZ(), vegetationInstances, vegetationLayoutFingerprint: vegetationLayoutFingerprint >>> 0, - roadsideFeatures, treesNear, treesMid, treesFar, shrubs, grassPlants, ferns, + roadsideFeatures, bridgeSections, treesNear, treesMid, treesFar, shrubs, grassPlants, ferns, oldestActiveChunk: Number.isFinite(oldestActiveChunk) ? oldestActiveChunk : -1, newestActiveChunk: Number.isFinite(newestActiveChunk) ? newestActiveChunk : -1, expectedActiveChunks: Math.max(0, this.activeEnd - this.activeStart + 1) diff --git a/src/world/ProceduralVegetationFactory.ts b/src/world/ProceduralVegetationFactory.ts index d559b61..c27de48 100644 --- a/src/world/ProceduralVegetationFactory.ts +++ b/src/world/ProceduralVegetationFactory.ts @@ -29,6 +29,7 @@ export interface ProceduralVegetationCatalog { readonly shrubs: readonly GroundLodVariant[]; readonly ferns: readonly GroundLodVariant[]; readonly grass: readonly GroundLodVariant[]; + readonly wheat: readonly GroundLodVariant[]; readonly dead: readonly GroundLodVariant[]; } @@ -190,6 +191,7 @@ export class ProceduralVegetationFactory { bark: MeshStandardMaterial; birch: MeshStandardMaterial; pine: MeshStandardMaterial; spruce: MeshStandardMaterial; leaves: MeshStandardMaterial; shrub: MeshStandardMaterial; grass: MeshStandardMaterial; dry: MeshStandardMaterial; + wheat: MeshStandardMaterial; }; constructor() { @@ -201,13 +203,15 @@ export class ProceduralVegetationFactory { leaves: this.createMaterial(0x416c3c, 0.94, 0.027, 'deciduous-leaves'), shrub: this.createMaterial(0x496e3d, 0.97, 0.042, 'shrub-leaves'), grass: this.createMaterial(0x71834c, 1, 0.075, 'grass', true), - dry: this.createMaterial(0x756448, 1, 0.035, 'dry-vegetation', true) + dry: this.createMaterial(0x756448, 1, 0.035, 'dry-vegetation', true), + wheat: this.createMaterial(0xc49a3d, 0.98, 0.052, 'wheat', true) }; this.catalog = { trees: treeDefinitions.map((definition) => this.createTreeVariant(definition.id, definition.family, definition.seed)), shrubs: Array.from({ length: 8 }, (_, index) => this.createShrubVariant(index)), ferns: Array.from({ length: 2 }, (_, index) => this.createFernVariant(index)), grass: Array.from({ length: 5 }, (_, index) => this.createGrassVariant(index)), + wheat: Array.from({ length: 2 }, (_, index) => this.createWheatVariant(index)), dead: [this.createDeadVariant('DEAD_TREE_A', 901), this.createDeadVariant('DEAD_TREE_B', 947), this.createStumpVariant(), this.createFallenBranchVariant()] }; @@ -422,6 +426,32 @@ export class ProceduralVegetationFactory { return { id: names[index], near: create(false), mid: create(true) }; } + private createWheatVariant(index: number): GroundLodVariant { + const create = (simplified: boolean): VegetationGeometry => { + const random = new Random(1760 + index * 103 + (simplified ? 3200 : 0)); + const builder = new GeometryBuilder(1); + const stalks = simplified ? 7 : 13 + index * 3; + for (let stalk = 0; stalk < stalks; stalk++) { + const angle = random.range(0, Math.PI * 2); + const radius = Math.sqrt(random.next()) * 0.42; + const root = new Vector3(Math.cos(angle) * radius, 0, Math.sin(angle) * radius); + const height = random.range(0.72, 1.02); + const lean = random.range(0.025, 0.09); + const middle = root.clone().add(new Vector3(Math.cos(angle) * lean * 0.35, height * 0.57, Math.sin(angle) * lean * 0.35)); + const tip = root.clone().add(new Vector3(Math.cos(angle) * lean, height, Math.sin(angle) * lean)); + builder.addBlade([root, middle, tip], [0.014, 0.009, 0.002], 0, 1); + if (!simplified || stalk % 2 === 0) { + builder.addCluster(tip.clone().add(new Vector3(0, -0.045, 0)), new Vector3(0, 1, 0), + random.range(0.085, 0.13), 0.018, 0.012, simplified ? 3 : 4, 2, 0.28, random, 0, 1); + } + } + const geometry = builder.build(`WHEAT_${index + 1}_${simplified ? 'mid' : 'near'}`); + return { id: geometry.name, geometry, material: this.materials.wheat, + triangles: geometry.getAttribute('position').count / 3 }; + }; + return { id: `WHEAT_${index + 1}`, near: create(false), mid: create(true) }; + } + private createDeadVariant(id: string, seed: number): GroundLodVariant { const create = (simplified: boolean): VegetationGeometry => { const random = new Random(seed + (simplified ? 1000 : 0)); diff --git a/src/world/RoadGenerator.ts b/src/world/RoadGenerator.ts index 933f03a..af30f97 100644 --- a/src/world/RoadGenerator.ts +++ b/src/world/RoadGenerator.ts @@ -1,6 +1,8 @@ import { Vector3 } from 'three'; import { CONFIG } from '../config/gameConfig'; import { hash01 } from './SeededRandom'; +import { WorldRegionDirector, type WorldRegionSample } from './WorldRegionDirector'; +import { FieldParcelSystem } from './FieldParcelSystem'; export interface RoadSample { position: Vector3; @@ -34,13 +36,19 @@ export interface GroundSurface { } export class RoadGenerator { + readonly regions: WorldRegionDirector; + readonly fieldParcels: FieldParcelSystem; private readonly phases: number[]; + private readonly regionSample: WorldRegionSample; private readonly featureSample: RoadSample; private readonly featurePlacement: RoadsideFeaturePlacement; private originOffsetZ = 0; constructor(readonly seed: number = CONFIG.seed) { + this.regions = new WorldRegionDirector(seed); + this.fieldParcels = new FieldParcelSystem(seed); this.phases = [0, 1, 2, 3, 4].map((i) => hash01(seed, i) * Math.PI * 2); + this.regionSample = this.regions.sample(0); this.featureSample = this.createSample(); this.featurePlacement = this.createRoadsideFeaturePlacement(); } @@ -58,6 +66,11 @@ export class RoadGenerator { } getRoadsideFeaturePlacement(chunkIndex: number, target: RoadsideFeaturePlacement): boolean { + const region = this.regions.sample((chunkIndex + 0.5) * CONFIG.road.chunkLength, this.regionSample); + if ((region.type === 'coast' || region.type === 'river_bridge') && region.blend > 0.2) { + target.type = 'none'; + return false; + } const roll = chunkIndex < 3 ? 1 : hash01(this.seed + 901, chunkIndex, 0); target.type = roll < 0.045 ? 'station' : roll < 0.115 ? 'rest' : 'none'; if (target.type === 'none') return false; @@ -139,6 +152,16 @@ export class RoadGenerator { return target; } const s = Math.max(0, this.originOffsetZ - renderZ); + const region = this.regions.sample(s, this.regionSample); + if (region.type === 'river_bridge' && s >= region.bridgeStart && s <= region.bridgeEnd) { + const road = this.sample(s, this.featureSample); + const lateral = (x - road.position.x) * road.right.x + (renderZ - road.position.z) * road.right.z; + if (Math.abs(lateral) <= CONFIG.road.width * 0.5 + CONFIG.road.shoulderWidth) { + target.height = road.position.y + 0.02; + target.paved = true; + return target; + } + } const centerChunk = Math.floor(s / CONFIG.road.chunkLength); for (let chunk = Math.max(3, centerChunk - 1); chunk <= centerChunk + 1; chunk++) { if (!this.getRoadsideFeaturePlacement(chunk, this.featurePlacement)) continue; @@ -151,6 +174,33 @@ export class RoadGenerator { return target; } + getWaterLevel(roadDistance: number): number { + const region = this.regions.sample(roadDistance, this.regionSample); + return region.type === 'coast' ? -5.8 : -6.5; + } + + getRiverWaterHalfWidth(roadDistance: number): number { + const region = this.regions.sample(roadDistance, this.regionSample); + if (region.type !== 'river_bridge') return 0; + const strength = region.blend * this.bridgeValleyInfluence(roadDistance, region); + return 180 + strength * 470; + } + + adjustSceneryLateral(roadDistance: number, lateral: number): number { + const region = this.regions.sample(roadDistance, this.regionSample); + if (region.type === 'coast' && region.blend > 0.15 && Math.sign(lateral) === region.waterSide) { + return -region.waterSide * Math.max(10, Math.abs(lateral)); + } + if (region.type === 'river_bridge') { + const strength = region.blend * this.bridgeValleyInfluence(roadDistance, region); + if (strength <= 0.04) return lateral; + const side = lateral < 0 ? -1 : 1; + const exclusionDistance = 170 + strength * 550; + return side * Math.max(Math.abs(lateral), exclusionDistance); + } + return lateral; + } + getMaximumRoadGroundGap(maxDistance = 10_000): number { const sample = this.createSample(); const offsets = [0, -CONFIG.road.width * 0.5, CONFIG.road.width * 0.5, @@ -189,6 +239,57 @@ export class RoadGenerator { return found >= 4; } + runBridgeSurfaceProbe(): boolean { + const bridge = this.regions.nextSpecial(0, 'river_bridge'); + const surface: GroundSurface = { height: 0, paved: false }; + const sample = this.createSample(); + for (let s = bridge.bridgeStart + 2; s < bridge.bridgeEnd; s += 83) { + this.sample(s, sample); + this.getDrivingSurface(sample.position.x, sample.position.z, surface); + if (!surface.paved || Math.abs(surface.height - (sample.position.y + 0.02)) > 0.02) return false; + if (sample.position.y - this.terrainHeight(sample.position.x, sample.position.z) < 5) return false; + } + return Math.abs((bridge.bridgeEnd - bridge.bridgeStart) - 1008) < 0.01; + } + + runRiverCorridorProbe(): boolean { + const region = this.regions.nextSpecial(0, 'river_bridge'); + const sample = this.createSample(); + const checkpoints = [region.bridgeStart + 36, (region.bridgeStart + region.bridgeEnd) * 0.5, region.bridgeEnd - 36]; + for (const distance of checkpoints) { + if (this.getRiverWaterHalfWidth(distance) < 640) return false; + if (Math.abs(this.adjustSceneryLateral(distance, 25)) < 700 || + Math.abs(this.adjustSceneryLateral(distance, -25)) < 700) return false; + this.sample(distance, sample); + for (const side of [-1, 1]) { + const x = sample.position.x + sample.right.x * side * 500; + const z = sample.position.z + sample.right.z * side * 500; + if (this.terrainHeight(x, z) > this.getWaterLevel(distance) - 0.5) return false; + } + } + return true; + } + + runRegionContinuityProbe(maxDistance = 1_000_000): boolean { + const sampleA = this.createSample(); + const sampleB = this.createSample(); + const schedule = this.regions.getSchedule(maxDistance); + for (const region of schedule) { + const checkpoints = [region.startDistance, region.startDistance + region.transitionDistance, + region.endDistance - region.transitionDistance, region.endDistance]; + if (region.type === 'river_bridge') checkpoints.push(region.bridgeStart, region.bridgeEnd); + for (const checkpoint of checkpoints) { + for (let offset = -12; offset < 12; offset += 2) { + this.sample(Math.max(0, checkpoint + offset), sampleA); + this.sample(Math.max(0, checkpoint + offset + 2), sampleB); + if (sampleA.position.distanceTo(sampleB.position) > 2.2 || sampleA.tangent.dot(sampleB.tangent) < 0.992 || + Math.abs(sampleA.curvature) > 0.0045) return false; + } + } + } + return true; + } + shiftOrigin(deltaZ: number): void { this.originOffsetZ += deltaZ; } getOriginOffsetZ(): number { return this.originOffsetZ; } @@ -200,9 +301,34 @@ export class RoadGenerator { const groundedRoadEdge = CONFIG.road.width * 0.5 + CONFIG.road.shoulderWidth; const blend = Math.min(1, Math.max(0, (distance - groundedRoadEdge) / 18)); const logicalZ = renderZ - this.originOffsetZ; - const hills = 4.2 * Math.sin(x * 0.031 + logicalZ * 0.012 + this.phases[3]) + const forestHills = 4.2 * Math.sin(x * 0.031 + logicalZ * 0.012 + this.phases[3]) + 2.4 * Math.sin(x * 0.073 - logicalZ * 0.019 + this.phases[4]); - return base - 0.02 + hills * blend; + const region = this.regions.sample(s, this.regionSample); + const fieldsHills = 1.35 * Math.sin(x * 0.014 + logicalZ * 0.004 + this.phases[3]) + + 0.55 * Math.sin(x * 0.035 - logicalZ * 0.007 + this.phases[4]); + const hills = region.type === 'fields' + ? forestHills + (fieldsHills - forestHills) * region.blend + : forestHills; + let terrain = base - 0.02 + hills * blend; + if (region.type === 'coast') { + const signedWaterDistance = (x - roadX) * region.waterSide; + const shore = this.smoothstep((signedWaterDistance - 18) / 68); + const coastLand = base - 0.02 + forestHills * blend * (1 - shore * 0.72); + const seaFloor = this.getWaterLevel(s) - 4.5 - 1.2 * Math.sin(x * 0.018 + logicalZ * 0.006); + const coastTerrain = coastLand + (seaFloor - coastLand) * shore; + terrain += (coastTerrain - terrain) * region.blend; + } + if (region.type === 'river_bridge') { + const valleyInfluence = this.bridgeValleyInfluence(s, region) * region.blend; + const lateral = Math.abs(x - roadX); + const waterHalfWidth = 180 + valleyInfluence * 470; + const bankStart = waterHalfWidth * 0.78; + const bank = this.smoothstep((lateral - bankStart) / 275); + const valleyFloor = this.getWaterLevel(s) - 3.8 + Math.sin(x * 0.024 + logicalZ * 0.005) * 0.7; + const valleyTerrain = valleyFloor + (base + forestHills * blend - valleyFloor) * bank; + terrain += (valleyTerrain - terrain) * valleyInfluence; + } + return terrain; } private flattenStartArea(x: number, renderZ: number, naturalHeight: number): number { @@ -265,9 +391,60 @@ export class RoadGenerator { const dz = position.z - (-distance + this.originOffsetZ); return dx * dx + dz * dz; } - private x(s: number): number { return 18 * Math.sin(s * 0.0038 + this.phases[0]) + 8 * Math.sin(s * 0.009 + this.phases[1]) + 3 * Math.sin(s * 0.017 + this.phases[2]); } - private dx(s: number): number { return 18 * 0.0038 * Math.cos(s * 0.0038 + this.phases[0]) + 8 * 0.009 * Math.cos(s * 0.009 + this.phases[1]) + 3 * 0.017 * Math.cos(s * 0.017 + this.phases[2]); } - private ddx(s: number): number { return -18 * 0.0038 ** 2 * Math.sin(s * 0.0038 + this.phases[0]) - 8 * 0.009 ** 2 * Math.sin(s * 0.009 + this.phases[1]) - 3 * 0.017 ** 2 * Math.sin(s * 0.017 + this.phases[2]); } - private height(s: number): number { return 1.8 * Math.sin(s * 0.005 + this.phases[3]) + 0.8 * Math.sin(s * 0.014 + this.phases[4]); } - private heightSlope(s: number): number { return 1.8 * 0.005 * Math.cos(s * 0.005 + this.phases[3]) + 0.8 * 0.014 * Math.cos(s * 0.014 + this.phases[4]); } + private x(s: number): number { + const forest = this.forestX(s); + const region = this.regions.sample(s, this.regionSample); + if (region.type === 'fields') { + const fields = 25 * Math.sin(s * 0.00165 + this.phases[0]) + 4 * Math.sin(s * 0.0042 + this.phases[1]); + return forest + (fields - forest) * region.blend; + } + if (region.type === 'coast') { + const coast = forest + 20 * Math.sin(s * 0.00225 + this.phases[1]) + 6 * Math.sin(s * 0.0044 + this.phases[2]); + return forest + (coast - forest) * region.blend; + } + if (region.type === 'river_bridge') { + const center = (region.bridgeStart + region.bridgeEnd) * 0.5; + const slope = Math.max(-0.018, Math.min(0.018, this.forestDx(center) * 0.12)); + const bridgeLine = this.forestX(center) + slope * (s - center); + return forest + (bridgeLine - forest) * region.blend; + } + return forest; + } + private dx(s: number): number { return (this.x(s + 0.5) - this.x(Math.max(0, s - 0.5))) / (s > 0.5 ? 1 : 0.5); } + private ddx(s: number): number { return (this.dx(s + 1) - this.dx(Math.max(0, s - 1))) / (s > 1 ? 2 : 1); } + private height(s: number): number { + const forest = this.forestHeight(s); + const region = this.regions.sample(s, this.regionSample); + if (region.type === 'fields') { + const fields = 1.15 * Math.sin(s * 0.0021 + this.phases[3]) + 0.38 * Math.sin(s * 0.006 + this.phases[4]); + return forest + (fields - forest) * region.blend; + } + if (region.type === 'coast') { + const coast = 2.8 + 2.6 * Math.sin(s * 0.00155 + this.phases[3]) + 0.85 * Math.sin(s * 0.0038 + this.phases[4]); + return forest + (coast - forest) * region.blend; + } + if (region.type === 'river_bridge') { + const bridgeHeight = 6.6 + 0.18 * Math.sin(s * 0.0012 + this.phases[4]); + return forest + (bridgeHeight - forest) * region.blend; + } + return forest; + } + private heightSlope(s: number): number { return (this.height(s + 0.5) - this.height(Math.max(0, s - 0.5))) / (s > 0.5 ? 1 : 0.5); } + private forestX(s: number): number { + return 18 * Math.sin(s * 0.0038 + this.phases[0]) + 8 * Math.sin(s * 0.009 + this.phases[1]) + + 3 * Math.sin(s * 0.017 + this.phases[2]); + } + private forestDx(s: number): number { + return 18 * 0.0038 * Math.cos(s * 0.0038 + this.phases[0]) + + 8 * 0.009 * Math.cos(s * 0.009 + this.phases[1]) + + 3 * 0.017 * Math.cos(s * 0.017 + this.phases[2]); + } + private forestHeight(s: number): number { + return 1.8 * Math.sin(s * 0.005 + this.phases[3]) + 0.8 * Math.sin(s * 0.014 + this.phases[4]); + } + private bridgeValleyInfluence(s: number, region: WorldRegionSample): number { + if (region.bridgeStart < 0) return 0; + return this.smoothstep((s - (region.bridgeStart - 1_200)) / 1_200) + * this.smoothstep(((region.bridgeEnd + 1_200) - s) / 1_200); + } } diff --git a/src/world/VegetationChunkRenderer.ts b/src/world/VegetationChunkRenderer.ts index 5efdaea..61f88ff 100644 --- a/src/world/VegetationChunkRenderer.ts +++ b/src/world/VegetationChunkRenderer.ts @@ -5,6 +5,7 @@ import type { RoadGenerator, RoadSample } from './RoadGenerator'; import type { RoadsideFeature } from './RoadsideFeature'; import type { GroundLodVariant, ProceduralVegetationFactory, TreeLodVariant, VegetationGeometry } from './ProceduralVegetationFactory'; import type { GraphicsSettings } from '../config/GraphicsSettings'; +import type { FieldParcelSample } from './FieldParcelSystem'; interface InstanceSource { matrices: Float32Array; colors: Float32Array; positions: Float32Array; lodStates: Uint8Array; @@ -36,8 +37,10 @@ export class VegetationChunkRenderer { private readonly shrubs: GroundBatch[]; private readonly ferns: GroundBatch[]; private readonly grass: GroundBatch[]; + private readonly wheat: GroundBatch[]; private readonly dead: GroundBatch[]; private readonly sample: RoadSample; + private readonly fieldSample: FieldParcelSample; private readonly logicalPositions: number[] = []; private vegetationScale = 1; private treeScale = 1; @@ -58,15 +61,17 @@ export class VegetationChunkRenderer { constructor(private readonly road: RoadGenerator, private readonly roadsideFeature: RoadsideFeature, factory: ProceduralVegetationFactory) { this.sample = road.sample(0); + this.fieldSample = road.fieldParcels.createSample(); const catalog = factory.catalog; const treeCapacity = (CONFIG.world.treeDensity + CONFIG.world.forestWallDensity) * 3; this.trees = catalog.trees.map((variant) => this.createTreeBatch(variant, treeCapacity)); this.shrubs = catalog.shrubs.map((variant) => this.createGroundBatch(variant, CONFIG.world.bushDensity * 3)); this.ferns = catalog.ferns.map((variant) => this.createGroundBatch(variant, CONFIG.world.fernDensity * 3)); this.grass = catalog.grass.map((variant) => this.createGroundBatch(variant, CONFIG.world.grassDensity * 3)); + this.wheat = catalog.wheat.map((variant) => this.createGroundBatch(variant, CONFIG.world.grassDensity * 2)); this.dead = catalog.dead.map((variant) => this.createGroundBatch(variant, 2)); for (const batch of this.trees) this.group.add(batch.near, batch.mid, batch.far); - for (const batch of [...this.shrubs, ...this.ferns, ...this.grass, ...this.dead]) this.group.add(batch.near, batch.mid); + for (const batch of [...this.shrubs, ...this.ferns, ...this.grass, ...this.wheat, ...this.dead]) this.group.add(batch.near, batch.mid); } setQuality(profile: GraphicsProfile): boolean { @@ -129,6 +134,7 @@ export class VegetationChunkRenderer { this.updateGroundLod(this.shrubs, cameraPosition, Math.min(85, shrubFar * .52), shrubFar, classifyDirectly, true); this.updateGroundLod(this.ferns, cameraPosition, Math.min(62, fernFar * .55), fernFar, classifyDirectly, false); this.updateGroundLod(this.grass, cameraPosition, Math.min(38, grassFar * .58), grassFar, classifyDirectly, false); + this.updateGroundLod(this.wheat, cameraPosition, Math.min(52, grassFar * .62), Math.min(this.vegetationDistance, Math.max(grassFar, 115)), classifyDirectly, false); this.updateGroundLod(this.dead, cameraPosition, Math.min(80, shrubFar * .5), shrubFar, classifyDirectly, true); this.lodDirty = false; } @@ -136,17 +142,31 @@ export class VegetationChunkRenderer { update(index: number, start: number): void { this.index = index; this.logicalPositions.length = 0; this.logicalCount = 0; this.lodDirty = true; for (const batch of this.trees) { batch.count = 0; batch.lodStates.fill(3); } - for (const batch of [...this.shrubs, ...this.ferns, ...this.grass, ...this.dead]) batch.count = 0; - const edgeTrees = Math.max(0, Math.round(CONFIG.world.treeDensity * this.treeScale)); - const forestTrees = Math.max(0, Math.round(CONFIG.world.forestWallDensity * this.treeScale)); + for (const batch of [...this.shrubs, ...this.ferns, ...this.grass, ...this.wheat, ...this.dead]) batch.count = 0; + const region = this.road.regions.sample(start + CONFIG.road.chunkLength * 0.5); + const fieldsBlend = region.type === 'fields' ? region.blend : 0; + const coastBlend = region.type === 'coast' ? region.blend : 0; + const riverBlend = region.type === 'river_bridge' ? region.blend : 0; + const treeRegionScale = (1 + (0.42 - 1) * coastBlend) * (1 - riverBlend * 0.97); + const forestRegionScale = (1 + (0.28 - 1) * coastBlend) * (1 - riverBlend * 0.99); + const grassRegionScale = (1 + (1.35 - 1) * fieldsBlend) * (1 + (0.72 - 1) * coastBlend) * (1 - riverBlend * 0.55); + const bushRegionScale = (1 + (0.72 - 1) * fieldsBlend) * (1 + (1.15 - 1) * coastBlend) * (1 - riverBlend * 0.88); + const edgeTrees = Math.max(0, Math.round(CONFIG.world.treeDensity * this.treeScale * treeRegionScale * (1 - fieldsBlend))); + const forestTrees = Math.max(0, Math.round(CONFIG.world.forestWallDensity * this.treeScale * forestRegionScale * (1 - fieldsBlend))); for (let i = 0; i < edgeTrees; i++) this.placeTree(i, start, false); for (let i = 0; i < forestTrees; i++) this.placeTree(i, start, true); - const grassCount = Math.max(0, Math.round(CONFIG.world.grassDensity * this.grassScale)); - const fernCount = Math.max(0, Math.round(CONFIG.world.fernDensity * this.bushScale)); - const shrubCount = Math.max(0, Math.round(CONFIG.world.bushDensity * this.bushScale)); + const fieldTrees = Math.max(0, Math.round(9 * this.treeScale * fieldsBlend)); + for (let i = 0; i < fieldTrees; i++) this.placeTree(i + 1400, start, i % 3 === 0, true); + const grassCount = Math.max(0, Math.round(CONFIG.world.grassDensity * this.grassScale * grassRegionScale)); + const fernCount = Math.max(0, Math.round(CONFIG.world.fernDensity * this.bushScale * bushRegionScale * (1 - fieldsBlend * .92))); + const shrubCount = Math.max(0, Math.round(CONFIG.world.bushDensity * this.bushScale * bushRegionScale * (1 - fieldsBlend))); for (let i = 0; i < grassCount; i++) this.placeGroundPlant(this.grass, 31, i, start, 4.9, 11.2, 0.32, 0.95, true); for (let i = 0; i < fernCount; i++) this.placeGroundPlant(this.ferns, 47, i, start, 6, 17, 0.52, 1.12, true); for (let i = 0; i < shrubCount; i++) this.placeGroundPlant(this.shrubs, 61, i, start, 7.6, 31, 0.72, 1.85, false); + const hedgeCount = Math.max(0, Math.round(18 * this.bushScale * fieldsBlend)); + for (let i = 0; i < hedgeCount; i++) this.placeFieldBorderPlant(this.shrubs, 1703, i, start, 0.48, 1.28); + const wheatCandidates = Math.max(0, Math.round(78 * this.grassScale * fieldsBlend)); + for (let i = 0; i < wheatCandidates; i++) this.placeWheatPatch(i, start); for (let i = 0; i < 2; i++) if (hash01(this.road.seed + 811, this.index, i) < 0.34) this.placeGroundPlant(this.dead, 83, i, start, 12, 58, 1.2, 4.2, false); this.flush(); @@ -160,7 +180,7 @@ export class VegetationChunkRenderer { const count = (batches: readonly GroundBatch[]): number => batches.reduce((sum, batch) => sum + batch.count, 0); return { total: this.logicalCount, treesNear: treeNear, treesMid: treeMid, treesFar: treeFar, - shrubs: count(this.shrubs), grass: count(this.grass), ferns: count(this.ferns), dead: count(this.dead) }; + shrubs: count(this.shrubs), grass: count(this.grass) + count(this.wheat), ferns: count(this.ferns), dead: count(this.dead) }; } getLogicalPositions(): number[] { return this.logicalPositions.slice(); } getDebugCoordinates(): string { @@ -186,7 +206,7 @@ export class VegetationChunkRenderer { mesh.name = `ProceduralVegetation:${variant.id}`; mesh.instanceMatrix.setUsage(DynamicDrawUsage); mesh.receiveShadow = true; mesh.count = 0; return mesh; } - private placeTree(i: number, start: number, distant: boolean): void { + private placeTree(i: number, start: number, distant: boolean, fieldBorder = false): void { const salt = distant ? 210 : 17; const clusterIndex = Math.floor(i / (distant ? 4 : 3)); const clusterSeed = clusterIndex * 13 + salt; @@ -197,7 +217,14 @@ export class VegetationChunkRenderer { const baseLateral = distant ? 38 + hash01(this.road.seed + salt, this.index, clusterSeed + 3) * 170 : 9.5 + hash01(this.road.seed + salt, this.index, clusterSeed + 3) * 52; let lateral = side * Math.max(7.8, baseLateral + (hash01(this.road.seed + salt, this.index, i * 7 + 4) - 0.5) * (distant ? 24 : 13)); + if (fieldBorder) { + const candidate = side * (45 + hash01(this.road.seed + 1669, this.index, i) * 175); + lateral = this.road.fieldParcels.snapLateralToBoundary(s, candidate); + if (Math.abs(lateral) < 30) lateral += Math.sign(lateral || side) * 145; + lateral += (hash01(this.road.seed + 1673, this.index, i) - .5) * 3.2; + } lateral = this.roadsideFeature.keepSceneryClear(s, lateral); + lateral = this.road.adjustSceneryLateral(s, lateral); this.road.sample(s, this.sample); position.copy(this.sample.position).addScaledVector(this.sample.right, lateral); position.y = this.road.terrainHeight(position.x, position.z) - 0.045; const speciesRoll = hash01(this.road.seed + 301, this.index, i + salt * 2); @@ -229,6 +256,7 @@ export class VegetationChunkRenderer { const side = hash01(this.road.seed + key, this.index, 1) > 0.5 ? 1 : -1; let lateral = side * (minLateral + hash01(this.road.seed + key, this.index, 2) * (maxLateral - minLateral)); lateral = this.roadsideFeature.keepSceneryClear(s, lateral); + lateral = this.road.adjustSceneryLateral(s, lateral); this.road.sample(s, this.sample); position.copy(this.sample.position).addScaledVector(this.sample.right, lateral); position.y = this.road.terrainHeight(position.x, position.z) - 0.025; const variantIndex = Math.floor(hash01(this.road.seed + key, this.index, 3) * batches.length) % batches.length; @@ -245,6 +273,49 @@ export class VegetationChunkRenderer { this.storeInstance(batch, instanceIndex, matrix, tint, position); this.record(position); } + + private placeFieldBorderPlant(batches: GroundBatch[], salt: number, i: number, start: number, + minHeight: number, maxHeight: number): void { + const key = salt * 997 + i * 11; + const s = start + hash01(this.road.seed + key, this.index, 0) * CONFIG.road.chunkLength; + const side = hash01(this.road.seed + key, this.index, 1) > .5 ? 1 : -1; + const candidate = side * (34 + hash01(this.road.seed + key, this.index, 2) * 145); + let lateral = this.road.fieldParcels.snapLateralToBoundary(s, candidate); + if (Math.abs(lateral) < 20) lateral += Math.sign(lateral || side) * 145; + lateral += (hash01(this.road.seed + key, this.index, 3) - .5) * 2.4; + this.placeGroundPlantAt(batches, key, i, s, lateral, minHeight, maxHeight, false); + } + + private placeWheatPatch(i: number, start: number): void { + const key = 1823 * 997 + i * 13; + const s = start + hash01(this.road.seed + key, this.index, 0) * CONFIG.road.chunkLength; + const side = hash01(this.road.seed + key, this.index, 1) > .5 ? 1 : -1; + const lateral = side * (8.5 + hash01(this.road.seed + key, this.index, 2) * 118); + this.road.fieldParcels.sample(s, lateral, this.fieldSample); + if (this.fieldSample.type !== 'wheat' || this.fieldSample.interiorStrength < .55) return; + this.placeGroundPlantAt(this.wheat, key, i, s, lateral, .74, 1.05, true, 2.1, 3.6); + } + + private placeGroundPlantAt(batches: GroundBatch[], key: number, i: number, s: number, inputLateral: number, + minHeight: number, maxHeight: number, alignToSlope: boolean, minWidth = .78, maxWidth = 1.2): void { + let lateral = this.roadsideFeature.keepSceneryClear(s, inputLateral); + lateral = this.road.adjustSceneryLateral(s, lateral); + this.road.sample(s, this.sample); position.copy(this.sample.position).addScaledVector(this.sample.right, lateral); + position.y = this.road.terrainHeight(position.x, position.z) - .025; + const variantIndex = Math.floor(hash01(this.road.seed + key, this.index, 4) * batches.length) % batches.length; + const targetHeight = minHeight + hash01(this.road.seed + key, this.index, 5) * (maxHeight - minHeight); + const width = minWidth + hash01(this.road.seed + key, this.index, 6) * (maxWidth - minWidth); + const slopeX = alignToSlope ? this.road.terrainHeight(position.x + .4, position.z) - this.road.terrainHeight(position.x - .4, position.z) : 0; + const slopeZ = alignToSlope ? this.road.terrainHeight(position.x, position.z + .4) - this.road.terrainHeight(position.x, position.z - .4) : 0; + euler.set(Math.max(-.12, Math.min(.12, slopeZ * .34)), hash01(this.road.seed + key, this.index, 7) * Math.PI * 2, + Math.max(-.12, Math.min(.12, -slopeX * .34)), 'YXZ'); + rotation.setFromEuler(euler); matrix.compose(position, rotation, scale.set(targetHeight * width, targetHeight, targetHeight * width)); + const batch = batches[variantIndex]; + if (batch.count >= batch.matrices.length / 16) return; + const brightness = .92 + hash01(this.road.seed + key + 17, this.index, i) * .14; + tint.setRGB(brightness, brightness * .98, brightness * .88); + this.storeInstance(batch, batch.count++, matrix, tint, position); this.record(position); + } private record(value: Vector3): void { this.logicalCount++; if (this.logicalPositions.length < 24) this.logicalPositions.push(value.x, value.z - this.road.getOriginOffsetZ()); } private flush(): void { @@ -257,7 +328,7 @@ export class VegetationChunkRenderer { this.copyConservativeBounds(batch.far, batch.near); this.copyConservativeBounds(batch.far, batch.mid); } - for (const batch of [...this.shrubs, ...this.ferns, ...this.grass, ...this.dead]) { + for (const batch of [...this.shrubs, ...this.ferns, ...this.grass, ...this.wheat, ...this.dead]) { batch.nearCount = batch.midCount = 0; // Compute one conservative bound from every source transform, retain it // after hiding the mesh, and share it with both LOD destinations. This diff --git a/src/world/WorldChunk.ts b/src/world/WorldChunk.ts index b718129..c56efb8 100644 --- a/src/world/WorldChunk.ts +++ b/src/world/WorldChunk.ts @@ -1,6 +1,6 @@ import { Box3, BoxGeometry, BufferAttribute, BufferGeometry, Color, - Group, IcosahedronGeometry, InstancedMesh, Matrix4, Mesh, Quaternion, Vector3 + Group, IcosahedronGeometry, InstancedMesh, MathUtils, Matrix4, Mesh, Quaternion, Vector3 } from 'three'; import { CONFIG, type GraphicsProfile } from '../config/gameConfig'; import { hash01 } from './SeededRandom'; @@ -10,6 +10,7 @@ import type { ProceduralVegetationFactory } from './ProceduralVegetationFactory' import { VegetationChunkRenderer, type VegetationRenderStats } from './VegetationChunkRenderer'; import { materials } from './WorldMaterials'; import type { GraphicsSettings } from '../config/GraphicsSettings'; +import type { FieldParcelSample } from './FieldParcelSystem'; const tempMatrix = new Matrix4(); const tempPosition = new Vector3(); @@ -54,7 +55,10 @@ function terrainGeometry(longSegments: number, crossSegments: number): BufferGeo const sharedGeometry = { dash: new BoxGeometry(0.16, 0.035, 3.2), rock: new IcosahedronGeometry(0.72, 0), - post: new BoxGeometry(0.12, 1.0, 0.12) + post: new BoxGeometry(0.12, 1.0, 0.12), + bridgeRail: new BoxGeometry(0.14, 0.14, 6.15), + bridgeBeam: new BoxGeometry(0.3, 0.38, 6.15), + bridgePier: new BoxGeometry(1, 1, 1) }; export class WorldChunk { @@ -72,6 +76,11 @@ export class WorldChunk { private readonly rightFarTerrain = new Mesh(terrainGeometry(CONFIG.road.chunkSegments, FAR_CROSS_SEGMENTS), materials.farGrass); private readonly leftSkirt = new Mesh(ribbonGeometry(CONFIG.road.chunkSegments), materials.farGrass); private readonly rightSkirt = new Mesh(ribbonGeometry(CONFIG.road.chunkSegments), materials.farGrass); + private readonly water = new Mesh(terrainGeometry(CONFIG.road.chunkSegments, 2), materials.water); + private readonly bridgeDeck = new Mesh(ribbonGeometry(CONFIG.road.chunkSegments), materials.bridgeConcrete); + private readonly bridgeRails = new InstancedMesh(sharedGeometry.bridgeRail, materials.bridgeRail, 24); + private readonly bridgeBeams = new InstancedMesh(sharedGeometry.bridgeBeam, materials.bridgeSteel, 36); + private readonly bridgePiers = new InstancedMesh(sharedGeometry.bridgePier, materials.bridgeConcrete, 2); private readonly dashes = new InstancedMesh(sharedGeometry.dash, materials.line, 12); private readonly leftEdge = new Mesh(ribbonGeometry(CONFIG.road.chunkSegments), materials.line); private readonly rightEdge = new Mesh(ribbonGeometry(CONFIG.road.chunkSegments), materials.line); @@ -79,25 +88,31 @@ export class WorldChunk { private readonly posts = new InstancedMesh(sharedGeometry.post, materials.post, 18); private readonly sampleA: RoadSample; private readonly sampleB: RoadSample; + private readonly fieldSample: FieldParcelSample; private readonly roadsideFeature: RoadsideFeature; private readonly vegetation: VegetationChunkRenderer; private vegetationScale = 1; private objectScale = 1; + private bridgeActive = false; index = Number.NaN; constructor(private readonly roadGenerator: RoadGenerator, factory: ProceduralVegetationFactory) { this.sampleA = roadGenerator.sample(0); this.sampleB = roadGenerator.sample(0); + this.fieldSample = roadGenerator.fieldParcels.createSample(); this.roadsideFeature = new RoadsideFeature(roadGenerator); this.vegetation = new VegetationChunkRenderer(roadGenerator, this.roadsideFeature, factory); this.group.add(this.leftFarTerrain, this.rightFarTerrain, this.leftMidTerrain, this.rightMidTerrain, - this.leftTerrain, this.rightTerrain, this.leftSkirt, this.rightSkirt, + this.leftTerrain, this.rightTerrain, this.leftSkirt, this.rightSkirt, this.water, + this.bridgeDeck, this.bridgeRails, this.bridgeBeams, this.bridgePiers, this.leftVerge, this.rightVerge, this.leftShoulder, this.rightShoulder, this.road, this.dashes, this.leftEdge, this.rightEdge, this.vegetation.group, this.rocks, this.posts); this.group.add(this.roadsideFeature.group); [this.road, this.leftShoulder, this.rightShoulder, this.leftVerge, this.rightVerge, this.leftTerrain, this.rightTerrain].forEach((mesh) => { mesh.receiveShadow = true; }); + this.bridgeDeck.receiveShadow = true; + this.bridgeRails.castShadow = this.bridgeBeams.castShadow = this.bridgePiers.castShadow = true; } setQuality(profile: GraphicsProfile): void { @@ -154,6 +169,8 @@ export class WorldChunk { this.updateTerrain(this.rightFarTerrain.geometry, start, CONFIG.world.midTerrainRadius, CONFIG.world.farTerrainRadius, FAR_CROSS_SEGMENTS); this.updateSkirt(this.leftSkirt.geometry, start, -CONFIG.world.farTerrainRadius); this.updateSkirt(this.rightSkirt.geometry, start, CONFIG.world.farTerrainRadius); + this.updateWater(start); + this.updateBridge(start); this.updateMarkings(start); this.roadsideFeature.update(index, start); this.updateScenery(start); @@ -163,7 +180,7 @@ export class WorldChunk { target.makeEmpty(); for (const mesh of [this.leftFarTerrain, this.rightFarTerrain, this.leftMidTerrain, this.rightMidTerrain, this.leftTerrain, this.rightTerrain, this.leftSkirt, this.rightSkirt, - this.leftVerge, this.rightVerge, this.leftShoulder, this.rightShoulder, this.road]) { + this.leftVerge, this.rightVerge, this.leftShoulder, this.rightShoulder, this.road, this.bridgeDeck]) { if (mesh.geometry.boundingBox) target.union(mesh.geometry.boundingBox); } return target; @@ -176,6 +193,7 @@ export class WorldChunk { getVegetationStats(): VegetationRenderStats { return this.vegetation.getStats(); } getRoadsideFeatureCount(): number { return this.roadsideFeature.getCount(); } + getBridgeSectionCount(): number { return this.bridgeActive ? 1 : 0; } getVegetationLogicalPositions(): number[] { const positions = this.vegetation.getLogicalPositions(); @@ -197,8 +215,8 @@ export class WorldChunk { dispose(): void { for (const mesh of [this.road, this.leftShoulder, this.rightShoulder, this.leftVerge, this.rightVerge, this.leftTerrain, this.rightTerrain, this.leftMidTerrain, this.rightMidTerrain, - this.leftFarTerrain, this.rightFarTerrain, this.leftSkirt, this.rightSkirt, - this.leftEdge, this.rightEdge]) mesh.geometry.dispose(); + this.leftFarTerrain, this.rightFarTerrain, this.leftSkirt, this.rightSkirt, this.water, + this.leftEdge, this.rightEdge, this.bridgeDeck]) mesh.geometry.dispose(); this.roadsideFeature.dispose(); } @@ -254,11 +272,41 @@ export class WorldChunk { } const normals = geometry.getAttribute('normal') as BufferAttribute; for (let i = 0; i < colors.count; i++) { + const longitudinal = Math.floor(i / row); + const cross = i % row; + const s = start + longitudinal / CONFIG.road.chunkSegments * CONFIG.road.chunkLength; + const region = this.roadGenerator.regions.sample(s); const slope = 1 - Math.max(0, normals.getY(i)); const height = positions.getY(i); const variation = hash01(this.roadGenerator.seed + 1, this.index, i); - color.setHSL(0.275 - slope * 0.055 + variation * 0.018, 0.33 - slope * 0.08, - 0.23 + variation * 0.06 + Math.max(-0.02, Math.min(0.02, height * 0.003)) - slope * 0.055); + const forestHue = 0.275 - slope * 0.055 + variation * 0.018; + const fieldsBlend = region.type === 'fields' ? region.blend : 0; + const coastBlend = region.type === 'coast' ? region.blend : 0; + const riverBlend = region.type === 'river_bridge' ? region.blend : 0; + let specialHue = forestHue; let specialSaturation = 0.33 - slope * .08; + let specialLightness = .23 + variation * .06; + if (fieldsBlend > 0) { + const offset = left + (right - left) * cross / crossSegments; + const parcel = this.roadGenerator.fieldParcels.sample(s, offset, this.fieldSample); + if (parcel.type === 'wheat') { specialHue = .125 + variation * .012; specialSaturation = .55; specialLightness = .39 + variation * .055; } + else if (parcel.type === 'meadow') { specialHue = .255 + variation * .018; specialSaturation = .39; specialLightness = .29 + variation * .055; } + else if (parcel.type === 'stubble') { specialHue = .105 + variation * .014; specialSaturation = .34; specialLightness = .31 + variation * .05; } + else { specialHue = .195 + variation * .018; specialSaturation = .27; specialLightness = .265 + variation * .05; } + specialHue = MathUtils.lerp(specialHue, .245, parcel.boundaryStrength * .75); + specialSaturation = MathUtils.lerp(specialSaturation, .32, parcel.boundaryStrength); + specialLightness = MathUtils.lerp(specialLightness, .235, parcel.boundaryStrength * .78); + } else if (coastBlend > 0) { + specialHue = .165 - slope * .04 + variation * .018; specialSaturation = .29; + specialLightness = .325 + variation * .065; + } else if (riverBlend > 0) { + specialHue = .235 - slope * .035 + variation * .012; specialSaturation = .31; + specialLightness = .285 + variation * .055; + } + const specialBlend = Math.max(fieldsBlend, coastBlend, riverBlend); + color.setHSL(MathUtils.lerp(forestHue, specialHue, specialBlend), + MathUtils.lerp(.33 - slope * .08, specialSaturation, specialBlend), + MathUtils.lerp(.23 + variation * .06, specialLightness, specialBlend) + + Math.max(-.02, Math.min(.02, height * .003)) - slope * .055); colors.setXYZ(i, color.r, color.g, color.b); } colors.needsUpdate = true; @@ -281,6 +329,92 @@ export class WorldChunk { geometry.computeBoundingSphere(); } + private updateWater(start: number): void { + const region = this.roadGenerator.regions.sample(start + CONFIG.road.chunkLength * 0.5); + if ((region.type !== 'coast' && region.type !== 'river_bridge') || region.blend <= 0.015) { + this.water.visible = false; + return; + } + const positions = this.water.geometry.getAttribute('position') as BufferAttribute; + const row = 3; + const inner = MathUtils.lerp(CONFIG.world.farTerrainRadius - 4, 28, region.blend); + for (let longitudinal = 0; longitudinal <= CONFIG.road.chunkSegments; longitudinal++) { + const s = start + longitudinal / CONFIG.road.chunkSegments * CONFIG.road.chunkLength; + const sample = this.roadGenerator.sample(s, this.sampleA); + for (let cross = 0; cross < row; cross++) { + const riverHalfWidth = region.type === 'river_bridge' ? this.roadGenerator.getRiverWaterHalfWidth(s) : 0; + const lateral = region.type === 'coast' + ? region.waterSide * MathUtils.lerp(inner, CONFIG.world.farTerrainRadius + 120, cross / (row - 1)) + : MathUtils.lerp(-riverHalfWidth, riverHalfWidth, cross / (row - 1)); + positions.setXYZ(longitudinal * row + cross, + sample.position.x + sample.right.x * lateral, this.roadGenerator.getWaterLevel(s), + sample.position.z + sample.right.z * lateral); + } + } + positions.needsUpdate = true; + this.water.geometry.computeVertexNormals(); + this.water.geometry.computeBoundingBox(); + this.water.geometry.computeBoundingSphere(); + this.water.visible = true; + this.water.renderOrder = -1; + } + + private updateBridge(start: number): void { + const center = start + CONFIG.road.chunkLength * 0.5; + const region = this.roadGenerator.regions.sample(center); + this.bridgeActive = region.type === 'river_bridge' && start >= region.bridgeStart && + start + CONFIG.road.chunkLength <= region.bridgeEnd + 0.01; + this.bridgeDeck.visible = this.bridgeActive; + if (!this.bridgeActive) { + this.bridgeRails.count = this.bridgeBeams.count = this.bridgePiers.count = 0; + this.bridgeRails.visible = this.bridgeBeams.visible = this.bridgePiers.visible = false; + return; + } + const deckHalfWidth = CONFIG.road.width * 0.5 + CONFIG.road.shoulderWidth; + this.updateRibbon(this.bridgeDeck.geometry, start, -deckHalfWidth, deckHalfWidth, -0.3); + for (let segment = 0; segment < 12; segment++) { + const s = start + 3 + segment * 6; + this.setBridgeBox(this.bridgeRails, segment * 2, s, -deckHalfWidth + 0.18, 0.78, tempScale.set(1, 1, 1)); + this.setBridgeBox(this.bridgeRails, segment * 2 + 1, s, deckHalfWidth - 0.18, 0.78, tempScale.set(1, 1, 1)); + for (let beam = 0; beam < 3; beam++) { + this.setBridgeBox(this.bridgeBeams, segment * 3 + beam, s, (beam - 1) * 4.2, -0.56, tempScale.set(1, 1, 1)); + } + } + this.bridgeRails.count = 24; + this.bridgeBeams.count = 36; + const bridgeChunk = Math.round(region.bridgeStart / CONFIG.road.chunkLength); + const supportChunk = (this.index - bridgeChunk) % 2 === 1; + this.bridgePiers.count = supportChunk ? 2 : 0; + if (supportChunk) { + const sample = this.roadGenerator.sample(center, this.sampleA); + for (let pier = 0; pier < 2; pier++) { + const lateral = pier === 0 ? -3.45 : 3.45; + tempPosition.copy(sample.position).addScaledVector(sample.right, lateral); + const riverBed = this.roadGenerator.terrainHeight(tempPosition.x, tempPosition.z); + const height = Math.max(1, sample.position.y - 0.48 - riverBed); + tempPosition.y = riverBed + height * 0.5; + tempQuat.setFromAxisAngle(up, sample.heading); + tempMatrix.compose(tempPosition, tempQuat, tempScale.set(1.15, height, 1.15)); + this.bridgePiers.setMatrixAt(pier, tempMatrix); + } + } + for (const mesh of [this.bridgeRails, this.bridgeBeams, this.bridgePiers]) { + mesh.visible = mesh.count > 0; + mesh.instanceMatrix.needsUpdate = true; + if (mesh.count > 0) { mesh.computeBoundingBox(); mesh.computeBoundingSphere(); } + } + } + + private setBridgeBox(mesh: InstancedMesh, index: number, s: number, lateral: number, + heightOffset: number, instanceScale: Vector3): void { + const sample = this.roadGenerator.sample(s, this.sampleB); + tempPosition.copy(sample.position).addScaledVector(sample.right, lateral); + tempPosition.y += heightOffset; + tempQuat.setFromAxisAngle(up, sample.heading); + tempMatrix.compose(tempPosition, tempQuat, instanceScale); + mesh.setMatrixAt(index, tempMatrix); + } + private setRoadInstance(mesh: InstancedMesh, i: number, s: number, lateral: number, scale: Vector3): void { const sample = this.roadGenerator.sample(s, this.sampleB); tempPosition.copy(sample.position).addScaledVector(sample.right, lateral); @@ -300,13 +434,19 @@ export class WorldChunk { private updateScenery(start: number): void { this.vegetation.update(this.index, start); - const rockCount = Math.max(0, Math.round(CONFIG.world.rockDensity * this.objectScale)); + const region = this.roadGenerator.regions.sample(start + CONFIG.road.chunkLength * 0.5); + const fieldsBlend = region.type === 'fields' ? region.blend : 0; + const coastBlend = region.type === 'coast' ? region.blend : 0; + const riverBlend = region.type === 'river_bridge' ? region.blend : 0; + const rockCount = Math.max(0, Math.round(CONFIG.world.rockDensity * this.objectScale * + (1 - fieldsBlend * 0.65) * (1 + coastBlend * 0.8) * (1 - riverBlend * 0.78))); this.rocks.count = rockCount; for (let i = 0; i < rockCount; i++) { const s = start + hash01(this.roadGenerator.seed + 4, this.index, i * 3) * CONFIG.road.chunkLength; const side = hash01(this.roadGenerator.seed + 4, this.index, i * 3 + 1) > 0.5 ? 1 : -1; let lateral = side * (9 + hash01(this.roadGenerator.seed + 4, this.index, i * 3 + 2) * 72); lateral = this.roadsideFeature.keepSceneryClear(s, lateral); + lateral = this.roadGenerator.adjustSceneryLateral(s, lateral); const sample = this.roadGenerator.sample(s, this.sampleA); tempPosition.copy(sample.position).addScaledVector(sample.right, lateral); tempPosition.y = this.roadGenerator.terrainHeight(tempPosition.x, tempPosition.z) + 0.35; @@ -317,10 +457,13 @@ export class WorldChunk { color.setHSL(0.27, 0.04, 0.34 + hash01(this.roadGenerator.seed + 10, this.index, i) * 0.1); this.rocks.setColorAt(i, color); } - for (let i = 0; i < 9; i++) { - const s = start + 4 + i * 8; - this.setRoadInstance(this.posts, i * 2, s, -CONFIG.road.width / 2 - 1.15, tempScale.set(1, 1, 1)); - this.setRoadInstance(this.posts, i * 2 + 1, s, CONFIG.road.width / 2 + 1.15, tempScale.set(1, 1, 1)); + this.posts.count = this.bridgeActive ? 0 : 18; + if (!this.bridgeActive) { + for (let i = 0; i < 9; i++) { + const s = start + 4 + i * 8; + this.setRoadInstance(this.posts, i * 2, s, -CONFIG.road.width / 2 - 1.15, tempScale.set(1, 1, 1)); + this.setRoadInstance(this.posts, i * 2 + 1, s, CONFIG.road.width / 2 + 1.15, tempScale.set(1, 1, 1)); + } } for (const mesh of [this.rocks, this.posts]) { mesh.instanceMatrix.needsUpdate = true; diff --git a/src/world/WorldMaterials.ts b/src/world/WorldMaterials.ts index 1717265..a3a5939 100644 --- a/src/world/WorldMaterials.ts +++ b/src/world/WorldMaterials.ts @@ -1,4 +1,29 @@ -import { Color, MeshStandardMaterial } from 'three'; +import { Color, DoubleSide, MeshPhysicalMaterial, MeshStandardMaterial } from 'three'; + +const waterTime = { value: 0 }; + +function proceduralWater(): MeshPhysicalMaterial { + const material = new MeshPhysicalMaterial({ + color: 0x2d7184, roughness: 0.2, metalness: 0.05, transmission: 0.08, + transparent: true, opacity: 0.82, depthWrite: false, side: DoubleSide, + clearcoat: 0.75, clearcoatRoughness: 0.18, envMapIntensity: 1.35 + }); + material.onBeforeCompile = (shader) => { + shader.uniforms.uWaterTime = waterTime; + shader.vertexShader = shader.vertexShader + .replace('#include ', '#include \nuniform float uWaterTime;\nvarying float vWaterRipple;') + .replace('#include ', `#include + float waveA = sin(position.x * .105 + position.z * .052 + uWaterTime * .72); + float waveB = sin(position.x * .041 - position.z * .087 + uWaterTime * .47); + transformed.y += (waveA + waveB * .55) * .065; + vWaterRipple = waveA * .5 + waveB * .5;`); + shader.fragmentShader = shader.fragmentShader + .replace('#include ', '#include \nvarying float vWaterRipple;') + .replace('#include ', '#include \ndiffuseColor.rgb *= .92 + vWaterRipple * .045;'); + }; + material.customProgramCacheKey = () => 'procedural-water-1'; + return material; +} function proceduralStandard(color: number, roughness: number, kind: 'road' | 'terrain'): MeshStandardMaterial { const material = new MeshStandardMaterial({ color, roughness, metalness: 0, vertexColors: kind === 'terrain' }); @@ -23,6 +48,10 @@ export const materials = { grass: proceduralStandard(0x789b66, 1, 'terrain'), midGrass: proceduralStandard(0x6f9060, 1, 'terrain'), farGrass: proceduralStandard(0x657f58, 1, 'terrain'), + water: proceduralWater(), + bridgeConcrete: new MeshStandardMaterial({ color: 0x777c7b, roughness: 0.86, metalness: 0.04 }), + bridgeSteel: new MeshStandardMaterial({ color: 0x3c4749, roughness: 0.48, metalness: 0.68 }), + bridgeRail: new MeshStandardMaterial({ color: 0xb7c0be, roughness: 0.36, metalness: 0.72 }), line: new MeshStandardMaterial({ color: 0xdedccf, roughness: 0.94, polygonOffset: true, polygonOffsetFactor: -1, polygonOffsetUnits: -1 }), rock: new MeshStandardMaterial({ color: 0xffffff, roughness: 1, vertexColors: true }), post: new MeshStandardMaterial({ color: 0xd7d5c9, roughness: 0.9 }), @@ -30,3 +59,5 @@ export const materials = { fog: new Color(0xadc8c4), horizon: new Color(0xc9d7c8) }; + +export function updateWaterTime(seconds: number): void { waterTime.value = seconds; } diff --git a/src/world/WorldRegionDirector.ts b/src/world/WorldRegionDirector.ts new file mode 100644 index 0000000..9c23be7 --- /dev/null +++ b/src/world/WorldRegionDirector.ts @@ -0,0 +1,240 @@ +export type WorldRegionType = 'forest' | 'fields' | 'coast' | 'river_bridge'; +export type SpecialWorldRegionType = Exclude; + +export interface WorldRegionSample { + type: WorldRegionType; + regionId: number; + startDistance: number; + endDistance: number; + localT: number; + blend: number; + transitionDistance: number; + bridgeStart: number; + bridgeEnd: number; + waterSide: -1 | 1; +} + +export interface RegionScheduleProbeResult { + passed: boolean; + specialRegions: number; + minimumForestGap: number; + minimumTypeGap: Record; + averageStartInterval: Record; + typeCounts: Record; + deterministic: boolean; + differentSeed: boolean; +} + +interface SpecialRegionRecord extends WorldRegionSample { + type: SpecialWorldRegionType; +} + +const SPECIAL_TYPES: readonly SpecialWorldRegionType[] = ['fields', 'coast', 'river_bridge']; +const MINIMUM_FOREST_GAP = 24_000; +const FIRST_REGION_RANGE: Record = { + fields: [40_000, 70_000], + river_bridge: [55_000, 85_000], + coast: [120_000, 180_000] +}; +const TYPE_COOLDOWN_RANGE: Record = { + fields: [35_000, 65_000], + river_bridge: [45_000, 78_000], + coast: [190_000, 300_000] +}; +const TYPE_HASH_SALT: Record = { + fields: 11, + river_bridge: 23, + coast: 37 +}; +const BRIDGE_CHUNK_LENGTH = 72; +const BRIDGE_CHUNKS = 14; + +function hash01(seed: number, a: number, b = 0): number { + let x = (seed ^ Math.imul(a + 0x9e3779b9, 0x85ebca6b) ^ Math.imul(b + 0xc2b2ae35, 0x27d4eb2f)) >>> 0; + x ^= x >>> 16; + x = Math.imul(x, 0x7feb352d); + x ^= x >>> 15; + x = Math.imul(x, 0x846ca68b); + x ^= x >>> 16; + return (x >>> 0) / 4294967296; +} + +function smoothstep(value: number): number { + const t = Math.max(0, Math.min(1, value)); + return t * t * (3 - 2 * t); +} + +/** A deterministic, logical-distance-only schedule. It owns no render objects. */ +export class WorldRegionDirector { + readonly seed: number; + private readonly regions: SpecialRegionRecord[] = []; + + constructor(seed: number) { this.seed = seed; } + + sample(roadDistance: number, target?: WorldRegionSample): WorldRegionSample { + const distance = Math.max(0, roadDistance); + this.ensureThrough(distance); + let previous: SpecialRegionRecord | undefined; + let next: SpecialRegionRecord | undefined; + for (const region of this.regions) { + if (region.endDistance >= distance) { next = region; break; } + previous = region; + } + if (next && distance >= next.startDistance) { + const transitionIn = smoothstep((distance - next.startDistance) / next.transitionDistance); + const transitionOut = smoothstep((next.endDistance - distance) / next.transitionDistance); + return this.copySample(next, target, Math.min(transitionIn, transitionOut), distance); + } + const forestStart = previous?.endDistance ?? 0; + const forestEnd = next?.startDistance ?? Number.POSITIVE_INFINITY; + const span = forestEnd - forestStart; + const output = target ?? this.emptySample(); + output.type = 'forest'; + output.regionId = 0; + output.startDistance = forestStart; + output.endDistance = forestEnd; + output.localT = Number.isFinite(span) && span > 0 ? (distance - forestStart) / span : 0; + output.blend = 0; + output.transitionDistance = 0; + output.bridgeStart = -1; + output.bridgeEnd = -1; + output.waterSide = 1; + return output; + } + + nextSpecial(roadDistance: number, requestedType?: SpecialWorldRegionType): WorldRegionSample { + const distance = Math.max(0, roadDistance); + let searchDistance = distance; + for (let attempts = 0; attempts < 32; attempts++) { + this.ensureThrough(searchDistance + 170_000); + const match = this.regions.find((region) => region.startDistance > distance && + (requestedType === undefined || region.type === requestedType)); + if (match) return this.copySample(match, undefined, 0); + searchDistance = this.regions[this.regions.length - 1].endDistance; + } + throw new Error(`Unable to schedule next ${requestedType ?? 'special'} region`); + } + + getSchedule(maxDistance: number): readonly WorldRegionSample[] { + this.ensureThrough(maxDistance); + return this.regions.filter((region) => region.startDistance <= maxDistance).map((region) => this.copySample(region, undefined, 1)); + } + + private ensureThrough(distance: number): void { + while (this.regions.length === 0 || this.regions[this.regions.length - 1].startDistance <= distance) { + const index = this.regions.length; + const previousEnd = index === 0 ? 0 : this.regions[index - 1].endDistance; + let type: SpecialWorldRegionType = 'fields'; + let requestedStart = Number.POSITIVE_INFINITY; + for (const candidateType of SPECIAL_TYPES) { + const candidateStart = this.nextStartForType(candidateType); + if (candidateStart < requestedStart) { + requestedStart = candidateStart; + type = candidateType; + } + } + const startDistance = Math.max(requestedStart, previousEnd + MINIMUM_FOREST_GAP); + const durationRoll = hash01(this.seed + 4103, index, 1); + const duration = type === 'fields' ? 6_000 + durationRoll * 9_000 + : type === 'coast' ? 8_000 + durationRoll * 7_000 + : 3_000 + durationRoll * 2_000; + const transitionDistance = type === 'fields' ? 1_200 : type === 'coast' ? 1_400 : 900; + const endDistance = startDistance + duration; + const center = (startDistance + endDistance) * 0.5; + const bridgeStart = type === 'river_bridge' + ? Math.round((center - BRIDGE_CHUNK_LENGTH * BRIDGE_CHUNKS * 0.5) / BRIDGE_CHUNK_LENGTH) * BRIDGE_CHUNK_LENGTH + : -1; + this.regions.push({ + type, regionId: index + 1, startDistance, endDistance, localT: 0, blend: 0, + transitionDistance, bridgeStart, + bridgeEnd: bridgeStart < 0 ? -1 : bridgeStart + BRIDGE_CHUNK_LENGTH * BRIDGE_CHUNKS, + waterSide: hash01(this.seed + 4111, index, 2) < 0.5 ? -1 : 1 + }); + } + } + + private nextStartForType(type: SpecialWorldRegionType): number { + let previous: SpecialRegionRecord | undefined; + let occurrence = 0; + for (const region of this.regions) { + if (region.type !== type) continue; + previous = region; + occurrence++; + } + const range = previous ? TYPE_COOLDOWN_RANGE[type] : FIRST_REGION_RANGE[type]; + const roll = hash01(this.seed + 4201 + TYPE_HASH_SALT[type], occurrence, TYPE_HASH_SALT[type]); + const spacing = range[0] + (range[1] - range[0]) * roll; + return previous ? previous.endDistance + spacing : spacing; + } + + private copySample(source: SpecialRegionRecord, target?: WorldRegionSample, blend = source.blend, + distance = source.startDistance): WorldRegionSample { + const output = target ?? this.emptySample(); + output.type = source.type; + output.regionId = source.regionId; + output.startDistance = source.startDistance; + output.endDistance = source.endDistance; + output.localT = (Math.max(source.startDistance, Math.min(source.endDistance, distance)) - source.startDistance) / + (source.endDistance - source.startDistance); + output.blend = blend; + output.transitionDistance = source.transitionDistance; + output.bridgeStart = source.bridgeStart; + output.bridgeEnd = source.bridgeEnd; + output.waterSide = source.waterSide; + return output; + } + + private emptySample(): WorldRegionSample { + return { + type: 'forest', regionId: 0, startDistance: 0, endDistance: Number.POSITIVE_INFINITY, + localT: 0, blend: 0, transitionDistance: 0, bridgeStart: -1, bridgeEnd: -1, waterSide: 1 + }; + } +} + +export function runRegionScheduleProbe(seed: number, maxDistance = 1_000_000): RegionScheduleProbeResult { + const first = new WorldRegionDirector(seed).getSchedule(maxDistance); + const repeated = new WorldRegionDirector(seed).getSchedule(maxDistance); + const changed = new WorldRegionDirector(seed + 1).getSchedule(maxDistance); + let minimumForestGap = Number.POSITIVE_INFINITY; + const typeCounts: Record = { fields: 0, coast: 0, river_bridge: 0 }; + const minimumTypeGap: Record = { + fields: Number.POSITIVE_INFINITY, coast: Number.POSITIVE_INFINITY, river_bridge: Number.POSITIVE_INFINITY + }; + const intervalSums: Record = { fields: 0, coast: 0, river_bridge: 0 }; + const intervalCounts: Record = { fields: 0, coast: 0, river_bridge: 0 }; + const previousByType: Partial> = {}; + for (let index = 0; index < first.length; index++) { + const type = first[index].type as SpecialWorldRegionType; + typeCounts[type]++; + const previousEnd = index === 0 ? 0 : first[index - 1].endDistance; + minimumForestGap = Math.min(minimumForestGap, first[index].startDistance - previousEnd); + const sameTypePrevious = previousByType[type]; + if (sameTypePrevious) { + minimumTypeGap[type] = Math.min(minimumTypeGap[type], first[index].startDistance - sameTypePrevious.endDistance); + intervalSums[type] += first[index].startDistance - sameTypePrevious.startDistance; + intervalCounts[type]++; + } + previousByType[type] = first[index]; + } + const averageStartInterval: Record = { + fields: intervalSums.fields / Math.max(1, intervalCounts.fields), + coast: intervalSums.coast / Math.max(1, intervalCounts.coast), + river_bridge: intervalSums.river_bridge / Math.max(1, intervalCounts.river_bridge) + }; + const fingerprint = (items: readonly WorldRegionSample[]): string => items + .map((item) => `${item.type}:${item.startDistance.toFixed(3)}:${item.endDistance.toFixed(3)}`).join('|'); + const deterministic = fingerprint(first) === fingerprint(repeated); + const differentSeed = fingerprint(first) !== fingerprint(changed); + const allTypes = SPECIAL_TYPES.every((type) => typeCounts[type] > 1); + const frequenciesPass = typeCounts.fields > typeCounts.coast && typeCounts.river_bridge > typeCounts.coast && + minimumTypeGap.fields >= TYPE_COOLDOWN_RANGE.fields[0] && + minimumTypeGap.river_bridge >= TYPE_COOLDOWN_RANGE.river_bridge[0] && + minimumTypeGap.coast >= TYPE_COOLDOWN_RANGE.coast[0]; + return { + passed: first.length >= 12 && minimumForestGap >= MINIMUM_FOREST_GAP && allTypes && frequenciesPass && + deterministic && differentSeed, + specialRegions: first.length, minimumForestGap, minimumTypeGap, averageStartInterval, + typeCounts, deterministic, differentSeed + }; +}