diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9f7cd94..4e4bd1d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,3 +24,16 @@ jobs: - run: npm ci - run: npm run check - run: npm run build + - name: Install browser test runtime + run: npx playwright install --with-deps chromium + - name: Exercise desktop and touch flight in Chromium + run: npm run test:e2e + - name: Keep browser test evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: browser-test-report + path: | + playwright-report/ + test-results/ + retention-days: 7 diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 505f84d..c51232d 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -39,6 +39,19 @@ jobs: run: npm run check - name: Build Rust/WASM and Vite site run: npm run build + - name: Install browser test runtime + run: npx playwright install --with-deps chromium + - name: Verify desktop and touch flight before publishing + run: npm run test:e2e + - name: Keep browser test evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: pages-browser-test-report + path: | + playwright-report/ + test-results/ + retention-days: 7 - name: Configure GitHub Pages uses: actions/configure-pages@v5 - name: Upload built site diff --git a/.gitignore b/.gitignore index 054eb41..91e3ff0 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,5 @@ dist/ *.tsbuildinfo rust/flight-core/target/ src/game/generated/ +playwright-report/ +test-results/ diff --git a/README.en.md b/README.en.md index a479e60..b1ae823 100644 --- a/README.en.md +++ b/README.en.md @@ -14,6 +14,7 @@ Play online: [GitHub Pages](https://kai987.github.io/FPV-drone-game/) · [Sites] - The original six aircraft carry six bombs with automatic reloading, smoke and debris on land, and splashes and ripples on water. GUARDIAN carries an underslung machine gun with muzzle flashes, tracers, impacts, and automatic reloading. The first hit on each target earns 100 points. - Day/night switching, a drone searchlight, lit windows, urban streetlights, and a harbor lighthouse. Optional motor, checkpoint, and bombing audio is muted by default. - A draggable, zoomable minimap, live telemetry, pause/restart, fullscreen, and multitouch mobile controls. +- A settings dialog with Auto / Low / Medium / High graphics, touch sensitivity, acceleration time, and vertical inversion. The browser remembers map, drone, and other preferences. - Instantly switch the header selector between **中文 / 日本語 / English**. Chinese is the default. The language is stored as `zh / ja / en` under `aeroflow-language` in localStorage. Switching preserves flight position and progress, the map, ammunition, wind, minimap view, and the existing 3D renderer. Flying and language switching still work when local storage is unavailable. Both handling modes automatically hover in calm air. Wind causes drift that needs correction. Sport offers higher speed, more inertia, and stronger banking feedback. This is an accessible game model, not a professional Acro/Rate, gravity-based flight, or real aerodynamic simulator. @@ -36,7 +37,7 @@ The mountain map has an 800 m altitude ceiling; all other maps have a 450 m ceil - **Harbor:** 125 warehouses, nine piers, nine gantry cranes, 27 trucks, four cargo ships, two breakwaters, and 2,932 containers, with 54 warehouses in the central district. Each of the six new piers is 960 m long. The sea has waves, reflections, and shore foam; the lighthouse has a rotating beam at night. - **Desert:** Follow an independent route over rolling dunes and wind-carved mesas. Red rock pillars, rock formations, cacti, and camps create a landscape distinct from the valley. - **Downtown:** The 198 lots use seven architectural forms, including curtain-wall offices, podiums and setbacks, twin towers, courtyard housing, masonry blocks, hotels, and crowned towers. Facades have mullions, sunshades, balconies, shop entrances, and rooftop equipment. Night lighting varies by building, floor, and room. Structural pieces and stepped roof support share the Rust collision geometry. -- **Mountains:** Fly between sharp summits, steep rock faces, undulating ridges, saddles, and pine woods. Dedicated alpine rock and wind-packed snow textures blend by slope, aspect, and elevation, exposing rock on cliffs and retaining snow on shelves. Rust terrain heights drive rendering, flight support, and projectile ground queries consistently. +- **Mountains:** Explore asymmetric multi-summit crowns, branching broken ridgelines, glacial cirques, and stepped cliffs. Unequal peak positions, elevations, and shoulder widths replace regular cone silhouettes. Dedicated alpine rock and wind-packed snow textures blend by slope, aspect, and elevation, exposing rock on cliffs and retaining snow on shelves. Rust and rendering use common terrain calculations, with finer ridgelines also shown on the minimap. - **Roads:** Each industrial map retains 21 main-road crossroads with zebra crossings and stop bars on all four approaches. Shared service roads connect the loading entrances of all 190 factory buildings and 125 harbor warehouses, avoiding buildings, cargo, tanks and the shoreline. The factory adds 148 T-junctions and 11 crossroads; the harbor adds 88 T-junctions and 7 crossroads. Long service roads have center dashes and junctions have zebra crossings; only the terminating approach stops at a T-junction. The 3D pavement, ground cutouts and minimap share the complete metre-scaled road layout. - **Switching:** On first entry, all six maps prepare their scenes, textures, Rust services, and day/night shaders, with per-map progress. Flying is enabled only after all are ready. Switching reuses cached scenes, returns to the selected map's spawn point, and resets the route, timer, ammunition, and score. Drone, game/handling mode, wind, day/night, sound, language, and camera view are retained. @@ -81,10 +82,25 @@ VECTOR is inspired by the [2017 DRL RacerX record report](https://www.guinnesswo | Minimap overview | Click the magnification or Route/Overview preset to return to 1× | | Interface language | Header 中文 / 日本語 / English selector | -Click the 3D scene during flight to enable mouse look. Esc releases the mouse and pauses. Switching browser tabs or losing window focus also pauses automatically. After takeoff on mobile, control flight with gestures on the flight view. Hold one finger to accelerate gradually from low speed; input reaches the selected aircraft and mode’s maximum after about two seconds. Drag up/down for forward/backward flight and left/right to strafe. Drag a second finger up/down to climb/descend and left/right to turn; both fingers can work together. Releasing a finger clears its axes and flight physics slows the aircraft. Assisted mode brakes faster, and wind can still cause drift. Bombing, wind direction, and the minimap sit in a panel below the flight view. Dragging or zooming the minimap does not steer the aircraft. Inputs, selectors, and modal dialogs isolate flight shortcuts to prevent accidental movement or bombing while using the interface. +Click the 3D scene during flight to enable mouse look. Esc releases the mouse and pauses. Switching browser tabs or losing window focus also pauses automatically. After takeoff on mobile, control flight with gestures on the flight view. Hold one finger to accelerate gradually from low speed; input reaches the selected aircraft and mode’s maximum after about two seconds by default. Drag up/down for forward/backward flight and left/right to strafe. Drag a second finger up/down to climb/descend and left/right to turn; both fingers can work together. Releasing a finger clears its axes and flight physics slows the aircraft. Assisted mode brakes faster, and wind can still cause drift. Bombing, wind direction, and the minimap sit in a panel below the flight view. Dragging or zooming the minimap does not steer the aircraft. Inputs, selectors, and modal dialogs isolate flight shortcuts to prevent accidental movement or bombing while using the interface. Touch gestures are enabled only when the primary pointer is coarse; narrowing a desktop window keeps mouse and keyboard controls. Gesture areas accept touch input only and clear active gestures when the input capability changes. +### Graphics and control preferences + +Open settings from the header. Every quality preset retains preparation of all six maps before flight. Changing quality returns to the current map’s spawn point, resets position, ammunition, and run progress, and prepares all maps again. + +| Quality | Panorama texture width | DPR cap | Shadow-map side | +| --- | --- | --- | --- | +| Auto | Touch-primary 3548; otherwise 3548 or 7096 | Touch-primary 1.25; otherwise 1.75 | Touch-primary 512; otherwise 1024 | +| Low | 3548 | 1.0 | Shadows off | +| Medium | 3548 | 1.5 | 1024 | +| High | 7096, or 3548 under GPU limits | 1.75 | 2048 | + +The rendering pixel ratio also never exceeds the device’s own DPR. Auto detects the primary input capability; desktop panorama selection additionally uses viewport width and GPU limits. Only High uses 2048 shadows. Quality controls pixel ratio, shadows, and decorative visibility distance without changing flight physics or courses. + +Touch sensitivity ranges from 0.5× to 2.0× (default 1), and acceleration to maximum input ranges from 500 to 4000 ms (default 2000 ms), with optional vertical-input inversion. `aeroflow:preferences` stores map, drone, game/handling mode, base wind, day/night, camera, sound, quality, and touch settings. Position, ammunition, and progress are not saved; reopening starts at spawn. A saved sound-on preference still requires a user gesture before audio plays. Flying remains available when storage is blocked. + ### Flight, wind, and target practice tips - **Timed challenge:** Fly through the illuminated rings in order, approaching their front side. Collisions slow the drone and add three seconds; persistent contact has a penalty cooldown. **Free flight** has no ring requirement or collision time penalty. @@ -114,12 +130,17 @@ Open the address printed in the terminal, normally [http://127.0.0.1:5173/](http ```sh npm run build:wasm # Build Rust and update WASM separately npm test # Build WASM, run native Cargo and Node tests -npm run check # npm test, then TypeScript checks +npm run check:generated # Read-only comparison of canonical and generated terrain +npm run check # Generated-data check, npm test, then TypeScript checks npm run build # Build WASM, check TypeScript, generate dist/ npm run preview # Preview existing dist/, normally http://127.0.0.1:4173/ +npm run test:e2e:install # Install Chromium on first use +npm run test:e2e # Playwright browser smoke tests ``` -Development, tests, checks, and production builds all generate WASM first. The development server does not watch Rust source. After Rust changes, run `npm run build:wasm` or restart `npm run dev`. `src/game/generated/flight_core.wasm`, Cargo's `target/`, `node_modules/`, and `dist/` are ignored build/dependency outputs that the commands above recreate from a fresh checkout. +The canonical alpine layout is [`data/alpine-terrain.json`](./data/alpine-terrain.json). `node scripts/generate-alpine-data.mjs` emits tracked TS/Rust constants; ordinary WASM builds regenerate them as well. `npm run check:generated` and `npm run check` reject stale or hand-edited outputs without repairing and hiding the drift. Independent TS and Rust mathematics, 1481-point height comparisons, multi-summit shape tests, and continuity checks remain in place. + +Development, tests, and production builds generate WASM. `check` first verifies generated-data consistency, then runs the same tests. The development server does not watch Rust source. After Rust changes, run `npm run build:wasm` or restart `npm run dev`. `src/game/generated/flight_core.wasm`, Cargo's `target/`, `node_modules/`, and `dist/` are ignored build/dependency outputs that the commands above recreate from a fresh checkout. Game artwork ships with the repository; no generative AI is called at runtime. Fonts may load from Google Fonts and fall back to system fonts offline or when unavailable. There are no account, database, paid API, or server-secret dependencies. @@ -130,12 +151,16 @@ Game artwork ships with the repository; no generative AI is called at runtime. F GitHub Pages setup: 1. In **Settings → Pages → Build and deployment → Source**, choose **GitHub Actions**. -2. Push changes to `main`. [pages.yml](./.github/workflows/pages.yml) installs Node.js 24 and Rust 1.93.0's WASM target, then runs `npm ci`, `npm run check`, and `npm run build`. +2. Push changes to `main`. [pages.yml](./.github/workflows/pages.yml) installs Node.js 24 and Rust 1.93.0's WASM target, then runs `npm ci`, `npm run check`, `npm run build`, and `npm run test:e2e`. 3. The workflow uploads `dist/` as the Pages artifact and deploys to the `github-pages` environment. Failed checks or builds prevent publication. 4. Confirm both `build` and `deploy` succeed, then open the [Pages game](https://kai987.github.io/FPV-drone-game/) and verify loading and takeoff. You can also select `main` in **Actions → Deploy game to GitHub Pages → Run workflow** to redeploy manually. Other branches are not published; pushes and pull requests use the separate [ci.yml](./.github/workflows/ci.yml) checks. `dist/` and generated WASM are not committed. Ordinary CI success does not establish deployment completion. Workflow reference: [GitHub custom Pages workflows](https://docs.github.com/en/pages/getting-started-with-github-pages/using-custom-workflows-with-github-pages). +The build writes `version.json` into `dist/`, and settings shows the build ID from the same `BUILD_INFO`. `sourceRevision` is the build repository’s Git HEAD; `sourceDirty` records uncommitted changes; `sourceFingerprint` fingerprints source and the actual WASM. Dirty builds are labelled, and only clean builds link to a source commit. To compare GitHub Pages and Sites, check `buildId` and those three fields from the same production `dist/`. Sites’ storage commit belongs to a separate Git history and is not automatically the GitHub source SHA. + +A GitHub commit link is shown only when origin is verified as this GitHub repository. Separate Site repository histories show a text revision instead of inventing a GitHub link. + ## Rust and rendering architecture - **Rust/WASM:** Flight position, velocity, attitude, and wind; terrain, rivers/lakes, bridges, roofs, decks, and obstacle spatial grids; bomb trajectories, first hits, scoring, and reloading; generation of woods, rocks, shrubs, terrain colors, and water textures; batched fish, livestock, and explosion animation calculations. @@ -145,19 +170,21 @@ One game shares one WASM instance and WebGL context. Each map owns independent w Maps are scenes generated from shared configuration and procedural models, not complete 3D map files packed into Rust. Industrial buildings, rotated cargo, piers, breakwaters, and ship hulls use the same metre-based layout for rendering, the minimap, and Rust collisions. Nine piers and two breakwaters are uploaded once into Rust's land union, keeping terrain/water classification and support heights consistent. -Initial loading reuses decoded images, overlaps texture downloads with scene preparation, and serially compiles and warms all six maps' day/night GPU resources. Trees use instanced billboards. Basic urban structures are instanced by material; details use 600 m spatial chunks and a 450 m visibility margin around their bounding spheres. Night streetlights use a fixed pool of eight lights. All map and rendering resources are released when leaving the game. +Initial loading reuses decoded images, overlaps texture downloads with scene preparation, and serially compiles and warms all six maps’ day/night GPU resources. Trees use instanced billboards. Basic urban structures are instanced by material; urban and alpine decorations use spatial chunks with visibility distance selected by graphics quality. Night streetlights use a fixed pool of eight lights. All map and rendering resources are released when leaving the game. The idle background updates at about 12 FPS. Paused and finished scenes render on demand; the main scene stops drawing behind the hangar, guide, or wind dialog and while the page is hidden. Day/night and camera changes still redraw a paused scene, and resuming never catches up paused time. A lost WebGL context clears movement and firing input and pauses flight. Restoring the view preserves position, ammunition, and score until manual resume. Startup interruptions and runtime errors display a reload action. Original TypeScript mathematics and frozen older scene/explosion equations remain independent test references. Production uses Rust services and shows a load failure instead of silently switching to JS physics. WASM calculations still run synchronously on the main thread, without a Worker. No FPS improvement is claimed for the Rust migration or map optimization; performance changes require separate measurement. -During flight, the game measures FPS, frame intervals, CPU time for simulation, scene updates and render submission, plus draw and resource counts. Sustained slow pacing lowers rendering pixel ratio in stages; stable pacing allows cautious recovery. Coarse-pointer devices target 30 FPS and other devices target 60 FPS, with pixel ratio capped by device DPR and 1.75. Reports update about once a second in the game canvas `data-performance-metrics`. These are CPU and frame-pacing measurements, not GPU execution time or a guarantee of reaching the target FPS. +During flight, the game measures FPS, frame intervals, CPU time for simulation, scene updates and render submission, plus draw and resource counts. Sustained slow pacing lowers rendering pixel ratio in stages; stable pacing allows cautious recovery. Coarse-pointer devices target 30 FPS and other devices target 60 FPS, with pixel ratio capped by device DPR and the selected quality preset. Reports update about once a second in the game canvas `data-performance-metrics`. These are CPU and frame-pacing measurements, not GPU execution time or a guarantee of reaching the target FPS. ### Main directories ```text rust-toolchain.toml Rust version and WASM target rust/flight-core/ Rust core, batch ABI, and native tests +data/alpine-terrain.json Canonical alpine layout +scripts/generate-alpine-data.mjs Generate/check TS and Rust terrain constants scripts/build-wasm.mjs Build and update WASM scripts/optimize-textures.mjs Offline texture re-encoding src/App.tsx Page, settings, and game state @@ -185,15 +212,17 @@ docs/asset-licenses.md Asset sources and offline processing records ## Validation -`npm run check` runs native Cargo tests, Node tests using the real WASM file, and TypeScript checks. `npm run build` validates production output. Test counts grow with features; use the command results as the current count. +`npm run check` checks generated-data freshness, runs native Cargo tests and Node tests using the real WASM file, and checks TypeScript. `npm run build` validates production output; `npm run test:e2e` runs Chromium browser smoke tests. Test counts grow with features; use command results as the current count. Coverage includes numerical compatibility across seven drones, two handling modes, four wind strengths, eight directions, and 30/60/120 fps; complete Valley and urban eight-ring routes using ordinary controls; pause, invalid time steps, bounds, bridges, roofs/decks, elevated and rotated-object collisions, weapon lifecycles, layered impact surfaces, records and language storage, map caching, and resource cleanup. Seeded scenery, complete terrain heights/colors, water textures/flow, batched fish/livestock/explosion animation, expanded-map roads, berths, land/water boundaries, and minimap bounds are also checked. -Browser checks include six-map preloading, map/drone switching, day/night, bombing, language changes, minimap/touch interaction at desktop and mobile sizes, page overflow, and the console. Browser viewport checks are not physical-phone GPU benchmarks, and real drone performance is outside validation scope. +CI runs Playwright’s Chromium smoke suite at desktop 1440×960 and mobile-equivalent 390×844. Browser checks cover six-map preparation, map/drone/day-night/settings interactions, rendered output, and console health. Mobile viewport and touch emulation are not physical-device GPU benchmarks; Safari on physical iPhone/iPad devices remains unverified. Real drone performance is outside the test scope. + +Linux CI uses software rendering, with a 60-second limit for actions and captures. Touch-flight evidence is captured after the gesture assertions and a pause. To exercise the same rendering path locally after a production build, run `CI=1 PLAYWRIGHT_SOFTWARE_WEBGL=1 npm run test:e2e`. ## Artwork and license -The snowy-mountain, pine-valley, and blue-sky panorama began as a 1774×887 image generated with built-in Image Gen, then received 4× Real-ESRGAN upscaling. A 7096×3548 HD WebP or 3548×1774 mobile version is selected according to viewport width and GPU capability. This is enhanced artwork, not native 7K/8K photography. The sky follows the camera, forests below the horizon transition into fog, and rivers/lakes share the panorama for reflections. +The snowy-mountain, pine-valley, and blue-sky panorama began as a 1774×887 image generated with built-in Image Gen, then received 4× Real-ESRGAN upscaling. A 7096×3548 HD WebP or 3548×1774 mobile version is selected according to graphics quality, primary input, viewport width, and GPU capability. This is enhanced artwork, not native 7K/8K photography. The sky follows the camera, forests below the horizon transition into fog, and rivers/lakes share the panorama for reflections. Transparent pines, grass, and weathered-rock textures are also generated artwork converted offline to WebP. Pine RGBA values are preserved pixel for pixel; grass and rocks retain their original dimensions. Texture optimization did not replace the HD panorama. Encoding tools are offline utilities, not player or build dependencies. Sources, processing commands, license notes, and SHA256 values are documented in the [asset records](./docs/asset-licenses.md) and [design notes](./docs/design.md). diff --git a/README.md b/README.md index fa2d48d..faa78b7 100644 --- a/README.md +++ b/README.md @@ -12,8 +12,9 @@ - 独立した6つのマップ。各マップに8個のチェックポイントリング、5個の練習標的、対応するミニマップがあります。タイムチャレンジと自由飛行、アシストとスポーツの操縦モードを選べます。 - 無風、微風、中程度、強風の4段階と、8方向の基準風向。離陸時は基準の方向から吹き、その後は実際の風向が時間とともに滑らかに変化します。風速も時間、位置、高度に応じて変化します。向かい風、追い風、横風が実際の対地速度と軌道に影響し、計器は風が来る方向の角度、ミニマップ横のコンパスは吹いていく方向を表示します。一時停止中は風も止まります。 - 従来の6機種は爆弾6発、自動補充、陸上の煙や破片、水上の飛沫や波紋に対応。GUARDIANは機体下の機銃、マズルフラッシュ、曳光弾、着弾効果、自動補充を搭載します。各標的への初回命中で100点を獲得します。 -- 昼夜切り替え、機体のサーチライト、明かりのついた窓、街灯、港の灯台。モーター、リング通過、投下の効果音は任意で有効にでき、初期状態はミュートです。 +- 昼夜切り替え、機体のサーチライト、明かりのついた窓、街灯、港の灯台。モーター、リング通過、投下の効果音は任意で有効にでき、初期設定はミュートです。 - ドラッグとズームに対応したミニマップ、リアルタイム計器、一時停止と再スタート、全画面表示、スマートフォンのマルチタッチ操作。 +- 画質をAuto / Low / Medium / Highから選べる設定画面。タッチ感度、加速時間、上下反転を調整でき、マップや機体などの設定をブラウザーに保存します。 - ヘッダーの選択欄で **中文 / 日本語 / English** を即座に切り替えられます。初期言語は中国語で、`zh / ja / en`をlocalStorageの`aeroflow-language`に保存します。切り替えても飛行位置と進行状況、マップ、弾数、風、ミニマップの表示範囲、既存の3Dレンダラーは維持されます。ローカルストレージが使えなくても、言語切り替えと飛行は可能です。 どちらの操縦モードも無風時には自動でホバリングします。風があると流されるため、修正操作が必要です。スポーツは速度、慣性、傾きの反応が大きくなります。遊びやすさを重視したゲームの飛行モデルであり、専門的なAcro/Rate、重力を含む飛行、実際の空力のシミュレーターではありません。 @@ -36,7 +37,7 @@ - **港**:倉庫125棟、埠頭9基、ガントリークレーン9基、トラック27台、貨物船4隻、防波堤2本、コンテナ2932個。中心街区には倉庫54棟を配置しています。追加した6つの埠頭はそれぞれ長さ960mです。海面には波、反射、岸辺の泡があり、夜間の灯台には回転する光があります。 - **砂漠**:風で削られた砂丘と台地を巡る独立した飛行コースです。砂色の地形、岩柱、サボテン、キャンプが谷とは異なる景観を作ります。 - **都心**:198の敷地に、ガラスのオフィス、低層部のある高層ビル、セットバック、双塔、L字型住宅、レンガ造、ホテルなど7形式を配置しています。外壁の窓枠、庇、バルコニー、店舗入口、屋上設備に奥行きがあり、夜間は建物・階・部屋ごとに明かりが変わります。構造部分と退いた屋上の支持面はRustの衝突形状と共通です。 -- **山岳**:鋭い峰、急な岩壁、起伏のある尾根と鞍部を巡ります。岩石と風成雪の専用テクスチャを、斜面の傾き・向き・高度に応じて混合し、急な岩壁の露岩と棚状地形の積雪を表現します。地形の高さはRustが計算し、描画、飛行の地面判定、投下物の着地点で一致します。 +- **山岳**:非対称の複数の峰、折れ曲がって分岐する尾根、氷河に削られた凹壁、段状の断崖を巡ります。峰の位置・高さ・山肩の幅を変え、規則的な円錐形を避けています。岩石と風成雪の専用テクスチャを、斜面の傾き・向き・高度に応じて混合し、急な岩壁の露岩と棚状地形の積雪を表現します。Rustと描画は共通の地形計算を使用し、ミニマップにも細い尾根を表示します。 - **道路**:工場と港の幹線道路にはそれぞれ21か所の十字路を維持し、四方向に横断歩道と停止線を配置しています。共用の構内道路は全190棟の工場と125棟の港湾倉庫の搬出入口につながり、建物・コンテナ・タンク・海岸線を避けます。工場にはT字路148か所と十字路11か所、港にはT字路88か所と十字路7か所を追加しました。長い構内道路には中央の破線、交差点には横断歩道を設け、T字路では接続する側の道路にのみ停止線を配置します。3D路面、地面の道路用スペース、ミニマップは完全なメートル単位の道路配置を共有します。 - **切り替え**:初回表示時に6マップのシーン、テクスチャ、Rustサービス、昼夜のシェーダーを準備し、マップごとの進捗を表示します。全ての準備が完了してから飛行できます。切り替えはキャッシュを再利用し、選んだマップの出発地点へ戻って、コース、時間、弾数、得点をリセットします。機体、ゲームと操縦のモード、風、昼夜、音、言語、視点は維持します。 @@ -81,10 +82,25 @@ VECTORは[DRL RacerXの2017年記録の記事](https://www.guinnessworldrecords. | ミニマップの全体表示 | 倍率またはコース/全域プリセットをクリックして1×へ戻す | | 表示言語 | ヘッダーの中文 / 日本語 / English選択欄 | -飛行中に3D画面をクリックするとマウス視点を使えます。Escでマウスを解放して一時停止します。タブを切り替えたりウィンドウのフォーカスが外れたりしたときも自動で停止します。スマートフォンでは離陸後に飛行画面をジェスチャーで操作します。1本指で長押しすると低速から徐々に加速し、約2秒で選択中の機体とモードの最大入力になります。上下のドラッグで前進・後退、左右で平行移動を操作します。2本目の指を上下にドラッグすると上昇・下降、左右では旋回し、2本を同時に使えます。指を離すと対応する入力が解除され、飛行物理に従って減速します。アシストモードは制動が速く、風があると流されることがあります。爆弾投下、風向、ミニマップは飛行画面の下のパネルに表示します。ミニマップのドラッグやズームは機体を動かしません。入力欄、選択欄、モーダル画面では飛行ショートカットを分離し、画面操作による意図しない移動や投下を防ぎます。 +飛行中に3D画面をクリックするとマウス視点を使えます。Escでマウスを解放して一時停止します。タブを切り替えたりウィンドウのフォーカスが外れたりしたときも自動で停止します。スマートフォンでは離陸後に飛行画面をジェスチャーで操作します。1本指で長押しすると低速から徐々に加速し、初期設定では約2秒で選択中の機体とモードの最大入力になります。上下のドラッグで前進・後退、左右で平行移動を操作します。2本目の指を上下にドラッグすると上昇・下降、左右では旋回し、2本を同時に使えます。指を離すと対応する入力が解除され、飛行物理に従って減速します。アシストモードは制動が速く、風があると流されることがあります。爆弾投下、風向、ミニマップは飛行画面の下のパネルに表示します。ミニマップのドラッグやズームは機体を動かしません。入力欄、選択欄、モーダル画面では飛行ショートカットを分離し、画面操作による意図しない移動や投下を防ぎます。 タッチジェスチャーは主なポインターがタッチ向けの端末でのみ有効です。パソコンのウインドウを狭くしても、マウスとキーボードの操作は変わりません。ジェスチャー領域はタッチ入力だけを受け付け、入力環境が変わると操作状態をリセットします。 +### 画質と操作設定 + +ヘッダーの設定ボタンから変更できます。6マップの事前準備は全ての画質で維持します。画質を変えると現在のマップの出発地点へ戻り、位置・弾数・今回の進行をリセットして、全マップを再準備します。 + +| 画質 | 全景テクスチャの幅 | DPR上限 | 影マップの一辺 | +| --- | --- | --- | --- | +| Auto | タッチ主入力3548、その他3548または7096 | タッチ1.25、その他1.75 | タッチ512、その他1024 | +| Low | 3548 | 1.0 | 影なし | +| Medium | 3548 | 1.5 | 1024 | +| High | 7096、GPU制限時3548 | 1.75 | 2048 | + +描画ピクセル比は端末のDPRも超えません。Autoは主入力がタッチ向けかどうかを判定し、デスクトップの全景は表示幅とGPU能力で選びます。2048の影はHighのみです。低負荷のために画素比、影、装飾の描画距離を調整し、飛行物理やコースは変えません。 + +タッチ感度は0.5〜2.0倍(初期値1)、最大入力までの加速時間は500〜4000ms(初期値2000ms)で、上下入力の反転も選べます。`aeroflow:preferences`にはマップ、機体、ゲーム/操縦モード、基準風、昼夜、視点、音声、画質、タッチ設定を保存します。位置・弾薬・進行状況は保存せず、次回も出発地点から始めます。音声を有効として保存していても、再生はユーザー操作後です。保存が使えない環境でもプレイできます。 + ### 飛行・風・投下のヒント - **タイムチャレンジ**:光るリングを順番に正面から通過します。衝突で減速し、3秒が加算されます。継続して接触している場合はペナルティのクールダウンがあります。**自由飛行**ではリング通過の条件や衝突による時間ペナルティはありません。 @@ -114,12 +130,17 @@ npm run dev ```sh npm run build:wasm # Rustを個別にビルドしてWASMを更新 npm test # WASM生成、CargoネイティブテストとNodeテスト -npm run check # npm testの後にTypeScriptチェック +npm run check:generated # 地形生成物が原本と一致するか、書き換えずに確認 +npm run check # 生成一致検査、npm test、TypeScriptチェック npm run build # WASM生成、TypeScriptチェック、dist/を生成 npm run preview # 既存dist/のプレビュー。通常http://127.0.0.1:4173/ +npm run test:e2e:install # 初回のみChromiumを用意 +npm run test:e2e # Playwrightのブラウザースモークテスト ``` -開発、テスト、チェック、本番ビルドでは先にWASMを生成します。開発サーバーはRustのソース変更を監視しないため、変更後は`npm run build:wasm`を実行するか、`npm run dev`を再起動します。`src/game/generated/flight_core.wasm`、Cargoの`target/`、`node_modules/`、`dist/`はGitで無視するビルド・依存関係の生成物で、新規チェックアウトでも上記コマンドで再生成できます。 +山地配置の原本は[`data/alpine-terrain.json`](./data/alpine-terrain.json)です。`node scripts/generate-alpine-data.mjs`で追跡対象のTS/Rust定数を生成し、通常のWASMビルドも自動生成します。`npm run check:generated`と`npm run check`は古い生成物や手編集を修復せずに失敗させます。TSとRustの数学アルゴリズム、1481点の高さ比較、多峰形状と連続性の独立テストは残しています。 + +開発、テスト、本番ビルドはWASMを生成します。`check`は最初に生成物の一致を検査してから同じテストを実行します。開発サーバーはRustのソース変更を監視しないため、変更後は`npm run build:wasm`を実行するか、`npm run dev`を再起動します。`src/game/generated/flight_core.wasm`、Cargoの`target/`、`node_modules/`、`dist/`はGitで無視するビルド・依存関係の生成物で、新規チェックアウトでも上記コマンドで再生成できます。 ゲーム素材はリポジトリに含まれ、実行時に生成AIを呼び出しません。フォントはGoogle Fontsから読み込む場合があり、オフラインなどではシステムフォントへ戻ります。アカウント、データベース、有料API、サーバー秘密情報への依存はありません。 @@ -130,12 +151,16 @@ npm run preview # 既存dist/のプレビュー。通常http://127.0.0.1:4173 GitHub Pagesの設定: 1. リポジトリの **Settings → Pages → Build and deployment → Source** で **GitHub Actions** を選びます。 -2. `main`へプッシュします。[pages.yml](./.github/workflows/pages.yml)がNode.js 24とRust 1.93.0のWASMターゲットを用意し、`npm ci`、`npm run check`、`npm run build`を実行します。 +2. `main`へプッシュします。[pages.yml](./.github/workflows/pages.yml)がNode.js 24とRust 1.93.0のWASMターゲットを用意し、`npm ci`、`npm run check`、`npm run build`、`npm run test:e2e`を実行します。 3. `dist/`をPages artifactとしてアップロードし、`github-pages`環境にデプロイします。チェックやビルドが失敗すると公開しません。 4. `build`と`deploy`の両方の成功を確認し、[Pagesのゲーム](https://kai987.github.io/FPV-drone-game/)で読み込みと離陸を確認します。 **Actions → Deploy game to GitHub Pages → Run workflow** で`main`を選び、手動で再公開することもできます。他のブランチは公開せず、プッシュとPRは独立した[ci.yml](./.github/workflows/ci.yml)で検証します。`dist/`と生成WASMはGitにコミットしません。通常のCI成功だけではデプロイ完了を意味しません。参考:[GitHubのカスタムPagesワークフロー](https://docs.github.com/en/pages/getting-started-with-github-pages/using-custom-workflows-with-github-pages)。 +ビルド時に`version.json`を`dist/`へ出力し、同じ`BUILD_INFO`から設定画面のビルドIDを表示します。`sourceRevision`はビルド元のGit HEAD、`sourceDirty`は未コミット変更の有無、`sourceFingerprint`はソースと実際のWASMの内容指紋です。未コミット変更がある場合はその旨を表示し、変更がない場合にソースコミットへのリンクを示します。GitHub PagesとSitesを照合するときは、同じ本番`dist/`の`buildId`とこれら3値を確認します。Sitesの保管用コミットは別のGit履歴なので、GitHubのSHAと直接同一視しません。 + +GitHubコミットへのリンクは、originがこのGitHubリポジトリと確認できる場合だけ表示します。Site専用リポジトリなど別の履歴ではSHAをテキスト表示し、GitHubへのリンクを推測しません。 + ## Rustと描画の構成 - **Rust/WASM**:位置、速度、姿勢、風の計算。地形、河湖、橋、屋根、甲板、障害物の空間グリッド照会。投下の弾道、初回命中、得点、補充。森林、岩、低木、地形色、水面テクスチャの生成。魚、家畜、爆発のアニメーションを一括計算します。 @@ -145,19 +170,21 @@ GitHub Pagesの設定: マップは共通設定と手続き型モデルから生成するシーンで、完成した3DマップファイルをRust内に梱包したものではありません。都市の建物、回転したコンテナ、埠頭、防波堤、船体は共通のメートル単位の配置で描画、ミニマップ、Rust衝突判定を駆動します。9埠頭と2防波堤をRustの陸地の和集合へ一度アップロードし、陸水判定と支持面の高さを一致させます。 -初回読み込みではデコード済み画像を再利用し、テクスチャのダウンロードとシーン準備を重ねて実行します。6マップの昼夜GPUリソースは順次コンパイルして事前描画します。木はインスタンス化した貼り板、都市の基本構造は材質ごとのインスタンスバッチを使い、細部は600mの空間ブロックに分けて、包囲球に450mの距離余裕を加えて表示を判定します。夜間の街灯は固定8灯のプールを使います。ゲームを離れる際に全マップと描画リソースを解放します。 +初回の読み込みではデコード済み画像を再利用し、画像転送とシーン準備を重ね、6マップの昼夜GPUリソースを順番にコンパイル・ウォームアップします。樹木はインスタンス化した板状モデルです。都市の基本構造は材質別のインスタンス描画を使い、都市や山地の装飾は空間チャンクに分けて画質に応じた距離で表示判定します。夜の街灯は固定8灯のプールを使います。ゲームを離れると全マップと描画リソースを解放します。 待機中の背景は約12FPSで更新します。一時停止中とフライト終了後は必要なときだけ描画し、ハンガー・ガイド・風設定を開いている間やページが非表示の間は、主画面の描画を停止します。停止中も昼夜や視点の変更は画面に反映され、再開時に停止中の時間を追加計算しません。WebGL接続が失われた場合は移動・射撃入力を解除して飛行を一時停止します。復元後も位置・弾薬・スコアを保持し、手動での再開を待ちます。初期読み込みの中断や実行時エラーでは、再読み込みの案内を表示します。 旧TypeScriptの数式や固定した旧シーン・爆発方程式は独立したテスト参照として残しています。本番ではRustサービスを使い、読み込み失敗時は通知を表示し、黙ってJS物理へ切り替えることはありません。WASMは引き続きメインスレッドで同期実行し、Workerは使用しません。Rust移行やマップ最適化によるFPS向上は主張しておらず、性能変化は別途測定が必要です。 -飛行中はFPS、フレーム間隔、シミュレーション・シーン更新・描画コマンド送信のCPU時間、描画回数とリソース数を測定します。低FPSが続くと描画ピクセル比を段階的に下げ、安定した後に慎重に戻します。粗いポインターの端末は30FPS、それ以外は60FPSを目標とし、ピクセル比は端末のDPRまたは1.75を超えません。約1秒ごとに更新する結果はゲームcanvasの`data-performance-metrics`にあり、GPU実行時間や目標FPSを保証する値ではありません。 +飛行中はFPS、フレーム間隔、シミュレーション・シーン更新・描画コマンド送信のCPU時間、描画回数とリソース数を測定します。低FPSが続くと描画ピクセル比を段階的に下げ、安定した後に慎重に戻します。粗いポインターの端末は30FPS、それ以外は60FPSを目標とし、ピクセル比は選択した画質の上限と端末のDPRを超えません。約1秒ごとに更新する結果はゲームcanvasの`data-performance-metrics`にあり、GPU実行時間や目標FPSを保証する値ではありません。 ### 主なディレクトリ ```text rust-toolchain.toml RustのバージョンとWASMターゲット rust/flight-core/ Rustコア、一括ABI、ネイティブテスト +data/alpine-terrain.json 山地配置の原本 +scripts/generate-alpine-data.mjs TS/Rustの地形定数生成と一致検査 scripts/build-wasm.mjs WASMの生成と更新 scripts/optimize-textures.mjs オフラインのテクスチャ再エンコード src/App.tsx ページ、設定、ゲーム状態 @@ -185,15 +212,17 @@ docs/asset-licenses.md 素材の出典とオフライン処理の記録 ## 検証 -`npm run check`はCargoネイティブテスト、実際のWASMファイルを使うNodeテスト、TypeScriptチェックを実行します。`npm run build`で本番ビルドを検証します。テスト数は機能追加で変わるため、最新の件数は実行結果を参照してください。 +`npm run check`は生成物の一致検査、Cargoネイティブテスト、実際のWASMファイルを使うNodeテスト、TypeScriptチェックを実行します。`npm run build`で本番出力を検証し、`npm run test:e2e`でChromiumによるブラウザースモークテストを実行します。テスト数は機能追加で変わるため、最新の件数は実行結果を参照してください。 7機体、2操縦モード、4段階の風、8方向、30/60/120fpsの数値互換性、通常入力による谷と都市の8リング全コースを検証します。一時停止、不正な時間刻み、境界、橋上・橋下、屋根・甲板、高架と回転物体の衝突、武器ライフサイクル、複数階層の着弾面、記録と言語保存、マップキャッシュ、リソース解放も対象です。シード付きシーン、地形全体の高さと色、水面模様と流向、魚・家畜・爆発の一括アニメーション、拡張マップの道路、泊位、陸水境界、ミニマップの範囲も確認します。 -ブラウザー検証では6マップの事前読み込み、マップと機体の変更、昼夜、投下、言語変更、デスクトップとスマートフォンサイズのミニマップ・タッチ操作、画面のはみ出し、コンソールを確認します。ブラウザーの表示サイズでの確認は実機スマートフォンのGPUベンチマークではなく、実ドローンの性能も検証対象には含みません。 +CIではPlaywrightのChromiumを使い、1440×960のデスクトップと390×844のモバイル相当環境でスモークテストを実行します。6マップの準備、マップ・機体・昼夜・設定の操作、描画とコンソールなどをブラウザーで確認します。モバイル表示とタッチのエミュレーションは実機GPUのベンチマークではなく、iPhone/iPadの実機Safariは未確認です。実ドローンの性能も検証対象には含みません。 + +Linux CIはソフトウェア描画を使うため、操作と画像取得の上限を60秒にしています。タッチ飛行の検証画像は操作の確認後に一時停止して取得します。同じ描画経路は、本番ビルド後に `CI=1 PLAYWRIGHT_SOFTWARE_WEBGL=1 npm run test:e2e` でローカルでも確認できます。 ## 素材とライセンス -雪山、松林の谷、青空の全景は内蔵Image Genで1774×887の原画を生成し、Real-ESRGANで4倍に超解像処理しました。表示幅とGPU能力に応じて7096×3548の高解像度WebPか3548×1774のモバイル版を選びます。これは補強した画像素材であり、ネイティブ7K/8K写真ではありません。空はカメラに追従し、地平線より下の森林は霧の色へ移行し、河湖の反射も同じ全景を使います。 +雪山、松林の谷、青空の全景は内蔵Image Genで1774×887の原画を生成し、Real-ESRGANで4倍に超解像処理しました。画質設定、主入力、表示幅、GPU能力に応じて7096×3548の高解像度WebPか3548×1774のモバイル版を選びます。これは補強した画像素材であり、ネイティブ7K/8K写真ではありません。空はカメラに追従し、地平線より下の森林は霧の色へ移行し、河湖の反射も同じ全景を使います。 透明な松、草、風化岩のテクスチャも生成素材で、オフラインでWebPへ変換しています。松のRGBA値は画素単位で維持し、草と岩は元の寸法を保持しています。テクスチャ最適化で高解像度全景を置き換えていません。エンコードツールはオフライン用途のみで、プレイやビルドの依存関係ではありません。出典、処理コマンド、ライセンス説明、SHA256は[素材の記録](./docs/asset-licenses.md)と[設計文書](./docs/design.md)を参照してください。 diff --git a/README.zh.md b/README.zh.md index 34eb3d8..13832a3 100644 --- a/README.zh.md +++ b/README.zh.md @@ -14,6 +14,7 @@ - 六款原有机型使用六枚炸弹、自动装填、陆地烟尘与碎屑、水面飞溅与涟漪。GUARDIAN使用机腹机枪,带枪口火光、曳光弹、命中效果与自动装填。每个靶标首次命中获得100分。 - 日夜切换、无人机探照灯、亮窗、都市路灯、海港灯塔;可选电机、穿环与投弹音效,默认静音。 - 可拖动和缩放的小地图、实时飞行仪表、暂停与重新起飞、全屏及手机多点触屏操作。 +- 设置窗口提供Auto / Low / Medium / High画质、触屏灵敏度、加速时间和上下反转,并在浏览器中记住地图、机型等偏好。 - 页头可立即切换 **中文 / 日本語 / English**。默认中文,语言以 `zh / ja / en` 保存在 localStorage 的 `aeroflow-language` 中。切换保留飞行位置与进度、地图、弹药、风况、小地图视野和现有三维渲染器;本地存储不可用时仍可切换语言和飞行。 两种操控模式在无风时均自动维持悬停;有风时会漂移,需要主动修正。运动模式提供更快速度、更大惯性和倾斜反馈,属于易上手的游戏模型,不是专业 Acro/Rate、重力飞行或真实空气动力学模拟。 @@ -36,7 +37,7 @@ - **海港**:125座仓库、9座码头、9座桥吊、27辆卡车、4艘货轮、2道防波堤和2932个集装箱,其中核心街区分布54座仓库;六座新增码头各长960m。海面具有波纹、反光和岸边浪花,夜间灯塔显示旋转光束。 - **沙漠**:沿起伏沙丘与风蚀台地探索独立航线,红褐岩柱、岩群、仙人掌和营地形成区别于山谷的荒漠景观。 - **市中心**:198个地块采用玻璃写字楼、裙楼退台、双塔、L形住宅、砖石低层、酒店与冠顶塔楼等七类建筑。立面包含窗框、遮阳肋、阳台、商铺入口与屋顶设备;夜间按建筑、楼层和房间分别亮灯。结构和退台屋顶的支撑面与Rust碰撞形状共用数据。 -- **山区**:攀升尖峰、陡峭岩壁和起伏山脊,穿过松林与鞍部。专用高山岩石、风成积雪纹理按坡度、朝向和海拔混合,陡壁露岩、平台积雪;Rust地形高度同步用于渲染、飞行支撑面与弹药着地查询。 +- **山区**:穿过不对称的多峰山冠、折线分叉山脊、冰斗凹壁和层状断崖。峰位、高度和山肩宽度各不相同,避免规则锥体轮廓。专用高山岩石、风成积雪纹理按坡度、朝向和海拔混合,陡壁露岩、平台积雪;Rust与渲染使用共同的地形计算,小地图也能展示更细的山脊。 - **道路**:工厂与海港的主干路网各保留21个十字路口,每个路口的四个方向均有斑马线与停止线。共享支路连接全部190座厂房与125座仓库的装卸入口,并避开建筑、货箱、储罐和海岸线;工厂新增148个T形路口与11个十字路口,海港新增88个T形路口与7个十字路口。长支路有中心虚线,接入路口有斑马线,T形路口仅终止支路设停止线。三维路面、地面留白与小地图共用完整的米制道路布局。 - **切换**:首次进入会准备六张地图的场景、纹理、Rust服务和日夜着色器,显示逐图进度,全部准备完成后才允许起飞。地图切换复用缓存,返回所选地图起点并重置航线、计时、弹药和得分;保留机型、游戏与操控模式、风况、昼夜、声音、语言和视角。 @@ -81,10 +82,25 @@ VECTOR的灵感来自 [DRL RacerX的2017年纪录报道](https://www.guinnesswor | 小地图总览 | 点击倍率或航线/全域预设恢复1× | | 界面语言 | 页头中文 / 日本語 / English选择器 | -飞行时点击三维画面可启用鼠标视角。Esc释放鼠标并暂停;切换标签页或失去窗口焦点也会自动暂停。手机起飞后在飞行画面上用手势操作:单指按住从低速逐渐加速,约2秒达到当前机型和模式的最大输入;上下拖动控制前后,左右拖动控制平移。第二根手指上下拖动控制升降,左右拖动控制转向,两指可同时操作。松手会撤销对应输入并由飞行物理减速;辅助模式制动更快,有风时仍可能漂移。投弹、风向和小地图移到画面下方的底部面板,小地图的拖动与缩放不会操控无人机。输入框、选择器和模态窗口会隔离飞行快捷键,避免操作界面时意外飞行或投弹。 +飞行时点击三维画面可启用鼠标视角。Esc释放鼠标并暂停;切换标签页或失去窗口焦点也会自动暂停。手机起飞后在飞行画面上用手势操作:单指按住从低速逐渐加速,默认约2秒达到当前机型和模式的最大输入;上下拖动控制前后,左右拖动控制平移。第二根手指上下拖动控制升降,左右拖动控制转向,两指可同时操作。松手会撤销对应输入并由飞行物理减速;辅助模式制动更快,有风时仍可能漂移。投弹、风向和小地图移到画面下方的底部面板,小地图的拖动与缩放不会操控无人机。输入框、选择器和模态窗口会隔离飞行快捷键,避免操作界面时意外飞行或投弹。 触屏手势仅在主要指针为触屏的设备上启用;缩窄电脑窗口不会改变鼠标与键盘操作。手势区只接收触摸输入,切换输入设备时会清除残留手势。 +### 画质与操作设置 + +从页眉的设置按钮调整。所有画质仍会预先准备六张地图。修改画质会返回当前地图起点,重置位置、弹药和本轮进度,并重新准备全部地图。 + +| 画质 | 全景纹理宽度 | DPR上限 | 阴影贴图边长 | +| --- | --- | --- | --- | +| Auto | 主触屏3548,其他3548或7096 | 主触屏1.25,其他1.75 | 主触屏512,其他1024 | +| Low | 3548 | 1.0 | 关闭阴影 | +| Medium | 3548 | 1.5 | 1024 | +| High | 7096,GPU受限时3548 | 1.75 | 2048 | + +渲染像素比例也不会超过设备DPR。Auto根据主输入是否为触屏判断,桌面全景再按画面宽度和GPU能力选择;只有High使用2048阴影。画质调整像素比例、阴影与装饰显示距离,不改变飞行物理或航线。 + +触屏灵敏度为0.5〜2.0倍(默认1),达到最大输入的加速时间为500〜4000ms(默认2000ms),另可反转上下输入。`aeroflow:preferences`保存地图、机型、游戏/操控模式、基准风、昼夜、视角、声音、画质与触屏设置;不保存坐标、弹药或进度,下次仍从起点开始。即使记住了声音开启状态,也只在用户操作后播放。存储不可用时仍可游玩。 + ### 飞行、风况与打靶提示 - **计时挑战**:按顺序从正面穿过亮色环。碰撞减速并增加3秒,持续接触有惩罚冷却。**自由飞行**无需穿环,也没有碰撞计时惩罚。 @@ -114,12 +130,17 @@ npm run dev ```sh npm run build:wasm # 单独编译Rust并更新WASM npm test # 构建WASM,运行Cargo原生测试与Node测试 -npm run check # npm test,再进行TypeScript检查 +npm run check:generated # 只读检查地形生成物与原本是否一致 +npm run check # 生成一致检查、npm test、TypeScript检查 npm run build # 构建WASM、检查TypeScript,生成dist/ npm run preview # 预览已有dist/,默认http://127.0.0.1:4173/ +npm run test:e2e:install # 首次安装Chromium +npm run test:e2e # Playwright浏览器冒烟测试 ``` -开发、测试、检查和生产构建都会先生成WASM。开发服务器不监听Rust源码;修改Rust后执行`npm run build:wasm`,或重启`npm run dev`。`src/game/generated/flight_core.wasm`、Cargo的`target/`、`node_modules/`和`dist/`均为忽略的构建或依赖产物,全新检出可由上述命令生成。 +山区布局原本位于[`data/alpine-terrain.json`](./data/alpine-terrain.json)。`node scripts/generate-alpine-data.mjs`生成纳入版本控制的TS/Rust常量,普通WASM构建也会自动生成。`npm run check:generated`与`npm run check`遇到过期或手工改动的生成物会失败,不会自动修复来掩盖差异。TS与Rust各自的数学算法、1481点高度对比、多峰形状及连续性测试继续保留。 + +开发、测试和生产构建会生成WASM;`check`先检查生成物一致性,再运行相同测试。开发服务器不监听Rust源码;修改Rust后执行`npm run build:wasm`,或重启`npm run dev`。`src/game/generated/flight_core.wasm`、Cargo的`target/`、`node_modules/`和`dist/`均为忽略的构建或依赖产物,全新检出可由上述命令生成。 游戏美术随仓库提供,运行时不调用生成式AI。字体可从Google Fonts加载,离线或不可用时回退到系统字体;没有账号、数据库、付费API或服务器密钥依赖。 @@ -130,12 +151,16 @@ npm run preview # 预览已有dist/,默认http://127.0.0.1:4173/ GitHub Pages设置: 1. 在仓库 **Settings → Pages → Build and deployment → Source** 选择 **GitHub Actions**。 -2. 将变更推送到`main`。[pages.yml](./.github/workflows/pages.yml)安装Node.js 24与Rust 1.93.0的WASM目标,执行`npm ci`、`npm run check`和`npm run build`。 +2. 将变更推送到`main`。[pages.yml](./.github/workflows/pages.yml)安装Node.js 24与Rust 1.93.0的WASM目标,执行`npm ci`、`npm run check`、`npm run build`及`npm run test:e2e`。 3. 工作流上传`dist/`作为Pages artifact,并部署到`github-pages`环境。检查或构建失败时不会发布。 4. 确认`build`和`deploy`均成功,再打开[Pages游戏](https://kai987.github.io/FPV-drone-game/)检查加载和起飞。 也可在 **Actions → Deploy game to GitHub Pages → Run workflow** 选择`main`手动重新发布。其他分支不发布;推送与PR通过独立的[ci.yml](./.github/workflows/ci.yml)进行检查。`dist/`及生成的WASM不提交Git。普通CI成功不等于部署完成。工作流参考:[GitHub自定义Pages工作流](https://docs.github.com/en/pages/getting-started-with-github-pages/using-custom-workflows-with-github-pages)。 +构建将`version.json`写入`dist/`,设置窗口从同一`BUILD_INFO`显示构建ID。`sourceRevision`表示构建时Git HEAD,`sourceDirty`表示是否有未提交修改,`sourceFingerprint`是源码和实际WASM的内容指纹;未提交状态会明确标注,干净版本才提供源码提交链接。核对GitHub Pages与Sites时,比较同一生产`dist/`的`buildId`及上述三项字段。Sites用于保存版本的提交属于另一Git历史,不直接视作GitHub的同一SHA。 + +只有origin确认属于此GitHub仓库时,界面才显示GitHub提交链接;Site专用仓库等独立历史仅显示SHA文字,不猜测GitHub链接。 + ## Rust与渲染架构 - **Rust/WASM**:飞行位置、速度、姿态与风场;地面、河湖、桥面、屋顶、甲板与障碍空间网格;投弹弹道、首次命中、计分和装填;树林、岩石、灌木、地形颜色与水纹生成;鱼群、牛羊及爆炸粒子的批量动画计算。 @@ -145,19 +170,21 @@ GitHub Pages设置: 地图是共享配置与程序模型生成的场景,不是作为完整三维地图文件打包进Rust。厂港的建筑、旋转货箱、码头、防波堤和船体由同一米制布局驱动渲染、小地图与Rust碰撞;九座码头和两道防波堤一次上传到Rust陆地并集,保持地面/水域判定和支撑高度一致。 -首次加载会重用已解码图像,将纹理下载与场景准备重叠,并依次预编译和预热六张地图的日夜GPU资源。树木使用实例化贴图;都市基础结构按材质批量实例化,细节按600m空间块组织,根据包围球与450m距离余量判断显示,夜间路灯使用固定八盏灯的池。离开游戏时释放全部地图与渲染资源。 +首次加载会重用已解码图像,将纹理下载与场景准备重叠,并依次预编译和预热六张地图的日夜GPU资源。树木使用实例化贴图;都市基础结构按材质批量实例化,都市与山区的装饰划分为空间块,按所选画质的显示距离判断可见性。夜间路灯使用固定八盏灯的池。离开游戏时释放全部地图与渲染资源。 待机背景以约12FPS更新;暂停和结算时按需绘制,打开机库、指南或风况菜单以及页面隐藏时停止主场景绘制。暂停后修改昼夜或视角仍会刷新画面,恢复飞行不会补算暂停时间。WebGL连接中断会清空移动与射击输入并暂停;画面恢复后保留位置、弹药和成绩,等待手动继续。首次加载中断或运行期异常会显示重新加载提示。 原TypeScript数学及冻结的旧场景/爆炸方程保留作独立测试参考,生产使用Rust服务,加载失败显示提示,不悄悄切回JS物理。WASM数值计算仍在主线程同步执行,没有Worker;没有声称Rust迁移或地图优化提高了多少FPS,性能变化需要单独测量。 -飞行中自动测量FPS、帧间隔、模拟/场景/渲染提交的CPU耗时和绘制/资源计数。持续低帧时逐档降低渲染像素比例,稳定后谨慎恢复;粗指针设备目标30FPS,其他设备目标60FPS,像素比例不会超过设备DPR或1.75。性能数据约每秒更新一次,位于游戏canvas的`data-performance-metrics`,属于CPU与帧节奏测量,不是GPU执行时间,也不是达到目标帧率的保证。 +飞行中自动测量FPS、帧间隔、模拟/场景/渲染提交的CPU耗时和绘制/资源计数。持续低帧时逐档降低渲染像素比例,稳定后谨慎恢复;粗指针设备目标30FPS,其他设备目标60FPS,像素比例不会超过所选画质上限与设备DPR。性能数据约每秒更新一次,位于游戏canvas的`data-performance-metrics`,属于CPU与帧节奏测量,不是GPU执行时间,也不是达到目标帧率的保证。 ### 主要目录 ```text rust-toolchain.toml Rust版本与WASM目标 rust/flight-core/ Rust核心、批量ABI及原生测试 +data/alpine-terrain.json 山区布局原本 +scripts/generate-alpine-data.mjs TS/Rust地形常量生成与一致检查 scripts/build-wasm.mjs 构建和更新WASM scripts/optimize-textures.mjs 离线纹理重编码 src/App.tsx 页面、设置和游戏状态 @@ -185,15 +212,17 @@ docs/asset-licenses.md 素材来源与离线处理记录 ## 验证 -`npm run check`运行Cargo原生测试、读取真实WASM的Node测试及TypeScript检查;`npm run build`验证生产构建。测试数量会随功能增长,以执行结果为准。 +`npm run check`运行生成物一致检查、Cargo原生测试、读取真实WASM的Node测试及TypeScript检查;`npm run build`验证生产输出,`npm run test:e2e`运行Chromium浏览器冒烟测试。测试数量会随功能增长,以执行结果为准。 覆盖七机型、两操控模式、四档风力、八风向及30/60/120fps的数值兼容;普通操纵输入完成山谷与都市八环航线;检查暂停、无效步长、边界、桥上/桥下、屋顶/甲板、高架与旋转箱体碰撞、武器生命周期、分层落点、成绩与语言存储、地图缓存和资源释放。另验证种子场景、完整地形高度与颜色、水纹/流向、鱼群/牛羊/爆炸批量动画,以及扩大地图的道路、泊位、陆水边界与小地图范围。 -浏览器功能验证包括预加载六图、地图与机型切换、昼夜、投弹、语言切换、桌面和手机尺寸的小地图/触屏操作、页面溢出及控制台。浏览器视口验收不等同于实体手机GPU基准;真实无人机性能也不在验证范围内。 +CI通过Playwright的Chromium,在1440×960桌面与390×844手机等效环境执行冒烟测试,检查六图准备、地图/机型/昼夜/设置操作、画面及控制台等。手机视口和触屏模拟不是实体GPU基准,尚未验证iPhone/iPad实机上的Safari;真实无人机性能也不在验证范围内。 + +Linux CI使用软件渲染,操作及截图的超时上限为60秒。触屏飞行测试先验证手势,再暂停飞行后截图留证。本地完成生产构建后,也可运行 `CI=1 PLAYWRIGHT_SOFTWARE_WEBGL=1 npm run test:e2e` 检查同一渲染路径。 ## 美术与许可 -雪峰、松林山谷和蓝天白云全景由内置Image Gen生成1774×887原图,经Real-ESRGAN四倍超分,提供7096×3548高清WebP及3548×1774手机版,按画面宽度和GPU能力选择其中一版。它是超分增强素材,不是原生7K/8K摄影。天空随相机移动,地平线下树林过渡为雾色,河湖反射共用全景。 +雪峰、松林山谷和蓝天白云全景由内置Image Gen生成1774×887原图,经Real-ESRGAN四倍超分,提供7096×3548高清WebP及3548×1774手机版,按画质、主输入、画面宽度和GPU能力选择其中一版。它是超分增强素材,不是原生7K/8K摄影。天空随相机移动,地平线下树林过渡为雾色,河湖反射共用全景。 透明松树、草地和风化岩石纹理也是生成素材,已离线转换为WebP;松树RGBA逐像素保留,草地与岩石保持原尺寸,高清全景没有被压缩优化替换。编码工具仅离线使用,不属于玩家或构建依赖。素材来源、处理命令、许可说明与SHA256详见[素材记录](./docs/asset-licenses.md)及[设计文档](./docs/design.md)。 diff --git a/data/alpine-terrain.json b/data/alpine-terrain.json new file mode 100644 index 0000000..d66f0c2 --- /dev/null +++ b/data/alpine-terrain.json @@ -0,0 +1,633 @@ +{ + "schemaVersion": 1, + "peaks": [ + { + "x": -1250, + "z": -1050, + "height": 665, + "radiusX": 470, + "radiusZ": 510 + }, + { + "x": 1050, + "z": -1450, + "height": 738, + "radiusX": 455, + "radiusZ": 435 + }, + { + "x": 1550, + "z": 650, + "height": 590, + "radiusX": 505, + "radiusZ": 470 + }, + { + "x": -1500, + "z": 1050, + "height": 570, + "radiusX": 490, + "radiusZ": 475 + }, + { + "x": 50, + "z": -2250, + "height": 625, + "radiusX": 450, + "radiusZ": 390 + } + ], + "ridges": [ + { + "ax": -1250, + "az": -1050, + "bx": -1500, + "bz": 1050, + "width": 250, + "height": 300 + }, + { + "ax": -1250, + "az": -1050, + "bx": 50, + "bz": -2250, + "width": 245, + "height": 320 + }, + { + "ax": 50, + "az": -2250, + "bx": 1050, + "bz": -1450, + "width": 230, + "height": 340 + }, + { + "ax": 1050, + "az": -1450, + "bx": 1550, + "bz": 650, + "width": 255, + "height": 320 + } + ], + "massifs": [ + { + "crests": [ + [ + [ + -1490, + -1550, + 319.2, + 250, + 190 + ], + [ + -1400, + -1385, + 485.45, + 260, + 190 + ], + [ + -1345, + -1230, + 438.9, + 255, + 170 + ], + [ + -1195, + -1085, + 665, + 280, + 175 + ], + [ + -1235, + -900, + 518.7, + 265, + 175 + ], + [ + -1095, + -700, + 339.15, + 230, + 170 + ] + ], + [ + [ + -1345, + -1230, + 438.9, + 180, + 150 + ], + [ + -1610, + -1120, + 432.25, + 180, + 150 + ], + [ + -1700, + -870, + 252.7, + 160, + 130 + ] + ], + [ + [ + -1235, + -900, + 518.7, + 150, + 160 + ], + [ + -990, + -870, + 412.3, + 160, + 150 + ], + [ + -950, + -635, + 186.2, + 135, + 120 + ] + ] + ], + "cirques": [ + [ + -1360, + -955, + 170, + 190, + 135 + ], + [ + -1020, + -1250, + 130, + 175, + 90 + ] + ] + }, + { + "crests": [ + [ + [ + 630, + -1600, + 369, + 160, + 280 + ], + [ + 795, + -1505, + 583.02, + 170, + 285 + ], + [ + 940, + -1580, + 472.32, + 180, + 275 + ], + [ + 1120, + -1475, + 738, + 165, + 290 + ], + [ + 1245, + -1345, + 553.5, + 175, + 280 + ], + [ + 1440, + -1260, + 369, + 150, + 250 + ] + ], + [ + [ + 940, + -1580, + 472.32, + 150, + 150 + ], + [ + 895, + -1320, + 464.94, + 160, + 150 + ], + [ + 750, + -1140, + 243.54, + 130, + 130 + ] + ], + [ + [ + 1245, + -1345, + 553.5, + 140, + 160 + ], + [ + 1335, + -1125, + 472.32, + 145, + 155 + ], + [ + 1520, + -1060, + 206.64, + 125, + 130 + ] + ] + ], + "cirques": [ + [ + 920, + -1280, + 170, + 180, + 170 + ], + [ + 1325, + -1525, + 130, + 180, + 120 + ] + ] + }, + { + "crests": [ + [ + [ + 1210, + 310, + 271.4, + 230, + 150 + ], + [ + 1370, + 400, + 477.9, + 245, + 160 + ], + [ + 1475, + 580, + 407.1, + 230, + 155 + ], + [ + 1630, + 700, + 590, + 255, + 165 + ], + [ + 1660, + 885, + 424.8, + 230, + 150 + ], + [ + 1835, + 1060, + 212.4, + 190, + 145 + ] + ], + [ + [ + 1475, + 580, + 407.1, + 150, + 155 + ], + [ + 1260, + 750, + 395.3, + 165, + 145 + ], + [ + 1170, + 950, + 182.9, + 125, + 130 + ] + ], + [ + [ + 1630, + 700, + 590, + 145, + 160 + ], + [ + 1860, + 580, + 430.7, + 155, + 140 + ], + [ + 1990, + 690, + 206.5, + 130, + 120 + ] + ] + ], + "cirques": [ + [ + 1430, + 780, + 170, + 190, + 140 + ], + [ + 1820, + 770, + 150, + 140, + 100 + ] + ] + }, + { + "crests": [ + [ + [ + -1860, + 750, + 210.9, + 175, + 260 + ], + [ + -1720, + 870, + 404.7, + 190, + 275 + ], + [ + -1580, + 970, + 513, + 185, + 280 + ], + [ + -1400, + 1070, + 433.2, + 180, + 270 + ], + [ + -1320, + 1255, + 570, + 190, + 280 + ], + [ + -1110, + 1310, + 239.4, + 160, + 230 + ] + ], + [ + [ + -1580, + 970, + 513, + 155, + 155 + ], + [ + -1735, + 1170, + 370.5, + 155, + 145 + ], + [ + -1775, + 1440, + 171, + 130, + 125 + ] + ], + [ + [ + -1400, + 1070, + 433.2, + 140, + 155 + ], + [ + -1320, + 850, + 359.1, + 150, + 145 + ], + [ + -1110, + 810, + 171, + 130, + 130 + ] + ] + ], + "cirques": [ + [ + -1400, + 910, + 170, + 170, + 140 + ], + [ + -1680, + 1280, + 160, + 160, + 105 + ] + ] + }, + { + "crests": [ + [ + [ + -450, + -2190, + 225, + 150, + 240 + ], + [ + -260, + -2265, + 468.75, + 160, + 250 + ], + [ + -110, + -2175, + 406.25, + 165, + 260 + ], + [ + 75, + -2290, + 625, + 175, + 270 + ], + [ + 220, + -2240, + 487.5, + 180, + 240 + ], + [ + 405, + -2370, + 568.75, + 165, + 230 + ], + [ + 560, + -2335, + 237.5, + 150, + 210 + ] + ], + [ + [ + -110, + -2175, + 406.25, + 150, + 145 + ], + [ + -125, + -1980, + 375, + 160, + 140 + ], + [ + -280, + -1895, + 162.5, + 125, + 120 + ] + ], + [ + [ + 220, + -2240, + 487.5, + 145, + 145 + ], + [ + 350, + -2045, + 412.5, + 150, + 145 + ], + [ + 510, + -1950, + 187.5, + 125, + 130 + ] + ] + ], + "cirques": [ + [ + -90, + -2050, + 190, + 150, + 130 + ], + [ + 330, + -2160, + 140, + 160, + 110 + ] + ] + } + ] +} diff --git a/e2e/game.spec.ts b/e2e/game.spec.ts new file mode 100644 index 0000000..669e706 --- /dev/null +++ b/e2e/game.spec.ts @@ -0,0 +1,209 @@ +import { test as base, expect } from '@playwright/test'; +import type { Page } from '@playwright/test'; + +const test = base.extend<{ appErrors: string[] }>({ + appErrors: [async ({ page, context }, use) => { + const errors: string[] = []; + page.on('pageerror', error => { errors.push(error.message); console.error('[browser exception]', error.message); }); + page.on('console', message => { + if (message.type() === 'error') { errors.push(message.text()); console.error('[browser error]', message.text()); } + }); + // The game itself is local. Fonts must not make CI depend on third-party network access. + await context.route('https://fonts.googleapis.com/**', route => route.fulfill({ contentType: 'text/css', body: '' })); + await context.addInitScript(() => { + try { if (!localStorage.getItem('aeroflow-language')) localStorage.setItem('aeroflow-language', 'en'); } catch { /* Storage fallback is tested separately. */ } + }); + await use(errors); + expect(errors, 'no JavaScript errors or WebGL shader compilation errors').toEqual([]); + }, { auto: true }], +}); + +const canvas = (page: Page) => page.locator('canvas[data-flight-core="rust-wasm"]'); +async function ready(page: Page) { + await expect(canvas(page)).toHaveAttribute('data-preloaded-maps', 'valley,factory,harbor,desert,downtown,mountains', { timeout: 100_000 }); + await expect(canvas(page)).toHaveAttribute('data-graphics-state', 'ready'); + await expect(page.locator('.scene-loading')).toHaveCount(0); +} +const number = async (page: Page, id: string) => Number(await page.getByTestId(id).textContent()); +const preferenceKey = 'aeroflow:preferences'; + +test('all six maps render, day/night switches, hangar opens, and keyboard flight pauses and resumes', async ({ page }, info) => { + await page.goto('/'); await ready(page); + await expect(page).toHaveTitle('AEROFLOW — FPV drone playground'); + for (const [id, name] of [['valley', 'Pine Valley'], ['factory', 'Iron Works'], ['harbor', 'Sea Port'], + ['desert', 'Red Dune Desert'], ['downtown', 'City Centre'], ['mountains', 'Alpine Ridges']]) { + await page.getByLabel(`Switch to ${name}`, { exact: true }).click(); + await expect(canvas(page)).toHaveAttribute('data-map-id', id); + await page.getByLabel('Switch to night', { exact: true }).click(); + await expect(page.getByLabel('Switch to day', { exact: true })).toBeVisible(); + await page.getByLabel('Switch to day', { exact: true }).click(); + } + await info.attach('alpine-day', { body: await canvas(page).screenshot(), contentType: 'image/png' }); + await page.locator('.drone-hangar-toggle').click(); + const hangar = page.getByRole('dialog'); + await expect(hangar).toBeVisible(); + await expect(hangar.locator('canvas')).toBeVisible(); + await hangar.getByRole('button', { name: 'Close hangar', exact: true }).click(); + await expect(hangar).toHaveCount(0); + await page.getByRole('button', { name: 'Free flight', exact: true }).click(); + await page.getByRole('button', { name: 'Start flight', exact: true }).click(); + const startAltitude = await number(page, 'altitude'); + await page.keyboard.down('Space'); + try { await expect.poll(() => number(page, 'altitude')).toBeGreaterThan(startAltitude + 3); } + finally { await page.keyboard.up('Space'); } + await page.keyboard.press('Escape'); + await expect(page.locator('.pause-panel')).toBeVisible(); + await page.locator('.pause-panel').getByRole('button', { name: 'Resume flight', exact: true }).click(); + await expect(page.locator('.pause-panel')).toHaveCount(0); + await page.keyboard.press('Escape'); + await page.locator('.pause-panel').getByRole('button', { name: 'Return to start', exact: true }).click(); + await expect(page.getByTestId('timer')).toHaveText('00:00.00'); +}); + +test('preferences survive a reload, quality really applies, build identity agrees, and reset retains personal records', async ({ page, context, request }, info) => { + await context.addInitScript(() => { + const Original = window.AudioContext; + Object.defineProperty(window, '__audioContextsCreated', { value: 0, writable: true }); + window.AudioContext = class extends Original { + constructor(options?: AudioContextOptions) { + super(options); + const owner = window as unknown as { __audioContextsCreated: number }; + owner.__audioContextsCreated++; + } + }; + }); + await page.goto('/'); await ready(page); + await page.getByLabel('Switch to City Centre', { exact: true }).click(); + await page.getByRole('button', { name: 'Free flight', exact: true }).click(); + await page.getByLabel('Switch to night', { exact: true }).click(); + await page.locator('.view-toggle').click(); + await page.getByRole('button', { name: 'Open settings', exact: true }).click(); + const settings = page.getByRole('dialog', { name: 'Flight preferences', exact: true }); + const version = await (await request.get('/version.json')).json(); + await expect(settings.getByTestId('build-info')).toContainText(version.buildId); + expect(version.sourceFingerprint).toMatch(/^[a-f0-9]{64}$/); + await settings.getByRole('combobox', { name: 'Graphics quality', exact: true }).selectOption('low'); + await settings.getByLabel('Control sensitivity', { exact: true }).press('End'); + await settings.getByLabel('Hold-to-accelerate time', { exact: true }).press('Home'); + await settings.getByLabel('Reverse vertical dragging', { exact: true }).check(); + await settings.getByLabel('Game sound', { exact: true }).check(); + await settings.getByRole('button', { name: 'Apply settings', exact: true }).click(); + await ready(page); + await expect(canvas(page)).toHaveAttribute('data-quality-preset', 'low'); + const budget = JSON.parse((await canvas(page).getAttribute('data-graphics-budget'))!); + expect(budget.panoramaResolution).toBe(3548); expect(budget.shadowMapSize).toBe(0); + await page.getByLabel('Switch to Alpine Ridges', { exact: true }).click(); + await expect(canvas(page)).toHaveAttribute('data-map-id', 'mountains'); + await info.attach('alpine-low-quality', { body: await canvas(page).screenshot(), contentType: 'image/png' }); + await page.getByLabel('Switch to City Centre', { exact: true }).click(); + const saved = await page.evaluate(key => JSON.parse(localStorage.getItem(key)!), preferenceKey); + expect(saved).toMatchObject({ version: 1, mapId: 'downtown', mode: 'free', night: true, cameraMode: 'bomb', + sound: true, qualityPreset: 'low', touch: { sensitivity: 2, accelerationMs: 500, invertVertical: true } }); + for (const transient of ['position', 'ammo', 'elapsed', 'checkpoint']) expect(saved).not.toHaveProperty(transient); + await page.reload(); await ready(page); + await expect(canvas(page)).toHaveAttribute('data-map-id', 'downtown'); + await expect(canvas(page)).toHaveAttribute('data-quality-preset', 'low'); + await expect(page.getByLabel('Switch to day', { exact: true })).toBeVisible(); + await expect(page.getByTestId('timer')).toHaveText('00:00.00'); + expect(await page.evaluate(() => (window as unknown as { __audioContextsCreated: number }).__audioContextsCreated)).toBe(0); + await page.getByRole('button', { name: 'Open settings', exact: true }).click(); + await expect(settings.getByLabel('Control sensitivity', { exact: true })).toHaveValue('2'); + await expect(settings.getByLabel('Hold-to-accelerate time', { exact: true })).toHaveValue('500'); + await expect(settings.getByLabel('Reverse vertical dragging', { exact: true })).toBeChecked(); + await info.attach('preferences', { body: await page.screenshot(), contentType: 'image/png' }); + await page.evaluate(() => localStorage.setItem('aeroflow:v5:best:valley:freestyle:assisted:calm', '42')); + await settings.getByRole('button', { name: 'Reset all preferences', exact: true }).click(); + await ready(page); + await expect(canvas(page)).toHaveAttribute('data-map-id', 'valley'); + await expect(canvas(page)).toHaveAttribute('data-quality-preset', 'auto'); + expect(await page.evaluate(() => localStorage.getItem('aeroflow:v5:best:valley:freestyle:assisted:calm'))).toBe('42'); +}); + +test('graphics context loss retains the flight and recovers without automatically resuming', async ({ page }) => { + await page.goto('/'); await ready(page); + await page.getByRole('button', { name: 'Free flight', exact: true }).click(); + await page.getByRole('button', { name: 'Start flight', exact: true }).click(); + await expect(page.getByTestId('timer')).not.toHaveText('00:00.00'); + const extension = await canvas(page).evaluateHandle(element => { + const gl = (element as HTMLCanvasElement).getContext('webgl2'); + const extension = gl?.getExtension('WEBGL_lose_context'); + if (!extension) throw new Error('This browser must expose WEBGL_lose_context for the recovery test'); + return extension; + }); + await extension.evaluate(value => value.loseContext()); + await expect(canvas(page)).toHaveAttribute('data-graphics-state', 'lost'); + const pausedTime = await page.getByTestId('timer').textContent(); + await extension.evaluate(value => value.restoreContext()); + await expect(canvas(page)).toHaveAttribute('data-graphics-state', 'ready', { timeout: 60_000 }); + await expect(page.locator('.pause-panel')).toBeVisible(); + await expect(page.getByTestId('timer')).toHaveText(pausedTime!); + await page.locator('.pause-panel').getByRole('button', { name: 'Resume flight', exact: true }).click(); + await expect(page.locator('.pause-panel')).toHaveCount(0); + await extension.dispose(); +}); + +test('all graphics presets render alpine shaders after rebuilding the six-map cache', async ({ page }, info) => { + test.skip(info.project.name !== 'chromium-desktop', 'Desktop covers the explicit high-memory override'); + await page.goto('/'); await ready(page); + await page.getByLabel('Switch to Alpine Ridges', { exact: true }).click(); + for (const preset of ['low', 'medium', 'high']) { + await page.getByRole('button', { name: 'Open settings', exact: true }).click(); + const settings = page.getByRole('dialog', { name: 'Flight preferences', exact: true }); + await settings.getByRole('combobox', { name: 'Graphics quality', exact: true }).selectOption(preset); + await settings.getByRole('button', { name: 'Apply settings', exact: true }).click(); + await expect(canvas(page)).toHaveAttribute('data-quality-preset', preset); + await ready(page); + await expect(canvas(page)).toHaveAttribute('data-map-id', 'mountains'); + const budget = JSON.parse((await canvas(page).getAttribute('data-graphics-budget'))!); + expect(budget.alpineDetail).toBe(preset); + await info.attach(`alpine-${preset}`, { body: await canvas(page).screenshot(), contentType: 'image/png' }); + } +}); + +test('malformed or unavailable preference storage never prevents map preparation', async ({ page, context }) => { + await context.addInitScript(() => { + localStorage.setItem('aeroflow:preferences', '{broken'); + const original = Storage.prototype.setItem; + Storage.prototype.setItem = function (key: string, value: string) { + if (key === 'aeroflow:preferences') throw new DOMException('Storage is disabled', 'QuotaExceededError'); + return original.call(this, key, value); + }; + }); + await page.goto('/'); await ready(page); + await expect(canvas(page)).toHaveAttribute('data-map-id', 'valley'); + await page.getByRole('button', { name: 'Open settings', exact: true }).click(); + await expect(page.getByRole('dialog')).toContainText('This browser cannot save settings.'); + await page.keyboard.press('Escape'); + await expect(page.getByRole('dialog')).toHaveCount(0); +}); + +test('landscape touch devices keep the mobile texture budget and gestures release their axes', async ({ page, context }, info) => { + test.skip(info.project.name !== 'chromium-touch', 'Requires a coarse primary pointer and real touch events'); + await page.setViewportSize({ width: 844, height: 390 }); + await page.goto('/'); await ready(page); + const budget = JSON.parse((await canvas(page).getAttribute('data-graphics-budget'))!); + expect(budget.panoramaResolution).toBe(3548); + expect(budget.maxPixelRatio).toBeLessThanOrEqual(1.25); + await page.setViewportSize({ width: 390, height: 844 }); + await page.getByRole('button', { name: 'Free flight', exact: true }).click(); + await page.getByRole('button', { name: 'Start flight', exact: true }).click(); + const controls = page.locator('.touch-gesture-controls'); + await expect(controls).toBeVisible(); + const bounds = (await controls.boundingBox())!; + const point = { x: bounds.x + bounds.width * 0.35, y: bounds.y + bounds.height * 0.58, id: 1 }; + const cdp = await context.newCDPSession(page); + await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [point] }); + try { + await expect(page.locator('.touch-gesture-flight')).toHaveCount(1); + await expect.poll(() => number(page, 'speed'), { timeout: 20_000 }).toBeGreaterThan(20); + } finally { await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }); } + await expect(page.locator('.touch-gesture-flight')).toHaveCount(0); + await expect.poll(() => number(page, 'speed'), { timeout: 20_000 }).toBeLessThan(15); + expect(await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth)).toBeLessThanOrEqual(1); + await cdp.detach(); + // The gesture assertions run in flight. Capture the evidence after pausing so + // SwiftShader's continuous flight frames do not compete with the screenshot. + await page.keyboard.press('Escape'); + await expect(page.locator('.pause-panel')).toBeVisible(); + await info.attach('touch-flight-paused', { body: await page.screenshot(), contentType: 'image/png' }); +}); diff --git a/package-lock.json b/package-lock.json index 3d2ba66..cee6500 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,12 +14,14 @@ "three": "^0.183.0" }, "devDependencies": { + "@playwright/test": "1.64.1", + "@types/node": "^24.19.2", "@types/react": "^19.2.0", "@types/react-dom": "^19.2.0", "@types/three": "^0.183.0", "@vitejs/plugin-react": "^5.1.4", "typescript": "^5.9.3", - "vite": "^7.3.1" + "vite": "^7.3.7" } }, "node_modules/@babel/code-frame": { @@ -823,6 +825,22 @@ "node": "^22.20 || ^24.12 || >=25" } }, + "node_modules/@playwright/test": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz", + "integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.64.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/@rolldown/pluginutils": { "version": "1.0.0-rc.3", "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.3.tgz", @@ -1278,6 +1296,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/node": { + "version": "24.19.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz", + "integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": ">=7.24.0 <7.24.7" + } + }, "node_modules/@types/react": { "version": "19.3.0", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", @@ -1680,6 +1708,35 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/playwright": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz", + "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.64.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", + "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/postcss": { "version": "8.5.28", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", @@ -1849,6 +1906,13 @@ "node": ">=14.17" } }, + "node_modules/undici-types": { + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", + "dev": true, + "license": "MIT" + }, "node_modules/update-browserslist-db": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.3.tgz", @@ -1881,9 +1945,9 @@ } }, "node_modules/vite": { - "version": "7.3.6", - "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.6.tgz", - "integrity": "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==", + "version": "7.3.7", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.7.tgz", + "integrity": "sha512-AHEzTORMbi7/7aXp7w7KZ5+DCUdSeLsJz0grY8xHpc9DHdYb0vQu6DqJfm2tOw3gDExNgPgnJTXxM6syYFHaCA==", "dev": true, "license": "MIT", "dependencies": { diff --git a/package.json b/package.json index 9f16909..d68100d 100644 --- a/package.json +++ b/package.json @@ -9,20 +9,25 @@ "build": "npm run build:wasm && tsc -b && vite build", "preview": "vite preview --host 127.0.0.1", "test": "npm run build:wasm && cargo test --locked --manifest-path rust/flight-core/Cargo.toml && node --experimental-strip-types --test tests/*.test.ts", - "check": "npm test && tsc -b" + "check:generated": "node scripts/generate-alpine-data.mjs --check", + "check": "npm run check:generated && npm test && tsc -b && tsc -p tsconfig.e2e.json", + "test:e2e": "playwright test", + "test:e2e:install": "playwright install chromium" }, "dependencies": { + "lucide-react": "^0.577.0", "react": "^19.2.0", "react-dom": "^19.2.0", - "three": "^0.183.0", - "lucide-react": "^0.577.0" + "three": "^0.183.0" }, "devDependencies": { + "@playwright/test": "1.64.1", + "@types/node": "^24.19.2", "@types/react": "^19.2.0", "@types/react-dom": "^19.2.0", "@types/three": "^0.183.0", "@vitejs/plugin-react": "^5.1.4", "typescript": "^5.9.3", - "vite": "^7.3.1" + "vite": "^7.3.7" } } diff --git a/playwright.config.ts b/playwright.config.ts new file mode 100644 index 0000000..74beeb7 --- /dev/null +++ b/playwright.config.ts @@ -0,0 +1,38 @@ +import { defineConfig } from '@playwright/test'; + +const softwareWebGL = process.platform === 'linux' || process.env.PLAYWRIGHT_SOFTWARE_WEBGL === '1'; + +export default defineConfig({ + testDir: './e2e', + timeout: process.env.CI ? 360_000 : 180_000, + expect: { timeout: 20_000 }, + fullyParallel: false, + workers: 1, + retries: process.env.CI ? 1 : 0, + forbidOnly: !!process.env.CI, + outputDir: 'test-results', + reporter: [['list'], ['html', { open: 'never' }]], + use: { + baseURL: 'http://127.0.0.1:4183', + // CI uses CPU rendering; compositor-backed clicks and captures can exceed 15s. + actionTimeout: process.env.CI ? 60_000 : 15_000, + navigationTimeout: 30_000, + locale: 'en-US', + trace: process.env.CI ? 'on-first-retry' : 'retain-on-failure', + screenshot: 'only-on-failure', + channel: 'chromium', + launchOptions: { args: softwareWebGL + ? ['--enable-unsafe-swiftshader', '--use-angle=swiftshader', '--disable-dev-shm-usage'] : [] }, + }, + projects: [ + { name: 'chromium-desktop', use: { browserName: 'chromium', viewport: { width: 1440, height: 960 } } }, + { name: 'chromium-touch', use: { browserName: 'chromium', viewport: { width: 390, height: 844 }, + deviceScaleFactor: 3, isMobile: true, hasTouch: true } }, + ], + webServer: { + command: 'npm run preview -- --port 4183 --strictPort', + url: 'http://127.0.0.1:4183', + timeout: 30_000, + reuseExistingServer: !process.env.CI, + }, +}); diff --git a/rust/flight-core/src/alpine_data.rs b/rust/flight-core/src/alpine_data.rs new file mode 100644 index 0000000..d296702 --- /dev/null +++ b/rust/flight-core/src/alpine_data.rs @@ -0,0 +1,154 @@ +// @generated from data/alpine-terrain.json; do not edit by hand. +// Regenerate with: node scripts/generate-alpine-data.mjs +// Runtime terrain mathematics stays independently implemented in world.rs. +pub(crate) struct AlpineMassif { + pub(crate) bounds: (f64, f64, f64, f64), + pub(crate) crests: &'static [&'static [(f64, f64, f64, f64, f64)]], + pub(crate) cirques: &'static [(f64, f64, f64, f64, f64)], +} +#[rustfmt::skip] +pub(crate) const ALPINE_MASSIFS: [AlpineMassif; 5] = [ + AlpineMassif { + bounds: (-2033.6, -616.4, -1883.6, -301.4), + crests: &[ + &[ + (-1490.0, -1550.0, 319.2, 250.0, 190.0), + (-1400.0, -1385.0, 485.45, 260.0, 190.0), + (-1345.0, -1230.0, 438.9, 255.0, 170.0), + (-1195.0, -1085.0, 665.0, 280.0, 175.0), + (-1235.0, -900.0, 518.7, 265.0, 175.0), + (-1095.0, -700.0, 339.15, 230.0, 170.0), + ], + &[ + (-1345.0, -1230.0, 438.9, 180.0, 150.0), + (-1610.0, -1120.0, 432.25, 180.0, 150.0), + (-1700.0, -870.0, 252.7, 160.0, 130.0), + ], + &[ + (-1235.0, -900.0, 518.7, 150.0, 160.0), + (-990.0, -870.0, 412.3, 160.0, 150.0), + (-950.0, -635.0, 186.2, 135.0, 120.0), + ], + ], + cirques: &[ + (-1360.0, -955.0, 170.0, 190.0, 135.0), + (-1020.0, -1250.0, 130.0, 175.0, 90.0), + ], + }, + AlpineMassif { + bounds: (285.2, 1864.8, -1944.8, -715.2), + crests: &[ + &[ + (630.0, -1600.0, 369.0, 160.0, 280.0), + (795.0, -1505.0, 583.02, 170.0, 285.0), + (940.0, -1580.0, 472.32, 180.0, 275.0), + (1120.0, -1475.0, 738.0, 165.0, 290.0), + (1245.0, -1345.0, 553.5, 175.0, 280.0), + (1440.0, -1260.0, 369.0, 150.0, 250.0), + ], + &[ + (940.0, -1580.0, 472.32, 150.0, 150.0), + (895.0, -1320.0, 464.94, 160.0, 150.0), + (750.0, -1140.0, 243.54, 130.0, 130.0), + ], + &[ + (1245.0, -1345.0, 553.5, 140.0, 160.0), + (1335.0, -1125.0, 472.32, 145.0, 155.0), + (1520.0, -1060.0, 206.64, 125.0, 130.0), + ], + ], + cirques: &[ + (920.0, -1280.0, 170.0, 180.0, 170.0), + (1325.0, -1525.0, 130.0, 180.0, 120.0), + ], + }, + AlpineMassif { + bounds: (864.4, 2295.6, 4.4, 1365.6), + crests: &[ + &[ + (1210.0, 310.0, 271.4, 230.0, 150.0), + (1370.0, 400.0, 477.9, 245.0, 160.0), + (1475.0, 580.0, 407.1, 230.0, 155.0), + (1630.0, 700.0, 590.0, 255.0, 165.0), + (1660.0, 885.0, 424.8, 230.0, 150.0), + (1835.0, 1060.0, 212.4, 190.0, 145.0), + ], + &[ + (1475.0, 580.0, 407.1, 150.0, 155.0), + (1260.0, 750.0, 395.3, 165.0, 145.0), + (1170.0, 950.0, 182.9, 125.0, 130.0), + ], + &[ + (1630.0, 700.0, 590.0, 145.0, 160.0), + (1860.0, 580.0, 430.7, 155.0, 140.0), + (1990.0, 690.0, 206.5, 130.0, 120.0), + ], + ], + cirques: &[ + (1430.0, 780.0, 170.0, 190.0, 140.0), + (1820.0, 770.0, 150.0, 140.0, 100.0), + ], + }, + AlpineMassif { + bounds: (-2193.6, -776.4, 416.4, 1773.6), + crests: &[ + &[ + (-1860.0, 750.0, 210.9, 175.0, 260.0), + (-1720.0, 870.0, 404.7, 190.0, 275.0), + (-1580.0, 970.0, 513.0, 185.0, 280.0), + (-1400.0, 1070.0, 433.2, 180.0, 270.0), + (-1320.0, 1255.0, 570.0, 190.0, 280.0), + (-1110.0, 1310.0, 239.4, 160.0, 230.0), + ], + &[ + (-1580.0, 970.0, 513.0, 155.0, 155.0), + (-1735.0, 1170.0, 370.5, 155.0, 145.0), + (-1775.0, 1440.0, 171.0, 130.0, 125.0), + ], + &[ + (-1400.0, 1070.0, 433.2, 140.0, 155.0), + (-1320.0, 850.0, 359.1, 150.0, 145.0), + (-1110.0, 810.0, 171.0, 130.0, 130.0), + ], + ], + cirques: &[ + (-1400.0, 910.0, 170.0, 170.0, 140.0), + (-1680.0, 1280.0, 160.0, 160.0, 105.0), + ], + }, + AlpineMassif { + bounds: (-772.4, 882.4, -2692.4, -1572.6), + crests: &[ + &[ + (-450.0, -2190.0, 225.0, 150.0, 240.0), + (-260.0, -2265.0, 468.75, 160.0, 250.0), + (-110.0, -2175.0, 406.25, 165.0, 260.0), + (75.0, -2290.0, 625.0, 175.0, 270.0), + (220.0, -2240.0, 487.5, 180.0, 240.0), + (405.0, -2370.0, 568.75, 165.0, 230.0), + (560.0, -2335.0, 237.5, 150.0, 210.0), + ], + &[ + (-110.0, -2175.0, 406.25, 150.0, 145.0), + (-125.0, -1980.0, 375.0, 160.0, 140.0), + (-280.0, -1895.0, 162.5, 125.0, 120.0), + ], + &[ + (220.0, -2240.0, 487.5, 145.0, 145.0), + (350.0, -2045.0, 412.5, 150.0, 145.0), + (510.0, -1950.0, 187.5, 125.0, 130.0), + ], + ], + cirques: &[ + (-90.0, -2050.0, 190.0, 150.0, 130.0), + (330.0, -2160.0, 140.0, 160.0, 110.0), + ], + }, +]; +#[rustfmt::skip] +pub(crate) const MOUNTAIN_RIDGES: [(f64, f64, f64, f64, f64, f64); 4] = [ + (-1250.0, -1050.0, -1500.0, 1050.0, 250.0, 300.0), + (-1250.0, -1050.0, 50.0, -2250.0, 245.0, 320.0), + (50.0, -2250.0, 1050.0, -1450.0, 230.0, 340.0), + (1050.0, -1450.0, 1550.0, 650.0, 255.0, 320.0), +]; diff --git a/rust/flight-core/src/lib.rs b/rust/flight-core/src/lib.rs index 8ad954b..da66785 100644 --- a/rust/flight-core/src/lib.rs +++ b/rust/flight-core/src/lib.rs @@ -4,6 +4,7 @@ //! turns left. This deliberately preserves the existing arcade flight model. mod abi; +mod alpine_data; pub mod effects; mod effects_abi; pub mod flight; diff --git a/rust/flight-core/src/world.rs b/rust/flight-core/src/world.rs index 31705b7..1349717 100644 --- a/rust/flight-core/src/world.rs +++ b/rust/flight-core/src/world.rs @@ -1,6 +1,7 @@ //! Numeric map queries. Scene-authored geometry is uploaded once; all runtime //! surface selection, water contours and obstacle broad/narrow phases are native. +use crate::alpine_data::{ALPINE_MASSIFS, MOUNTAIN_RIDGES}; use crate::flight::Vec3; use std::collections::HashMap; @@ -264,27 +265,6 @@ const DESERT_MESAS: [(f64, f64, f64, f64, f64); 4] = [ (1550.0, 850.0, 120.0, 340.0, 240.0), (-1550.0, 1250.0, 150.0, 300.0, 330.0), ]; -const MOUNTAIN_PEAKS: [(f64, f64, f64, f64, f64); 5] = [ - (-1250.0, -1050.0, 665.0, 470.0, 510.0), - (1050.0, -1450.0, 738.0, 455.0, 435.0), - (1550.0, 650.0, 590.0, 505.0, 470.0), - (-1500.0, 1050.0, 570.0, 490.0, 475.0), - (50.0, -2250.0, 625.0, 450.0, 390.0), -]; -// Fixed orientations are precomputed to keep terrain batches and flight queries cheap. -const MOUNTAIN_ORIENTATIONS: [(f64, f64); 5] = [ - (0.97133797485202955, -0.23770262642713458), - (0.93937271284737889, 0.34289780745545134), - (0.85252452205950568, -0.52268722893065922), - (0.98006657784124163, 0.19866933079506122), - (0.99500416527802582, -0.099833416646828155), -]; -const MOUNTAIN_RIDGES: [(f64, f64, f64, f64, f64, f64); 4] = [ - (-1250.0, -1050.0, -1500.0, 1050.0, 250.0, 300.0), - (-1250.0, -1050.0, 50.0, -2250.0, 245.0, 320.0), - (50.0, -2250.0, 1050.0, -1450.0, 230.0, 340.0), - (1050.0, -1450.0, 1550.0, 650.0, 255.0, 320.0), -]; fn exploration_peaks(peaks: &[(f64, f64, f64, f64, f64)], x: f64, z: f64) -> f64 { peaks .iter() @@ -322,49 +302,63 @@ fn mountains_height(x: f64, z: f64) -> f64 { let foothills = 18.0 + (x * 0.0034 + (z * 0.002).sin()).sin() * 9.0 + (z * 0.0045 - x * 0.001).sin() * 7.0; let mut height: f64 = 0.0; - for (index, &(cx, cz, peak_height, rx, rz)) in MOUNTAIN_PEAKS.iter().enumerate() { - let (cosine, sine) = MOUNTAIN_ORIENTATIONS[index]; - let dx = x - cx; - let dz = z - cz; - let mut u = (dx * cosine + dz * sine) / rx; - let mut v = (-dx * sine + dz * cosine) / rz; - let radius = u.hypot(v); - let taper = radius.min(1.0); - let phase = index as f64; - u += (z * 0.004 + phase * 1.7).sin() * (x * 0.0023 + phase).sin() * 0.055 * taper; - v += (x * 0.0041 + phase * 2.1).sin() * 0.04 * taper; - let angle = v.atan2(u); - let lobes = 1.0 - + 0.14 * (angle * 3.0 + phase * 1.7).sin() - + 0.07 * (angle * 7.0 - phase * 1.3).sin(); - let polygon = (u.abs() + v.abs() * 0.32).max(v.abs() * 1.02 + u.abs() * 0.28); - let facets = (u.hypot(v) * 0.7 + polygon * 0.3) / lobes; - let crown = (1.0 - facets).max(0.0).powf(0.86); - let skirt = (-(u * u + v * v) * 1.65).exp(); - let gullies = if facets >= 1.0 { - 1.0 - } else { - 1.0 - 0.12 - * (angle * 5.0 + phase * 1.7 + (angle * 2.0 + phase).sin() * 0.6 + radius * 0.7) - .sin() - .abs() - * (std::f64::consts::PI * facets).sin() - }; - let mut mass = peak_height * (0.86 * crown + 0.14 * skirt) * gullies; - if crown > 0.0 { - let shell = 4.0 * crown * (1.0 - crown); - let coarse = alpine_noise(dx / 180.0, dz / 180.0, index as u32 + 11); - let medium = alpine_noise(dx / 70.0, dz / 70.0, index as u32 + 37); - let fine = alpine_noise(dx / 28.0, dz / 28.0, index as u32 + 71); - let channel = (1.0 - - (angle * 3.0 + (angle * 2.0 + phase).sin() * 0.8 + radius * 0.9) - .sin() - .abs()) - .powi(3); - mass += peak_height - * shell - * (0.25 * (coarse - 0.5) + 0.11 * (medium - 0.5) + 0.035 * (fine - 0.5) - - 0.19 * channel); + for (index, fold) in ALPINE_MASSIFS.iter().enumerate() { + // Bounds are derived once from the crest nodes and maximum shoulder width. + let (min_x, max_x, min_z, max_z) = fold.bounds; + if x < min_x || x > max_x || z < min_z || z > max_z { + continue; + } + let coarse = alpine_noise(x / 155.0, z / 155.0, index as u32 + 11); + let fracture = (alpine_noise(x / 95.0, z / 95.0, index as u32 + 37) - 0.5) * 0.12 + + (alpine_noise(x / 42.0, z / 42.0, index as u32 + 71) - 0.5) * 0.04; + let mut mass: f64 = 0.0; + for crest_nodes in fold.crests { + for pair in crest_nodes.windows(2) { + let (ax, az, ah, al, ar) = pair[0]; + let (bx, bz, bh, bl, br) = pair[1]; + let dx = bx - ax; + let dz = bz - az; + let length_squared = dx * dx + dz * dz; + let length = length_squared.sqrt(); + let px = x - ax; + let pz = z - az; + let t = ((px * dx + pz * dz) / length_squared).clamp(0.0, 1.0); + let bend = 4.0 * t * (1.0 - t) * (coarse - 0.5) * 38.0; + let distance = + (px - dx * t + dz / length * bend).hypot(pz - dz * t - dx / length * bend); + let signed_normal = (dx * pz - dz * px) / length - bend; + let direction = (0.5 + 0.5 * signed_normal / distance.max(32.0)).clamp(0.0, 1.0); + let blend = direction * direction * (3.0 - 2.0 * direction); + let left = al + (bl - al) * t; + let right = ar + (br - ar) * t; + let width = (right + (left - right) * blend) * (0.88 + coarse * 0.24); + let r = distance / width; + if r >= 1.0 { + continue; + } + let inner = 0.16 + coarse * 0.04; + let outer = 0.58 + coarse * 0.04; + let profile = if r < inner { + 1.0 - 0.12 * r / inner + } else if r < outer { + let t = (r - inner) / (outer - inner); + let eased = t * 0.45 + t * t * (3.0 - 2.0 * t) * 0.55; + 0.88 - eased * 0.62 + } else { + 0.26 * ((1.0 - r) / (1.0 - outer)).powf(1.6) + }; + let crest = ah + (bh - ah) * t; + let broken_crest = crest + 4.0 * t * (1.0 - t) * (coarse - 0.5) * 36.0; + mass = mass.max( + broken_crest * profile + crest * 4.0 * profile * (1.0 - profile) * fracture, + ); + } + } + for &(cx, cz, rx, rz, depth) in fold.cirques { + let u = (x - cx) / rx; + let v = (z - cz) / rz; + let bowl = (1.0 - u * u - v * v).max(0.0); + mass -= depth * bowl.powf(1.4); } height = height.max(mass); } diff --git a/rust/flight-core/tests/world.rs b/rust/flight-core/tests/world.rs index 360c019..60a26be 100644 --- a/rust/flight-core/tests/world.rs +++ b/rust/flight-core/tests/world.rs @@ -237,22 +237,44 @@ fn desert_dunes_mountain_peaks_and_downtown_have_distinct_ground_profiles() { assert!(mesa > dune + 100.0); world.set_map_kind(5); let foothill = world.ground_height(0.0, 80.0); - let summit = world.ground_height(1050.0, -1450.0); + let summit = world.ground_height(1120.0, -1475.0); assert!(summit > foothill + 500.0 && summit < 780.0); world.set_map_kind(4); near(world.ground_height(1050.0, -1450.0), 2.0); } #[test] -fn alpine_crowns_are_sharp_and_connected_by_lower_ridges() { +fn alpine_folded_massifs_have_offset_summits_and_unequal_faces() { let mut world = world(); assert!(world.set_map_kind(5)); - for (x, z) in [(-1250.0, -1050.0), (1050.0, -1450.0), (1550.0, 650.0)] { - let crown = world.ground_height(x, z); - assert!(crown > 450.0 && crown < 780.0); + for (cx, cz) in [ + (-1250.0, -1050.0), + (1050.0, -1450.0), + (1550.0, 650.0), + (-1500.0, 1050.0), + (50.0, -2250.0), + ] { + let mut summit = (cx, cz, f64::NEG_INFINITY); + for ix in -25..=25 { + for iz in -25..=25 { + let x = cx + f64::from(ix) * 20.0; + let z = cz + f64::from(iz) * 20.0; + let y = world.ground_height(x, z); + if y > summit.2 { + summit = (x, z, y); + } + } + } + assert!(summit.2 > 530.0 && summit.2 < 780.0); + assert!((summit.0 - cx).hypot(summit.1 - cz) > 35.0); + let mut smallest = f64::INFINITY; + let mut largest = f64::NEG_INFINITY; for (dx, dz) in [(80.0, 0.0), (-80.0, 0.0), (0.0, 80.0), (0.0, -80.0)] { - assert!(crown - world.ground_height(x + dx, z + dz) > 70.0); + let drop = summit.2 - world.ground_height(summit.0 + dx, summit.1 + dz); + smallest = smallest.min(drop); + largest = largest.max(drop); } + assert!(largest - smallest > 70.0 && smallest < 200.0 && largest > 190.0); } for (x, z) in [ (-1375.0, 0.0), diff --git a/scripts/build-info.ts b/scripts/build-info.ts new file mode 100644 index 0000000..6bee71b --- /dev/null +++ b/scripts/build-info.ts @@ -0,0 +1,61 @@ +import { createHash } from 'node:crypto'; +import { execFileSync } from 'node:child_process'; +import { existsSync, lstatSync, readFileSync, readdirSync } from 'node:fs'; +import { join, relative } from 'node:path'; +import type { BuildInfo } from '../src/game/build-info.ts'; + +const INPUTS = ['src', 'public', 'data', 'rust/flight-core/src', 'scripts', 'index.html', + 'package.json', 'package-lock.json', 'vite.config.ts', 'tsconfig.json', 'rust-toolchain.toml', + 'rust/flight-core/Cargo.toml', 'rust/flight-core/Cargo.lock']; + +/** Include source and the actual compiled WASM; ignore timestamps and machine paths. */ +export function sourceFingerprint(root: string): string { + const hash = createHash('sha256'); + const files: string[] = []; + const collect = (path: string) => { + if (!existsSync(path)) return; + const stat = lstatSync(path); + if (stat.isSymbolicLink()) throw new Error(`Build input must not be a symbolic link: ${relative(root, path)}`); + if (stat.isDirectory()) { + for (const name of readdirSync(path).sort()) if (!name.startsWith('.')) collect(join(path, name)); + } else if (stat.isFile() && !path.endsWith('.tmp')) files.push(path); + }; + for (const input of INPUTS) collect(join(root, input)); + for (const path of files.sort()) { + const bytes = readFileSync(path); + hash.update(relative(root, path).replaceAll('\\', '/')).update('\0'); + hash.update(String(bytes.length)).update('\0').update(bytes).update('\0'); + } + return hash.digest('hex'); +} + +export function createBuildInfo(root: string): BuildInfo { + const git = (args: string[]) => { + try { return execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); } + catch { return null; } + }; + const head = git(['rev-parse', '--verify', 'HEAD']); + const sourceRevision = head && /^[a-f0-9]{40,64}$/.test(head) ? head : null; + const origin = git(['remote', 'get-url', 'origin']); + let sourceRepository: string | null = null; + try { + const url = new URL(origin?.replace(/^git@github\.com:/, 'https://github.com/') ?? ''); + const repository = url.pathname.replace(/\.git\/?$/, '').replace(/\/$/, '').toLowerCase(); + if (url.hostname.toLowerCase() === 'github.com' && repository === '/kai987/fpv-drone-game') { + sourceRepository = 'https://github.com/kai987/FPV-drone-game'; + } + } catch { /* A separate Site repository or archive must not invent a GitHub link. */ } + const status = git(['status', '--porcelain', '--untracked-files=normal']); + const sourceDirty = sourceRevision === null || status === null || status !== ''; + const fingerprint = sourceFingerprint(root); + let appVersion = 'unknown'; + try { + const version = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')).version; + if (typeof version === 'string') appVersion = version; + } catch { /* Source archives still have an unambiguous content fingerprint. */ } + return { + schemaVersion: 1, appVersion, + buildId: `${sourceRevision?.slice(0, 8) ?? 'archive'}${sourceDirty ? '-dirty' : ''}-${fingerprint.slice(0, 12)}`, + sourceRevision, sourceRepository, sourceDirty, sourceFingerprint: fingerprint, + }; +} diff --git a/scripts/build-wasm.mjs b/scripts/build-wasm.mjs index af75b29..3268b1c 100644 --- a/scripts/build-wasm.mjs +++ b/scripts/build-wasm.mjs @@ -2,12 +2,17 @@ import { copyFile, mkdir, readFile, rename, rm } from 'node:fs/promises'; import { dirname, join } from 'node:path'; import { spawnSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; +import { syncAlpineData } from './generate-alpine-data.mjs'; const projectRoot = fileURLToPath(new URL('../', import.meta.url)); const targetDirectory = join(projectRoot, 'rust/flight-core/target'); const outputFile = join(projectRoot, 'src/game/generated/flight_core.wasm'); const artifactFile = join(targetDirectory, 'wasm32-unknown-unknown/release/flight_core.wasm'); +// Builds regenerate placement constants; validation can opt into a read-only +// stale check so CI does not silently repair a hand-edited generated file. +await syncAlpineData({ root: projectRoot, check: process.argv.includes('--check-generated') }); + const build = spawnSync('cargo', [ 'build', '--release', '--locked', '--target', 'wasm32-unknown-unknown', '--manifest-path', join(projectRoot, 'rust/flight-core/Cargo.toml'), diff --git a/scripts/generate-alpine-data.mjs b/scripts/generate-alpine-data.mjs new file mode 100644 index 0000000..265b44d --- /dev/null +++ b/scripts/generate-alpine-data.mjs @@ -0,0 +1,166 @@ +import { readFile, writeFile, mkdir } from 'node:fs/promises'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const projectRoot = fileURLToPath(new URL('../', import.meta.url)); +export const ALPINE_DATA_FILE = 'data/alpine-terrain.json'; +export const ALPINE_GENERATED_FILES = [ + 'src/game/alpine-massifs.ts', + 'rust/flight-core/src/alpine_data.rs', +]; + +function object(value, keys, label) { + if (!value || typeof value !== 'object' || Array.isArray(value) + || Object.keys(value).sort().join(',') !== [...keys].sort().join(',')) + throw new Error(`${label} must contain exactly: ${keys.join(', ')}`); +} +function list(value, minimum, label) { + if (!Array.isArray(value) || value.length < minimum) throw new Error(`${label} needs at least ${minimum} entries`); +} +function finite(value, label) { + if (typeof value !== 'number' || !Number.isFinite(value)) throw new Error(`${label} must be finite`); +} +function positive(value, label) { + finite(value, label); + if (value <= 0) throw new Error(`${label} must be positive`); +} +function tuple(value, label) { + if (!Array.isArray(value) || value.length !== 5) throw new Error(`${label} must be a five-number tuple`); + value.forEach((number, index) => finite(number, `${label}[${index}]`)); + value.slice(2).forEach((number, index) => positive(number, `${label}[${index + 2}]`)); +} + +/** Reject malformed widths, radii and zero-length crests before either language compiles them. */ +export function validateAlpineData(data) { + object(data, ['schemaVersion', 'peaks', 'ridges', 'massifs'], 'Alpine data'); + if (data.schemaVersion !== 1) throw new Error('Unsupported alpine schemaVersion'); + list(data.peaks, 1, 'peaks'); + data.peaks.forEach((peak, index) => { + object(peak, ['x', 'z', 'height', 'radiusX', 'radiusZ'], `peaks[${index}]`); + finite(peak.x, `peaks[${index}].x`); finite(peak.z, `peaks[${index}].z`); + for (const key of ['height', 'radiusX', 'radiusZ']) positive(peak[key], `peaks[${index}].${key}`); + }); + list(data.ridges, 1, 'ridges'); + data.ridges.forEach((ridge, index) => { + object(ridge, ['ax', 'az', 'bx', 'bz', 'width', 'height'], `ridges[${index}]`); + for (const key of ['ax', 'az', 'bx', 'bz']) finite(ridge[key], `ridges[${index}].${key}`); + for (const key of ['width', 'height']) positive(ridge[key], `ridges[${index}].${key}`); + if (ridge.ax === ridge.bx && ridge.az === ridge.bz) throw new Error(`ridges[${index}] has zero length`); + }); + list(data.massifs, 1, 'massifs'); + data.massifs.forEach((massif, index) => { + object(massif, ['crests', 'cirques'], `massifs[${index}]`); + list(massif.crests, 1, `massifs[${index}].crests`); + list(massif.cirques, 0, `massifs[${index}].cirques`); + massif.crests.forEach((crest, chain) => { + const label = `massifs[${index}].crests[${chain}]`; + list(crest, 2, label); + crest.forEach((node, position) => { + tuple(node, `${label}[${position}]`); + if (position && node[0] === crest[position - 1][0] && node[1] === crest[position - 1][1]) + throw new Error(`${label} contains a zero-length segment`); + }); + }); + massif.cirques.forEach((cirque, position) => tuple(cirque, `massifs[${index}].cirques[${position}]`)); + }); + return data; +} + +function typescript(data) { + const peaks = data.peaks.map(p => ` { x: ${p.x}, z: ${p.z}, height: ${p.height}, radiusX: ${p.radiusX}, radiusZ: ${p.radiusZ} },`).join('\n'); + const ridges = data.ridges.map(r => ` { ax: ${r.ax}, az: ${r.az}, bx: ${r.bx}, bz: ${r.bz}, width: ${r.width}, height: ${r.height} },`).join('\n'); + const massifs = data.massifs.map(m => ` { crests: [\n${m.crests.map(c => ` [${c.map(n => `[${n.join(', ')}]`).join(', ')}],`).join('\n')}\n ], cirques: [${m.cirques.map(c => `[${c.join(', ')}]`).join(', ')}] },`).join('\n'); + return `// @generated from ${ALPINE_DATA_FILE}; do not edit by hand. +// Regenerate with: node scripts/generate-alpine-data.mjs +export type AlpineCrest = readonly [x: number, z: number, height: number, leftShoulder: number, rightShoulder: number]; +export type AlpineCirque = readonly [x: number, z: number, radiusX: number, radiusZ: number, depth: number]; +export interface AlpineMassif { readonly crests: readonly (readonly AlpineCrest[])[]; readonly cirques: readonly AlpineCirque[]; } +export interface AlpinePeak { readonly x: number; readonly z: number; readonly height: number; readonly radiusX: number; readonly radiusZ: number; } +export interface AlpineRidge { readonly ax: number; readonly az: number; readonly bx: number; readonly bz: number; readonly width: number; readonly height: number; } + +export const MOUNTAIN_PEAKS: readonly AlpinePeak[] = Object.freeze([ +${peaks} +]); +export const MOUNTAIN_RIDGES: readonly AlpineRidge[] = Object.freeze([ +${ridges} +]); +export const ALPINE_MASSIFS: readonly AlpineMassif[] = [ +${massifs} +]; +`; +} + +function rustNumber(number) { + const value = String(number); + return /[.eE]/.test(value) ? value : `${value}.0`; +} +const rustTuple = values => `(${values.map(rustNumber).join(', ')})`; +function rust(data) { + const massifs = data.massifs.map(massif => { + const nodes = massif.crests.flat(); + // Retain the native broad-phase envelope: the widest possible shoulder + // (1.12x) plus the existing 20 m bend allowance. The independent TS reference + // keeps its own culling calculation; neither changes the terrain mathematics. + const padding = Math.max(...nodes.flatMap(node => [node[3], node[4]])) * 1.12 + 20; + // Normalize only the broad-phase culling bounds to nanometres. This keeps + // the original authored Rust literals instead of JS decimal-arithmetic tails; + // every actual crest coordinate, width and height is emitted unrounded. + const bounds = [Math.min(...nodes.map(n => n[0])) - padding, Math.max(...nodes.map(n => n[0])) + padding, + Math.min(...nodes.map(n => n[1])) - padding, Math.max(...nodes.map(n => n[1])) + padding].map(value => Number(value.toFixed(9))); + return ` AlpineMassif {\n bounds: ${rustTuple(bounds)},\n crests: &[\n${massif.crests.map(crest => ` &[\n${crest.map(node => ` ${rustTuple(node)},`).join('\n')}\n ],`).join('\n')}\n ],\n cirques: &[\n${massif.cirques.map(cirque => ` ${rustTuple(cirque)},`).join('\n')}\n ],\n },`; + }).join('\n'); + const ridges = data.ridges.map(r => ` ${rustTuple([r.ax, r.az, r.bx, r.bz, r.width, r.height])},`).join('\n'); + return `// @generated from ${ALPINE_DATA_FILE}; do not edit by hand. +// Regenerate with: node scripts/generate-alpine-data.mjs +// Runtime terrain mathematics stays independently implemented in world.rs. +pub(crate) struct AlpineMassif { + pub(crate) bounds: (f64, f64, f64, f64), + pub(crate) crests: &'static [&'static [(f64, f64, f64, f64, f64)]], + pub(crate) cirques: &'static [(f64, f64, f64, f64, f64)], +} +#[rustfmt::skip] +pub(crate) const ALPINE_MASSIFS: [AlpineMassif; ${data.massifs.length}] = [ +${massifs} +]; +#[rustfmt::skip] +pub(crate) const MOUNTAIN_RIDGES: [(f64, f64, f64, f64, f64, f64); ${data.ridges.length}] = [ +${ridges} +]; +`; +} + +/** Only authored placement is shared; independent terrain algorithms and parity tests remain. */ +export function generateAlpineSources(input) { + const data = validateAlpineData(input); + return new Map([[ALPINE_GENERATED_FILES[0], typescript(data)], [ALPINE_GENERATED_FILES[1], rust(data)]]); +} + +export async function syncAlpineData({ root = projectRoot, check = false } = {}) { + const data = JSON.parse(await readFile(join(root, ALPINE_DATA_FILE), 'utf8')); + const outputs = generateAlpineSources(data); + const stale = []; + for (const [name, expected] of outputs) { + let actual; + try { actual = await readFile(join(root, name), 'utf8'); } + catch (error) { if (error.code !== 'ENOENT') throw error; } + if (actual !== expected) stale.push(name); + } + if (check && stale.length) throw new Error(`Stale alpine data: ${stale.join(', ')}. Run node scripts/generate-alpine-data.mjs`); + if (!check) for (const name of stale) { + await mkdir(dirname(join(root, name)), { recursive: true }); + await writeFile(join(root, name), outputs.get(name)); + } + return { updated: check ? [] : stale, checked: [...outputs.keys()] }; +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const args = process.argv.slice(2); + if (args.some(arg => arg !== '--check') || args.length > 1) { + console.error('Usage: node scripts/generate-alpine-data.mjs [--check]'); process.exitCode = 1; + } else { + try { + const result = await syncAlpineData({ check: args.includes('--check') }); + console.log(args.includes('--check') ? 'Alpine generated data is current' : `Alpine data: ${result.updated.length} generated files updated`); + } catch (error) { console.error(error.message); process.exitCode = 1; } + } +} diff --git a/src/App.tsx b/src/App.tsx index e6a1509..fcedcdf 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,5 +1,5 @@ import { useEffect, useMemo, useRef, useState } from 'react'; -import { ArrowRight, Camera, Globe, ChevronDown, Drone, Maximize, Minimize, Moon, Pause, Play, RotateCcw, Sun, Volume2, VolumeX, Trophy, Wind } from 'lucide-react'; +import { ArrowRight, Camera, Globe, ChevronDown, Drone, Maximize, Minimize, Moon, Pause, Play, RotateCcw, SlidersHorizontal, Sun, Volume2, VolumeX, Trophy, Wind } from 'lucide-react'; import { FlightEngine } from './game/engine'; import { useI18n } from './i18n/context'; import { isLocale } from './i18n/locale'; @@ -7,7 +7,7 @@ import type { NoticeMessage } from './i18n/locale'; import { translateNotice } from './i18n/messages'; import type { MapLoadProgress } from './game/map-cache'; import { loadFlightCore } from './game/load-flight-core'; -import { DEFAULT_MAP_ID, MAPS, getMapSpec } from './game/map-catalog'; +import { MAPS, getMapSpec } from './game/map-catalog'; import type { MapId } from './game/map-catalog'; import { EMPTY_TELEMETRY, formatTime } from './game/types'; import type { CameraMode, FlightMode, RaceMode, Status } from './game/types'; @@ -19,13 +19,17 @@ import TouchControls from './components/TouchControls'; import AimControls from './components/AimControls'; import WeaponPanel from './components/WeaponPanel'; import DroneHangar from './components/DroneHangar'; -import { DEFAULT_DRONE_ID, getDroneSpec } from './game/drone-catalog'; +import { getDroneSpec } from './game/drone-catalog'; import type { DroneId } from './game/drone-catalog'; -import { DEFAULT_WIND_SETTINGS } from './game/wind'; import type { WindSettings } from './game/wind'; import { bestTimeKey, readBestTime } from './game/records'; import WindPanel, { WindSettingsDialog } from './components/WindPanel'; +import PreferencesDialog from './components/PreferencesDialog'; +import type { AdjustablePreferences } from './components/PreferencesDialog'; +import { defaultFlightPreferences, readFlightPreferences, saveFlightPreferences } from './game/preferences'; +import type { QualityPreset } from './game/graphics-quality'; +import type { TouchSettings } from './components/touch-settings'; const MAP_SHORT_LABELS: Record = { valley: '山谷', factory: '工厂', harbor: '海港', desert: '沙漠', downtown: '市中心', mountains: '山区', @@ -40,20 +44,29 @@ export default function App() { const noticeTimeout = useRef | undefined>(undefined); const hangarTrigger = useRef(null); const guideTrigger = useRef(null); + const preferencesTrigger = useRef(null); + const [initialPreferences] = useState(() => { + try { return readFlightPreferences(localStorage); } catch { return defaultFlightPreferences(); } + }); const [status, setStatus] = useState('ready'); const [telemetry, setTelemetry] = useState(EMPTY_TELEMETRY); - const [mode, setMode] = useState('race'); - const [flightMode, setFlightMode] = useState('assisted'); - const [cameraMode, setCameraMode] = useState('chase'); - const [sound, setSound] = useState(false); - const [night, setNight] = useState(false); + const [mode, setMode] = useState(initialPreferences.mode); + const [flightMode, setFlightMode] = useState(initialPreferences.flightMode); + const [cameraMode, setCameraMode] = useState(initialPreferences.cameraMode); + const [sound, setSound] = useState(initialPreferences.sound); + const [night, setNight] = useState(initialPreferences.night); const [fullscreen, setFullscreen] = useState(false); const [guide, setGuide] = useState(false); const [hangar, setHangar] = useState(false); const [weatherOpen, setWeatherOpen] = useState(false); - const [windSettings, setWindSettings] = useState({ ...DEFAULT_WIND_SETTINGS }); - const [droneId, setDroneId] = useState(DEFAULT_DRONE_ID); - const [mapId, setMapId] = useState(DEFAULT_MAP_ID); + const [preferencesOpen, setPreferencesOpen] = useState(false); + const [qualityPreset, setQualityPreset] = useState(initialPreferences.qualityPreset); + const [touchSettings, setTouchSettings] = useState(initialPreferences.touch); + const [restartSerial, setRestartSerial] = useState(0); + const [storageAvailable, setStorageAvailable] = useState(true); + const [windSettings, setWindSettings] = useState(initialPreferences.windSettings); + const [droneId, setDroneId] = useState(initialPreferences.droneId); + const [mapId, setMapId] = useState(initialPreferences.mapId); const [notice, setNotice] = useState(''); const [error, setError] = useState(''); const [graphics, setGraphics] = useState('ready'); @@ -62,7 +75,7 @@ export default function App() { const [best, setBest] = useState>({}); const [finishedRecordKey, setFinishedRecordKey] = useState(null); const settingsLocked = status === 'flying' || status === 'paused'; - const modalOpen = hangar || guide || weatherOpen; + const modalOpen = hangar || guide || weatherOpen || preferencesOpen; const graphicsReady = graphics === 'ready' && !error; const selectedDrone = getDroneSpec(droneId); const selectedMap = getMapSpec(mapId); @@ -77,6 +90,12 @@ export default function App() { setNotice(message); clearTimeout(noticeTimeout.current); noticeTimeout.current = setTimeout(() => setNotice(''), 3600); }; + useEffect(() => { + try { + setStorageAvailable(saveFlightPreferences(localStorage, { version: 1, mapId, droneId, mode, flightMode, + cameraMode, windSettings, night, sound, qualityPreset, touch: touchSettings })); + } catch { setStorageAvailable(false); } + }, [mapId, droneId, mode, flightMode, cameraMode, windSettings, night, sound, qualityPreset, touchSettings]); useEffect(() => { let cancelled = false; const loading = new AbortController(); @@ -115,7 +134,7 @@ export default function App() { return { ...current, [key]: seconds }; }); }, - }, loadFlightCore(), settings.current.mapId, loading.signal, loadingStarted); + }, loadFlightCore(), settings.current.mapId, loading.signal, loadingStarted, qualityPreset); if (cancelled) { game.dispose(); return; } engine.current = game; const translate = translateRef.current; @@ -128,12 +147,6 @@ export default function App() { await game.preloadMaps(progress => { if (!cancelled) setMapProgress(progress); }); if (cancelled) return; setNotice(''); clearTimeout(noticeTimeout.current); - const activeGame = game; - void activeGame.audio.enable(settings.current.sound).catch(() => { - if (!cancelled && engine.current === activeGame && settings.current.sound) { - setSound(false); notify('浏览器暂未允许声音播放'); - } - }); setLoaded(true); } catch (failure) { game?.dispose(); @@ -151,7 +164,27 @@ export default function App() { cancelled = true; loading.abort(); clearTimeout(noticeTimeout.current); game?.dispose(); if (engine.current === game) engine.current = null; }; - }, []); + }, [qualityPreset, restartSerial]); + useEffect(() => { + const game = engine.current; + if (!loaded || !sound || !game) return; + // Restored sound is only a preference. Create/resume audio inside the next + // real input handler, never as a side effect of loading or restoring state. + const stopListening = () => { + window.removeEventListener('pointerdown', unlock, true); + window.removeEventListener('keydown', unlock, true); + }; + const unlock = () => { + stopListening(); + if (engine.current !== game) return; + void game.audio.enable(true).catch(() => { + if (engine.current === game && settings.current.sound) { setSound(false); notify('浏览器暂未允许声音播放'); } + }); + }; + window.addEventListener('pointerdown', unlock, { capture: true, once: true }); + window.addEventListener('keydown', unlock, { capture: true, once: true }); + return stopListening; + }, [loaded, sound]); useEffect(() => { if (engine.current) { engine.current.mode = mode; engine.current.flightMode = flightMode; } }, [mode, flightMode, loaded]); useEffect(() => { engine.current?.setWind(windSettings); }, [windSettings, loaded]); useEffect(() => { engine.current?.setNight(night); }, [night, loaded]); @@ -177,6 +210,30 @@ export default function App() { engine.current?.pause(); setHangar(true); }; const openWeather = () => { engine.current?.pause(); setWeatherOpen(true); }; + const openPreferences = () => { + preferencesTrigger.current?.focus({ preventScroll: true }); + engine.current?.pause(); setPreferencesOpen(true); + }; + const applyPreferences = (next: AdjustablePreferences) => { + const rebuild = next.qualityPreset !== qualityPreset; + if (rebuild) setLoaded(false); + else if (next.sound !== sound) { + const game = engine.current; + void game?.audio.enable(next.sound).catch(() => { + if (engine.current === game) { setSound(false); notify('浏览器暂未允许声音播放'); } + }); + } + setQualityPreset(next.qualityPreset); setTouchSettings(next.touch); setSound(next.sound); + setPreferencesOpen(false); + if (!rebuild) notify('设置已应用'); + }; + const resetPreferences = () => { + const defaults = defaultFlightPreferences(); + setLoaded(false); setPreferencesOpen(false); + setMapId(defaults.mapId); setDroneId(defaults.droneId); setMode(defaults.mode); setFlightMode(defaults.flightMode); + setCameraMode(defaults.cameraMode); setWindSettings(defaults.windSettings); setNight(defaults.night); setSound(defaults.sound); + setQualityPreset(defaults.qualityPreset); setTouchSettings(defaults.touch); setRestartSerial(current => current + 1); + }; const applyWind = (settings: WindSettings) => { engine.current?.setWind(settings); setWindSettings(settings); setWeatherOpen(false); notify(settingsLocked ? '风况已更新 · 继续飞行体验风偏' : '风况已更新 · 准备起飞'); @@ -212,7 +269,9 @@ export default function App() { return
AEROFLOW - +
@@ -249,7 +308,7 @@ export default function App() { {status === 'finished' && graphicsReady ?

{t('漂亮的一次飞行。')}

{t('{count} 个检查点全部完成', { count: selectedMap.checkpoints.length })}

{formatTime(telemetry.elapsed)}
{!telemetry.recordEligible ? t('本轮调整过风况,不计入个人最佳') : finishedRecordKey === bestTimeKey(droneId, flightMode, windSettings, mapId) ? t('本图同风况最佳 · {time}', { time: formatTime(personalBest ?? telemetry.elapsed) }) : t('本轮已完成 · 新风况用于下次起飞')}
: null}
{translateNotice(locale, notice)}
- {status === 'flying' ? engine.current?.setTouch(axis, value)} /> : null} + {status === 'flying' ? engine.current?.setTouch(axis, value)} /> : null} {status === 'flying' && telemetry.weapons.kind === 'machine-gun' ? engine.current?.aim(dx, dy)} /> : null} {status === 'flying' ? : null}
@@ -264,5 +323,8 @@ export default function App() { {weatherOpen ? setWeatherOpen(false)} /> : null} {guide ? setGuide(false)} /> : null} {hangar ? setHangar(false)} /> : null} + {preferencesOpen ? setPreferencesOpen(false)} + onOpenGuide={() => { preferencesTrigger.current?.focus({ preventScroll: true }); setPreferencesOpen(false); setGuide(true); }} /> : null} ; } diff --git a/src/components/BuildInfo.tsx b/src/components/BuildInfo.tsx new file mode 100644 index 0000000..6b0ae21 --- /dev/null +++ b/src/components/BuildInfo.tsx @@ -0,0 +1,15 @@ +import { BUILD_INFO } from '../game/build-info'; +import { useI18n } from '../i18n/context'; + +export default function BuildInfo() { + const { t } = useI18n(); + return
+ {t('版本信息')} · {BUILD_INFO.buildId} + {BUILD_INFO.sourceRevision && !BUILD_INFO.sourceDirty && BUILD_INFO.sourceRepository ? {t('源码版本')} ↗ : + {BUILD_INFO.sourceRevision && BUILD_INFO.sourceDirty ? t('包含未提交更改') + : `${t('源码版本')} · ${BUILD_INFO.sourceRevision?.slice(0, 8) ?? '—'}`} + } +
; +} diff --git a/src/components/ControlsGuide.tsx b/src/components/ControlsGuide.tsx index 9956509..b5ceff5 100644 --- a/src/components/ControlsGuide.tsx +++ b/src/components/ControlsGuide.tsx @@ -43,7 +43,8 @@ export default function ControlsGuide({ onClose }: { onClose: () => void }) {
F
{t("守卫者:按住机枪连射,松开停止")}
N
{t("随时切换日间 / 夜间,保留当前飞行进度")}
-

{t("鼠标与触屏")}

{t("飞行时点击画面可启用鼠标视角,Esc 释放鼠标并暂停。手机上,单指按住飞行画面会柔和前进,持续按住约 2 秒,推进输入渐增至满量程;向上拖前进、向下拖后退、向左右拖平移,拖得越远控制幅度越大。松开手指释放控制并减速,风仍可能让飞机缓慢漂移。")}

{t("保持第一根手指,再按下第二根手指:上下拖动控制升降,左右拖动控制转向,向右拖即右转。松开某根手指只释放它控制的方向。投弹、小地图与风向菜单已移至手机页面底部;小地图拖动不会操纵飞机,右上角视角按钮可切换俯视瞄准。")}

+

{t("鼠标与触屏")}

{t("飞行时点击画面可启用鼠标视角,Esc 释放鼠标并暂停。手机上,单指按住飞行画面会柔和前进,默认持续按住约 2 秒,推进输入渐增至满量程;向上拖前进、向下拖后退、向左右拖平移,拖得越远控制幅度越大。松开手指释放控制并减速,风仍可能让飞机缓慢漂移。")}

{t("保持第一根手指,再按下第二根手指:上下拖动控制升降,左右拖动控制转向,向右拖即右转。松开某根手指只释放它控制的方向。投弹、小地图与风向菜单已移至手机页面底部;小地图拖动不会操纵飞机,右上角视角按钮可切换俯视瞄准。")}

+

{t('触屏灵敏度、加速时间和上下反转可在设置中调整;上述拖动方向以默认未反转为准。')}

{t("迎着风,修正航迹")}

{t("点击画面左上角的风况按钮,选择无风、微风、中等风或强风,以及八个基准来风方向。风向表示“从哪里吹来”,例如北风从北向南吹。起飞后实际来向会随时间平滑偏转;实时度数表示来向,小地图箭头表示吹向,暂停时冻结。机头转向后,仪表会重新显示迎风、顺风或左右前后侧风。风速也随时间、位置和高度变化。")}

{t("迎风时地速下降,顺风时地速提高;侧风会把无人机推离航线,用 A/D 或触屏平移修正。辅助模式减轻风偏,运动模式保留更多风的影响。下方速度表显示地速,鼠标悬停可查看空速;机库速度是无风参考。打开风况设置会暂停,应用后保留位置,关闭后可继续;飞行中改变风况的这一轮不计入个人最佳。")}

{t("怎样完成挑战?")}

{t("按顺序,从正面穿过 8 个飞行环。当前目标会亮起,小地图会标出航线。碰到地形或树木会减速,并增加 3 秒计时;自由飞行没有计时惩罚。")}

{t("沿河流,拜访乡间村落")}

{t("松林山谷的飞行区域为 3.6 × 3.6 公里,工厂与海港各为 7.2 × 7.2 公里。沙漠、市中心和山区各为 4.8 × 4.8 公里;沙漠可探索沙丘与岩柱,市中心可沿大道穿过高楼,山区可在山脊与雪峰之间攀升。山谷包含蜿蜒河道、翡翠湖与松影湖。沿河寻找小桥和乡间小屋,牧场里有牛羊,河湖浅水里有游动的鱼。小地图可切换「航线 / 全域」;自由飞行默认显示全域。用「− / +」在 1×、2×、4×、8× 之间缩放,点击倍率恢复 1×;放大后地图跟随无人机;鼠标或手指拖动地图可自由查看其他区域,此时暂停跟随。点击「跟随」回到无人机;聚焦地图后也可用方向键平移、Home 重新跟随。全域 1× 已显示完整地图,先放大即可拖动。升高后更容易看清湖岸和远山;山区最高可飞到 800 米,其余地图为 450 米。接触水面会自动稳住机身。")}

{t("怎样找到鱼群?")}{t("选自由飞行,把小地图切到「航线」,沿河飞到木桥下游的浅蓝鱼形标记。减速悬停在水面上方约 2–8 米,按 V 切到「俯视瞄准」(手机点击右上角视角按钮),向下观察;白天更容易看清。湖里的鱼标可在「全域」查看。")}

{t("点击右上角「日间 / 夜间」或按 N,可在飞行中切换昼夜;位置、计时和弹药都会保留。")}

diff --git a/src/components/PreferencesDialog.css b/src/components/PreferencesDialog.css new file mode 100644 index 0000000..46d2fa3 --- /dev/null +++ b/src/components/PreferencesDialog.css @@ -0,0 +1,41 @@ +.preferences-entry { display: flex; align-items: center; gap: 7px; padding: 0; font-size: 14px; color: var(--muted); background: transparent; white-space: nowrap; } +.preferences-entry[aria-expanded="true"] { color: var(--ink); } +.preferences-dialog { width: min(580px, calc(100% - 28px)); max-height: calc(100dvh - 32px); overflow-y: auto; padding: 28px; color: var(--ink); background: var(--paper); border: 1px solid var(--line); border-radius: 18px; box-shadow: 0 20px 90px #14291c35; } +.preferences-dialog::backdrop { background: #15271dcc; backdrop-filter: blur(5px); } +.preferences-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; } +.preferences-heading h2 { margin: 6px 0 0; font-size: 26px; letter-spacing: -.5px; } +.preferences-intro { color: var(--muted); font-size: 12px; line-height: 1.7; margin: 12px 0 20px; } +.preferences-section { border-top: 1px solid var(--line); padding-top: 16px; margin-top: 18px; } +.preferences-section h3 { margin: 0 0 14px; font-size: 14px; font-weight: 700; } +.preferences-field { display: flex; align-items: center; justify-content: space-between; gap: 16px; font-size: 13px; } +.preferences-field select { min-height: 44px; height: 44px; min-width: 150px; padding: 0 12px; font: inherit; color: var(--ink); background: var(--paper); border: 1px solid var(--line); border-radius: 7px; } +.preferences-help, .preferences-storage-note { color: var(--muted); font-size: 11px; line-height: 1.7; margin: 7px 0 12px; } +.preferences-check { display: flex; gap: 10px; align-items: center; min-height: 44px; font-size: 13px; cursor: pointer; } +.preferences-check input { width: 19px; height: 19px; accent-color: #647c31; flex-shrink: 0; } +.preferences-slider { display: grid; grid-template-columns: 1fr auto; gap: 5px 12px; margin: 12px 0; align-items: center; font-size: 13px; } +.preferences-slider output { font-size: 12px; font-variant-numeric: tabular-nums; color: var(--muted); } +.preferences-slider input { grid-column: 1 / -1; width: 100%; margin: 0; height: 36px; accent-color: #647c31; cursor: pointer; } +.preferences-quality-note { display: flex; align-items: flex-start; gap: 9px; margin: 20px 0 12px; padding: 12px; border: 1px solid var(--line); border-radius: 8px; font-size: 11px; line-height: 1.7; color: var(--muted); } +.preferences-quality-note svg { margin-top: 2px; } +.preferences-quality-note.is-changing { background: #e6efce; border-color: #a8bf66; color: #34481d; } +.preferences-actions { display: flex; gap: 10px; align-items: center; margin-top: 18px; } +.preferences-actions .primary-button { min-height: 44px; padding: 11px 18px; flex: 1; } +.preferences-actions .text-button, .preferences-reset .text-button { display: inline-flex; align-items: center; justify-content: center; gap: 7px; min-height: 44px; padding: 6px; font-size: 12px; } +.preferences-reset { margin-top: 20px; border-top: 1px solid var(--line); padding-top: 14px; } +.preferences-reset p { margin: 0; color: var(--muted); font-size: 10px; line-height: 1.7; } +.preferences-reset .text-button { margin-top: 3px; } +.preferences-build-info { border-top: 1px solid var(--line); margin-top: 12px; padding-top: 12px; color: var(--muted); font-size: 10px; line-height: 1.6; overflow-wrap: anywhere; } +.build-info { display: flex; flex-wrap: wrap; gap: 5px 12px; align-items: baseline; min-width: 0; overflow-wrap: anywhere; } +.build-info > span, .build-info code { min-width: 0; overflow-wrap: anywhere; } +.build-info a { text-underline-offset: 3px; } +.night .preferences-quality-note.is-changing { background: #324623; color: #e2eccd; } +@media (max-width: 980px), (pointer: coarse) { + .app-shell .topbar .guide-entry { display: none; } + .app-shell .topbar .preferences-entry { min-width: 44px; width: 44px; min-height: 44px; justify-content: center; } + .app-shell .topbar .preferences-entry span { display: none; } +} +@media (max-width: 480px) { + .preferences-dialog { padding: 19px; width: calc(100% - 20px); max-height: calc(100dvh - 20px); border-radius: 13px; } + .preferences-heading h2 { font-size: 23px; } + .preferences-actions { align-items: stretch; flex-direction: column; gap: 4px; } +} diff --git a/src/components/PreferencesDialog.tsx b/src/components/PreferencesDialog.tsx new file mode 100644 index 0000000..50d8ba2 --- /dev/null +++ b/src/components/PreferencesDialog.tsx @@ -0,0 +1,80 @@ +import { useEffect, useId, useRef, useState } from 'react'; +import type { ReactNode } from 'react'; +import { BookOpen, Check, RotateCcw, SlidersHorizontal, X } from 'lucide-react'; +import type { QualityPreset } from '../game/graphics-quality'; +import { isQualityPreset } from '../game/graphics-quality'; +import { useI18n } from '../i18n/context'; +import BuildInfo from './BuildInfo'; +import type { TouchSettings } from './touch-settings'; +import './PreferencesDialog.css'; + +export interface AdjustablePreferences { + qualityPreset: QualityPreset; + touch: TouchSettings; + sound: boolean; +} + +interface PreferencesDialogProps { + value: AdjustablePreferences; + storageAvailable: boolean; + onApply(value: AdjustablePreferences): void; + onReset(): void; + onClose(): void; + onOpenGuide(): void; + buildInfo?: ReactNode; +} + +const PRESETS: readonly [QualityPreset, string][] = [['auto', '自动'], ['low', '低'], ['medium', '中'], ['high', '高']]; + +export default function PreferencesDialog({ value, storageAvailable, onApply, onReset, onClose, onOpenGuide, buildInfo = }: PreferencesDialogProps) { + const { t, languageTag } = useI18n(); + const dialog = useRef(null); + const closeButton = useRef(null); + const id = useId(); + const [draft, setDraft] = useState(() => ({ ...value, touch: { ...value.touch } })); + const qualityChanged = draft.qualityPreset !== value.qualityPreset; + const updateTouch = (change: Partial) => setDraft(current => ({ ...current, touch: { ...current.touch, ...change } })); + useEffect(() => { + const element = dialog.current; + const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null; + element?.showModal(); closeButton.current?.focus({ preventScroll: true }); + return () => { element?.close(); if (opener?.isConnected) opener.focus({ preventScroll: true }); }; + }, []); + return { event.preventDefault(); onClose(); }} + onKeyDown={event => { event.stopPropagation(); if (event.key === 'Escape') { event.preventDefault(); onClose(); } }} + onKeyUp={event => event.stopPropagation()} onClick={event => { if (event.target === dialog.current) onClose(); }}> +
AEROFLOW / PREFERENCES

{t('飞行偏好')}

+
+

{t('保留常用设置,让下一次起飞更顺手。飞行已暂停,关闭后可手动继续。')}

+
+

{t('画面与声音')}

+ +

{t('自动会根据设备和帧率调整;低画质优先流畅,高画质保留更多细节。')}

+ +

{t('声音偏好会保存;重新打开网页后,声音从下一次点击或按键开始。')}

+
+
+

{t('触屏飞行手势')}

+
{Math.round(draft.touch.sensitivity * 100)}% + updateTouch({ sensitivity: Number(event.target.value) })} />
+
{t('{seconds} 秒', { seconds: (draft.touch.accelerationMs / 1_000).toLocaleString(languageTag, { maximumFractionDigits: 2 }) })} + updateTouch({ accelerationMs: Number(event.target.value) })} />
+ +

{t('上下反转仅影响触屏飞行的前后与升降手势,不改变键盘、鼠标或机枪瞄准。')}

+
+

+

+

{t(storageAvailable ? '机型、地图、模式、风况、昼夜、视角及这些偏好保存在本浏览器;位置、弹药和飞行进度不保存。' : '浏览器无法保存设置;当前页面内仍可正常调整,重新打开后这些更改可能不会保留。')}

+
+
+

{t('重置全部偏好会返回山谷起点并重新准备地图,个人最佳与语言选择会保留。')}

+
+ {buildInfo ?
{buildInfo}
: null} +
; +} diff --git a/src/components/TouchControls.tsx b/src/components/TouchControls.tsx index 034c6fd..61e0055 100644 --- a/src/components/TouchControls.tsx +++ b/src/components/TouchControls.tsx @@ -5,15 +5,18 @@ import { useI18n } from '../i18n/context'; import { TouchGestureController, TOUCH_GESTURE_RADIUS } from './touch-gesture'; import type { TouchFlightAxes, TouchFlightAxis, TouchGestureSnapshot } from './touch-gesture'; import { isTouchPointer, useTouchInput } from './useTouchInput'; +import { DEFAULT_TOUCH_SETTINGS } from './touch-settings'; +import type { TouchSettings } from './touch-settings'; import './TouchControls.css'; interface TouchControlsProps { onAxis: (axis: TouchFlightAxis, value: number) => void; + settings?: TouchSettings; } const AXES: TouchFlightAxis[] = ['forward', 'strafe', 'climb', 'yaw']; -export default function TouchControls({ onAxis }: TouchControlsProps) { +export default function TouchControls({ onAxis, settings = DEFAULT_TOUCH_SETTINGS }: TouchControlsProps) { const { t } = useI18n(); const controllerRef = useRef(null); if (controllerRef.current === null) controllerRef.current = new TouchGestureController(); @@ -87,6 +90,9 @@ export default function TouchControls({ onAxis }: TouchControlsProps) { }, []); useLayoutEffect(() => { if (!enabled) reset(); }, [enabled]); + useLayoutEffect(() => { + reset(); controller.configure(settings); + }, [settings.sensitivity, settings.accelerationMs, settings.invertVertical]); function position(event: PointerEvent) { const bounds = event.currentTarget.getBoundingClientRect(); diff --git a/src/components/exploration-minimap.ts b/src/components/exploration-minimap.ts index 331e24e..b0c4d60 100644 --- a/src/components/exploration-minimap.ts +++ b/src/components/exploration-minimap.ts @@ -7,10 +7,10 @@ const TERRAIN_PALETTES = { mountains: ['#324b3b', '#4a6248', '#697959', '#858a6f', '#97988b', '#b9c2bc', '#e0e8e5'], }; -/** A handful of cached SVG paths replace hundreds of terrain rectangles per telemetry update. */ +/** Cached color bands retain narrow alpine ridges without per-frame terrain sampling. */ function terrainPaths(id: 'desert' | 'mountains') { const bounds = getMapSpec(id).bounds; - const cells = 32; + const cells = id === 'mountains' ? 64 : 32; const width = (bounds.maxX - bounds.minX) / cells; const depth = (bounds.maxZ - bounds.minZ) / cells; const palette = TERRAIN_PALETTES[id]; diff --git a/src/components/touch-gesture.ts b/src/components/touch-gesture.ts index 54247d5..6b9a6f2 100644 --- a/src/components/touch-gesture.ts +++ b/src/components/touch-gesture.ts @@ -29,14 +29,15 @@ function clamp(value: number, min: number, max: number) { return Math.max(min, Math.min(max, value)); } -function displacement(value: number) { +function displacement(value: number, sensitivity: number) { + value *= sensitivity; const distance = Math.abs(value); return distance <= TOUCH_GESTURE_DEAD_ZONE ? 0 : Math.sign(value) * clamp((distance - TOUCH_GESTURE_DEAD_ZONE) / (TOUCH_GESTURE_RADIUS - TOUCH_GESTURE_DEAD_ZONE), 0, 1); } -function throttleAt(finger: GestureFinger, now: number) { - const fraction = clamp((now - finger.pressedAt) / TOUCH_GESTURE_RAMP_MS, 0, 1); +function throttleAt(finger: GestureFinger, now: number, accelerationMs: number) { + const fraction = clamp((now - finger.pressedAt) / accelerationMs, 0, 1); const eased = fraction * fraction * (3 - 2 * fraction); return INITIAL_THROTTLE + (1 - INITIAL_THROTTLE) * eased; } @@ -49,11 +50,21 @@ function approach(current: number, target: number, step: number) { /** Two independently owned pointer roles; a remaining finger is never promoted. */ export class TouchGestureController { + private settings: TouchSettings; private flight: GestureFinger | null = null; private attitude: GestureFinger | null = null; private axes: TouchFlightAxes = { ...ZERO }; private lastSampleAt: number | null = null; + constructor(settings?: Partial) { + this.settings = normalizeTouchSettings(settings); + } + + configure(settings: TouchSettings): void { + this.settings = normalizeTouchSettings(settings); + this.reset(); + } + get active() { return this.flight !== null || this.attitude !== null; } @@ -106,7 +117,7 @@ export class TouchGestureController { return { axes: { ...this.axes }, fingers: [this.flight, this.attitude].filter((finger): finger is GestureFinger => finger !== null).map(finger => ({ ...finger })), - throttle: this.flight ? throttleAt(this.flight, Number.isFinite(now) ? now : this.flight.pressedAt) : 0, + throttle: this.flight ? throttleAt(this.flight, Number.isFinite(now) ? now : this.flight.pressedAt, this.settings.accelerationMs) : 0, }; } @@ -116,21 +127,21 @@ export class TouchGestureController { this.lastSampleAt = this.active ? Math.max(now, this.lastSampleAt ?? now) : null; const target = { ...ZERO }; if (this.flight) { - const horizontal = displacement(this.flight.x - this.flight.originX); - const vertical = displacement(this.flight.originY - this.flight.y); + const horizontal = displacement(this.flight.x - this.flight.originX, this.settings.sensitivity); + const vertical = displacement((this.flight.originY - this.flight.y) * (this.settings.invertVertical ? -1 : 1), this.settings.sensitivity); // Blend from forward cruising to the dragged direction without a jump at // the dead zone. Upward travel preserves cruising; downward travel brakes // through neutral, while a full sideways drag remains a pure strafe. const cruising = 1 - Math.abs(horizontal); const forward = cruising * (1 - Math.abs(vertical)) + vertical; const length = Math.max(1, Math.hypot(forward, horizontal)); - const throttle = throttleAt(this.flight, now); + const throttle = throttleAt(this.flight, now, this.settings.accelerationMs); target.forward = forward / length * throttle; target.strafe = horizontal / length * throttle; } if (this.attitude) { - target.climb = displacement(this.attitude.originY - this.attitude.y); - target.yaw = -displacement(this.attitude.x - this.attitude.originX); + target.climb = displacement((this.attitude.originY - this.attitude.y) * (this.settings.invertVertical ? -1 : 1), this.settings.sensitivity); + target.yaw = -displacement(this.attitude.x - this.attitude.originX, this.settings.sensitivity); } const step = AXIS_SLEW_PER_SECOND * delta; for (const axis of Object.keys(ZERO) as TouchFlightAxis[]) { @@ -144,3 +155,5 @@ export class TouchGestureController { return this.snapshot(now); } } +import { normalizeTouchSettings } from './touch-settings.ts'; +import type { TouchSettings } from './touch-settings.ts'; diff --git a/src/components/touch-settings.ts b/src/components/touch-settings.ts new file mode 100644 index 0000000..08d8254 --- /dev/null +++ b/src/components/touch-settings.ts @@ -0,0 +1,21 @@ +export interface TouchSettings { + sensitivity: number; + accelerationMs: number; + invertVertical: boolean; +} + +export const DEFAULT_TOUCH_SETTINGS: Readonly = Object.freeze({ + sensitivity: 1, accelerationMs: 2_000, invertVertical: false, +}); + +/** Stored preferences and UI input use the same finite, bounded values. */ +export function normalizeTouchSettings(value: unknown): TouchSettings { + const source = value && typeof value === 'object' && !Array.isArray(value) ? value as Partial : {}; + const bounded = (candidate: unknown, fallback: number, minimum: number, maximum: number) => + typeof candidate === 'number' && Number.isFinite(candidate) ? Math.max(minimum, Math.min(maximum, candidate)) : fallback; + return { + sensitivity: bounded(source.sensitivity, DEFAULT_TOUCH_SETTINGS.sensitivity, 0.5, 2), + accelerationMs: bounded(source.accelerationMs, DEFAULT_TOUCH_SETTINGS.accelerationMs, 500, 4_000), + invertVertical: typeof source.invertVertical === 'boolean' ? source.invertVertical : DEFAULT_TOUCH_SETTINGS.invertVertical, + }; +} diff --git a/src/game/alpine-massifs.ts b/src/game/alpine-massifs.ts new file mode 100644 index 0000000..eba5f92 --- /dev/null +++ b/src/game/alpine-massifs.ts @@ -0,0 +1,48 @@ +// @generated from data/alpine-terrain.json; do not edit by hand. +// Regenerate with: node scripts/generate-alpine-data.mjs +export type AlpineCrest = readonly [x: number, z: number, height: number, leftShoulder: number, rightShoulder: number]; +export type AlpineCirque = readonly [x: number, z: number, radiusX: number, radiusZ: number, depth: number]; +export interface AlpineMassif { readonly crests: readonly (readonly AlpineCrest[])[]; readonly cirques: readonly AlpineCirque[]; } +export interface AlpinePeak { readonly x: number; readonly z: number; readonly height: number; readonly radiusX: number; readonly radiusZ: number; } +export interface AlpineRidge { readonly ax: number; readonly az: number; readonly bx: number; readonly bz: number; readonly width: number; readonly height: number; } + +export const MOUNTAIN_PEAKS: readonly AlpinePeak[] = Object.freeze([ + { x: -1250, z: -1050, height: 665, radiusX: 470, radiusZ: 510 }, + { x: 1050, z: -1450, height: 738, radiusX: 455, radiusZ: 435 }, + { x: 1550, z: 650, height: 590, radiusX: 505, radiusZ: 470 }, + { x: -1500, z: 1050, height: 570, radiusX: 490, radiusZ: 475 }, + { x: 50, z: -2250, height: 625, radiusX: 450, radiusZ: 390 }, +]); +export const MOUNTAIN_RIDGES: readonly AlpineRidge[] = Object.freeze([ + { ax: -1250, az: -1050, bx: -1500, bz: 1050, width: 250, height: 300 }, + { ax: -1250, az: -1050, bx: 50, bz: -2250, width: 245, height: 320 }, + { ax: 50, az: -2250, bx: 1050, bz: -1450, width: 230, height: 340 }, + { ax: 1050, az: -1450, bx: 1550, bz: 650, width: 255, height: 320 }, +]); +export const ALPINE_MASSIFS: readonly AlpineMassif[] = [ + { crests: [ + [[-1490, -1550, 319.2, 250, 190], [-1400, -1385, 485.45, 260, 190], [-1345, -1230, 438.9, 255, 170], [-1195, -1085, 665, 280, 175], [-1235, -900, 518.7, 265, 175], [-1095, -700, 339.15, 230, 170]], + [[-1345, -1230, 438.9, 180, 150], [-1610, -1120, 432.25, 180, 150], [-1700, -870, 252.7, 160, 130]], + [[-1235, -900, 518.7, 150, 160], [-990, -870, 412.3, 160, 150], [-950, -635, 186.2, 135, 120]], + ], cirques: [[-1360, -955, 170, 190, 135], [-1020, -1250, 130, 175, 90]] }, + { crests: [ + [[630, -1600, 369, 160, 280], [795, -1505, 583.02, 170, 285], [940, -1580, 472.32, 180, 275], [1120, -1475, 738, 165, 290], [1245, -1345, 553.5, 175, 280], [1440, -1260, 369, 150, 250]], + [[940, -1580, 472.32, 150, 150], [895, -1320, 464.94, 160, 150], [750, -1140, 243.54, 130, 130]], + [[1245, -1345, 553.5, 140, 160], [1335, -1125, 472.32, 145, 155], [1520, -1060, 206.64, 125, 130]], + ], cirques: [[920, -1280, 170, 180, 170], [1325, -1525, 130, 180, 120]] }, + { crests: [ + [[1210, 310, 271.4, 230, 150], [1370, 400, 477.9, 245, 160], [1475, 580, 407.1, 230, 155], [1630, 700, 590, 255, 165], [1660, 885, 424.8, 230, 150], [1835, 1060, 212.4, 190, 145]], + [[1475, 580, 407.1, 150, 155], [1260, 750, 395.3, 165, 145], [1170, 950, 182.9, 125, 130]], + [[1630, 700, 590, 145, 160], [1860, 580, 430.7, 155, 140], [1990, 690, 206.5, 130, 120]], + ], cirques: [[1430, 780, 170, 190, 140], [1820, 770, 150, 140, 100]] }, + { crests: [ + [[-1860, 750, 210.9, 175, 260], [-1720, 870, 404.7, 190, 275], [-1580, 970, 513, 185, 280], [-1400, 1070, 433.2, 180, 270], [-1320, 1255, 570, 190, 280], [-1110, 1310, 239.4, 160, 230]], + [[-1580, 970, 513, 155, 155], [-1735, 1170, 370.5, 155, 145], [-1775, 1440, 171, 130, 125]], + [[-1400, 1070, 433.2, 140, 155], [-1320, 850, 359.1, 150, 145], [-1110, 810, 171, 130, 130]], + ], cirques: [[-1400, 910, 170, 170, 140], [-1680, 1280, 160, 160, 105]] }, + { crests: [ + [[-450, -2190, 225, 150, 240], [-260, -2265, 468.75, 160, 250], [-110, -2175, 406.25, 165, 260], [75, -2290, 625, 175, 270], [220, -2240, 487.5, 180, 240], [405, -2370, 568.75, 165, 230], [560, -2335, 237.5, 150, 210]], + [[-110, -2175, 406.25, 150, 145], [-125, -1980, 375, 160, 140], [-280, -1895, 162.5, 125, 120]], + [[220, -2240, 487.5, 145, 145], [350, -2045, 412.5, 150, 145], [510, -1950, 187.5, 125, 130]], + ], cirques: [[-90, -2050, 190, 150, 130], [330, -2160, 140, 160, 110]] }, +]; diff --git a/src/game/alpine-terrain-material.ts b/src/game/alpine-terrain-material.ts index 3d50c26..18c5892 100644 --- a/src/game/alpine-terrain-material.ts +++ b/src/game/alpine-terrain-material.ts @@ -1,4 +1,5 @@ import * as THREE from 'three'; +import type { AlpineDetail } from './graphics-quality.ts'; export interface AlpineTerrainTextures { grassTexture: THREE.Texture; @@ -68,10 +69,36 @@ const ALPINE_MATERIAL_GLSL = /* glsl */ ` ${ALPINE_FIELD_GLSL} `; +// Five image samples retain the same snowline and cliff/meadow distinction on +// small GPUs, without the multi-scale joints, drift layers or derivative bump. +const LIGHT_ALPINE_COLOR_GLSL = /* glsl */ ` + #include + vec3 alpineN = normalize(alpineSurfaceNormal); + vec3 alpineWeights = pow(abs(alpineN), vec3(4.0)); + alpineWeights /= max(dot(alpineWeights, vec3(1.0)), 0.001); + vec2 alpineXZ = alpinePoint.xz; + float alpineMacro = alpineNoise(alpineXZ * 0.007); + vec3 alpineFineStone = alpineTriplanar(alpineRock, alpinePoint / 12.0, alpineWeights); + vec3 alpineStone = alpineFineStone * mix(0.72, 1.06, alpineMacro); + vec3 alpineMeadow = texture2D(alpineGrass, alpineXZ / 12.0).rgb * vec3(1.22, 1.29, 1.10); + float alpineUpright = clamp(alpineN.y, 0.0, 1.0); + float alpineRocky = clamp(smoothstep(0.08, 0.40, 1.0 - alpineUpright) + + smoothstep(180.0, 390.0, alpinePoint.y) * 0.72, 0.0, 1.0); + float alpineAspect = dot(alpineN, normalize(vec3(0.55, 0.0, 0.83))); + float alpineSnowLine = 335.0 + (alpineMacro - 0.5) * 100.0 + alpineAspect * 43.0; + float alpineElevationSnow = smoothstep(alpineSnowLine - 34.0, alpineSnowLine + 105.0, alpinePoint.y); + float alpineHolding = mix(0.10, 1.0, smoothstep(0.19, 0.80, alpineUpright)); + float alpineSnowCover = smoothstep(0.10, 0.66, alpineElevationSnow * alpineHolding * 0.82); + vec3 alpinePackedSnow = texture2D(alpineSnow, alpineXZ / 8.0).rgb; + diffuseColor.rgb = mix(mix(alpineMeadow, alpineStone, alpineRocky), alpinePackedSnow, alpineSnowCover); + float alpineStoneHeight = alpineLuminance(alpineFineStone); + float alpineSnowHeight = alpineLuminance(alpinePackedSnow); +`; + /** Generated rock/snow albedos are combined with live PBR light and shadows. */ -export function createAlpineTerrainMaterial(textures: AlpineTerrainTextures): THREE.MeshStandardMaterial { - const material = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.91, metalness: 0 }); - material.name = 'Alpine granite, wind-packed snow and meadow'; +export function createAlpineTerrainMaterial(textures: AlpineTerrainTextures, detail: AlpineDetail = 'high'): THREE.MeshStandardMaterial { + const material = new THREE.MeshStandardMaterial({ roughness: 0.91, metalness: 0 }); + material.name = `Alpine granite, wind-packed snow and meadow (${detail})`; material.onBeforeCompile = shader => { shader.uniforms.alpineGrass = { value: textures.grassTexture }; shader.uniforms.alpineRock = { value: textures.rockTexture }; @@ -83,7 +110,7 @@ export function createAlpineTerrainMaterial(textures: AlpineTerrainTextures): TH alpineSurfaceNormal = normal; `); shader.fragmentShader = ALPINE_MATERIAL_GLSL + shader.fragmentShader; - shader.fragmentShader = shader.fragmentShader.replace('#include ', ` + let colorFragment = ` #include vec3 alpineN = normalize(alpineSurfaceNormal); vec3 alpineWeights = pow(abs(alpineN), vec3(4.0)); @@ -151,7 +178,12 @@ export function createAlpineTerrainMaterial(textures: AlpineTerrainTextures): TH alpineSnowHeight * 0.025 + alpineDrifts * 0.018, alpineSnowCover); float alpinePixelMetres = max(length(dFdx(alpinePoint)), length(dFdy(alpinePoint))); float alpineReliefFade = 1.0 - smoothstep(0.10, 1.7, alpinePixelMetres); - `); + `; + if (detail === 'medium') { + colorFragment = colorFragment.replace('alpineJoints(alpineFace / 43.0 + alpineJointWarp * 0.57)', '0.0') + .replaceAll('alpineFbm(', 'alpineNoise('); + } + shader.fragmentShader = shader.fragmentShader.replace('#include ', detail === 'low' ? LIGHT_ALPINE_COLOR_GLSL : colorFragment); shader.fragmentShader = shader.fragmentShader.replace('#include ', ` #include // Clear snow has a softer highlight than rough, fractured rock, without @@ -160,20 +192,20 @@ export function createAlpineTerrainMaterial(textures: AlpineTerrainTextures): TH roughnessFactor = mix(mix(0.98, alpineRockRoughness, alpineRocky), 0.69 + (1.0 - alpineSnowHeight) * 0.16, alpineSnowCover); `); - shader.fragmentShader = shader.fragmentShader.replace('#include ', ` + if (detail === 'high') shader.fragmentShader = shader.fragmentShader.replace('#include ', ` #include vec2 alpineHeightGradient = vec2(dFdx(alpineSurfaceHeight), dFdy(alpineSurfaceHeight)) * alpineReliefFade; normal = alpinePerturb(-vViewPosition, normal, alpineHeightGradient, faceDirection); `); }; - material.customProgramCacheKey = () => 'alpine-granite-snow-pbr-triplanar-v6'; + material.customProgramCacheKey = () => `alpine-granite-snow-pbr-triplanar-v7-${detail}`; return material; } /** Generated loose-stone albedo uses transformed instance coordinates, not unit meshes. */ -export function createAlpineRockMaterial({ rockTexture }: Pick): THREE.MeshStandardMaterial { +export function createAlpineRockMaterial({ rockTexture }: Pick, detail: AlpineDetail = 'high'): THREE.MeshStandardMaterial { const material = new THREE.MeshStandardMaterial({ color: '#ffffff', roughness: 0.94, metalness: 0 }); - material.name = 'Alpine fractured granite rock'; + material.name = `Alpine fractured granite rock (${detail})`; material.onBeforeCompile = shader => { shader.uniforms.alpineRock = { value: rockTexture }; shader.vertexShader = 'varying vec3 alpineRockPoint; varying vec3 alpineRockNormal;\n' + shader.vertexShader; @@ -202,7 +234,14 @@ export function createAlpineRockMaterial({ rockTexture }: Pick', ` + shader.fragmentShader = shader.fragmentShader.replace('#include ', detail === 'low' ? ` + #include + vec3 alpineLooseWeights = pow(abs(normalize(alpineRockNormal)), vec3(4.0)); + alpineLooseWeights /= max(dot(alpineLooseWeights, vec3(1.0)), 0.001); + vec3 alpineLooseFine = alpineTriplanar(alpineRock, alpineRockPoint / 7.0, alpineLooseWeights); + float alpineLooseHeight = alpineLuminance(alpineLooseFine); + diffuseColor.rgb = alpineLooseFine; + ` : ` #include vec3 alpineLooseWeights = pow(abs(normalize(alpineRockNormal)), vec3(4.0)); alpineLooseWeights /= max(dot(alpineLooseWeights, vec3(1.0)), 0.001); @@ -210,7 +249,7 @@ export function createAlpineRockMaterial({ rockTexture }: Pick roughnessFactor = 0.84 + (1.0 - alpineLooseHeight) * 0.14; `); - shader.fragmentShader = shader.fragmentShader.replace('#include ', ` + if (detail === 'high') shader.fragmentShader = shader.fragmentShader.replace('#include ', ` #include normal = alpinePerturb(-vViewPosition, normal, vec2(dFdx(alpineLooseRelief), dFdy(alpineLooseRelief)), faceDirection); `); }; - material.customProgramCacheKey = () => 'alpine-loose-granite-triplanar-v1'; + material.customProgramCacheKey = () => `alpine-loose-granite-triplanar-v2-${detail}`; return material; } diff --git a/src/game/build-info.ts b/src/game/build-info.ts new file mode 100644 index 0000000..c42140f --- /dev/null +++ b/src/game/build-info.ts @@ -0,0 +1,14 @@ +export interface BuildInfo { + schemaVersion: 1; + appVersion: string; + buildId: string; + sourceRevision: string | null; + sourceRepository: string | null; + sourceDirty: boolean; + sourceFingerprint: string; +} + +declare const __AEROFLOW_BUILD_INFO__: BuildInfo; + +/** The same immutable identity is embedded in the app and emitted as version.json. */ +export const BUILD_INFO: Readonly = Object.freeze(__AEROFLOW_BUILD_INFO__); diff --git a/src/game/downtown-buildings.ts b/src/game/downtown-buildings.ts index 8166b1b..5ae6d32 100644 --- a/src/game/downtown-buildings.ts +++ b/src/game/downtown-buildings.ts @@ -2,12 +2,14 @@ import * as THREE from 'three'; import { getDowntownBuildingParts } from './downtown-architecture.ts'; import type { DowntownBuildingInput, DowntownFacade } from './downtown-architecture.ts'; import type { UrbanBox } from './map-layout.ts'; +import type { Vec3 } from './flight.ts'; +import { sceneryChunkKey, updateDetailVisibility } from './scenery-chunks.ts'; interface Pose extends UrbanBox { color?: string; } -interface Batch { material: THREE.Material; geometry: THREE.BufferGeometry; poses: Pose[]; shadows: boolean; } +interface Batch { material: THREE.Material; geometry: THREE.BufferGeometry; poses: Pose[]; shadows: boolean; detail: boolean; } /** Batched, metre-scaled architecture; the same stepped pieces are uploaded to Rust. */ -export function createDowntownBuildings(scene: THREE.Scene, buildings: readonly DowntownBuildingInput[]) { +export function createDowntownBuildings(scene: THREE.Scene, buildings: readonly DowntownBuildingInput[], detailDistance = 480) { const group = new THREE.Group(); group.name = 'Downtown architecture and street-facing detail'; scene.add(group); const geometries = new Set(), materials = new Set(), textures = new Set(); const ownGeometry = (value: T): T => { geometries.add(value); return value; }; @@ -18,6 +20,7 @@ export function createDowntownBuildings(scene: THREE.Scene, buildings: readonly const night = { value: 0 }; const lights: { material: THREE.MeshStandardMaterial; day: number; night: number }[] = []; const beacons: THREE.InstancedMesh[] = []; + const detailChunks: THREE.InstancedMesh[] = []; const standard = (color: string, roughness = 0.8, metalness = 0.05) => ownMaterial(new THREE.MeshStandardMaterial({ color, roughness, metalness })); const trim = standard('#c8c5b8', 0.78), darkTrim = standard('#4b5354', 0.55, 0.35), roof = standard('#8c9390', 0.94); const metal = standard('#8a9697', 0.58, 0.45), planter = standard('#637c5a', 0.98), canopy = standard('#42646c', 0.45, 0.28); @@ -25,14 +28,15 @@ export function createDowntownBuildings(scene: THREE.Scene, buildings: readonly lights.push({ material: lobby, day: 0.03, night: 0.23 }); const beacon = ownMaterial(new THREE.MeshStandardMaterial({ color: '#b7654e', emissive: '#e76544', emissiveIntensity: 0.2, roughness: 0.4 })); lights.push({ material: beacon, day: 0.2, night: 0.8 }); - const add = (material: THREE.Material, value: Pose, geometry: THREE.BufferGeometry = unitBox, shadows = true) => { - const key = `${geometry.uuid}:${material.uuid}:${shadows}`; + const add = (material: THREE.Material, value: Pose, geometry: THREE.BufferGeometry = unitBox, shadows = true, decorative = false) => { + const detail = decorative && material !== beacon; + const key = `${geometry.uuid}:${material.uuid}:${shadows}:${detail}:${sceneryChunkKey(value.x, value.z, detail)}`; let entry = batches.get(key); - if (!entry) { entry = { material, geometry, poses: [], shadows }; batches.set(key, entry); } + if (!entry) { entry = { material, geometry, poses: [], shadows, detail }; batches.set(key, entry); } entry.poses.push(value); }; const box = (material: THREE.Material, x: number, base: number, z: number, width: number, height: number, depth: number, shadows = true, color?: string) => - add(material, { x, z, width, depth, base, height, color }, unitBox, shadows); + add(material, { x, z, width, depth, base, height, color }, unitBox, shadows, true); const body = (material: THREE.Material, value: UrbanBox, color?: string) => add(material, { ...value, color }); const facadeMaterials = new Map(); const palettes: Record = { @@ -182,6 +186,8 @@ export function createDowntownBuildings(scene: THREE.Scene, buildings: readonly if (pose.color) mesh.setColorAt(index, color.set(pose.color)); }); mesh.castShadow = entry.shadows; mesh.receiveShadow = true; mesh.computeBoundingSphere(); + mesh.userData.sceneryDetail = entry.detail; + if (entry.detail) detailChunks.push(mesh); mesh.name = `Downtown architectural batch ${instances.length + 1}`; group.add(mesh); instances.push(mesh); if (entry.material === beacon) beacons.push(mesh); } @@ -190,7 +196,10 @@ export function createDowntownBuildings(scene: THREE.Scene, buildings: readonly return { group, setNight(enabled: boolean) { night.value = enabled ? 1 : 0; lights.forEach(light => { light.material.emissiveIntensity = enabled ? light.night : light.day; }); }, - update(time: number) { beacons.forEach(mesh => { mesh.visible = Math.sin(time * 1.6) > -0.8; }); }, + update(time: number, viewPosition?: Vec3) { + updateDetailVisibility(detailChunks, viewPosition, detailDistance); + beacons.forEach(mesh => { mesh.visible = Math.sin(time * 1.6) > -0.8; }); + }, dispose() { if (disposed) return; disposed = true; instances.forEach(mesh => mesh.dispose()); geometries.forEach(value => value.dispose()); materials.forEach(value => value.dispose()); textures.forEach(value => value.dispose()); diff --git a/src/game/engine.ts b/src/game/engine.ts index b786205..c92b1a2 100644 --- a/src/game/engine.ts +++ b/src/game/engine.ts @@ -38,6 +38,8 @@ import { GUN_CAPACITY, GUN_RANGE, GUN_SHOTS_PER_SECOND } from './gun'; import { createGunVisuals } from './gun-visuals'; import { RenderLoop, renderModeFor } from './render-loop'; import type { GraphicsState } from './render-loop'; +import { resolveGraphicsQuality } from './graphics-quality'; +import type { GraphicsQuality, QualityPreset } from './graphics-quality'; export interface EngineEvents { telemetry: (value: Telemetry) => void; @@ -112,9 +114,7 @@ export class FlightEngine { private previousPose = createFlightState(); private displayPose = createFlightState(); private readonly simulationClock = new FixedSimulationClock(); - private readonly renderPerformance = new RenderPerformanceMonitor({ - devicePixelRatio: window.devicePixelRatio, isMobile: matchMedia('(pointer: coarse)').matches, - }); + private readonly renderPerformance: RenderPerformanceMonitor; private status: Status = 'ready'; private keys = new Set(); private lastTime = 0; @@ -137,11 +137,12 @@ export class FlightEngine { get droneId(): DroneId { return this.selectedDroneId; } get windSettings(): Readonly { return this.currentWind; } get recordEligible(): boolean { return this.unchangedWind; } + get qualityPreset(): QualityPreset { return this.quality.preset; } /** Start the selected images before WASM/CPU work, sharing the actual renderer and decoded Images. */ static async create(host: HTMLDivElement, events: EngineEvents, flightCore: Promise, mapId: MapId = DEFAULT_MAP_ID, signal: AbortSignal = new AbortController().signal, - startedAt = performance.now()): Promise { + startedAt = performance.now(), qualityPreset: QualityPreset = 'auto'): Promise { // The shared module may reject even if WebGL fails before its await is reached. void flightCore.catch(() => {}); const metrics = createLoadingMetrics(startedAt); @@ -150,10 +151,13 @@ export class FlightEngine { let assets: WorldAssets | undefined; try { if (signal.aborted) throw new DOMException('Loading cancelled', 'AbortError'); - renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' }); - renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.75)); - const resolution = host.getBoundingClientRect().width * renderer.getPixelRatio() > 900 - && renderer.capabilities.maxTextureSize >= 7096 ? 7096 : 3548; + const device = { isMobile: matchMedia('(pointer: coarse)').matches, devicePixelRatio: window.devicePixelRatio, + viewportWidth: host.getBoundingClientRect().width, maxTextureSize: 0 }; + const initialQuality = resolveGraphicsQuality(qualityPreset, device); + renderer = new THREE.WebGLRenderer({ antialias: initialQuality.antialias, powerPreference: 'high-performance' }); + const quality = resolveGraphicsQuality(qualityPreset, { ...device, maxTextureSize: renderer.capabilities.maxTextureSize }); + renderer.setPixelRatio(quality.maxPixelRatio); + const resolution = quality.panoramaResolution; stopRenderer(); const stopTextures = metrics.measure('textures'); assets = preloadWorldAssets(resolution); @@ -166,7 +170,7 @@ export class FlightEngine { } metrics.record('wasm', startedAt); if (signal.aborted) throw new DOMException('Loading cancelled', 'AbortError'); - return new FlightEngine(host, events, core, mapId, renderer, assets, metrics, resolution); + return new FlightEngine(host, events, core, mapId, renderer, assets, metrics, quality); } catch (error) { assets?.dispose(); renderer?.dispose(); if (renderer && !renderer.getContext().isContextLost()) renderer.forceContextLoss(); @@ -176,10 +180,12 @@ export class FlightEngine { private constructor(private host: HTMLDivElement, private events: EngineEvents, flightCore: WebAssembly.Module, mapId: MapId, renderer: THREE.WebGLRenderer, private assets: WorldAssets, - private loadingMetrics: LoadingMetrics, resolution: 3548 | 7096) { + private loadingMetrics: LoadingMetrics, private readonly quality: GraphicsQuality) { this.renderer = renderer; + this.renderPerformance = new RenderPerformanceMonitor({ devicePixelRatio: window.devicePixelRatio, + isMobile: quality.targetFps === 30, maxPixelRatio: quality.maxPixelRatio }); this.renderer.setPixelRatio(this.renderPerformance.pixelRatio); - this.panoramaResolution = resolution; + this.panoramaResolution = quality.panoramaResolution; let maps: FlightEngine['maps'] | undefined; try { this.runtime = createRustRuntime(flightCore); @@ -200,11 +206,13 @@ export class FlightEngine { this.renderer.outputColorSpace = THREE.SRGBColorSpace; this.renderer.toneMapping = THREE.ACESFilmicToneMapping; this.renderer.toneMappingExposure = 1.2; - this.renderer.shadowMap.enabled = true; + this.renderer.shadowMap.enabled = quality.shadowMapSize > 0; this.renderer.shadowMap.type = THREE.PCFShadowMap; this.renderer.domElement.setAttribute('aria-label', `三维${this.mapSpec.name}飞行画面,飞行时点击可启用鼠标视角`); this.renderer.domElement.dataset.flightCore = 'rust-wasm'; this.renderer.domElement.dataset.numericServices = 'world,weapons,scene,particles,ecology'; + this.renderer.domElement.dataset.qualityPreset = quality.preset; + this.renderer.domElement.dataset.graphicsBudget = JSON.stringify(quality); this.renderer.domElement.dataset.textureResolution = mapId === 'valley' ? String(this.panoramaResolution) : 'procedural'; this.renderer.domElement.dataset.mapId = mapId; this.renderer.domElement.dataset.preloadedMaps = ''; @@ -250,6 +258,7 @@ export class FlightEngine { resolution: this.panoramaResolution, maxAnisotropy: this.renderer.capabilities.getMaxAnisotropy(), assets: this.assets, + quality: this.quality, }, id); kernel.setObstacles(world.obstacles); simulation = createWorldFlightSimulation(this.runtime, kernel.handle); diff --git a/src/game/exploration-layout.ts b/src/game/exploration-layout.ts index 82e6581..30d20c5 100644 --- a/src/game/exploration-layout.ts +++ b/src/game/exploration-layout.ts @@ -1,5 +1,7 @@ import type { UrbanBox } from './map-layout.ts'; import { getDowntownBuildingParts, getDowntownRoofDetails } from './downtown-architecture.ts'; +import { ALPINE_MASSIFS, MOUNTAIN_RIDGES } from './alpine-massifs.ts'; +export { MOUNTAIN_PEAKS, MOUNTAIN_RIDGES } from './alpine-massifs.ts'; export type ExplorationMapId = 'desert' | 'downtown' | 'mountains'; export interface TerrainPeak { readonly x: number; readonly z: number; readonly height: number; readonly radiusX: number; readonly radiusZ: number; } @@ -25,23 +27,6 @@ export const DESERT_MESAS: readonly TerrainPeak[] = Object.freeze([ { x: 1550, z: 850, height: 120, radiusX: 340, radiusZ: 240 }, { x: -1550, z: 1250, height: 150, radiusX: 300, radiusZ: 330 }, ]); -export const MOUNTAIN_PEAKS: readonly TerrainPeak[] = Object.freeze([ - { x: -1250, z: -1050, height: 665, radiusX: 470, radiusZ: 510 }, - { x: 1050, z: -1450, height: 738, radiusX: 455, radiusZ: 435 }, - { x: 1550, z: 650, height: 590, radiusX: 505, radiusZ: 470 }, - { x: -1500, z: 1050, height: 570, radiusX: 490, radiusZ: 475 }, - { x: 50, z: -2250, height: 625, radiusX: 450, radiusZ: 390 }, -]); -const MOUNTAIN_ROTATIONS = [-0.24, 0.35, -0.55, 0.2, -0.1] as const; -const MOUNTAIN_ORIENTATIONS = MOUNTAIN_ROTATIONS.map(angle => ({ cosine: Math.cos(angle), sine: Math.sin(angle) })); -/** Linked, narrow ridgelines create saddles between the peaks, leaving the training valley open. */ -export const MOUNTAIN_RIDGES = Object.freeze([ - { ax: -1250, az: -1050, bx: -1500, bz: 1050, width: 250, height: 300 }, - { ax: -1250, az: -1050, bx: 50, bz: -2250, width: 245, height: 320 }, - { ax: 50, az: -2250, bx: 1050, bz: -1450, width: 230, height: 340 }, - { ax: 1050, az: -1450, bx: 1550, bz: 650, width: 255, height: 320 }, -]); - export function isExplorationMap(id: string): id is ExplorationMapId { return id === 'desert' || id === 'downtown' || id === 'mountains'; } @@ -68,36 +53,61 @@ function alpineNoise(x: number, z: number, seed: number): number { return a + (b - a) * u + (c + (d - c) * u - (a + (b - a) * u)) * v; } +// Compile the authored crest chains once. A folded massif has several displaced +// high points and unequal shoulders instead of a radius around one cone apex. +const ALPINE_FOLDS = ALPINE_MASSIFS.map(massif => { + const nodes = massif.crests.flat(), padding = Math.max(...nodes.flatMap(node => [node[3], node[4]])) * 1.12 + 20; + return { ...massif, minX: Math.min(...nodes.map(node => node[0])) - padding, + maxX: Math.max(...nodes.map(node => node[0])) + padding, + minZ: Math.min(...nodes.map(node => node[1])) - padding, maxZ: Math.max(...nodes.map(node => node[1])) + padding, + segments: massif.crests.flatMap(crest => crest.slice(1).map((b, i) => { + const a = crest[i], dx = b[0] - a[0], dz = b[1] - a[1], lengthSquared = dx * dx + dz * dz; + return { a, b, dx, dz, lengthSquared, length: Math.sqrt(lengthSquared) }; + })) }; +}); function alpineMassHeight(x: number, z: number): number { let height = 0; - for (let index = 0; index < MOUNTAIN_PEAKS.length; index++) { - const peak = MOUNTAIN_PEAKS[index], { cosine, sine } = MOUNTAIN_ORIENTATIONS[index]; - const dx = x - peak.x, dz = z - peak.z; - let u = (dx * cosine + dz * sine) / peak.radiusX; - let v = (-dx * sine + dz * cosine) / peak.radiusZ; - const radius = Math.hypot(u, v), taper = Math.min(1, radius); - u += Math.sin(z * 0.004 + index * 1.7) * Math.sin(x * 0.0023 + index) * 0.055 * taper; - v += Math.sin(x * 0.0041 + index * 2.1) * 0.04 * taper; - // Unequal angular spurs break the four planar faces of a perfect pyramid. - const angle = Math.atan2(v, u); - const lobes = 1 + 0.14 * Math.sin(angle * 3 + index * 1.7) + 0.07 * Math.sin(angle * 7 - index * 1.3); - const polygon = Math.max(Math.abs(u) + Math.abs(v) * 0.32, Math.abs(v) * 1.02 + Math.abs(u) * 0.28); - const facets = (Math.hypot(u, v) * 0.7 + polygon * 0.3) / lobes; - const crown = Math.max(0, 1 - facets) ** 0.86; - const skirt = Math.exp(-(u * u + v * v) * 1.65); - const gullies = facets >= 1 ? 1 : 1 - 0.12 * Math.abs(Math.sin(angle * 5 + index * 1.7 + Math.sin(angle * 2 + index) * 0.6 + radius * 0.7)) - * Math.sin(Math.PI * facets); - let mass = peak.height * (0.86 * crown + 0.14 * skirt) * gullies; - if (crown > 0) { - // Erosion is strongest on the flank and vanishes at the summit and foot. - // Metre-scaled layers form rock buttresses and branching drainage gullies. - const shell = 4 * crown * (1 - crown); - const coarse = alpineNoise(dx / 180, dz / 180, index + 11); - const medium = alpineNoise(dx / 70, dz / 70, index + 37); - const fine = alpineNoise(dx / 28, dz / 28, index + 71); - const channel = (1 - Math.abs(Math.sin(angle * 3 + Math.sin(angle * 2 + index) * 0.8 + radius * 0.9))) ** 3; - mass += peak.height * shell * (0.25 * (coarse - 0.5) + 0.11 * (medium - 0.5) - + 0.035 * (fine - 0.5) - 0.19 * channel); + for (let index = 0; index < ALPINE_FOLDS.length; index++) { + const fold = ALPINE_FOLDS[index]; + if (x < fold.minX || x > fold.maxX || z < fold.minZ || z > fold.maxZ) continue; + const coarse = alpineNoise(x / 155, z / 155, index + 11); + const fracture = (alpineNoise(x / 95, z / 95, index + 37) - 0.5) * 0.12 + + (alpineNoise(x / 42, z / 42, index + 71) - 0.5) * 0.04; + let mass = 0; + for (const segment of fold.segments) { + const { a, b, dx, dz, lengthSquared, length } = segment; + const px = x - a[0], pz = z - a[1]; + const t = Math.max(0, Math.min(1, (px * dx + pz * dz) / lengthSquared)); + const bend = 4 * t * (1 - t) * (coarse - 0.5) * 38; + const distance = Math.hypot(px - dx * t + dz / length * bend, pz - dz * t - dx / length * bend); + const signedNormal = (dx * pz - dz * px) / length - bend; + // Smoothly join unequal shoulders across the bent crest and around its + // end caps: choosing a width by a hard side sign creates height jumps. + const direction = Math.max(0, Math.min(1, 0.5 + 0.5 * signedNormal / Math.max(distance, 32))); + const blend = direction * direction * (3 - 2 * direction); + const left = a[3] + (b[3] - a[3]) * t, right = a[4] + (b[4] - a[4]) * t; + const width = (right + (left - right) * blend) * (0.88 + coarse * 0.24); + const r = distance / width; + if (r >= 1) continue; + const inner = 0.16 + coarse * 0.04, outer = 0.58 + coarse * 0.04; + let profile: number; + if (r < inner) profile = 1 - 0.12 * r / inner; + else if (r < outer) { + const t = (r - inner) / (outer - inner), eased = t * 0.45 + t * t * (3 - 2 * t) * 0.55; + profile = 0.88 - eased * 0.62; + } else profile = 0.26 * ((1 - r) / (1 - outer)) ** 1.6; + const crest = a[2] + (b[2] - a[2]) * t; + const brokenCrest = crest + 4 * t * (1 - t) * (coarse - 0.5) * 36; + // A continuous cliff band gives way to a lower scree apron. Its transition + // spans dozens of metres, remaining representable by the terrain mesh. + mass = Math.max(mass, brokenCrest * profile + crest * 4 * profile * (1 - profile) * fracture); + } + // Off-axis glacial bowls cut headwalls and hanging shoulders into the folds; + // neither the outline nor the erosion is symmetric about a single summit. + for (const [cx, cz, rx, rz, depth] of fold.cirques) { + const u = (x - cx) / rx, v = (z - cz) / rz; + const bowl = Math.max(0, 1 - u * u - v * v); + mass -= depth * bowl ** 1.4; } height = Math.max(height, mass); } diff --git a/src/game/exploration-world.ts b/src/game/exploration-world.ts index 74f4f7e..a636b2c 100644 --- a/src/game/exploration-world.ts +++ b/src/game/exploration-world.ts @@ -9,9 +9,10 @@ import { URBAN_SKY_GLSL } from './urban-sky.ts'; import { createDowntownBuildings } from './downtown-buildings.ts'; import { createAlpineTerrainMaterial, createAlpineRockMaterial } from './alpine-terrain-material.ts'; import { DOWNTOWN_STREETS, explorationGroundHeight, getExplorationLayout, isExplorationMap } from './exploration-layout.ts'; +import { sceneryChunkKey, splitTerrainGrid, updateDetailVisibility } from './scenery-chunks.ts'; interface InstancePose { x: number; y: number; z: number; width: number; height: number; depth: number; yaw: number; color?: string; } -interface Batch { geometry: THREE.BufferGeometry; material: THREE.Material; poses: InstancePose[]; shadows: boolean; } +interface Batch { geometry: THREE.BufferGeometry; material: THREE.Material; poses: InstancePose[]; shadows: boolean; detail: boolean; } /** New environments share the exact terrain and solid footprints used by the Rust world. */ export function createExplorationWorld(_runtime: RustRuntime, kernel: WorldKernel, map: MapSpec, _options: PanoramaOptions = {}) { @@ -41,18 +42,22 @@ export function createExplorationWorld(_runtime: RustRuntime, kernel: WorldKerne const canopyGeometry = ownGeometry(new THREE.IcosahedronGeometry(1, 1)); const batches = new Map(); const instances: THREE.InstancedMesh[] = []; + const detailChunks: THREE.InstancedMesh[] = []; + const detailDistance = _options.quality?.detailDistance ?? 480; const dummy = new THREE.Object3D(); const temporaryColor = new THREE.Color(); let seed = desert ? 45017 : city ? 98413 : 73463; const random = () => { seed = (seed * 1664525 + 1013904223) >>> 0; return seed / 4294967296; }; - const batch = (geometry: THREE.BufferGeometry, material: THREE.Material, pose: InstancePose, shadows = true) => { - const key = `${geometry.uuid}:${material.uuid}:${shadows}`; + const batch = (geometry: THREE.BufferGeometry, material: THREE.Material, pose: InstancePose, shadows = true, detail = false) => { + const key = `${geometry.uuid}:${material.uuid}:${shadows}:${detail}:${sceneryChunkKey(pose.x, pose.z, detail)}`; let entry = batches.get(key); - if (!entry) { entry = { geometry, material, poses: [], shadows }; batches.set(key, entry); } + if (!entry) { entry = { geometry, material, poses: [], shadows, detail }; batches.set(key, entry); } entry.poses.push(pose); }; const box = (material: THREE.Material, x: number, y: number, z: number, width: number, height: number, depth: number, yaw = 0, shadows = true, color?: string) => batch(boxGeometry, material, { x, y, z, width, height, depth, yaw, color }, shadows); + const detailBox = (material: THREE.Material, x: number, y: number, z: number, width: number, height: number, depth: number) => + batch(boxGeometry, material, { x, y, z, width, height, depth, yaw: 0 }, false, true); const cylinder = (material: THREE.Material, x: number, y: number, z: number, radius: number, height: number, shadows = true) => batch(cylinderGeometry, material, { x, y, z, width: radius, height, depth: radius, yaw: 0 }, shadows); const heightAt = (x: number, z: number) => explorationGroundHeight(id, x, z); @@ -70,8 +75,9 @@ export function createExplorationWorld(_runtime: RustRuntime, kernel: WorldKerne const hemisphere = new THREE.HemisphereLight('#e8f1f6', desert ? '#a27d54' : '#556651', 2.25); const sun = new THREE.DirectionalLight(desert ? '#ffe2ab' : '#fff1d9', 2.6); - sun.castShadow = true; - sun.shadow.mapSize.set(1024, 1024); + const shadowSize = _options.quality?.shadowMapSize ?? 1024; + sun.castShadow = shadowSize > 0; + sun.shadow.mapSize.set(shadowSize || 512, shadowSize || 512); Object.assign(sun.shadow.camera, { left: -250, right: 250, top: 250, bottom: -250, near: 10, far: 1100 }); sun.shadow.normalBias = 0.6; sun.shadow.bias = -0.0002; sun.shadow.radius = 2; sun.position.set(-180, 350, 240); @@ -103,7 +109,7 @@ export function createExplorationWorld(_runtime: RustRuntime, kernel: WorldKerne // Raster material detail follows the same world-space terrain used by Rust. const terrainMaterial = ownMaterial(texturedAlpine - ? createAlpineTerrainMaterial({ grassTexture: alpineGrass, rockTexture: alpineRock, snowTexture: alpineSnow }) + ? createAlpineTerrainMaterial({ grassTexture: alpineGrass, rockTexture: alpineRock, snowTexture: alpineSnow }, _options.quality?.alpineDetail) : new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 1, metalness: 0 })); if (!texturedAlpine) { terrainMaterial.onBeforeCompile = shader => { @@ -136,10 +142,13 @@ export function createExplorationWorld(_runtime: RustRuntime, kernel: WorldKerne samples[index * 2 + 1] = positions.getZ(index) + (minZ + maxZ) / 2; } const heights = kernel.sampleTerrain(samples).heights; - const colors = new Float32Array(positions.count * 3); + // The textured alpine shader derives its albedo from position and normal. + // Avoid four extra JS height queries per vertex for unused fallback colors. + const colors = texturedAlpine ? undefined : new Float32Array(positions.count * 3); for (let index = 0; index < positions.count; index++) { const x = samples[index * 2], z = samples[index * 2 + 1], y = heights[index]; positions.setXYZ(index, x, y, z); + if (!colors) continue; if (desert) { const variation = Math.sin(x * 0.0021 + z * 0.0011) * 0.14 + Math.cos(z * 0.004) * 0.08; temporaryColor.copy(sandLow).lerp(sandHigh, THREE.MathUtils.clamp(0.45 + y / 220 + variation, 0, 1)); @@ -153,16 +162,28 @@ export function createExplorationWorld(_runtime: RustRuntime, kernel: WorldKerne } temporaryColor.toArray(colors, index * 3); } - geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3)); geometry.computeVertexNormals(); geometry.computeBoundingSphere(); - const mesh = new THREE.Mesh(geometry, terrainMaterial); mesh.name = `${map.englishName} terrain`; mesh.receiveShadow = true; mesh.castShadow = id === 'mountains'; scene.add(mesh); + if (colors) geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3)); + geometry.computeVertexNormals(); geometry.computeBoundingSphere(); + const tiled = id === 'mountains' && maxX - minX === 4800 && maxZ - minZ === 4800; + const renderGeometry = tiled ? splitTerrainGrid(geometry, segmentsX, segmentsZ) : [geometry]; + if (tiled) { geometries.delete(geometry); geometry.dispose(); } + for (const tile of renderGeometry) { + if (tiled) ownGeometry(tile); + const mesh = new THREE.Mesh(tile, terrainMaterial); mesh.name = `${map.englishName} terrain`; + mesh.receiveShadow = true; mesh.castShadow = id === 'mountains'; scene.add(mesh); + } } if (city) terrainPatch(-9000, 9000, -9000, 9000, 12, 12); else { - terrainPatch(-2400, 2400, -2400, 2400, id === 'mountains' ? 384 : 256, id === 'mountains' ? 384 : 256); + const terrainSegments = id === 'mountains' ? 384 : 256; + terrainPatch(-2400, 2400, -2400, 2400, terrainSegments, terrainSegments); terrainPatch(-9000, -2400, -9000, 9000, 40, 80); terrainPatch(2400, 9000, -9000, 9000, 40, 80); - terrainPatch(-2400, 2400, -9000, -2400, 40, 40); - terrainPatch(-2400, 2400, 2400, 9000, 40, 40); + // Northern crest chains reach the map edge. Share their boundary vertices + // with the distant landscape so coarse outer sampling cannot open a crack. + const outerEdgeSegments = id === 'mountains' ? terrainSegments : 40; + terrainPatch(-2400, 2400, -9000, -2400, outerEdgeSegments, 40); + terrainPatch(-2400, 2400, 2400, 9000, outerEdgeSegments, 40); } const concrete = standard('#c2c2b4'), dark = standard('#303a3e', 0.8), white = standard('#eeecd8'), steel = standard('#53636b', 0.55, 0.5); @@ -219,7 +240,7 @@ export function createExplorationWorld(_runtime: RustRuntime, kernel: WorldKerne pavement(white, along, street + lane, 4.2, 0.12, 2.1); } } - downtownBuildings = createDowntownBuildings(scene, layout.buildings); + downtownBuildings = createDowntownBuildings(scene, layout.buildings, detailDistance); const treeCanopy = standard('#5d7959'); const carMaterials = ['#c9c4b3', '#485b68', '#9c6656', '#8e9a91'].map(color => standard(color, 0.4, 0.28)); // Sparse street details remain readable while approaching, without per-window meshes. @@ -233,12 +254,12 @@ export function createExplorationWorld(_runtime: RustRuntime, kernel: WorldKerne batch(canopyGeometry, treeCanopy, { x, y: 8, z, width: 3.5, height: 4.1, depth: 3.5, yaw: 0, color: random() > 0.5 ? '#739269' : '#5e7f5e' }); cylinder(steel, x, 6.4, z + 15, 0.09, 8.8); box(steel, x - side * 1.7, 10.7, z + 15, 3.6, 0.16, 0.19); - box(warmLight, x - side * 3.1, 10.55, z + 15, 1.1, 0.12, 0.45, 0, false); + detailBox(warmLight, x - side * 3.1, 10.55, z + 15, 1.1, 0.12, 0.45); streetLights.push(new THREE.Vector3(x - side * 3.1, 10.2, z + 15)); if (random() < 0.3) { const car = carMaterials[Math.floor(random() * carMaterials.length)]; box(car, street + side * 13, 2.85, z + 37, 1.9, 1.4, 4.6); - box(dark, street + side * 13, 3.65, z + 37, 1.65, 0.65, 2.1, 0, false); + detailBox(dark, street + side * 13, 3.65, z + 37, 1.65, 0.65, 2.1); } } } @@ -246,7 +267,7 @@ export function createExplorationWorld(_runtime: RustRuntime, kernel: WorldKerne for (const side of [-1, 1]) for (let z = 45; z <= 145; z += 25) pavement(concrete, side * 28, z, 14, 23, 2.09); } else { // One low-poly batch for the scenery authored alongside collision boxes. - const rock = !desert && alpineRock ? ownMaterial(createAlpineRockMaterial({ rockTexture: alpineRock })) : standard('#b37451', 0.97); + const rock = !desert && alpineRock ? ownMaterial(createAlpineRockMaterial({ rockTexture: alpineRock }, _options.quality?.alpineDetail)) : standard('#b37451', 0.97); if (desert || !alpineRock) { rock.onBeforeCompile = shader => { shader.vertexShader = 'varying vec3 strataPoint;\n' + shader.vertexShader; @@ -274,8 +295,8 @@ export function createExplorationWorld(_runtime: RustRuntime, kernel: WorldKerne for (const building of layout.buildings) { box(concrete, building.x, building.base + building.height / 2, building.z, building.width, building.height, building.depth); box(desert ? white : wood, building.x, building.base + building.height + 0.15, building.z, building.width + 1, 0.3, building.depth + 1); - box(dark, building.x, building.base + 1.8, building.z + building.depth / 2 + 0.02, 2.2, 3.6, 0.1, 0, false); - box(warmLight, building.x + building.width * 0.25, building.base + 2.7, building.z + building.depth / 2 + 0.03, 1.6, 1.4, 0.1, 0, false); + detailBox(dark, building.x, building.base + 1.8, building.z + building.depth / 2 + 0.02, 2.2, 3.6, 0.1); + detailBox(warmLight, building.x + building.width * 0.25, building.base + 2.7, building.z + building.depth / 2 + 0.03, 1.6, 1.4, 0.1); } // Scenic trails follow the numerical ground, rather than floating over slopes. const curve = new THREE.CatmullRomCurve3([map.spawn, ...map.checkpoints.map(checkpoint => checkpoint.position)].map(point => new THREE.Vector3(point.x, 0, point.z)), false, 'centripetal'); @@ -308,7 +329,7 @@ export function createExplorationWorld(_runtime: RustRuntime, kernel: WorldKerne const x = (random() - 0.5) * 4700, z = (random() - 0.5) * 4700; if (nearCourse(x, z, 14)) continue; const size = 0.8 + random() * 3.2; - batch(stoneGeometry, rock, { x, y: heightAt(x, z) + size * 0.2, z, width: size, height: size * 0.65, depth: size * 0.8, yaw: random() * 6.28, color: '#ad8968' }, false); + batch(stoneGeometry, rock, { x, y: heightAt(x, z) + size * 0.2, z, width: size, height: size * 0.65, depth: size * 0.8, yaw: random() * 6.28, color: '#ad8968' }, false, true); } } else { // Geometry trees retain a silhouette from above, while the snow line stays treeless. @@ -338,6 +359,8 @@ export function createExplorationWorld(_runtime: RustRuntime, kernel: WorldKerne if (pose.color) mesh.setColorAt(index, temporaryColor.set(pose.color)); }); mesh.castShadow = entry.shadows; mesh.receiveShadow = true; mesh.computeBoundingSphere(); mesh.name = `${map.englishName} shared scenery`; + mesh.userData.sceneryDetail = entry.detail; + if (entry.detail) detailChunks.push(mesh); instances.push(mesh); scene.add(mesh); } batches.clear(); @@ -392,7 +415,8 @@ export function createExplorationWorld(_runtime: RustRuntime, kernel: WorldKerne localLamps.forEach((light, index) => { const value = nearestLamps[index]; if (value) light.position.copy(value.position); light.intensity = value ? 65 : 0; }); } highlights.forEach((highlight, index) => { highlight.visible = index === nextCheckpoint; if (highlight.visible) highlight.scale.setScalar(1 + Math.sin(time * 1.8) * 0.0025); }); - downtownBuildings?.update(time); + updateDetailVisibility(detailChunks, cameraPosition ?? focus, detailDistance); + downtownBuildings?.update(time, cameraPosition ?? focus); }, dispose() { if (disposed) return; disposed = true; diff --git a/src/game/graphics-quality.ts b/src/game/graphics-quality.ts new file mode 100644 index 0000000..1a79260 --- /dev/null +++ b/src/game/graphics-quality.ts @@ -0,0 +1,46 @@ +/** Serializable user preference. Auto is resolved once for each renderer lifetime. */ +export const QUALITY_PRESETS = ['auto', 'low', 'medium', 'high'] as const; +export type QualityPreset = typeof QUALITY_PRESETS[number]; +export type AlpineDetail = 'low' | 'medium' | 'high'; + +export interface GraphicsDevice { + isMobile: boolean; + devicePixelRatio: number; + viewportWidth: number; + maxTextureSize: number; +} + +export interface GraphicsQuality { + readonly preset: QualityPreset; + readonly maxPixelRatio: number; + readonly panoramaResolution: 3548 | 7096; + /** Zero disables shadow allocation and rendering entirely. */ + readonly shadowMapSize: 0 | 512 | 1024 | 2048; + readonly alpineDetail: AlpineDetail; + readonly detailDistance: number; + readonly antialias: boolean; + readonly targetFps: 30 | 60; +} + +export function isQualityPreset(value: unknown): value is QualityPreset { + return typeof value === 'string' && QUALITY_PRESETS.some(preset => preset === value); +} + +/** No browser globals: landscape phones remain within the mobile texture budget. */ +export function resolveGraphicsQuality(preset: QualityPreset, device: GraphicsDevice): GraphicsQuality { + const selected = isQualityPreset(preset) ? preset : 'auto'; + const dpr = Number.isFinite(device.devicePixelRatio) && device.devicePixelRatio > 0 ? device.devicePixelRatio : 1; + const width = Number.isFinite(device.viewportWidth) ? Math.max(0, device.viewportWidth) : 0; + const targetFps = device.isMobile ? 30 : 60; + if (selected === 'low') return Object.freeze({ preset: selected, maxPixelRatio: Math.min(dpr, 1), + panoramaResolution: 3548, shadowMapSize: 0, alpineDetail: 'low', detailDistance: 260, antialias: false, targetFps }); + if (selected === 'medium' || selected === 'auto' && device.isMobile) { + return Object.freeze({ preset: selected, maxPixelRatio: Math.min(dpr, selected === 'auto' ? 1.25 : 1.5), + panoramaResolution: 3548, shadowMapSize: selected === 'auto' ? 512 : 1024, + alpineDetail: 'medium', detailDistance: selected === 'auto' ? 350 : 480, antialias: true, targetFps }); + } + const maxPixelRatio = Math.min(dpr, 1.75); + const hd = device.maxTextureSize >= 7096 && (selected === 'high' || width * maxPixelRatio > 900); + return Object.freeze({ preset: selected, maxPixelRatio, panoramaResolution: hd ? 7096 : 3548, + shadowMapSize: selected === 'high' ? 2048 : 1024, alpineDetail: 'high', detailDistance: 760, antialias: true, targetFps }); +} diff --git a/src/game/preferences.ts b/src/game/preferences.ts new file mode 100644 index 0000000..93f4d38 --- /dev/null +++ b/src/game/preferences.ts @@ -0,0 +1,72 @@ +import { DEFAULT_DRONE_ID, DRONES } from './drone-catalog.ts'; +import type { DroneId } from './drone-catalog.ts'; +import { DEFAULT_MAP_ID, MAPS } from './map-catalog.ts'; +import type { MapId } from './map-catalog.ts'; +import type { CameraMode, FlightMode, RaceMode } from './types.ts'; +import { DEFAULT_WIND_SETTINGS, WIND_PRESETS } from './wind.ts'; +import type { WindSettings } from './wind.ts'; +import { isQualityPreset } from './graphics-quality.ts'; +import type { QualityPreset } from './graphics-quality.ts'; +import { normalizeTouchSettings } from '../components/touch-settings.ts'; +import type { TouchSettings } from '../components/touch-settings.ts'; + +export const PREFERENCES_STORAGE_KEY = 'aeroflow:preferences'; +export const PREFERENCES_VERSION = 1; + +export interface FlightPreferences { + version: typeof PREFERENCES_VERSION; + mapId: MapId; + droneId: DroneId; + mode: RaceMode; + flightMode: FlightMode; + cameraMode: CameraMode; + windSettings: WindSettings; + night: boolean; + sound: boolean; + qualityPreset: QualityPreset; + touch: TouchSettings; +} + +export function defaultFlightPreferences(): FlightPreferences { + return { version: PREFERENCES_VERSION, mapId: DEFAULT_MAP_ID, droneId: DEFAULT_DRONE_ID, + mode: 'race', flightMode: 'assisted', cameraMode: 'chase', windSettings: { ...DEFAULT_WIND_SETTINGS }, + night: false, sound: false, qualityPreset: 'auto', touch: normalizeTouchSettings(undefined) }; +} + +/** Only known settings are retained. Flight position, ammunition and progress are never serialized. */ +export function normalizeFlightPreferences(value: unknown): FlightPreferences { + const defaults = defaultFlightPreferences(); + if (!value || typeof value !== 'object' || Array.isArray(value)) return defaults; + const source = value as Partial; + if (source.version !== PREFERENCES_VERSION) return defaults; + const wind = source.windSettings; + const direction = typeof wind?.direction === 'number' && Number.isFinite(wind.direction) + ? ((wind.direction % 360) + 360) % 360 : defaults.windSettings.direction; + return { + version: PREFERENCES_VERSION, + mapId: MAPS.some(map => map.id === source.mapId) ? source.mapId! : defaults.mapId, + droneId: DRONES.some(drone => drone.id === source.droneId) ? source.droneId! : defaults.droneId, + mode: source.mode === 'race' || source.mode === 'free' ? source.mode : defaults.mode, + flightMode: source.flightMode === 'assisted' || source.flightMode === 'sport' ? source.flightMode : defaults.flightMode, + cameraMode: source.cameraMode === 'chase' || source.cameraMode === 'bomb' || source.cameraMode === 'fpv' ? source.cameraMode : defaults.cameraMode, + windSettings: { strength: wind && Object.hasOwn(WIND_PRESETS, wind.strength) ? wind.strength : defaults.windSettings.strength, direction }, + night: typeof source.night === 'boolean' ? source.night : defaults.night, + sound: typeof source.sound === 'boolean' ? source.sound : defaults.sound, + qualityPreset: isQualityPreset(source.qualityPreset) ? source.qualityPreset : defaults.qualityPreset, + touch: normalizeTouchSettings(source.touch), + }; +} + +export function readFlightPreferences(storage?: Pick): FlightPreferences { + try { + const value = storage?.getItem(PREFERENCES_STORAGE_KEY); + return value && value.length <= 8_192 ? normalizeFlightPreferences(JSON.parse(value)) : defaultFlightPreferences(); + } catch { return defaultFlightPreferences(); } +} + +export function saveFlightPreferences(storage: Pick, preferences: FlightPreferences): boolean { + try { + storage.setItem(PREFERENCES_STORAGE_KEY, JSON.stringify(normalizeFlightPreferences(preferences))); + return true; + } catch { return false; } +} diff --git a/src/game/records.ts b/src/game/records.ts index 3732028..ed2f2cd 100644 --- a/src/game/records.ts +++ b/src/game/records.ts @@ -6,7 +6,7 @@ import type { MapId } from './map-catalog.ts'; export function bestTimeKey(drone: DroneId, mode: FlightMode, wind: WindSettings, mapId: MapId = 'valley') { const weather = wind.strength === 'calm' ? 'calm' : `${wind.strength}:${((wind.direction % 360) + 360) % 360}`; - const revision = mapId === 'mountains' ? ':sharp-ridges-v2' : mapId === 'downtown' ? ':architecture-v2' : ''; + const revision = mapId === 'mountains' ? ':broken-ridges-v3' : mapId === 'downtown' ? ':architecture-v2' : ''; return `aeroflow:v5:best:${mapId}${revision}:${drone}:${mode}:${weather}`; } diff --git a/src/game/render-performance.ts b/src/game/render-performance.ts index eb17ebd..deffd8a 100644 --- a/src/game/render-performance.ts +++ b/src/game/render-performance.ts @@ -29,6 +29,8 @@ export interface RendererPerformanceInfo { export interface RenderPerformanceOptions { isMobile: boolean; devicePixelRatio: number; + /** Preset/device budget; adaptive resolution may reduce this, never exceed it. */ + maxPixelRatio?: number; } const SAMPLE_WINDOW_MS = 1_000; @@ -73,9 +75,10 @@ export class RenderPerformanceMonitor { private submissionTotal = 0; private latest: Readonly; - constructor({ isMobile, devicePixelRatio }: RenderPerformanceOptions) { + constructor({ isMobile, devicePixelRatio, maxPixelRatio = 1.75 }: RenderPerformanceOptions) { this.targetFps = isMobile ? 30 : 60; - const maximum = Math.min(Number.isFinite(devicePixelRatio) && devicePixelRatio > 0 ? devicePixelRatio : 1, 1.75); + const ceiling = Number.isFinite(maxPixelRatio) && maxPixelRatio > 0 ? Math.min(maxPixelRatio, 1.75) : 1.75; + const maximum = Math.min(Number.isFinite(devicePixelRatio) && devicePixelRatio > 0 ? devicePixelRatio : 1, ceiling); this.levels = [...new Set(PIXEL_RATIO_LEVELS.map(ratio => Math.min(ratio, maximum)))]; this.level = this.levels.length - 1; this.latest = { diff --git a/src/game/scenery-chunks.ts b/src/game/scenery-chunks.ts new file mode 100644 index 0000000..befc459 --- /dev/null +++ b/src/game/scenery-chunks.ts @@ -0,0 +1,56 @@ +import * as THREE from 'three'; +import type { Vec3 } from './flight.ts'; + +/** Structures keep their full silhouette; small decorations use finer regional batches. */ +export function sceneryChunkKey(x: number, z: number, detail = false): string { + const size = detail ? 600 : 1200; + return `${Math.floor(x / size)}:${Math.floor(z / size)}`; +} + +export function updateDetailVisibility(chunks: readonly THREE.InstancedMesh[], position: Vec3 | undefined, distance: number): void { + for (const chunk of chunks) { + const sphere = chunk.boundingSphere; + if (!position || !sphere) { chunk.visible = true; continue; } + const dx = position.x - sphere.center.x, dy = position.y - sphere.center.y, dz = position.z - sphere.center.z; + chunk.visible = dx * dx + dy * dy + dz * dz <= (sphere.radius + distance) ** 2; + } +} + +/** + * Split an already sampled plane after its normals are calculated. Shared edge + * positions, normals, UVs and triangle winding are copied without resampling the + * physical terrain or averaging each tile's edges independently. + */ +export function splitTerrainGrid(source: THREE.BufferGeometry, segmentsX: number, segmentsZ: number, tileCells = 96): THREE.BufferGeometry[] { + if (!Number.isInteger(segmentsX) || !Number.isInteger(segmentsZ) || segmentsX < 1 || segmentsZ < 1 + || !Number.isInteger(tileCells) || tileCells < 1 || !source.index + || source.getAttribute('position').count !== (segmentsX + 1) * (segmentsZ + 1)) { + throw new RangeError('A complete indexed terrain grid is required'); + } + const tiles: THREE.BufferGeometry[] = []; + for (let row = 0; row < segmentsZ; row += tileCells) for (let column = 0; column < segmentsX; column += tileCells) { + const width = Math.min(tileCells, segmentsX - column), depth = Math.min(tileCells, segmentsZ - row); + const tile = new THREE.BufferGeometry(); + for (const [name, attribute] of Object.entries(source.attributes)) { + const values = new Float32Array((width + 1) * (depth + 1) * attribute.itemSize); + for (let z = 0; z <= depth; z++) for (let x = 0; x <= width; x++) { + const input = (row + z) * (segmentsX + 1) + column + x; + const output = (z * (width + 1) + x) * attribute.itemSize; + for (let component = 0; component < attribute.itemSize; component++) values[output + component] = attribute.getComponent(input, component); + } + tile.setAttribute(name, new THREE.BufferAttribute(values, attribute.itemSize, attribute.normalized)); + } + const indices: number[] = []; + for (let z = 0; z < depth; z++) for (let x = 0; x < width; x++) { + const input = ((row + z) * segmentsX + column + x) * 6; + for (let corner = 0; corner < 6; corner++) { + const original = source.index.getX(input + corner); + indices.push((Math.floor(original / (segmentsX + 1)) - row) * (width + 1) + original % (segmentsX + 1) - column); + } + } + tile.setIndex(indices); tile.computeBoundingSphere(); + tile.userData.terrainTile = { column, row, width, depth, segmentsX, segmentsZ }; + tiles.push(tile); + } + return tiles; +} diff --git a/src/game/urban-world.ts b/src/game/urban-world.ts index e9432fc..2416d9d 100644 --- a/src/game/urban-world.ts +++ b/src/game/urban-world.ts @@ -445,7 +445,8 @@ export function createUrbanWorld(runtime: RustRuntime, kernel: WorldKernel, map: const hemisphere = new THREE.HemisphereLight('#e4f0f3', '#737764', 2.25); scene.add(hemisphere); const sun = new THREE.DirectionalLight('#fff0d5', 2.6); sun.position.set(-180, 285, 235); sun.target.position.set(0, 0, 55); - sun.castShadow = true; sun.shadow.mapSize.set(2048, 2048); + const shadowSize = _panoramaOptions.quality?.shadowMapSize ?? 2048; + sun.castShadow = shadowSize > 0; sun.shadow.mapSize.set(shadowSize || 512, shadowSize || 512); sun.shadow.camera.left = sun.shadow.camera.bottom = -240; sun.shadow.camera.right = sun.shadow.camera.top = 240; sun.shadow.camera.near = 10; sun.shadow.camera.far = 750; sun.shadow.bias = -0.0002; sun.shadow.normalBias = 0.38; scene.add(sun, sun.target); @@ -558,9 +559,9 @@ export function createUrbanWorld(runtime: RustRuntime, kernel: WorldKernel, map: detailView.set(viewPosition.x, viewPosition.y, viewPosition.z); for (const chunk of detailChunks) { const sphere = chunk.boundingSphere!; - chunk.visible = detailView.distanceToSquared(sphere.center) < (sphere.radius + 450) ** 2; + chunk.visible = detailView.distanceToSquared(sphere.center) < (sphere.radius + (_panoramaOptions.quality?.detailDistance ?? 450)) ** 2; } - for (const sign of buildingSigns) sign.visible = detailView.distanceToSquared(sign.position) < 460 ** 2; + for (const sign of buildingSigns) sign.visible = detailView.distanceToSquared(sign.position) < (_panoramaOptions.quality?.detailDistance ?? 460) ** 2; } if (focus) { const nearby = night ? lampSites.filter(site => (site.x - focus.x) ** 2 + (site.z - focus.z) ** 2 < 130 ** 2) diff --git a/src/game/world.ts b/src/game/world.ts index edb83cf..9ef8850 100644 --- a/src/game/world.ts +++ b/src/game/world.ts @@ -21,6 +21,7 @@ import type { WorldKernel } from './world-kernel.ts'; import { createSceneSimulation } from './scene-simulation.ts'; import { preloadWorldAssets } from './world-assets.ts'; import type { WorldAsset, WorldAssets } from './world-assets.ts'; +import type { GraphicsQuality } from './graphics-quality.ts'; export { groundHeight } from './landscape.ts'; @@ -66,6 +67,7 @@ export interface PanoramaOptions { resolution?: 3548 | 7096; maxAnisotropy?: number; assets?: WorldAssets; + quality?: GraphicsQuality; } export function createWorld(runtime: RustRuntime, kernel: WorldKernel, panoramaOptions: PanoramaOptions = {}, mapId: MapId = DEFAULT_MAP_ID) { @@ -115,8 +117,9 @@ export function createWorld(runtime: RustRuntime, kernel: WorldKernel, panoramaO const sun = new THREE.DirectionalLight('#fff2d7', 2.55); sun.position.set(-180, 282, 235); sun.target.position.set(0, 0, 55); - sun.castShadow = true; - sun.shadow.mapSize.set(2048, 2048); + const shadowSize = panoramaOptions.quality?.shadowMapSize ?? 2048; + sun.castShadow = shadowSize > 0; + sun.shadow.mapSize.set(shadowSize || 512, shadowSize || 512); sun.shadow.camera.left = -270; sun.shadow.camera.right = 270; sun.shadow.camera.top = 270; diff --git a/src/i18n/guide-messages.ts b/src/i18n/guide-messages.ts index bb49b92..277b57b 100644 --- a/src/i18n/guide-messages.ts +++ b/src/i18n/guide-messages.ts @@ -47,9 +47,9 @@ export const GUIDE_MESSAGES = { '向下投放一枚炸弹,飞行中可投弹': ['下向きに爆弾を 1 発投下。飛行中に使えます', 'Drop one bomb downward while flying'], '随时切换日间 / 夜间,保留当前飞行进度': ['昼間 / 夜間を切り替え。飛行の進行状況は保持されます', 'Switch day / night while preserving flight progress'], '鼠标与触屏': ['マウスとタッチ操作', 'Mouse and touch controls'], - '飞行时点击画面可启用鼠标视角,Esc 释放鼠标并暂停。手机上,单指按住飞行画面会柔和前进,持续按住约 2 秒,推进输入渐增至满量程;向上拖前进、向下拖后退、向左右拖平移,拖得越远控制幅度越大。松开手指释放控制并减速,风仍可能让飞机缓慢漂移。': [ - '飛行中に画面をクリックするとマウス視点を使えます。Escでマウスを解放し、一時停止します。スマートフォンでは飛行画面を指1本で押すとゆっくり前進し、約2秒押し続けると推進入力が最大まで滑らかに増えます。上へドラッグで前進、下へドラッグで後退、左右へドラッグで横移動し、移動距離が大きいほど操作量が増えます。指を離すと操作入力が解除されて減速しますが、風で少し流されることがあります。', - 'Click the flight view to enable mouse look; Esc releases the mouse and pauses. On phones, press the flight view with one finger to move gently forward. Hold for about two seconds to gradually reach full thrust input. Drag up to fly forward, down to reverse, or sideways to strafe; dragging farther increases the input. Release to stop applying control and slow down. Wind can still cause gentle drift.', + '飞行时点击画面可启用鼠标视角,Esc 释放鼠标并暂停。手机上,单指按住飞行画面会柔和前进,默认持续按住约 2 秒,推进输入渐增至满量程;向上拖前进、向下拖后退、向左右拖平移,拖得越远控制幅度越大。松开手指释放控制并减速,风仍可能让飞机缓慢漂移。': [ + '飛行中に画面をクリックするとマウス視点を使えます。Escでマウスを解放し、一時停止します。スマートフォンでは飛行画面を指1本で押すとゆっくり前進し、初期設定では約2秒押し続けると推進入力が最大まで滑らかに増えます。上へドラッグで前進、下へドラッグで後退、左右へドラッグで横移動し、移動距離が大きいほど操作量が増えます。指を離すと操作入力が解除されて減速しますが、風で少し流されることがあります。', + 'Click the flight view to enable mouse look; Esc releases the mouse and pauses. On phones, press the flight view with one finger to move gently forward. By default, hold for about two seconds to gradually reach full thrust input. Drag up to fly forward, down to reverse, or sideways to strafe; dragging farther increases the input. Release to stop applying control and slow down. Wind can still cause gentle drift.', ], '保持第一根手指,再按下第二根手指:上下拖动控制升降,左右拖动控制转向,向右拖即右转。松开某根手指只释放它控制的方向。投弹、小地图与风向菜单已移至手机页面底部;小地图拖动不会操纵飞机,右上角视角按钮可切换俯视瞄准。': [ '1本目の指を押したまま2本目を置くと、上下ドラッグで上昇・下降、左右ドラッグで旋回を操作できます。右へドラッグすると右旋回です。指を離すと、その指の操作だけが解除されます。爆弾投下・ミニマップ・風向のパネルはスマートフォンのページ下部にあります。ミニマップをドラッグしても機体は操作されません。右上の視点ボタンで俯瞰照準に切り替えられます。', diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index c670644..3ee0873 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -4,10 +4,11 @@ import { GUIDE_MESSAGES } from './guide-messages.ts'; import { HANGAR_MESSAGES } from './hangar-messages.ts'; import { MINIMAP_MESSAGES } from './minimap-messages.ts'; import { PANEL_MESSAGES } from './panel-messages.ts'; +import { SETTINGS_MESSAGES } from './settings-messages.ts'; import { interpolate } from './locale.ts'; import type { Locale, LocalizedMessage, MessageCatalog, MessageParams, NoticeMessage } from './locale.ts'; -export const MESSAGE_GROUPS = [APP_MESSAGES, CATALOG_MESSAGES, GUIDE_MESSAGES, HANGAR_MESSAGES, MINIMAP_MESSAGES, PANEL_MESSAGES]; +export const MESSAGE_GROUPS = [APP_MESSAGES, CATALOG_MESSAGES, GUIDE_MESSAGES, HANGAR_MESSAGES, MINIMAP_MESSAGES, PANEL_MESSAGES, SETTINGS_MESSAGES]; export const MESSAGES: MessageCatalog = Object.assign({}, ...MESSAGE_GROUPS); export function translate(locale: Locale, source: string, params?: MessageParams): string { diff --git a/src/i18n/settings-messages.ts b/src/i18n/settings-messages.ts new file mode 100644 index 0000000..78a5255 --- /dev/null +++ b/src/i18n/settings-messages.ts @@ -0,0 +1,36 @@ +import type { MessageCatalog } from './locale.ts'; + +export const SETTINGS_MESSAGES: MessageCatalog = { + '设置': ['設定', 'Settings'], + '打开设置': ['設定を開く', 'Open settings'], + '关闭设置': ['設定を閉じる', 'Close settings'], + '飞行偏好': ['フライト設定', 'Flight preferences'], + '保留常用设置,让下一次起飞更顺手。飞行已暂停,关闭后可手动继续。': ['使い慣れた設定で、次のフライトへ。飛行中は一時停止し、閉じた後に手動で再開できます。', 'Keep your preferred setup for the next flight. Active flights pause here and can be resumed manually after closing.'], + '画面与声音': ['画面とサウンド', 'Graphics and sound'], + '画质': ['画質', 'Graphics quality'], + '自动': ['自動', 'Automatic'], + '低': ['低', 'Low'], + '中': ['中', 'Medium'], + '高': ['高', 'High'], + '自动会根据设备和帧率调整;低画质优先流畅,高画质保留更多细节。': ['自動は端末とフレームレートに合わせて調整します。低画質は軽快さを、高画質は細部を優先します。', 'Automatic adapts to the device and frame rate. Low favors smoothness; High retains more detail.'], + '游戏声音': ['ゲームのサウンド', 'Game sound'], + '声音偏好会保存;重新打开网页后,声音从下一次点击或按键开始。': ['サウンドの設定は保存します。再訪時は、次のクリックやキー操作から再生します。', 'The sound preference is saved. After reopening, audio starts with your next click or key press.'], + '触屏飞行手势': ['タッチ飛行操作', 'Touch flight gestures'], + '操控灵敏度': ['操作感度', 'Control sensitivity'], + '按住加速时间': ['長押しの加速時間', 'Hold-to-accelerate time'], + '{seconds} 秒': ['{seconds} 秒', '{seconds} s'], + '反转上下拖动': ['上下ドラッグを反転', 'Reverse vertical dragging'], + '上下反转仅影响触屏飞行的前后与升降手势,不改变键盘、鼠标或机枪瞄准。': ['上下反転はタッチ飛行の前後移動と昇降に適用します。キーボード・マウス・機銃照準には影響しません。', 'Vertical reversal applies to touch flight movement and climb. Keyboard, mouse, and gun aiming remain unchanged.'], + '更改画质会重新准备全部地图,并返回当前地图起点;位置、弹药和本轮进度会重置。': ['画質の変更時は全マップを再準備し、現在のマップのスタートへ戻ります。位置・弾薬・今回の進行はリセットされます。', 'Changing quality prepares every map again and returns to the current map start. Position, ammunition, and the current run are reset.'], + '机型、地图、模式、风况、昼夜、视角及这些偏好保存在本浏览器;位置、弹药和飞行进度不保存。': ['機体・マップ・モード・風・昼夜・視点と各設定を、このブラウザーに保存します。位置・弾薬・飛行の進行は保存しません。', 'Aircraft, map, modes, wind, day/night, view, and these preferences are saved in this browser. Position, ammunition, and flight progress are not saved.'], + '浏览器无法保存设置;当前页面内仍可正常调整,重新打开后这些更改可能不会保留。': ['ブラウザーで設定を保存できません。このページでは調整できますが、再訪時には変更が残らない場合があります。', 'This browser cannot save settings. Adjustments still work on this page, but these changes may not survive reopening.'], + '应用设置': ['設定を適用', 'Apply settings'], + '查看操作指南': ['操作ガイドを見る', 'View flight guide'], + '重置全部偏好会返回山谷起点并重新准备地图,个人最佳与语言选择会保留。': ['全設定のリセットは谷のスタート地点へ戻り、マップを再準備します。自己ベストと言語設定は保持します。', 'Resetting all preferences returns to the valley start and prepares the maps again. Personal bests and language are retained.'], + '重置全部偏好': ['全設定を初期値に戻す', 'Reset all preferences'], + '设置已应用': ['設定を適用しました', 'Settings applied'], + '触屏灵敏度、加速时间和上下反转可在设置中调整;上述拖动方向以默认未反转为准。': ['タッチ感度・加速時間・上下反転は設定で調整できます。上記の方向は、反転していない初期設定の説明です。', 'Touch sensitivity, acceleration time, and vertical reversal can be adjusted in Settings. The directions above describe the default, non-reversed controls.'], + '版本信息': ['バージョン情報', 'Build information'], + '源码版本': ['ソースのバージョン', 'Source revision'], + '包含未提交更改': ['未コミットの変更を含む', 'Includes uncommitted changes'], +}; diff --git a/tests/alpine-data.test.ts b/tests/alpine-data.test.ts new file mode 100644 index 0000000..bdde9dd --- /dev/null +++ b/tests/alpine-data.test.ts @@ -0,0 +1,67 @@ +import assert from 'node:assert/strict'; +import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import test from 'node:test'; +import { ALPINE_MASSIFS, MOUNTAIN_PEAKS, MOUNTAIN_RIDGES } from '../src/game/alpine-massifs.ts'; +import { ALPINE_DATA_FILE, ALPINE_GENERATED_FILES, generateAlpineSources, syncAlpineData } from '../scripts/generate-alpine-data.mjs'; + +const canonical = JSON.parse(await readFile(new URL('../data/alpine-terrain.json', import.meta.url), 'utf8')); + +test('generated alpine placement retains every canonical coordinate in the runtime reference', async () => { + assert.deepEqual(MOUNTAIN_PEAKS, canonical.peaks); + assert.deepEqual(MOUNTAIN_RIDGES, canonical.ridges); + assert.deepEqual(ALPINE_MASSIFS, canonical.massifs); + const result = await syncAlpineData({ check: true }); + assert.deepEqual(result.updated, []); + assert.deepEqual(result.checked, ALPINE_GENERATED_FILES); +}); + +test('alpine generation is deterministic and independent of JSON object key order', () => { + const reordered = { massifs: canonical.massifs, ridges: canonical.ridges, peaks: canonical.peaks, schemaVersion: canonical.schemaVersion }; + assert.deepEqual(generateAlpineSources(reordered), generateAlpineSources(canonical)); +}); + +test('alpine check detects missing, edited and outdated outputs without repairing them', async () => { + const root = await mkdtemp(join(tmpdir(), 'aeroflow-alpine-data-')); + try { + await mkdir(dirname(join(root, ALPINE_DATA_FILE)), { recursive: true }); + await writeFile(join(root, ALPINE_DATA_FILE), JSON.stringify(canonical)); + await assert.rejects(syncAlpineData({ root, check: true }), /Stale alpine data/); + await assert.rejects(readFile(join(root, ALPINE_GENERATED_FILES[0])), { code: 'ENOENT' }); + assert.equal((await syncAlpineData({ root })).updated.length, 2); + const name = ALPINE_GENERATED_FILES[0]; + const original = await readFile(join(root, name), 'utf8'); + const edited = `${original}// manual change\n`; + await writeFile(join(root, name), edited); + await assert.rejects(syncAlpineData({ root, check: true }), /Stale alpine data: src\/game\/alpine-massifs.ts/); + assert.equal(await readFile(join(root, name), 'utf8'), edited, 'check must preserve the edited output'); + const repaired = await syncAlpineData({ root }); + assert.deepEqual(repaired.updated, [name]); + const rustBefore = await readFile(join(root, ALPINE_GENERATED_FILES[1]), 'utf8'); + const revised = structuredClone(canonical); + revised.massifs[0].crests[0][0][2] += 1; + await writeFile(join(root, ALPINE_DATA_FILE), JSON.stringify(revised)); + await assert.rejects(syncAlpineData({ root, check: true }), /Stale alpine data/); + assert.equal(await readFile(join(root, ALPINE_GENERATED_FILES[1]), 'utf8'), rustBefore); + assert.equal((await syncAlpineData({ root })).updated.length, 2); + await syncAlpineData({ root, check: true }); + } finally { await rm(root, { recursive: true, force: true }); } +}); + +test('invalid terrain placement fails before it can emit divisions by zero or non-finite fields', () => { + const invalid = [ + (data: typeof canonical) => { data.massifs[0].crests[0][1] = [...data.massifs[0].crests[0][0]]; }, + (data: typeof canonical) => { data.massifs[0].crests[0][0][3] = 0; }, + (data: typeof canonical) => { data.massifs[0].cirques[0][4] = -1; }, + (data: typeof canonical) => { data.peaks[0].height = Infinity; }, + (data: typeof canonical) => { data.ridges[0].width = NaN; }, + (data: typeof canonical) => { data.ridges[0].bx = data.ridges[0].ax; data.ridges[0].bz = data.ridges[0].az; }, + (data: typeof canonical) => { data.massifs[0].crests[0][0].pop(); }, + (data: typeof canonical) => { data.peaks[0].raduisX = 10; }, + ]; + for (const corrupt of invalid) { + const data = structuredClone(canonical); corrupt(data); + assert.throws(() => generateAlpineSources(data), /must|zero-length|zero length/); + } +}); diff --git a/tests/build-info.test.ts b/tests/build-info.test.ts new file mode 100644 index 0000000..9acb147 --- /dev/null +++ b/tests/build-info.test.ts @@ -0,0 +1,69 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { createBuildInfo, sourceFingerprint } from '../scripts/build-info.ts'; + +function fixture() { + const root = mkdtempSync(join(tmpdir(), 'aeroflow-build-info-')); + mkdirSync(join(root, 'src')); + mkdirSync(join(root, 'public')); + writeFileSync(join(root, 'package.json'), '{"version":"1.0.0"}'); + writeFileSync(join(root, 'src', 'main.ts'), 'export const game = 1;'); + writeFileSync(join(root, 'public', 'texture.webp'), Buffer.from([1, 2, 3, 4])); + return root; +} + +test('build identity is reproducible across checkouts and detects changes to source and shipped assets', () => { + const a = fixture(), b = fixture(); + try { + const before = sourceFingerprint(a); + assert.equal(sourceFingerprint(b), before, 'machine paths and timestamps do not change identity'); + writeFileSync(join(a, 'README.md'), 'Documentation is not part of the browser build.'); + assert.equal(sourceFingerprint(a), before); + writeFileSync(join(a, 'public', 'texture.webp'), Buffer.from([1, 2, 3, 5])); + assert.notEqual(sourceFingerprint(a), before, 'the actual texture bytes are part of the identity'); + writeFileSync(join(a, 'public', 'texture.webp'), readFileSync(join(b, 'public', 'texture.webp'))); + writeFileSync(join(a, 'src', 'main.ts'), 'export const game = 2;'); + assert.notEqual(sourceFingerprint(a), before); + } finally { rmSync(a, { recursive: true }); rmSync(b, { recursive: true }); } +}); + +test('a clean commit is identified exactly, while uncommitted source never claims to be that release', () => { + const root = fixture(); + const git = (...args: string[]) => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); + try { + git('init'); git('add', '.'); + git('-c', 'user.name=Build test', '-c', 'user.email=build@example.invalid', '-c', 'commit.gpgsign=false', 'commit', '-m', 'Fixture'); + git('remote', 'add', 'origin', 'https://github.com/kai987/FPV-drone-game.git'); + const clean = createBuildInfo(root); + assert.equal(clean.sourceRevision, git('rev-parse', 'HEAD')); + assert.equal(clean.sourceDirty, false); + assert.equal(clean.sourceRepository, 'https://github.com/kai987/FPV-drone-game'); + assert.equal(clean.appVersion, '1.0.0'); + writeFileSync(join(root, 'src', 'main.ts'), 'export const game = 3;'); + const changed = createBuildInfo(root); + assert.equal(changed.sourceRevision, clean.sourceRevision); + assert.equal(changed.sourceDirty, true); + assert.notEqual(changed.buildId, clean.buildId); + assert.notEqual(changed.sourceFingerprint, clean.sourceFingerprint); + git('remote', 'set-url', 'origin', 'https://site-source.example.invalid/project.git'); + assert.equal(createBuildInfo(root).sourceRepository, null, 'Site repository SHAs never become invented GitHub links'); + git('remote', 'set-url', 'origin', 'git@github.com:kai987/FPV-drone-game.git'); + assert.equal(createBuildInfo(root).sourceRepository, clean.sourceRepository); + } finally { rmSync(root, { recursive: true }); } +}); + +test('source archives without Git have an honest content identity and no invented revision', () => { + const root = fixture(); + try { + const info = createBuildInfo(root); + assert.equal(info.sourceRevision, null); + assert.equal(info.sourceRepository, null); + assert.equal(info.sourceDirty, true); + assert.match(info.sourceFingerprint, /^[a-f0-9]{64}$/); + assert.match(info.buildId, /^archive-dirty-[a-f0-9]{12}$/); + } finally { rmSync(root, { recursive: true }); } +}); diff --git a/tests/downtown-architecture.test.ts b/tests/downtown-architecture.test.ts index 0fae64a..577325a 100644 --- a/tests/downtown-architecture.test.ts +++ b/tests/downtown-architecture.test.ts @@ -55,7 +55,8 @@ test('real Three.js city batches represent structural pieces and release their o boxes.push({ x: position.x, y: position.y, z: position.z, width: scale.x, height: scale.y, depth: scale.z }); } }); - assert.ok(meshes.length < 60, `architecture uses ${meshes.length} batches`); + assert.ok(meshes.length < 900, `architecture uses ${meshes.length} regional batches`); + assert.ok(meshes.every(mesh => mesh.frustumCulled && mesh.boundingSphere!.radius < 1100), 'batches have local bounds instead of spanning the entire city'); assert.ok(boxes.length < 20_000, 'detail remains instanced rather than adding individual windows'); const representatives = new Map(getExplorationLayout('downtown').buildings.map(building => [getDowntownBuildingParts(building).archetype, building])); for (const building of representatives.values()) for (const part of getDowntownBuildingParts(building).solids) { @@ -64,6 +65,12 @@ test('real Three.js city batches represent structural pieces and release their o && Math.abs(box.y - part.base - part.height / 2) < 0.002 && Math.abs(box.width - part.width) < 0.002 && Math.abs(box.height - part.height) < 0.002 && Math.abs(box.depth - part.depth) < 0.002), 'native structural piece also exists in the rendered model'); } + city.update(0, { x: 10000, y: 500, z: 10000 }); + assert.ok(meshes.some(mesh => mesh.userData.sceneryDetail && !mesh.visible), 'far decorations are removed from draw traversal'); + assert.ok(meshes.filter(mesh => !mesh.userData.sceneryDetail).every(mesh => mesh.visible), 'physical building silhouettes and roof support stay rendered at every distance'); + const nearDetail = meshes.find(mesh => mesh.userData.sceneryDetail)!; + city.update(0, nearDetail.boundingSphere!.center); + assert.equal(nearDetail.visible, true, 'nearby facade and rooftop detail returns'); let releasedGeometry = 0, releasedMaterial = 0, releasedTexture = 0; geometries.forEach(value => value.addEventListener('dispose', () => releasedGeometry++)); materials.forEach(value => value.addEventListener('dispose', () => releasedMaterial++)); diff --git a/tests/exploration-physics.test.ts b/tests/exploration-physics.test.ts index efd06db..6be146b 100644 --- a/tests/exploration-physics.test.ts +++ b/tests/exploration-physics.test.ts @@ -160,12 +160,12 @@ test('natural landmarks are distinct, finite and well below the mountain altitud const desertHeights = samples.map(point => explorationGroundHeight('desert', point.x, point.z)); const mountainHeights = samples.map(point => explorationGroundHeight('mountains', point.x, point.z)); assert.ok(Math.max(...desertHeights) - Math.min(...desertHeights) > 140); - assert.ok(Math.max(...mountainHeights) - Math.min(...mountainHeights) > 600); assert.ok(Math.max(...mountainHeights) < 780); let envelopeMaximum = -Infinity; for (let x = -2400; x <= 2400; x += 20) for (let z = -2400; z <= 2400; z += 20) { envelopeMaximum = Math.max(envelopeMaximum, explorationGroundHeight('mountains', x, z)); } assert.ok(envelopeMaximum > 700 && envelopeMaximum < 780, 'sharper ridgelines remain below the 800 m ceiling'); + assert.ok(envelopeMaximum - Math.min(...mountainHeights) > 600, 'displaced summits retain the full alpine relief'); assert.ok([...desertHeights, ...mountainHeights].every(height => Number.isFinite(height) && height > -2)); }); diff --git a/tests/graphics-quality.test.ts b/tests/graphics-quality.test.ts new file mode 100644 index 0000000..1d8d756 --- /dev/null +++ b/tests/graphics-quality.test.ts @@ -0,0 +1,56 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { isQualityPreset, resolveGraphicsQuality } from '../src/game/graphics-quality.ts'; +import { RenderPerformanceMonitor } from '../src/game/render-performance.ts'; + +const desktop = { isMobile: false, devicePixelRatio: 2, viewportWidth: 1440, maxTextureSize: 16384 }; + +test('auto mobile remains within the light panorama budget after rotation or on large tablets', () => { + for (const viewportWidth of [390, 844, 1366, 3000]) { + const mobile = resolveGraphicsQuality('auto', { ...desktop, isMobile: true, devicePixelRatio: 3, viewportWidth }); + assert.equal(mobile.panoramaResolution, 3548); + assert.equal(mobile.maxPixelRatio, 1.25); + assert.equal(mobile.shadowMapSize, 512); + assert.equal(mobile.alpineDetail, 'medium'); + assert.equal(mobile.targetFps, 30); + } +}); + +test('explicit high can opt into HD while respecting device texture and DPR limits', () => { + assert.equal(resolveGraphicsQuality('high', { ...desktop, isMobile: true, viewportWidth: 390 }).panoramaResolution, 7096); + assert.equal(resolveGraphicsQuality('high', { ...desktop, maxTextureSize: 4096 }).panoramaResolution, 3548); + for (const preset of ['auto', 'low', 'medium', 'high'] as const) { + assert.ok(resolveGraphicsQuality(preset, { ...desktop, devicePixelRatio: 0.8 }).maxPixelRatio <= 0.8); + } + assert.equal(resolveGraphicsQuality('auto', { ...desktop, viewportWidth: 300, devicePixelRatio: 1 }).panoramaResolution, 3548); +}); + +test('presets change the complete rendering budget together without changing geography', () => { + const low = resolveGraphicsQuality('low', desktop), medium = resolveGraphicsQuality('medium', desktop), high = resolveGraphicsQuality('high', desktop); + assert.deepEqual([low.panoramaResolution, medium.panoramaResolution, high.panoramaResolution], [3548, 3548, 7096]); + assert.deepEqual([low.shadowMapSize, medium.shadowMapSize, high.shadowMapSize], [0, 1024, 2048]); + assert.equal(resolveGraphicsQuality('auto', desktop).shadowMapSize, 1024, 'auto never upgrades the default shadow allocation'); + assert.deepEqual([low.alpineDetail, medium.alpineDetail, high.alpineDetail], ['low', 'medium', 'high']); + assert.ok(low.detailDistance < medium.detailDistance && medium.detailDistance < high.detailDistance); + assert.equal(low.antialias, false); assert.equal(high.antialias, true); + assert.ok([low, medium, high].every(value => Object.isFrozen(value))); +}); + +test('storage-facing preset validation rejects unknown types and budgets tolerate invalid measurements', () => { + for (const value of ['auto', 'low', 'medium', 'high']) assert.equal(isQualityPreset(value), true); + for (const value of [null, undefined, 1, {}, 'ultra', 'HIGH']) assert.equal(isQualityPreset(value), false); + const budget = resolveGraphicsQuality('auto', { ...desktop, devicePixelRatio: NaN, viewportWidth: NaN, maxTextureSize: NaN }); + assert.equal(budget.maxPixelRatio, 1); assert.equal(budget.panoramaResolution, 3548); +}); + +test('adaptive DPR never upgrades beyond the resolved preset even after sustained headroom', () => { + const monitor = new RenderPerformanceMonitor({ isMobile: true, devicePixelRatio: 3, maxPixelRatio: 1.25 }); + const info = { render: { calls: 10, triangles: 1000 }, memory: { geometries: 3, textures: 2 } }; + for (let time = 0; time < 60000; time += 20) { + monitor.recordFrame(time, 1, 1, 1, info); + assert.ok(monitor.pixelRatio <= 1.25); + } + assert.equal(monitor.pixelRatio, 1.25); + const low = new RenderPerformanceMonitor({ isMobile: false, devicePixelRatio: 3, maxPixelRatio: 1 }); + assert.equal(low.pixelRatio, 1); +}); diff --git a/tests/mountain-topography.test.ts b/tests/mountain-topography.test.ts index 64ff894..0dd8aeb 100644 --- a/tests/mountain-topography.test.ts +++ b/tests/mountain-topography.test.ts @@ -2,22 +2,60 @@ import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import test from 'node:test'; import { MOUNTAIN_PEAKS, MOUNTAIN_RIDGES, explorationGroundHeight } from '../src/game/exploration-layout.ts'; +import { ALPINE_MASSIFS } from '../src/game/alpine-massifs.ts'; import { createRustRuntime } from '../src/game/rust-runtime.ts'; import { createWorldKernel } from '../src/game/world-kernel.ts'; const module = await WebAssembly.compile(await readFile(new URL('../src/game/generated/flight_core.wasm', import.meta.url))); -test('alpine summits have a narrow crown and remain flyable beneath the altitude ceiling', () => { +test('massif summits are displaced and retain unequal shoulders beneath the altitude ceiling', () => { const world = createWorldKernel(createRustRuntime(module), 'mountains'); try { for (const peak of MOUNTAIN_PEAKS) { - const summit = world.groundHeight(peak.x, peak.z); - assert.ok(summit > 450 && summit < 780, 'summits retain room beneath the 800 m flight limit'); - for (const [dx, dz] of [[80, 0], [-80, 0], [0, 80], [0, -80]]) { - const flank = world.groundHeight(peak.x + dx, peak.z + dz); - assert.ok(summit - flank > 70, `the summit at ${peak.x}/${peak.z} must have a visible shoulder, not a rounded dome`); - assert.ok(Math.abs(flank - explorationGroundHeight('mountains', peak.x + dx, peak.z + dz)) < 1e-8); + let summit = { x: peak.x, z: peak.z, y: -Infinity }; + for (let x = peak.x - 550; x <= peak.x + 550; x += 10) for (let z = peak.z - 550; z <= peak.z + 550; z += 10) { + const y = world.groundHeight(x, z); + if (y > summit.y) summit = { x, z, y }; } + assert.ok(summit.y > 530 && summit.y < 780, 'all five massif regions retain real summits below the 800 m ceiling'); + assert.ok(Math.hypot(summit.x - peak.x, summit.z - peak.z) > 35, 'the summit is displaced from the old radial cone centre'); + const drops = [[80, 0], [-80, 0], [0, 80], [0, -80]].map(([dx, dz]) => { + const flank = world.groundHeight(summit.x + dx, summit.z + dz); + assert.ok(Math.abs(flank - explorationGroundHeight('mountains', summit.x + dx, summit.z + dz)) < 1e-8); + return summit.y - flank; + }); + assert.ok(Math.max(...drops) - Math.min(...drops) > 70, 'a high crest has an unequal long shoulder and an abrupt opposing face'); + assert.ok(Math.min(...drops) < 200 && Math.max(...drops) > 190, 'shoulders and cliffs coexist instead of four equally falling cone sides'); + } + } finally { world.dispose(); } +}); + +test('each massif has separated prominent skyline crests instead of one triangular outline', () => { + const world = createWorldKernel(createRustRuntime(module), 'mountains'); + try { + for (const peak of MOUNTAIN_PEAKS) { + const prominent: number[] = []; + // A projected upper envelope tests what the silhouette actually contains, + // independently of the authored crest nodes or their construction method. + for (const axis of ['x', 'z']) { + const skyline: number[] = []; + for (let along = -500; along <= 500; along += 20) { + let maximum = -Infinity; + for (let across = -550; across <= 550; across += 20) + maximum = Math.max(maximum, world.groundHeight(peak.x + (axis === 'x' ? along : across), peak.z + (axis === 'z' ? along : across))); + skyline.push(maximum); + } + const summit = Math.max(...skyline); + let count = 0; + for (let i = 2; i < skyline.length - 2; i++) { + if (skyline[i] < summit * 0.6 || skyline[i] < skyline[i - 1] || skyline[i] <= skyline[i + 1]) continue; + const left = Math.min(...skyline.slice(Math.max(0, i - 8), i)); + const right = Math.min(...skyline.slice(i + 1, i + 9)); + if (skyline[i] - Math.max(left, right) > 32) count++; + } + prominent.push(count); + } + assert.ok(Math.max(...prominent) >= 2, `the massif near ${peak.x}/${peak.z} has multiple substantial crests and a real separating col`); } } finally { world.dispose(); } }); @@ -85,3 +123,19 @@ test('mountain flanks include metre-scaled erosion and buttresses rather than sm assert.ok(brokenFaces >= 6, 'erosion changes the shape of multiple distinct rock faces at 20–200 m scales'); } finally { world.dispose(); } }); + +test('bent crest shoulders and end caps have continuous support across either side', () => { + const world = createWorldKernel(createRustRuntime(module), 'mountains'); + try { + for (const massif of ALPINE_MASSIFS) for (const crest of massif.crests) for (let index = 1; index < crest.length; index++) { + const a = crest[index - 1], b = crest[index], dx = b[0] - a[0], dz = b[1] - a[1], length = Math.hypot(dx, dz); + for (const t of [-0.08, 0, 0.2, 0.6, 1, 1.08]) for (const offset of [-15, -5, 0, 5, 15]) { + const x = a[0] + dx * t - dz / length * offset, z = a[1] + dz * t + dx / length * offset; + const left = world.groundHeight(x - dz / length * 0.001, z + dx / length * 0.001); + const right = world.groundHeight(x + dz / length * 0.001, z - dx / length * 0.001); + assert.ok(Math.abs(left - right) < 0.1, `crossing two millimetres near ${x}/${z} must not jump between unequal shoulder widths`); + assert.ok(Math.abs(left - explorationGroundHeight('mountains', x - dz / length * 0.001, z + dx / length * 0.001)) < 1e-8); + } + } + } finally { world.dispose(); } +}); diff --git a/tests/preferences.test.ts b/tests/preferences.test.ts new file mode 100644 index 0000000..daf951b --- /dev/null +++ b/tests/preferences.test.ts @@ -0,0 +1,64 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { defaultFlightPreferences, normalizeFlightPreferences, PREFERENCES_STORAGE_KEY, readFlightPreferences, saveFlightPreferences } from '../src/game/preferences.ts'; + +test('all user preferences round-trip while position, ammunition and run state are excluded', () => { + const value = { ...defaultFlightPreferences(), mapId: 'mountains', droneId: 'guardian', mode: 'free', flightMode: 'sport', + cameraMode: 'fpv', windSettings: { strength: 'strong', direction: 90 }, night: true, sound: true, qualityPreset: 'low', + touch: { sensitivity: 1.65, accelerationMs: 750, invertVertical: true }, + position: { x: 10, y: 120, z: 300 }, ammo: 3, elapsed: 42, status: 'flying' } as const; + const values = new Map(); + assert.equal(saveFlightPreferences({ setItem: (key, text) => { values.set(key, text); } }, value), true); + const restored = readFlightPreferences({ getItem: key => values.get(key) ?? null }); + const { position: _position, ammo: _ammo, elapsed: _elapsed, status: _status, ...expected } = value; + assert.deepEqual(restored, expected); + const stored = JSON.parse(values.get(PREFERENCES_STORAGE_KEY)!); + for (const key of ['position', 'ammo', 'elapsed', 'status']) assert.equal(Object.hasOwn(stored, key), false); +}); + +test('missing, damaged and unknown preference schemas safely fall back', () => { + for (const text of [null, '', '{invalid', 'null', '[]', '"settings"', '{"version":0}', '{"version":2}', '{"version":"1"}']) { + assert.deepEqual(readFlightPreferences({ getItem: () => text }), defaultFlightPreferences()); + } + assert.deepEqual(readFlightPreferences(), defaultFlightPreferences()); + assert.deepEqual(readFlightPreferences({ getItem: () => ' '.repeat(8_193) }), defaultFlightPreferences()); +}); + +test('invalid individual choices fall back without losing valid choices from the same schema', () => { + const value = normalizeFlightPreferences({ version: 1, mapId: 'removed-map', droneId: 'removed-drone', mode: 'arcade', + flightMode: 'sport', cameraMode: 'orbit', windSettings: { strength: '__proto__', direction: -45 }, night: true, + sound: 'true', qualityPreset: 'ultra', touch: { sensitivity: 10, accelerationMs: -20, invertVertical: 'yes' } }); + const defaults = defaultFlightPreferences(); + assert.equal(value.mapId, defaults.mapId); assert.equal(value.droneId, defaults.droneId); + assert.equal(value.mode, defaults.mode); assert.equal(value.cameraMode, defaults.cameraMode); + assert.equal(value.flightMode, 'sport'); assert.equal(value.night, true); assert.equal(value.sound, false); + assert.equal(value.qualityPreset, 'auto'); + assert.deepEqual(value.windSettings, { strength: 'breeze', direction: 315 }); + assert.deepEqual(value.touch, { sensitivity: 2, accelerationMs: 500, invertVertical: false }); + assert.deepEqual(normalizeFlightPreferences({ version: 1, windSettings: { strength: 'calm', direction: Infinity }, + touch: { sensitivity: NaN, accelerationMs: Infinity } }).windSettings, { strength: 'calm', direction: defaults.windSettings.direction }); +}); + +test('blocked reads, blocked writes and full storage do not prevent a usable default or current settings', () => { + assert.deepEqual(readFlightPreferences({ getItem: () => { throw new Error('Storage disabled'); } }), defaultFlightPreferences()); + const current = defaultFlightPreferences(); current.mapId = 'harbor'; current.touch.sensitivity = 1.5; + const before = structuredClone(current); + assert.equal(saveFlightPreferences({ setItem: () => { throw new Error('Quota exceeded'); } }, current), false); + assert.deepEqual(current, before, 'failed persistence must not mutate live settings'); +}); + +test('a preference reset never clears personal bests or the independently saved language', () => { + const values = new Map([['aeroflow-language', 'ja'], ['aeroflow:v5:best:valley:freestyle:assisted:calm', '33']]); + saveFlightPreferences({ setItem: (key, text) => { values.set(key, text); } }, defaultFlightPreferences()); + assert.equal(values.get('aeroflow-language'), 'ja'); + assert.equal(values.get('aeroflow:v5:best:valley:freestyle:assisted:calm'), '33'); +}); + +test('defaults and normalized nested settings are independent mutable copies', () => { + const first = defaultFlightPreferences(); first.touch.sensitivity = 2; first.windSettings.direction = 0; + assert.equal(defaultFlightPreferences().touch.sensitivity, 1); + assert.equal(defaultFlightPreferences().windSettings.direction, 315); + const source = { ...defaultFlightPreferences(), touch: { sensitivity: 1.5, accelerationMs: 1_000, invertVertical: true } }; + const normalized = normalizeFlightPreferences(source); normalized.touch.sensitivity = 0.5; + assert.equal(source.touch.sensitivity, 1.5); +}); diff --git a/tests/records.test.ts b/tests/records.test.ts index d4cc973..f008bc7 100644 --- a/tests/records.test.ts +++ b/tests/records.test.ts @@ -16,6 +16,17 @@ test('revised city solids and alpine courses retain old records without comparin } }); +test('broken alpine ridges preserve the previous terrain record without using it for the revised course', () => { + const wind = { strength: 'breeze', direction: 315 } as const; + const previousKey = 'aeroflow:v5:best:mountains:sharp-ridges-v2:freestyle:assisted:breeze:315'; + const values: Record = { [previousKey]: '48' }; + const storage = { getItem: (key: string) => values[key] ?? null }; + assert.equal(readBestTime(storage, 'freestyle', 'assisted', wind, 'mountains'), null); + values[bestTimeKey('freestyle', 'assisted', wind, 'mountains')] = '51'; + assert.equal(readBestTime(storage, 'freestyle', 'assisted', wind, 'mountains'), 51); + assert.equal(values[previousKey], '48'); +}); + test('wind records separate direction and strength while calm ignores direction', () => { const key = (strength: 'calm' | 'breeze' | 'strong', direction: number) => bestTimeKey('freestyle', 'sport', { strength, direction }); assert.notEqual(key('breeze', 0), key('breeze', 180)); diff --git a/tests/scenery-chunks.test.ts b/tests/scenery-chunks.test.ts new file mode 100644 index 0000000..85d6cd2 --- /dev/null +++ b/tests/scenery-chunks.test.ts @@ -0,0 +1,47 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import * as THREE from 'three'; +import { splitTerrainGrid, updateDetailVisibility } from '../src/game/scenery-chunks.ts'; + +test('terrain tiles preserve every original triangle, edge height, UV and shared normal', () => { + const source = new THREE.PlaneGeometry(160, 120, 8, 6); source.rotateX(-Math.PI / 2); + const positions = source.attributes.position; + for (let i = 0; i < positions.count; i++) positions.setY(i, Math.sin(positions.getX(i) * 0.05) * 30 + Math.cos(positions.getZ(i) * 0.07) * 15); + source.computeVertexNormals(); + const tiles = splitTerrainGrid(source, 8, 6, 3); + assert.equal(tiles.length, 6); + const originals = new Map(); + const key = (p: THREE.BufferAttribute | THREE.InterleavedBufferAttribute, i: number) => `${p.getX(i)}:${p.getZ(i)}`; + for (let i = 0; i < positions.count; i++) originals.set(key(positions, i), i); + let duplicatedEdges = 0; + const seen = new Set(); + for (const tile of tiles) { + assert.ok(tile.boundingSphere!.radius < 100, 'tiles have independent, local culling bounds'); + for (let i = 0; i < tile.attributes.position.count; i++) { + const id = key(tile.attributes.position, i), original = originals.get(id)!; + if (seen.has(id)) duplicatedEdges++; + seen.add(id); + for (const name of ['position', 'normal', 'uv']) { + const a = source.getAttribute(name), b = tile.getAttribute(name); + for (let axis = 0; axis < a.itemSize; axis++) assert.equal(b.getComponent(i, axis), a.getComponent(original, axis)); + } + } + } + assert.ok(duplicatedEdges > 0, 'adjacent tiles really share identical edge data'); + const triangles = (geometry: THREE.BufferGeometry) => { + const output: string[] = [], p = geometry.attributes.position, index = geometry.index!; + for (let i = 0; i < index.count; i += 3) output.push([0, 1, 2].map(corner => key(p, index.getX(i + corner))).join('|')); + return output; + }; + assert.deepEqual(tiles.flatMap(triangles).sort(), triangles(source).sort(), 'no triangle is dropped, rewound or changed'); + tiles.forEach(tile => tile.dispose()); source.dispose(); +}); + +test('decorative visibility measures distance to the whole chunk, including nearby edges', () => { + const mesh = new THREE.InstancedMesh(new THREE.BoxGeometry(10, 10, 10), new THREE.MeshBasicMaterial(), 1); + mesh.setMatrixAt(0, new THREE.Matrix4().makeTranslation(300, 0, 0)); mesh.computeBoundingSphere(); + updateDetailVisibility([mesh], { x: 0, y: 0, z: 0 }, 100); assert.equal(mesh.visible, false); + updateDetailVisibility([mesh], { x: 200, y: 0, z: 0 }, 100); assert.equal(mesh.visible, true); + updateDetailVisibility([mesh], undefined, 100); assert.equal(mesh.visible, true, 'warmup may prepare every decoration'); + mesh.dispose(); mesh.geometry.dispose(); (mesh.material as THREE.Material).dispose(); +}); diff --git a/tests/touch-preferences.test.ts b/tests/touch-preferences.test.ts new file mode 100644 index 0000000..c32bb99 --- /dev/null +++ b/tests/touch-preferences.test.ts @@ -0,0 +1,59 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { TouchGestureController } from '../src/components/touch-gesture.ts'; +import { DEFAULT_TOUCH_SETTINGS, normalizeTouchSettings } from '../src/components/touch-settings.ts'; + +function advance(controller: TouchGestureController, start: number, duration: number) { + let snapshot = controller.sample(start); + for (let now = start + 16; now < start + duration; now += 16) snapshot = controller.sample(now); + snapshot = controller.sample(start + duration); + for (const axis of Object.values(snapshot.axes)) assert.ok(Number.isFinite(axis) && Math.abs(axis) <= 1); + return snapshot; +} + +test('touch settings reject nonfinite data and bound customization to usable ranges', () => { + assert.deepEqual(normalizeTouchSettings({ sensitivity: NaN, accelerationMs: Infinity, invertVertical: 'true' }), DEFAULT_TOUCH_SETTINGS); + assert.deepEqual(normalizeTouchSettings({ sensitivity: 0, accelerationMs: 99_000, invertVertical: true }), + { sensitivity: 0.5, accelerationMs: 4_000, invertVertical: true }); + for (const invalid of [null, [], false, 'settings']) assert.deepEqual(normalizeTouchSettings(invalid), DEFAULT_TOUCH_SETTINGS); +}); + +test('the configured hold duration changes acceleration without changing the maximum thrust', () => { + const fast = new TouchGestureController({ accelerationMs: 500 }); + const slow = new TouchGestureController({ accelerationMs: 4_000 }); + for (const controller of [fast, slow]) controller.begin(1, 100, 200, 0); + assert.equal(advance(fast, 0, 1_000).axes.forward, 1); + const slowAtOneSecond = advance(slow, 0, 1_000); + assert.ok(slowAtOneSecond.axes.forward > 0.16 && slowAtOneSecond.axes.forward < 0.4); + assert.equal(advance(slow, 1_000, 3_000).axes.forward, 1); +}); + +test('sensitivity changes travel needed for steering while retaining the same bounded directions', () => { + const low = new TouchGestureController({ sensitivity: 0.5 }); + const high = new TouchGestureController({ sensitivity: 2 }); + for (const controller of [low, high]) { controller.begin(1, 100, 200, 0); controller.move(1, 140, 200); } + const gentle = advance(low, 0, 2_000).axes, strong = advance(high, 0, 2_000).axes; + assert.ok(gentle.strafe > 0 && gentle.strafe < 0.3); + assert.equal(strong.strafe, 1); assert.equal(strong.forward, 0); +}); + +test('vertical reversal changes both forward/back and climb gestures without reversing yaw or strafe', () => { + const normal = new TouchGestureController(); + const reversed = new TouchGestureController({ invertVertical: true }); + for (const controller of [normal, reversed]) { + controller.begin(1, 100, 200, 0); controller.begin(2, 300, 200, 0); + controller.move(1, 100, 124); controller.move(2, 376, 124); + } + const a = advance(normal, 0, 2_000).axes, b = advance(reversed, 0, 2_000).axes; + assert.equal(a.forward, 1); assert.equal(b.forward, -1); + assert.equal(a.climb, 1); assert.equal(b.climb, -1); + assert.equal(a.yaw, b.yaw); assert.equal(a.strafe, b.strafe); +}); + +test('changing settings cancels existing pointer roles and cannot leave stale thrust active', () => { + const controller = new TouchGestureController(); controller.begin(1, 100, 200, 0); + assert.equal(advance(controller, 0, 2_000).axes.forward, 1); + controller.configure({ sensitivity: 1.5, accelerationMs: 750, invertVertical: true }); + assert.equal(controller.active, false); assert.deepEqual(controller.pointerIds, []); + assert.deepEqual(controller.sample(2_016).axes, { forward: 0, strafe: 0, climb: 0, yaw: 0 }); +}); diff --git a/tsconfig.e2e.json b/tsconfig.e2e.json new file mode 100644 index 0000000..2d7c8e1 --- /dev/null +++ b/tsconfig.e2e.json @@ -0,0 +1,5 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { "types": ["node"] }, + "include": ["playwright.config.ts", "e2e/**/*.ts"] +} diff --git a/vite.config.ts b/vite.config.ts index 355cacd..031cc1d 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,3 +1,26 @@ import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; -export default defineConfig({ plugins: [react()], base: './', build: { chunkSizeWarningLimit: 650, rollupOptions: { output: { manualChunks: { three: ['three'], react: ['react', 'react-dom'] } } } } }); +import { fileURLToPath } from 'node:url'; +import { createBuildInfo } from './scripts/build-info.ts'; + +export default defineConfig(() => { + const info = createBuildInfo(fileURLToPath(new URL('.', import.meta.url))); + const version = JSON.stringify(info, null, 2) + '\n'; + return { + plugins: [react(), { + name: 'aeroflow-build-identity', + configureServer(server) { + server.middlewares.use((request, response, next) => { + if (request.url?.split('?')[0] !== '/version.json') return next(); + response.setHeader('Content-Type', 'application/json'); + response.setHeader('Cache-Control', 'no-store'); + response.end(version); + }); + }, + generateBundle() { this.emitFile({ type: 'asset', fileName: 'version.json', source: version }); }, + }], + define: { __AEROFLOW_BUILD_INFO__: JSON.stringify(info) }, + base: './', + build: { chunkSizeWarningLimit: 650, rollupOptions: { output: { manualChunks: { three: ['three'], react: ['react', 'react-dom'] } } } }, + }; +});