Compare commits

...

684 Commits

Author SHA1 Message Date
louis-e
996e8756d0 Mock emit_map_preview_ready 2025-12-01 18:36:29 +01:00
louis-e
0c5bd51ba4 Mock emit_map_preview_ready 2025-12-01 18:32:26 +01:00
louis-e
7965dc3737 Fix CLI build issue 2025-12-01 18:07:52 +01:00
Louis Erbkamm
c54187b43a Merge branch 'main' into benchmark-map-preview 2025-12-01 18:04:14 +01:00
Louis Erbkamm
57a4a801cf Modify benchmark workflow for map preview and checkout
Updated the benchmark workflow to use actions/checkout@v5 and added steps to check for and upload a map preview artifact.
2025-12-01 18:04:08 +01:00
louis-e
beb7b73d11 Include map preview in CI benchmark 2025-12-01 18:02:59 +01:00
Louis Erbkamm
0c47e365bc Merge pull request #644 from louis-e/dependabot/cargo/semver-1.0.27
build(deps): bump semver from 1.0.26 to 1.0.27
2025-12-01 17:47:50 +01:00
Louis Erbkamm
dad3ab3b34 Merge pull request #643 from louis-e/dependabot/github_actions/actions/checkout-6
build(deps): bump actions/checkout from 5 to 6
2025-12-01 17:47:40 +01:00
Louis Erbkamm
b8b63a2bc5 Merge pull request #647 from louis-e/map-preview
Display map preview in GUI
2025-12-01 17:44:05 +01:00
louis-e
cab20b5e50 Fix clippy lint 2025-12-01 17:43:43 +01:00
louis-e
0e879837fa Remove block category comments 2025-12-01 17:42:37 +01:00
louis-e
92be2ccf00 Improve map preview generation time 2025-12-01 17:38:10 +01:00
louis-e
3b76d707d9 Display map preview in GUI 2025-12-01 17:08:54 +01:00
dependabot[bot]
be8559dee7 build(deps): bump semver from 1.0.26 to 1.0.27
Bumps [semver](https://github.com/dtolnay/semver) from 1.0.26 to 1.0.27.
- [Release notes](https://github.com/dtolnay/semver/releases)
- [Commits](https://github.com/dtolnay/semver/compare/1.0.26...1.0.27)

---
updated-dependencies:
- dependency-name: semver
  dependency-version: 1.0.27
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-12-01 02:41:00 +00:00
dependabot[bot]
94eda2fad3 build(deps): bump actions/checkout from 5 to 6
Bumps [actions/checkout](https://github.com/actions/checkout) from 5 to 6.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-12-01 02:27:47 +00:00
Louis Erbkamm
7d86854e3c Merge pull request #640 from louis-e/reintroduce-sutherland-hodgeman
Reintroduce Sutherland-Hodgman Clipping Algorithm
2025-11-28 11:28:25 +01:00
louis-e
cddaa89d35 Fix polyline clipping for segments crossing bbox with external endpoints 2025-11-28 11:12:17 +01:00
louis-e
453845977d Fix polyline clipping for segments crossing bbox with external endpoints 2025-11-28 11:10:43 +01:00
louis-e
4e196e51bd Move sutherland hodgman into own clipping file 2025-11-28 10:57:47 +01:00
louis-e
ea4dc5dc08 Remove unused dependencies 2025-11-28 10:40:06 +01:00
louis-e
c56ff83094 Fix cargo fmt 2025-11-28 01:43:55 +01:00
louis-e
2b40a520ff Reintroduce initial Sutherland-Hodgman clipping 2025-11-28 01:43:16 +01:00
louis-e
a192be981a Fix clippy 2025-11-26 15:02:12 +01:00
louis-e
eb77bca10d Refactor code comments 2025-11-26 14:49:41 +01:00
louis-e
4a891c3603 Clean up code 2025-11-26 14:40:36 +01:00
louis-e
84adfdd931 Remove floodfill abort artifacts 2025-11-26 14:32:24 +01:00
louis-e
823b6ba052 Remove debugging changes 2025-11-26 14:22:04 +01:00
louis-e
2ba8157ec9 Remove debug logging 2025-11-26 14:15:20 +01:00
louis-e
7235ba0be9 Merge remote changes, keeping our Sutherland-Hodgman implementation 2025-11-26 13:53:53 +01:00
louis-e
dee580c564 fix: cargo fmt 2025-11-26 13:48:32 +01:00
louis-e
41fc5662e0 fix: restore performance with Sutherland-Hodgman clipping and correct water rendering
- Fix O(n*m) performance regression in highway processing by building connectivity map once
- Store unclipped ways in ways_map for proper relation member merging (merge_loopy_loops)
- Use clipped ways for standalone way processing
- Add empty vector guard in merge_loopy_loops to prevent panic
- Expose build_highway_connectivity_map as public API
- Add debug_logging module for development diagnostics
2025-11-26 13:39:29 +01:00
louis-e
ac884b8c2a Correctly clip multipolygons 2025-11-23 18:34:10 +01:00
louis-e
7a9b792bee Restore node filtering for performance without breaking water features 2025-11-23 17:34:08 +01:00
Louis Erbkamm
83e9a634e5 Update baseline time and memory in benchmark workflow 2025-11-22 14:45:51 +01:00
Louis Erbkamm
56ddea57d0 Merge pull request #638 from louis-e/telemetry-nofeatures-fix
Fix no-default-features build
2025-11-22 14:37:34 +01:00
Louis Erbkamm
430a4970f5 Merge branch 'main' into telemetry-nofeatures-fix 2025-11-22 14:30:34 +01:00
Louis Erbkamm
74fbdabaee Update benchmark command with new bounding box 2025-11-22 14:30:25 +01:00
louis-e
2643155e9a Fix no-default-features build 2025-11-22 13:50:55 +01:00
Louis Erbkamm
d45c360074 Enable pr-benchmark workflow 2025-11-22 13:44:39 +01:00
Louis Erbkamm
6277a14d22 Merge pull request #618 from louis-e/dependabot/cargo/tokio-1.48.0
build(deps): bump tokio from 1.47.0 to 1.48.0
2025-11-17 21:57:36 +01:00
Louis Erbkamm
c355f243e3 Merge pull request #619 from louis-e/dependabot/cargo/geo-0.31.0
build(deps): bump geo from 0.30.0 to 0.31.0
2025-11-17 21:57:25 +01:00
Louis Erbkamm
2c31d2659c Merge pull request #630 from louis-e/crash-telemetry
WIP: Crash telemetry collection
2025-11-17 21:56:50 +01:00
louis-e
996e06ab2c Log panic to log file 2025-11-17 21:54:48 +01:00
louis-e
e11231ad0f Fix cargo fmt 2025-11-17 21:39:38 +01:00
louis-e
9adf31121e Send error telemetry data 2025-11-17 21:30:47 +01:00
louis-e
69da18fbfb Extend telemetry by more endpoints 2025-11-17 21:28:00 +01:00
louis-e
5976cc2868 Improve responsive UI layout 2025-11-17 19:15:04 +01:00
louis-e
a85eaed835 Add telemetry toggle and link to privacy policy 2025-11-17 19:09:16 +01:00
louis-e
37c3d85672 Fix clippy errors 2025-11-17 17:01:16 +01:00
louis-e
15b698a1eb WIP: Crash telemetry collection 2025-11-17 00:10:38 +01:00
Louis Erbkamm
834ce7b51d Merge pull request #629 from louis-e/2.3.1-release-prep
Prepare release 2.3.1
2025-11-16 19:52:38 +01:00
louis-e
93b6f5ac99 Prepare release 2.3.1 2025-11-16 19:52:09 +01:00
Louis Erbkamm
77df683deb Merge pull request #628 from louis-e/terrain-only-mode
Terrain only mode
2025-11-16 19:47:08 +01:00
louis-e
9d791f4299 Fix cargo fmt 2025-11-16 19:44:20 +01:00
louis-e
a2dff0b84b Backend for terrain only mode 2025-11-16 19:40:08 +01:00
louis-e
24630351b9 UI frontend for terrain only mode 2025-11-16 19:24:10 +01:00
Louis Erbkamm
819b03e3b1 Merge pull request #627 from louis-e/floodfill-stuck-fix
Fix stuck at 70% generation
2025-11-16 18:57:43 +01:00
Louis Erbkamm
f315245637 Improve timeout checks in floodfill algorithm
Added timeout checks in inner loops for better performance.
2025-11-16 18:56:05 +01:00
Louis Erbkamm
16c9f3c3bf Merge branch 'main' into floodfill-stuck-fix 2025-11-16 18:51:58 +01:00
louis-e
3043ca6d24 Fix stuck at 70% generation 2025-11-16 18:50:59 +01:00
Louis Erbkamm
3657878f01 Merge pull request #626 from louis-e/ground_crash_fix
Fix ground crash
2025-11-16 17:44:21 +01:00
louis-e
44cc57c3dd Add arnis website references 2025-11-16 17:43:11 +01:00
louis-e
408caa9176 Improve logging 2025-11-16 17:42:57 +01:00
louis-e
3191a3676d Fix src\ground.rs:27 panic crash 2025-11-16 17:42:26 +01:00
dependabot[bot]
8fff2d2fb5 build(deps): bump geo from 0.30.0 to 0.31.0
Bumps [geo](https://github.com/georust/geo) from 0.30.0 to 0.31.0.
- [Changelog](https://github.com/georust/geo/blob/main/CHANGES.md)
- [Commits](https://github.com/georust/geo/compare/geo-0.30.0...geo-0.31.0)

---
updated-dependencies:
- dependency-name: geo
  dependency-version: 0.31.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-11-01 02:13:26 +00:00
dependabot[bot]
8c702a36ff build(deps): bump tokio from 1.47.0 to 1.48.0
Bumps [tokio](https://github.com/tokio-rs/tokio) from 1.47.0 to 1.48.0.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.47.0...tokio-1.48.0)

---
updated-dependencies:
- dependency-name: tokio
  dependency-version: 1.48.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-11-01 02:13:08 +00:00
Louis Erbkamm
9bedca071a Revise official website links in README
Updated official project website information in README.
2025-10-24 19:57:32 +02:00
Louis Erbkamm
d611837746 Merge pull request #592 from louis-e/dependabot/cargo/fastnbt-2.6.0
build(deps): bump fastnbt from 2.5.0 to 2.6.0
2025-10-02 13:13:03 +02:00
Louis Erbkamm
e06fcaf7a2 Merge pull request #590 from louis-e/dependabot/cargo/tauri-2.8.5
build(deps): bump tauri from 2.7.0 to 2.8.5
2025-10-02 13:10:06 +02:00
Louis Erbkamm
1f2772f052 Merge pull request #589 from louis-e/dependabot/cargo/tempfile-3.23.0
build(deps): bump tempfile from 3.21.0 to 3.23.0
2025-10-02 13:08:37 +02:00
Louis Erbkamm
82f3460043 Merge pull request #586 from scd31/fix-rivers
Fix rivers
2025-10-02 13:05:28 +02:00
dependabot[bot]
65d6bb6c99 build(deps): bump fastnbt from 2.5.0 to 2.6.0
Bumps [fastnbt](https://github.com/owengage/fastnbt) from 2.5.0 to 2.6.0.
- [Commits](https://github.com/owengage/fastnbt/compare/fastnbt-2.5.0...fastnbt-2.6.0)

---
updated-dependencies:
- dependency-name: fastnbt
  dependency-version: 2.6.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-10-01 02:15:16 +00:00
dependabot[bot]
7ebee82982 build(deps): bump tauri from 2.7.0 to 2.8.5
Bumps [tauri](https://github.com/tauri-apps/tauri) from 2.7.0 to 2.8.5.
- [Release notes](https://github.com/tauri-apps/tauri/releases)
- [Commits](https://github.com/tauri-apps/tauri/compare/tauri-v2.7.0...tauri-v2.8.5)

---
updated-dependencies:
- dependency-name: tauri
  dependency-version: 2.8.5
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-10-01 02:14:36 +00:00
dependabot[bot]
5056e83dff build(deps): bump tempfile from 3.21.0 to 3.23.0
Bumps [tempfile](https://github.com/Stebalien/tempfile) from 3.21.0 to 3.23.0.
- [Changelog](https://github.com/Stebalien/tempfile/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Stebalien/tempfile/compare/v3.21.0...v3.23.0)

---
updated-dependencies:
- dependency-name: tempfile
  dependency-version: 3.23.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-10-01 02:14:14 +00:00
Stephen D
3cb0b994e1 handle bays 2025-09-29 18:54:56 -04:00
Stephen D
5ded3c961e fix docks 2025-09-29 18:54:56 -04:00
Stephen D
893c14bff8 fix rivers 2025-09-29 18:54:56 -04:00
Louis Erbkamm
4f8e0020e3 Merge pull request #582 from louis-e/manual_is_multiple_of
Fix indentation
2025-09-27 15:14:43 +02:00
Louis Erbkamm
456018abf7 Fix indentation
Reduced timeout checking frequency for better performance.
2025-09-27 15:14:15 +02:00
Louis Erbkamm
175bdc4582 Merge pull request #581 from louis-e/manual_is_multiple_of
Use manual % check since is_multiple_of() is unstable on stable Rust
2025-09-27 15:00:20 +02:00
Louis Erbkamm
ed294a3973 Optimize timeout checking in floodfill algorithm
Reduced timeout checking frequency for better performance and added a manual check for stability.
2025-09-27 14:59:55 +02:00
Louis Erbkamm
6c966fc9cc Implement manual % check for block counter
Add manual check for block counter multiple of batch size
2025-09-27 14:59:10 +02:00
Louis Erbkamm
ecfc6634fc Add rustfmt component to Rust toolchain setup 2025-09-27 14:49:55 +02:00
Louis Erbkamm
a336ccd1aa Merge pull request #579 from louis-e/disable-benchmark
Temporarily disable benchmark workflow
2025-09-25 21:10:20 +02:00
louis-e
f702a41af1 Temporarily disable benchmark workflow 2025-09-25 21:09:57 +02:00
Louis Erbkamm
29c4dc6d7c Merge pull request #561 from louis-e/elevated-highways-layer-support 2025-09-13 20:44:42 +02:00
Louis Erbkamm
f60b341eca Merge branch 'main' into elevated-highways-layer-support 2025-09-13 20:39:34 +02:00
louis-e
92c5e52f46 Disable negative layer highways 2025-09-13 20:39:10 +02:00
Louis Erbkamm
e4d7dd15c2 Merge pull request #566 from louis-e/root-dir-cleanup
Clean up root directory
2025-09-13 16:55:58 +02:00
Louis Erbkamm
cc6748115b Merge branch 'main' into root-dir-cleanup 2025-09-13 16:55:50 +02:00
louis-e
ce9496aea5 Link images as relative paths 2025-09-13 16:54:37 +02:00
louis-e
4c87eb8141 Use include_str instead of read_to_string 2025-09-13 16:52:14 +02:00
louis-e
ada475f73e Remove asset suffix from asset/ subdirectories 2025-09-13 16:51:50 +02:00
Louis Erbkamm
e5a82ba526 Merge pull request #563 from scd31/metadata
Metadata
2025-09-13 16:46:25 +02:00
Louis Erbkamm
309ac19b09 Fix cargo fmt in save_metadata function 2025-09-13 16:42:46 +02:00
Louis Erbkamm
90df7688df Implement error handling for saving world metadata 2025-09-13 16:38:56 +02:00
Louis Erbkamm
5b3889a7bb Add Latvian language option to dropdown 2025-09-13 15:20:32 +02:00
Louis Erbkamm
67deb739e6 Merge branch 'main' into metadata 2025-09-13 15:17:24 +02:00
Louis Erbkamm
7c08d21f36 Merge pull request #533 from scd31/nix
Nix development fix/improvements
2025-09-13 15:16:57 +02:00
louis-e
280acc7a8a Move example_transformations.json to tests/ directory 2025-09-13 14:24:11 +02:00
louis-e
ee59da5d9b Clean up root dir by combining assets 2025-09-13 14:19:59 +02:00
louis-e
b772cb6ab9 Move gui-src/ to src/gui/ 2025-09-13 14:16:55 +02:00
Louis Erbkamm
2646947ed0 Merge pull request #536 from freeutka/main
Add latvian language
2025-09-13 14:12:59 +02:00
Louis Erbkamm
b9976fd562 Merge pull request #534 from scd31/dynmap-fix
fix dynmap, and maybe other things
2025-09-13 11:12:14 +02:00
Louis Erbkamm
a621703da4 Refactor data check to use is_empty method 2025-09-13 11:01:38 +02:00
Louis Erbkamm
87efd02c74 Merge branch 'main' into dynmap-fix 2025-09-13 10:58:02 +02:00
Louis Erbkamm
6a6b58fd8f Fix block property insertion in world_editor 2025-09-13 10:57:45 +02:00
Stephen D
855c6fe846 switch to mold linker for performance 2025-09-07 19:03:48 -04:00
Stephen D
1592951fe3 world metadata 2025-09-07 16:06:58 -04:00
louis-e
e267e04350 Fix cargo fmt and clippy 2025-09-07 21:39:03 +02:00
louis-e
c2e8d5959f feat: add elevated highways with layer-based elevation 2025-09-07 18:55:42 +02:00
Stephen D
ffe8f865d2 initial cleanup 2025-09-07 11:02:25 -04:00
Louis Erbkamm
4f9f4f127a Merge pull request #558 from louis-e/interior-entityblock-removal
Replace entity blocks in building interior generation for lag reduction
2025-09-03 16:26:09 +02:00
louis-e
014208426b Replace entity blocks in building interior generation for lag reduction 2025-09-03 16:25:22 +02:00
Louis Erbkamm
6d848ef7cd Merge pull request #557 from louis-e/rollercoasters
Add rollercoasters
2025-09-03 16:23:33 +02:00
louis-e
1e25dfea37 Add rollercoasters 2025-09-03 16:13:47 +02:00
Louis Erbkamm
903efec459 Merge pull request #556 from louis-e/elevation-tilecache-crash
Implement faulty elevation tile cache detection crash
2025-09-03 15:48:27 +02:00
Louis Erbkamm
22b3969c72 Merge branch 'main' into elevation-tilecache-crash 2025-09-03 15:41:15 +02:00
Louis Erbkamm
0f62c4283b Remove clear_tile_cache function and improve error logging
Removed the clear_tile_cache function and updated error handling for file removal.
2025-09-03 15:40:19 +02:00
Louis Erbkamm
4299e64cba Merge pull request #549 from louis-e/dependabot/cargo/semver-1.0.26
build(deps): bump semver from 1.0.24 to 1.0.26
2025-09-03 15:38:20 +02:00
Louis Erbkamm
0cd386b399 Merge pull request #550 from louis-e/dependabot/cargo/tempfile-3.21.0
build(deps): bump tempfile from 3.20.0 to 3.21.0
2025-09-03 15:38:12 +02:00
Louis Erbkamm
2fdecbe206 Merge pull request #551 from louis-e/dependabot/cargo/fastanvil-0.32.0
build(deps): bump fastanvil from 0.31.0 to 0.32.0
2025-09-03 15:37:54 +02:00
Louis Erbkamm
75d1ab14e7 Merge pull request #552 from louis-e/dependabot/github_actions/actions/checkout-5
build(deps): bump actions/checkout from 4 to 5
2025-09-03 15:36:58 +02:00
Louis Erbkamm
f9c18ae5f6 Merge pull request #548 from louis-e/dependabot/cargo/tauri-build-2.4.0
build(deps): bump tauri-build from 2.3.1 to 2.4.0
2025-09-03 15:36:42 +02:00
Louis Erbkamm
963fe2327b Merge pull request #553 from louis-e/dependabot/github_actions/actions/download-artifact-5
build(deps): bump actions/download-artifact from 4 to 5
2025-09-03 15:36:26 +02:00
Louis Erbkamm
2a8ff6f641 Merge branch 'main' into elevation-tilecache-crash 2025-09-03 15:34:49 +02:00
louis-e
ff3ea1093a Implement faulty elevation tile cache detection crash 2025-09-03 15:32:50 +02:00
Louis Erbkamm
fd401ab23f Merge pull request #555 from louis-e/taginfo-refinement
Refine elements based on taginfo feedback
2025-09-03 15:03:00 +02:00
louis-e
3f67e060eb Refine elements based on taginfo feedback 2025-09-03 15:01:08 +02:00
dependabot[bot]
858c2f4c93 build(deps): bump actions/download-artifact from 4 to 5
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 4 to 5.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-09-01 06:22:06 +00:00
dependabot[bot]
e8fad0e197 build(deps): bump actions/checkout from 4 to 5
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 5.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-09-01 06:00:27 +00:00
dependabot[bot]
7ebc66db7e build(deps): bump fastanvil from 0.31.0 to 0.32.0
Bumps [fastanvil](https://github.com/owengage/fastnbt) from 0.31.0 to 0.32.0.
- [Commits](https://github.com/owengage/fastnbt/compare/fastanvil-0.31.0...fastanvil-0.32.0)

---
updated-dependencies:
- dependency-name: fastanvil
  dependency-version: 0.32.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-09-01 05:29:00 +00:00
dependabot[bot]
28b75a22cf build(deps): bump tempfile from 3.20.0 to 3.21.0
Bumps [tempfile](https://github.com/Stebalien/tempfile) from 3.20.0 to 3.21.0.
- [Changelog](https://github.com/Stebalien/tempfile/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Stebalien/tempfile/compare/v3.20.0...v3.21.0)

---
updated-dependencies:
- dependency-name: tempfile
  dependency-version: 3.21.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-09-01 05:22:02 +00:00
dependabot[bot]
9ee9f0de64 build(deps): bump semver from 1.0.24 to 1.0.26
Bumps [semver](https://github.com/dtolnay/semver) from 1.0.24 to 1.0.26.
- [Release notes](https://github.com/dtolnay/semver/releases)
- [Commits](https://github.com/dtolnay/semver/compare/1.0.24...1.0.26)

---
updated-dependencies:
- dependency-name: semver
  dependency-version: 1.0.26
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-09-01 05:19:45 +00:00
dependabot[bot]
5b874a5c29 build(deps): bump tauri-build from 2.3.1 to 2.4.0
Bumps [tauri-build](https://github.com/tauri-apps/tauri) from 2.3.1 to 2.4.0.
- [Release notes](https://github.com/tauri-apps/tauri/releases)
- [Commits](https://github.com/tauri-apps/tauri/compare/tauri-build-v2.3.1...tauri-build-v2.4.0)

---
updated-dependencies:
- dependency-name: tauri-build
  dependency-version: 2.4.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-09-01 05:17:50 +00:00
freeutka
eeecdc8f99 Create lv.json 2025-08-25 12:20:23 +03:00
Louis Erbkamm
8b33e152ef Remove icon_url from taginfo.json 2025-08-24 19:28:05 +02:00
Louis Erbkamm
ca8e50fbf1 Merge pull request #535 from louis-e/taginfo
Add comprehensive taginfo.json for OSM tag documentation
2025-08-24 18:22:18 +02:00
louis-e
7f4ef9130f Add comprehensive taginfo.json for OSM tag documentation 2025-08-24 18:18:02 +02:00
Stephen D
8d183543be fix dynmap, and maybe other things 2025-08-24 09:01:39 -04:00
Stephen D
dd07fba15c missed a file 2025-08-24 08:58:02 -04:00
Stephen D
083fbed040 nix development fix/improvements 2025-08-24 08:57:07 -04:00
Louis Erbkamm
4191fa4902 Merge pull request #532 from sralmai/patch-1
Update README.md
2025-08-24 12:25:07 +02:00
David Samuelson
6c82265ee3 Update README.md
Fix lat and long ordering in the command line build example.
2025-08-24 05:16:05 -05:00
Louis Erbkamm
7d978047b4 Enhance bug report template with additional details
Updated bug report template for clarity and detail.
2025-08-24 02:59:43 +02:00
Louis Erbkamm
0dcf4d2bc9 Merge pull request #515 from louis-e/major-release-prep
Major release preperation
2025-08-23 18:20:51 +02:00
Louis Erbkamm
0fd8f938e7 Merge branch 'main' into major-release-prep 2025-08-23 18:19:56 +02:00
Louis Erbkamm
97f891b5c9 Merge pull request #530 from louis-e/castle-material
Minor element generation enhancements
2025-08-23 18:10:59 +02:00
louis-e
4a92d3f249 Remove oak_trapdoor barrier 2025-08-23 18:10:03 +02:00
louis-e
fac0e06b1d Fix cargo fmt 2025-08-23 18:07:04 +02:00
louis-e
21d9dbddbc Enhance swing sets 2025-08-23 18:05:48 +02:00
louis-e
002ae8c7cf Enhance parking spaces 2025-08-23 18:03:12 +02:00
louis-e
09ab08bec2 Enhance greenfield and cemetery 2025-08-23 18:02:59 +02:00
Louis Erbkamm
14ecfa8aab Merge pull request #529 from louis-e/castle-material
Castle materials
2025-08-23 17:08:15 +02:00
louis-e
532e3bbb89 Implement specific castle materials 2025-08-23 17:07:42 +02:00
louis-e
ce7a2ad97e Implement specific castle materials 2025-08-23 17:07:32 +02:00
Louis Erbkamm
bc7a0d80c4 Merge pull request #528 from louis-e/window-resizable
Implement #343: Allow window to be resizable
2025-08-23 16:45:32 +02:00
louis-e
074a4f0b52 Implement #343: Allow window to be resizable 2025-08-23 16:44:36 +02:00
Louis Erbkamm
c4e2bf1b4d Merge pull request #527 from louis-e/discord-button
Add Discord button link to settings
2025-08-23 16:40:07 +02:00
louis-e
53e6be6f4a Add Discord button link to settings 2025-08-23 16:39:41 +02:00
Louis Erbkamm
37f1510399 Merge pull request #526 from louis-e/http-fallback
Fix cargo fmt
2025-08-23 16:34:13 +02:00
louis-e
dadd6917f9 Fix cargo fmt 2025-08-23 16:33:10 +02:00
Louis Erbkamm
d7dd4f64ba Merge pull request #525 from louis-e/http-fallback
Add automatic HTTP fallback for HTTPS tile loading failures
2025-08-23 16:28:15 +02:00
louis-e
6f47321ee7 Add automatic HTTP fallback for HTTPS tile loading failures 2025-08-23 16:27:23 +02:00
Louis Erbkamm
60b5f45c39 Merge pull request #524 from louis-e/linux-gpu-drivers
Fix #486: Map not loading due to GPU driver conflicts
2025-08-23 16:06:56 +02:00
louis-e
c714541434 Fix #486: Map not loading due to GPU driver conflicts 2025-08-23 16:06:07 +02:00
Louis Erbkamm
162a650f53 Merge pull request #523 from scd31/args-typo
fix typo in args
2025-08-23 15:49:56 +02:00
Stephen D
21bed97226 fix typo in args 2025-08-22 23:21:30 -04:00
Louis Erbkamm
07d4ad94bb Add Community Discord to README 2025-08-22 23:49:51 +02:00
Louis Erbkamm
0c403fd09e Add Community Discord to README 2025-08-22 23:49:15 +02:00
Louis Erbkamm
c8cdf74f02 Add Community Discord to README 2025-08-22 23:44:50 +02:00
Louis Erbkamm
ef6debdff2 Add Community Discord to README 2025-08-22 23:05:04 +02:00
Louis Erbkamm
dba37f9f2d Add Community Discord to README 2025-08-22 23:04:39 +02:00
Louis Erbkamm
1f02c40cb9 Merge branch 'main' into major-release-prep 2025-08-22 16:04:23 +02:00
Louis Erbkamm
9351883ae0 Merge pull request #522 from louis-e/fix-macos-builds-universal
Fix MacOS CI universal release builds
2025-08-22 16:02:18 +02:00
louis-e
2e3b66fe4a Fix MacOS CI release builds 2025-08-22 16:01:33 +02:00
Louis Erbkamm
d6151ab333 Merge pull request #520 from louis-e/fix-macos-builds
Fix MacOS builds
2025-08-22 15:17:25 +02:00
louis-e
1a56e5f08f Adjust baseline memory usage 2025-08-22 15:14:08 +02:00
louis-e
e3335cb6e6 ci: switch to Linux-only builds for faster PR feedback 2025-08-22 15:13:09 +02:00
louis-e
3a65e8b877 Remove mapbox argument 2025-08-22 15:03:58 +02:00
louis-e
fa84a8e4cc Remove mapbox argument 2025-08-22 15:00:37 +02:00
louis-e
257a3bcac4 Fix MacOS CI release builds 2025-08-22 14:57:36 +02:00
Louis Erbkamm
f262613871 Merge pull request #518 from louis-e/minor-fixes
Minor fixes
2025-08-22 02:15:42 +02:00
louis-e
43215ad19f Remove double call 2025-08-22 00:04:16 +02:00
louis-e
00541e43ef Fix missing tree leave block 2025-08-22 00:03:17 +02:00
Louis Erbkamm
732693b71d Merge pull request #516 from louis-e/gui-feature-gate-fix
fix: add feature gate for GUI-dependent spawn update code
2025-08-21 23:04:40 +02:00
louis-e
eaaf320c04 Remove chests from building interior 2025-08-21 23:04:16 +02:00
louis-e
79507637c2 Update benchmark baseline values 2025-08-21 22:54:25 +02:00
Louis Erbkamm
a722235e97 Merge pull request #514 from danieldegroot2/bbox-openstreetmap-provider
Update bbox.js - Use preferred tile.openstreetmap.org URL
2025-08-21 22:51:29 +02:00
louis-e
53f29e6e4d fix: add feature gate for GUI-dependent spawn update code 2025-08-21 22:48:19 +02:00
louis-e
89363f926a Update and modernize README 2025-08-21 22:43:41 +02:00
Louis Erbkamm
c06b5df768 Add recognition.png 2025-08-21 22:42:08 +02:00
louis-e
909e2ab97f Update Arnis version 2025-08-21 22:28:03 +02:00
louis-e
43ed19f456 Update and modernize README 2025-08-21 22:27:43 +02:00
Louis Erbkamm
5ec087c3ed Add documentation.png 2025-08-21 22:24:09 +02:00
Louis Erbkamm
20eee2b0ec Add documentation.png 2025-08-21 22:21:59 +02:00
Louis Erbkamm
821b9b9cb5 Add preview.jpg 2025-08-21 22:09:38 +02:00
Louis Erbkamm
fff9783806 Add files via upload 2025-08-21 21:28:22 +02:00
danieldegroot2
fd66b51169 Update bbox.js - Use preferred tile.openstreetmap.org URL
See https://github.com/openstreetmap/operations/issues/737
2025-08-21 20:58:41 +02:00
Louis Erbkamm
f8a2dc622a Add banner.png 2025-08-21 20:22:49 +02:00
Louis Erbkamm
9aeb35ac99 Merge pull request #513 from louis-e/minor-terrain-fixes
Update spawn point Y coord according to terrain
2025-08-21 19:28:52 +02:00
louis-e
84bef5fcd1 Enlarge CI benchmark area 2025-08-21 19:13:03 +02:00
louis-e
0230e7cb4c Fix cargo fmt and clippy 2025-08-21 19:02:44 +02:00
louis-e
fd9af964cc Enlarge CI benchmark area 2025-08-21 19:01:28 +02:00
louis-e
954391d468 Add support button 2025-08-21 18:55:35 +02:00
louis-e
c0ab878b91 Fix building offset when non-terrain mode 2025-08-21 18:40:57 +02:00
louis-e
af24887399 Update spawn point Y coord according to terrain 2025-08-21 18:01:42 +02:00
Louis Erbkamm
3cb9496252 Merge pull request #512 from louis-e/map-themes
Add map themes to settings
2025-08-21 17:25:16 +02:00
louis-e
a76d0e7121 Add map theme setting 2025-08-21 17:21:10 +02:00
louis-e
a9e883fc86 Add new map style translation 2025-08-21 17:20:42 +02:00
louis-e
6da977cc11 Update license 2025-08-21 17:20:24 +02:00
Louis Erbkamm
acbe81db93 Merge pull request #509 from louis-e/session-lock
Add session.lock to prevent world access during generation
2025-08-20 21:38:58 +02:00
louis-e
0249a0e933 Add session.lock to prevent world access during generation 2025-08-20 21:26:54 +02:00
louis-e
7748ef0cd6 Add session.lock to prevent world access during generation 2025-08-20 21:23:23 +02:00
Louis Erbkamm
5cb82abc9b Merge pull request #508 from louis-e/terrain-smoothness
Deprecate ground level input
2025-08-20 21:17:48 +02:00
louis-e
4fa486bc27 Add session.lock to prevent world access during generation 2025-08-20 21:15:39 +02:00
louis-e
4fb467988c Deprecate ground level input 2025-08-20 21:03:28 +02:00
Louis Erbkamm
adc0bcb3ee Merge pull request #506 from louis-e/gui-fixes
Minor GUI Fixes
2025-08-10 21:24:54 +02:00
louis-e
b8b41a3541 Fix floodfill algorithm for U-shape buildings 2025-08-10 20:40:01 +02:00
louis-e
c02ee9e988 Fix bbox map priority 2025-08-10 20:39:48 +02:00
louis-e
3ccc6c0853 Shorten translations for fitting UI 2025-08-10 19:55:54 +02:00
louis-e
b1c0aea317 Revert version check change 2025-08-10 19:55:39 +02:00
louis-e
651aed65fb Add translations for interior and roof generation 2025-08-10 19:42:51 +02:00
louis-e
f180d84ef2 Fix dropdown preview language 2025-08-10 19:37:48 +02:00
louis-e
2cee6f6ab2 Clear bbox and spawn point when searching for new city 2025-08-10 19:28:44 +02:00
louis-e
bbf52e8b89 Fix bbox selection preserved when custom input is invalid 2025-08-10 19:13:04 +02:00
Louis Erbkamm
8ec67f8420 Merge pull request #498 from louis-e/dependabot/cargo/clap-4.5.42
build(deps): bump clap from 4.5.23 to 4.5.42
2025-08-03 23:00:03 +02:00
Louis Erbkamm
a431a05f0d Merge pull request #499 from louis-e/dependabot/cargo/tokio-1.47.0
build(deps): bump tokio from 1.44.2 to 1.47.0
2025-08-03 22:59:53 +02:00
Louis Erbkamm
37b80f02db Merge pull request #500 from louis-e/dependabot/cargo/geo-0.30.0
build(deps): bump geo from 0.29.3 to 0.30.0
2025-08-03 22:59:47 +02:00
Louis Erbkamm
7dff3ac865 Merge pull request #501 from louis-e/dependabot/cargo/rfd-0.15.4
build(deps): bump rfd from 0.15.3 to 0.15.4
2025-08-03 22:59:33 +02:00
Louis Erbkamm
7e1981672b Merge pull request #505 from louis-e/elevation-crop-mapping-fix
Elevation crop mapping fix
2025-08-03 22:30:29 +02:00
louis-e
e0c3ab3451 Fix clippy #[allow(clippy::uninlined_format_args)] 2025-08-03 22:30:04 +02:00
louis-e
9ea526f0eb Fix elevation coordinate drift with geographic pixel cropping 2025-08-03 22:25:19 +02:00
louis-e
3307f63864 Update progress percentages 2025-08-03 22:21:58 +02:00
Louis Erbkamm
fb70f00da8 Merge pull request #496 from louis-e/maps-search-box
Add city search box to map with geocoding support
2025-08-03 14:21:46 +02:00
louis-e
58cff26d37 Add autocomplete off tag to search box 2025-08-03 14:21:28 +02:00
louis-e
a7c5e1baee Color adaptions on search box 2025-08-03 14:08:57 +02:00
dependabot[bot]
29fc3ce916 build(deps): bump rfd from 0.15.3 to 0.15.4
Bumps [rfd](https://github.com/PolyMeilex/rfd) from 0.15.3 to 0.15.4.
- [Release notes](https://github.com/PolyMeilex/rfd/releases)
- [Changelog](https://github.com/PolyMeilex/rfd/blob/master/CHANGELOG.md)
- [Commits](https://github.com/PolyMeilex/rfd/compare/0.15.3...0.15.4)

---
updated-dependencies:
- dependency-name: rfd
  dependency-version: 0.15.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-08-01 02:58:35 +00:00
dependabot[bot]
d3365d01b1 build(deps): bump geo from 0.29.3 to 0.30.0
Bumps [geo](https://github.com/georust/geo) from 0.29.3 to 0.30.0.
- [Changelog](https://github.com/georust/geo/blob/main/CHANGES.md)
- [Commits](https://github.com/georust/geo/compare/geo-0.29.3...geo-0.30.0)

---
updated-dependencies:
- dependency-name: geo
  dependency-version: 0.30.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-08-01 02:58:06 +00:00
dependabot[bot]
04cbb6427e build(deps): bump tokio from 1.44.2 to 1.47.0
Bumps [tokio](https://github.com/tokio-rs/tokio) from 1.44.2 to 1.47.0.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.44.2...tokio-1.47.0)

---
updated-dependencies:
- dependency-name: tokio
  dependency-version: 1.47.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-08-01 02:57:46 +00:00
dependabot[bot]
3680bc8849 build(deps): bump clap from 4.5.23 to 4.5.42
Bumps [clap](https://github.com/clap-rs/clap) from 4.5.23 to 4.5.42.
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_complete-v4.5.23...clap_complete-v4.5.42)

---
updated-dependencies:
- dependency-name: clap
  dependency-version: 4.5.42
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-08-01 02:57:26 +00:00
louis-e
5cfb3faece Add city search box to map with geocoding support 2025-07-23 21:39:33 +02:00
Louis Erbkamm
3217eea558 Merge pull request #495 from louis-e/man_made
Add man_made tagged elements
2025-07-23 21:24:28 +02:00
louis-e
c3b2624307 Fix cargo fmt and clippy 2025-07-23 21:21:33 +02:00
louis-e
12a401c690 Remove unused import 2025-07-23 21:19:33 +02:00
louis-e
d188f6d579 Add man_made tagged elements 2025-07-23 21:18:16 +02:00
Louis Erbkamm
d2fb65c715 Merge pull request #494 from louis-e/better-waterways
Better waterway parsing
2025-07-23 21:16:19 +02:00
louis-e
d370c72425 Fix cargo fmt 2025-07-23 21:13:46 +02:00
louis-e
3e9f71f81a Fix polygon closure preservation in bbox clipping for multipolygon water areas 2025-07-23 16:43:16 +02:00
louis-e
6b2c4eb55b Fix cargo clippy 2025-07-21 23:07:05 +02:00
louis-e
88a7cf2f6e Runtime detect and fix faulty terrain tiles 2025-07-21 22:54:30 +02:00
louis-e
d7296f69d3 Fix more polyline clipping in sutherland hodgman algorithm 2025-07-21 22:52:50 +02:00
louis-e
c298300a27 Minor improvements to water area generation 2025-07-21 22:19:28 +02:00
Louis Erbkamm
9b752a8915 Merge pull request #484 from louis-e/dependabot/cargo/tauri-plugin-log-2.6.0
build(deps): bump tauri-plugin-log from 2.2.2 to 2.6.0
2025-07-21 21:39:35 +02:00
dependabot[bot]
0285e63dbf build(deps): bump tauri-plugin-log from 2.2.2 to 2.6.0
Bumps [tauri-plugin-log](https://github.com/tauri-apps/plugins-workspace) from 2.2.2 to 2.6.0.
- [Release notes](https://github.com/tauri-apps/plugins-workspace/releases)
- [Commits](https://github.com/tauri-apps/plugins-workspace/compare/os-v2.2.2...log-v2.6.0)

---
updated-dependencies:
- dependency-name: tauri-plugin-log
  dependency-version: 2.6.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-07-21 19:38:47 +00:00
louis-e
33097aa302 Add more waterway types 2025-07-21 21:32:39 +02:00
louis-e
c6504a2fa3 Better waterway parsing 2025-07-21 21:31:54 +02:00
Louis Erbkamm
8da93ab628 Merge pull request #482 from louis-e/dependabot/cargo/reqwest-0.12.15
build(deps): bump reqwest from 0.12.12 to 0.12.15
2025-07-21 21:05:06 +02:00
Louis Erbkamm
8ba4d3ddef Merge pull request #483 from louis-e/dependabot/cargo/flate2-1.1.2
build(deps): bump flate2 from 1.1.1 to 1.1.2
2025-07-21 21:05:01 +02:00
Louis Erbkamm
74ceb3afb8 Merge pull request #485 from louis-e/dependabot/cargo/tauri-build-2.0.5
build(deps): bump tauri-build from 2.0.4 to 2.0.5
2025-07-21 21:04:33 +02:00
Louis Erbkamm
c886894e14 Merge pull request #493 from louis-e/terrain-aws-migration
Migrate from Mapbox to AWS Terrain Tiles
2025-07-21 21:01:06 +02:00
louis-e
8d6c666f75 Fix cargo fmt and clippy 2025-07-21 20:52:23 +02:00
louis-e
de2bce5a0a Support landuse relations 2025-07-21 20:50:07 +02:00
louis-e
8e9d6f0ad1 Revert water areas 2025-07-21 20:46:09 +02:00
louis-e
eb13dabd16 Refine element processors 2025-07-21 20:44:50 +02:00
louis-e
af612095fa Refine elevation parameters 2025-07-21 20:44:37 +02:00
louis-e
8132881f86 Add old tile cache directory name to gitignorew 2025-07-20 23:57:28 +02:00
louis-e
994ae0d770 Rename tile cache directory 2025-07-20 23:56:01 +02:00
louis-e
da10ffc655 Revert conditional terrain disablement 2025-07-20 23:52:12 +02:00
Louis Erbkamm
d987ae73d0 Merge branch 'main' into dependabot/cargo/reqwest-0.12.15 2025-07-20 23:49:47 +02:00
Louis Erbkamm
f4accbbf8c Merge branch 'main' into dependabot/cargo/flate2-1.1.2 2025-07-20 23:49:44 +02:00
Louis Erbkamm
9887efd1e3 Merge branch 'main' into dependabot/cargo/tauri-build-2.0.5 2025-07-20 23:49:28 +02:00
Louis Erbkamm
50f5a1a844 Merge branch 'main' into terrain-aws-migration 2025-07-20 23:45:52 +02:00
louis-e
5cd590f165 Migrate from Mapbox to AWS Terrain Tiles 2025-07-20 23:45:29 +02:00
Louis Erbkamm
1d031a75bc Merge pull request #492 from louis-e/natural-extension
Add support for more natural elements
2025-07-20 23:42:50 +02:00
Louis Erbkamm
a17ef09727 Fix cargo fmt and clippy 2025-07-20 23:37:22 +02:00
Louis Erbkamm
ed20642e8b Merge branch 'main' into natural-extension 2025-07-20 23:33:47 +02:00
louis-e
501825d05b Fix cargo fmt and clippy 2025-07-20 23:33:31 +02:00
Louis Erbkamm
6ee1b55924 Merge pull request #491 from louis-e/sutherland-hodgman-algorithm
Implement Sutherland-Hodgman algorithm for element clipping
2025-07-20 23:32:42 +02:00
Louis Erbkamm
1a206b8e69 Fix cargo fmt and clippy 2025-07-20 23:30:08 +02:00
louis-e
52fe87b90d Add more natural elements 2025-07-20 23:24:12 +02:00
louis-e
3ea85009e7 Implement Sutherland-Hodgman algorithm for element clipping 2025-07-20 23:21:36 +02:00
Louis Erbkamm
bd5a7b9bee Merge pull request #465 from louis-e/buildings-foundation
Buildings Overhaul
2025-07-20 23:18:19 +02:00
louis-e
799c7d6007 Fix cargo fmt 2025-07-20 23:11:06 +02:00
louis-e
7f28089c14 Fix interior wall roof clipping 2025-07-20 23:07:28 +02:00
louis-e
4bb69b6b16 Fix cargo fmt and clippy 2025-07-20 18:35:09 +02:00
louis-e
36d084d02f Minor refinements 2025-07-20 17:14:34 +02:00
louis-e
9d4ce48d8d Remove args from roof generation 2025-07-20 15:10:57 +02:00
louis-e
6f7efd8a1c Change stair block mapping 2025-07-20 15:08:09 +02:00
louis-e
37ec4be8fc Fix cargo fmt and clippy 2025-07-20 01:35:15 +02:00
louis-e
6b43f12769 Fixed scanlines in floodfill algorithm 2025-07-20 01:30:27 +02:00
louis-e
06357abe97 Improve generation time by implementing floodfill caching 2025-07-20 01:03:25 +02:00
louis-e
86c92104dd Remove unused vars and log lines 2025-07-20 00:33:49 +02:00
louis-e
c9551d8ec0 Fix cargo fmt and clippy 2025-07-19 23:45:06 +02:00
louis-e
6b676eab08 Change roof material choice chance 2025-07-19 23:39:59 +02:00
louis-e
2a6a507082 Temporary improvement for water_areas generation speed 2025-07-19 23:37:09 +02:00
louis-e
9a7c00a3c4 Fix metal barriers 2025-07-19 23:34:12 +02:00
louis-e
57dcd72979 Add highway outline 2025-07-19 23:33:55 +02:00
louis-e
486dcdee2e Revert floodfill optimization 2025-07-19 23:33:41 +02:00
louis-e
7f01b596cb Conditional terrain disablement based on bbox size 2025-07-19 20:47:39 +02:00
louis-e
4a672811c0 Calculate terrain blur in relation to bbox size 2025-07-19 20:47:13 +02:00
louis-e
0ec64fc13d Fix min_levels tag 2025-07-19 20:11:32 +02:00
louis-e
f9796c60a0 Improve floodfill performance 2025-07-19 20:06:14 +02:00
louis-e
2fd0244889 Performance improvements 2025-07-19 20:00:27 +02:00
louis-e
7e6ab21a9e Fixed cargo fmt and clippy 2025-07-19 18:17:20 +02:00
louis-e
dd7578d8d3 Add support for custom block property creation 2025-07-19 18:14:17 +02:00
louis-e
4b766095c8 Improved hipped and gabled roofs 2025-07-19 16:19:11 +02:00
louis-e
e8d718772a Fix progress updates 2025-07-13 20:46:25 +02:00
louis-e
0a488655d2 Unified cone building roof 2025-07-13 19:25:45 +02:00
louis-e
aed978947d Improved pyramidal building roof 2025-07-13 19:08:10 +02:00
louis-e
f4d35eebf7 Improved skillion roof type 2025-07-13 17:27:26 +02:00
louis-e
97fe4e264b More floor variations 2025-07-13 15:54:40 +02:00
louis-e
d53af0a3f4 Fix cargo fmt and clippy 2025-07-13 02:16:42 +02:00
louis-e
3e7e4b663e Refactored building block color mapping 2025-07-13 02:13:16 +02:00
louis-e
a86506b28d Add building accent blocks 2025-07-12 22:43:12 +02:00
louis-e
b9250651a2 Conditional roof generation 2025-07-12 21:23:35 +02:00
louis-e
98ed4e3f1c Fix cargo formatting 2025-07-12 16:26:41 +02:00
Louis Erbkamm
73776578bf Update elevation differences 2025-07-12 16:22:07 +02:00
Louis Erbkamm
aa36db7f13 Merge branch 'main' into buildings-foundation 2025-07-12 16:20:54 +02:00
louis-e
38c2550f0d Remove wiki 2025-07-12 16:12:30 +02:00
louis-e
4c8108bdf9 Added window glass block variation 2025-07-12 16:11:22 +02:00
louis-e
0ff6cabcf5 Shift floors for visual variation 2025-07-12 15:39:31 +02:00
Louis Erbkamm
dd22bbb943 Merge pull request #487 from louis-e/gui-settings
GUI Settings refactored languages
2025-07-02 16:39:28 +02:00
louis-e
5bbe3f1ec9 removed handleLanguageSelection() 2025-07-02 16:39:14 +02:00
louis-e
1db53c4656 Added localized language and fillground attribute 2025-07-02 16:27:58 +02:00
louis-e
43f3f2f67d Added localized language and fillground attribute 2025-07-02 16:25:55 +02:00
louis-e
dc3ea8df5e Removed duplicate functions 2025-07-02 16:14:23 +02:00
louis-e
f9776c4472 Added language dropdown 2025-07-02 16:07:00 +02:00
Louis Erbkamm
27f8c70a10 Merge pull request #474 from XianlinSheng/dev-unicoord
Rearrange geocoord and bbox into coordinate_system in the same style as cartesian point and xzbbox
2025-07-02 14:40:34 +02:00
louis-e
6842a44e2a Fix fmt 2025-07-02 14:33:04 +02:00
louis-e
b28ce5cc12 Fix clippy 2025-07-02 14:29:16 +02:00
louis-e
d56894debd Resolve cargo fmt warnings 2025-07-02 13:56:36 +02:00
louis-e
2571e43f7e Merge dev-unicoord into main with conflict resolution 2025-07-02 13:54:33 +02:00
louis-e
0d3f1b6b5d Merge dev-unicoord into main with conflict resolution 2025-07-02 13:54:04 +02:00
dependabot[bot]
174374e514 build(deps): bump tauri-build from 2.0.4 to 2.0.5
Bumps [tauri-build](https://github.com/tauri-apps/tauri) from 2.0.4 to 2.0.5.
- [Release notes](https://github.com/tauri-apps/tauri/releases)
- [Commits](https://github.com/tauri-apps/tauri/compare/tauri-build-v2.0.4...tauri-build-v2.0.5)

---
updated-dependencies:
- dependency-name: tauri-build
  dependency-version: 2.0.5
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-07-01 06:29:54 +00:00
dependabot[bot]
f3fbe6e84d build(deps): bump flate2 from 1.1.1 to 1.1.2
Bumps [flate2](https://github.com/rust-lang/flate2-rs) from 1.1.1 to 1.1.2.
- [Release notes](https://github.com/rust-lang/flate2-rs/releases)
- [Commits](https://github.com/rust-lang/flate2-rs/compare/1.1.1...1.1.2)

---
updated-dependencies:
- dependency-name: flate2
  dependency-version: 1.1.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-07-01 05:39:35 +00:00
dependabot[bot]
34d5d4ae22 build(deps): bump reqwest from 0.12.12 to 0.12.15
Bumps [reqwest](https://github.com/seanmonstar/reqwest) from 0.12.12 to 0.12.15.
- [Release notes](https://github.com/seanmonstar/reqwest/releases)
- [Changelog](https://github.com/seanmonstar/reqwest/blob/master/CHANGELOG.md)
- [Commits](https://github.com/seanmonstar/reqwest/compare/v0.12.12...v0.12.15)

---
updated-dependencies:
- dependency-name: reqwest
  dependency-version: 0.12.15
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-07-01 05:30:35 +00:00
Louis Erbkamm
666e47ce7e Change ANDESITE_WALL to STONE_BRICK_WALL 2025-06-24 22:17:46 +02:00
Louis Erbkamm
5a3b92b4f3 Merge pull request #466 from GMart/Update-block-types
Update barrier generation
2025-06-24 22:16:03 +02:00
Garrett M
a300f793ec Merge branch 'louis-e:main' into Update-block-types 2025-06-24 10:02:39 -04:00
Louis Erbkamm
cccea1d87a Merge pull request #468 from louis-e/dependabot/cargo/serde_json-1.0.140
build(deps): bump serde_json from 1.0.134 to 1.0.140
2025-06-22 16:46:12 +02:00
dependabot[bot]
19bac86e5e build(deps): bump serde_json from 1.0.134 to 1.0.140
Bumps [serde_json](https://github.com/serde-rs/json) from 1.0.134 to 1.0.140.
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.134...v1.0.140)

---
updated-dependencies:
- dependency-name: serde_json
  dependency-version: 1.0.140
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-06-22 13:46:51 +00:00
Louis Erbkamm
491057255c Merge pull request #470 from louis-e/dependabot/cargo/indicatif-0.17.11
build(deps): bump indicatif from 0.17.9 to 0.17.11
2025-06-22 15:42:32 +02:00
dependabot[bot]
44fe74083a build(deps): bump indicatif from 0.17.9 to 0.17.11
Bumps [indicatif](https://github.com/console-rs/indicatif) from 0.17.9 to 0.17.11.
- [Release notes](https://github.com/console-rs/indicatif/releases)
- [Commits](https://github.com/console-rs/indicatif/compare/0.17.9...0.17.11)

---
updated-dependencies:
- dependency-name: indicatif
  dependency-version: 0.17.11
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-06-22 13:42:04 +00:00
Louis Erbkamm
10fbc7e85a Merge pull request #469 from louis-e/dependabot/cargo/rfd-0.15.3
build(deps): bump rfd from 0.15.2 to 0.15.3
2025-06-22 15:41:18 +02:00
Louis Erbkamm
cdafe0488a Merge pull request #471 from louis-e/dependabot/cargo/image-0.25.6
build(deps): bump image from 0.24.9 to 0.25.6
2025-06-22 15:41:02 +02:00
Louis Erbkamm
df3c9d2507 Merge pull request #472 from louis-e/dependabot/github_actions/actions/checkout-4
build(deps): bump actions/checkout from 3 to 4
2025-06-22 15:40:50 +02:00
Louis Erbkamm
5cbcd68f46 Merge pull request #452 from akx/terrain-fixes
Terrain fixes
2025-06-22 15:40:37 +02:00
Louis Erbkamm
fe10b7d079 Merge branch 'main' into terrain-fixes 2025-06-22 15:24:45 +02:00
louis-e
b8ffb51bdc Return ground 2025-06-22 15:24:17 +02:00
XianlinSheng
404e733f65 merge 2025-06-09 21:36:45 -04:00
louis-e
2fd3d47ca1 Move interior generation into own file 2025-06-02 20:42:09 +02:00
louis-e
a327552fba Add more detailed interior 2025-06-02 20:14:46 +02:00
Louis Erbkamm
e95a6ff738 Add Wiki reference 2025-06-01 16:43:47 +02:00
louis-e
d2f1fca921 Revert cargo fmt 2025-06-01 15:59:57 +02:00
louis-e
7df43604e2 Add interior toggle button 2025-06-01 15:43:36 +02:00
louis-e
96e40cf15f Fix fmt and clippy 2025-06-01 15:30:58 +02:00
louis-e
e6dfa5d59e Add building interior generation 2025-06-01 15:28:35 +02:00
dependabot[bot]
b760f0e720 build(deps): bump actions/checkout from 3 to 4
Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '4'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-06-01 03:06:57 +00:00
dependabot[bot]
fec3059157 build(deps): bump image from 0.24.9 to 0.25.6
Bumps [image](https://github.com/image-rs/image) from 0.24.9 to 0.25.6.
- [Changelog](https://github.com/image-rs/image/blob/main/CHANGES.md)
- [Commits](https://github.com/image-rs/image/compare/v0.24.9...v0.25.6)

---
updated-dependencies:
- dependency-name: image
  dependency-version: 0.25.6
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-06-01 02:43:02 +00:00
dependabot[bot]
57fee8b273 build(deps): bump rfd from 0.15.2 to 0.15.3
Bumps [rfd](https://github.com/PolyMeilex/rfd) from 0.15.2 to 0.15.3.
- [Release notes](https://github.com/PolyMeilex/rfd/releases)
- [Changelog](https://github.com/PolyMeilex/rfd/blob/master/CHANGELOG.md)
- [Commits](https://github.com/PolyMeilex/rfd/compare/0.15.2...0.15.3)

---
updated-dependencies:
- dependency-name: rfd
  dependency-version: 0.15.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-06-01 02:42:28 +00:00
Garrett M
6c62ada7cc Add whitelist items to gate nodes
Add additional whitelist items to gate nodes, to hopefully improve the look of gates
2025-05-30 20:41:01 -04:00
Garrett M
ead52305cf Merge branch 'louis-e:main' into Update-block-types 2025-05-30 16:04:07 -04:00
Garrett M
662c8a9a27 Update barrier generation
Update barrier generation: Separate out ways and nodes. Add gates and stiles, etc as nodes.
Update metal and related barriers to IRON_BARS
2025-05-30 16:03:23 -04:00
Louis Erbkamm
101b340071 Merge pull request #462 from louis-e/new-icon
Add new desktop icon
2025-05-30 01:53:36 +02:00
louis-e
39a7461f82 Automatically calculate roof_height_boost 2025-05-30 01:44:58 +02:00
louis-e
c49605d993 Improve gabled roof 2025-05-30 01:34:05 +02:00
louis-e
3e3948d345 Improve hipped roof 2025-05-30 01:19:30 +02:00
louis-e
d32e4edaa3 Remove txt 2025-05-30 01:01:26 +02:00
Garrett M
d115ee2ec7 Fix Floor map and add new block
Fix type with building floor variations color map, and add oak trapdoor block
2025-05-29 18:56:49 -04:00
louis-e
1a41766f2e World name adaption 2025-05-30 00:54:22 +02:00
louis-e
b191bc294a Unified roofs 2025-05-30 00:37:48 +02:00
louis-e
d146f3fd83 Revert combined roof types 2025-05-30 00:11:02 +02:00
louis-e
eea839f5ad Add roofs 2025-05-30 00:10:27 +02:00
louis-e
2c0c475f57 Fix unused warning 2025-05-29 22:15:34 +02:00
louis-e
37ed36b433 Add tall building specific windows 2025-05-29 21:28:58 +02:00
louis-e
548e0f9456 Fix foundation 2025-05-29 21:04:40 +02:00
louis-e
eb7ec70f39 Generate buildings with foundation 2025-05-29 16:59:49 +02:00
Aarni Koskela
cb32be70b2 Fix lint issue 2025-05-24 18:22:18 +00:00
louis-e
8fbf432b5b Add new desktop icon 2025-05-24 03:15:56 +02:00
Louis Erbkamm
e86937ec1b Merge branch 'main' into terrain-fixes 2025-05-24 02:38:32 +02:00
Louis Erbkamm
71e28d1403 Merge pull request #457 from akx/fix-benchmark-ci
CI: fix benchmark time to not include build
2025-05-24 02:36:25 +02:00
Louis Erbkamm
de79896dc5 Merge pull request #451 from akx/overflows
Some overflow fixes
2025-05-24 02:35:11 +02:00
Louis Erbkamm
047e3a0feb Merge pull request #461 from louis-e/spawn-position
Select spawn position using marker
2025-05-24 02:14:41 +02:00
louis-e
97d59d8e0c Abort when spawn point in bbox verification fails 2025-05-24 02:09:07 +02:00
louis-e
fda9a3a6b2 Fix bbox drawing issue 2025-05-24 02:04:17 +02:00
louis-e
82145250ae Fine tune construction generation 2025-05-24 02:02:39 +02:00
louis-e
4df49422df Add marker to set spawn position 2025-05-24 01:14:24 +02:00
Louis Erbkamm
db123792d4 Merge pull request #450 from akx/more-fixes-1
Data parsing fixes
2025-05-23 21:34:45 +02:00
Louis Erbkamm
526b6ae5e8 Merge pull request #460 from louis-e/remove-unneeded-src
Remove unneeded js and css files
2025-05-23 21:29:26 +02:00
louis-e
55e8688031 Remove unneeded js and css files 2025-05-23 21:17:12 +02:00
Louis Erbkamm
8001014454 Merge branch 'main' into terrain-fixes 2025-05-23 21:04:32 +02:00
Louis Erbkamm
188bacad88 Merge branch 'main' into fix-benchmark-ci 2025-05-23 20:58:18 +02:00
Louis Erbkamm
a2cd96214d pr-benchmark.yml: Fix token 2025-05-23 20:58:09 +02:00
Louis Erbkamm
103693b28d pr-benchmark.yml: Add permissions to fix CI error 2025-05-23 20:44:56 +02:00
Aarni Koskela
07503c1763 Adjust benchmark baseline time now that it doesn't include build 2025-05-19 09:04:35 +03:00
Aarni Koskela
03c72c7a14 CI: use Swatinem/rust-cache 2025-05-19 09:04:35 +03:00
Aarni Koskela
58157cee37 CI: don't require clippy for benchmark 2025-05-19 09:04:35 +03:00
Aarni Koskela
806dd11b51 CI: separate benchmark build from run step 2025-05-19 09:04:35 +03:00
Aarni Koskela
6a94435d33 Default to new hard-coded mapbox access token if none provided 2025-05-19 08:26:38 +03:00
Aarni Koskela
a188f521bb Print out terrain heights 2025-05-19 08:21:30 +03:00
Aarni Koskela
2969966fd1 Cache Mapbox tiles locally to avoid requests when possible 2025-05-19 08:21:30 +03:00
Aarni Koskela
b4c6f55ef4 De-hardcode Mapbox access token (it gives 401 now anyway) 2025-05-19 08:21:30 +03:00
Aarni Koskela
654124be75 Move elevation data fetching out of the ground impl 2025-05-19 08:21:29 +03:00
Aarni Koskela
384f541254 Handle Mapbox API errors 2025-05-19 08:20:52 +03:00
Aarni Koskela
5e44313730 Separate terrain constructor for flat and fetch cases 2025-05-19 08:20:52 +03:00
Louis Erbkamm
885c3a7127 Merge pull request #456 from louis-e/map-provider-switch
Switch map provider from Mapbox to OSM
2025-05-18 22:49:14 +02:00
louis-e
b86289c49a Switch map provider from Mapbox to OSM 2025-05-18 22:44:44 +02:00
Louis Erbkamm
144ac58468 Merge pull request #447 from akx/ci-fixes
Small CI fixes
2025-05-18 19:59:01 +02:00
Louis Erbkamm
03a4997cac updated checkout@v3 to v4 2025-05-18 19:58:19 +02:00
Louis Erbkamm
fd4aefaf2b Merge branch 'main' into ci-fixes 2025-05-18 19:48:19 +02:00
XianlinSheng
4edfddb33c merge 2025-05-18 12:35:29 -04:00
XianlinSheng
f46fb696ce Merge branch 'main' into dev-unicoord 2025-05-18 12:29:45 -04:00
Louis Erbkamm
0bc6967d83 Merge pull request #130 from louis-e/dependabot/github_actions/actions/upload-artifact-4
Bump actions/upload-artifact from 3 to 4
2025-05-18 16:46:02 +02:00
Louis Erbkamm
a37612626c Merge pull request #129 from louis-e/dependabot/github_actions/actions/checkout-4
Bump actions/checkout from 3 to 4
2025-05-18 16:45:44 +02:00
Louis Erbkamm
5e8bb3f5a0 Merge pull request #131 from louis-e/dependabot/github_actions/softprops/action-gh-release-2
Bump softprops/action-gh-release from 1 to 2
2025-05-18 16:45:38 +02:00
Louis Erbkamm
4226438075 Merge pull request #132 from louis-e/dependabot/github_actions/actions/download-artifact-4
Bump actions/download-artifact from 3 to 4
2025-05-18 16:45:11 +02:00
Louis Erbkamm
cd30fc74af Merge pull request #454 from louis-e/mapbox-token
Fix expired mapbox token
2025-05-18 16:34:38 +02:00
louis-e
62c3f94857 Fix expired mapbox token 2025-05-18 16:33:03 +02:00
Louis Erbkamm
5de8f1c78d Prepare hotfix release 2025-05-18 16:29:05 +02:00
Louis Erbkamm
d0295bfd40 Prepare hotfix release 2025-05-18 16:28:52 +02:00
Louis Erbkamm
b3b3436efd pr-benchmark.yml: update generation time logic 2025-05-18 15:47:41 +02:00
XianlinSheng
dea764783b merge 2025-05-16 13:06:00 -04:00
Aarni Koskela
f42d15780c Use wrapping multiplication for parking spot markings 2025-05-16 13:10:45 +03:00
Aarni Koskela
d19cf5aef2 Avoid integer overflow when dealing with large enough water areas 2025-05-16 13:10:45 +03:00
Aarni Koskela
bf2e3d5b94 Do overflow checks even in release (avoids some hangs, but panics instead) 2025-05-16 13:10:45 +03:00
Aarni Koskela
4145e30194 CI: Run CI when CI spec changes 2025-05-16 12:31:25 +03:00
Aarni Koskela
6ec1827178 CI: Don't run lints/clippy in all environments 2025-05-16 12:31:25 +03:00
Aarni Koskela
3a05023540 CI: use Swatinem/rust-cache 2025-05-16 12:31:25 +03:00
Aarni Koskela
b0437cfc62 Use buffered writer for debug file 2025-05-16 12:27:31 +03:00
Aarni Koskela
883b4b56dc Split OSM data during parsing 2025-05-16 12:27:31 +03:00
Aarni Koskela
00b5e5393a Give parse_osm_data ownership of the data instead of cloning 2025-05-16 12:26:20 +03:00
Louis Erbkamm
948bef41ae Merge pull request #448 from louis-e/clippy-fix
Fix clippy
2025-05-15 21:11:32 +02:00
Louis Erbkamm
fe54a11fde Fix clippy 2025-05-15 21:10:15 +02:00
Louis Erbkamm
400004ec51 Merge pull request #446 from akx/retrieve-improvements
Small data retrieval improvements
2025-05-15 20:59:29 +02:00
Louis Erbkamm
c6377f7155 pr-benchmark.yml: Adapted time baseline 2025-05-15 20:36:37 +02:00
Louis Erbkamm
20e6621bb5 Merge pull request #444 from GMart/FixScaling
Fix scaling of roads and building heights
2025-05-15 20:35:33 +02:00
Aarni Koskela
fdc5156036 Remove undocumented write-data-when-debugging feature 2025-05-15 15:42:12 +03:00
Aarni Koskela
23583c77de Separate fetch-data-from-file and fetch-data-from-overpass; add save_file option 2025-05-15 15:42:12 +03:00
Aarni Koskela
6d599e19c0 Improve error message for invalid bbox 2025-05-15 15:42:12 +03:00
Aarni Koskela
4ff0d6e2be Move Minecraft world directory validation to args parser 2025-05-15 15:42:11 +03:00
Garrett M
95f1c4d9b5 Merge branch 'louis-e:main' into FixScaling 2025-05-12 08:20:25 -04:00
Louis Erbkamm
b13eb1fcdf Merge pull request #409 from XianlinSheng/main
Open up a map editing architecture in the workflow for transformation, and enables generating at non-origin
2025-05-12 00:29:34 +02:00
Garrett M
0866649444 Fix stripes and aeroways
Have stripes and aeroways respect the scaling. Stripes with the .floor() function never showed the stripes at a low scaling. ceil() seems to work.
Undo accidental mod: with function in buildings.rs
2025-05-11 00:44:23 -04:00
Garrett M
958160918b Fix scaling of roads and building heights
Fix road widths to respect scaling. Buildings now respect scale for start_y_offset, fixing most floating buildings
2025-05-10 16:20:32 -04:00
XianlinSheng
8bd98a72aa change xzbbox fields to standard common names: bounding_rect, min, max 2025-05-04 19:25:24 -04:00
XianlinSheng
f7c3404328 move geo_distance etc to coordinate_system::transformation; pack lat_lon_to_minecraft_coords into method CoordTransformation.transform_point(llpoint) 2025-05-04 01:41:22 -04:00
XianlinSheng
ef2f341456 osm_parser returns xzbbox directly, remove explicit usage of scale_factor_x in the main pipeline 2025-05-03 17:22:29 -04:00
XianlinSheng
4e82b0a497 move bbox and geocoord into coordinate_system::geographic 2025-05-03 17:04:21 -04:00
XianlinSheng
d0b671625b move ground fetch to data fetching section, which also enables rotation architecture 2025-05-03 15:48:19 -04:00
XianlinSheng
657d50b6e0 support new main.rs 2025-05-03 14:23:15 -04:00
Louis Erbkamm
922e752684 Merge pull request #425 from GMart/Update-block-types
Update leisure and highway element processing
2025-05-03 16:37:09 +02:00
Garrett M
873f6aa995 Merge branch 'louis-e:main' into Update-block-types 2025-05-02 11:17:34 -04:00
Garrett M
0cd4c0e28d Add comments and dirt block option
Add comments to code, add dirt to option for dog park, playground, etc.
2025-05-02 11:16:44 -04:00
Garrett M
97eebbb977 Fixes for stairs and unneeded tag
In Leisure, soccer golf is used less than 1000 time worldwide. Removed since it will rarely be used.
in highways, changes stairs to be GRAY_CONCRETE for now, until they are properly added.
2025-05-02 11:06:59 -04:00
Louis Erbkamm
7ae6dc8143 Merge pull request #430 from Oleg4260/main
Implement wetlands
2025-05-02 17:04:52 +02:00
Oleg4260
a112cda485 Merge branch 'louis-e:main' into main 2025-05-02 12:44:40 +03:00
Garrett M
116f753e45 Merge branch 'louis-e:main' into Update-block-types 2025-05-01 18:36:46 -04:00
Louis Erbkamm
3c41be1ad0 Merge pull request #416 from benjamin051000/separate-gui-logic
Move GUI logic to its own file
2025-05-01 23:51:39 +02:00
Louis Erbkamm
7ad15c70c3 main.rs: fix fmt 2025-05-01 23:03:47 +02:00
Louis Erbkamm
bf53f4bb2f gui.rs: fix fmt 2025-05-01 23:01:15 +02:00
Louis Erbkamm
be819c01a0 Update gui.rs with latest changes 2025-05-01 22:59:47 +02:00
Louis Erbkamm
899cb2ee16 Merge branch 'main' into separate-gui-logic 2025-05-01 22:58:49 +02:00
Louis Erbkamm
b63b3ae05a pr-benchmark.yml: add memory annotation 2025-05-01 22:01:07 +02:00
Oleg4260
48c2e93292 Merge branch 'main' into main 2025-05-01 18:34:58 +03:00
Garrett M
4395eb6dd6 Merge branch 'louis-e:main' into Update-block-types 2025-05-01 09:11:31 -04:00
Louis Erbkamm
e8bbbec0f9 pr-benchmark.yml: add more stats 2025-05-01 15:07:07 +02:00
Garrett M
b16c0f84ac Merge branch 'louis-e:main' into Update-block-types 2025-05-01 09:03:48 -04:00
Louis Erbkamm
6efee57cbc pr-benchmark.yml: fix reference time 2025-05-01 14:52:10 +02:00
Louis Erbkamm
41ae099887 pr-benchmark.yml: enable terrain 2025-05-01 14:46:58 +02:00
Louis Erbkamm
781bb79ae5 Merge pull request #434 from louis-e/dependabot/cargo/once_cell-1.21.3
Bump once_cell from 1.20.2 to 1.21.3
2025-05-01 14:40:27 +02:00
Louis Erbkamm
3b378296a3 Merge pull request #433 from louis-e/dependabot/cargo/windows-0.61.1
Bump windows from 0.59.0 to 0.61.1
2025-05-01 14:40:15 +02:00
Louis Erbkamm
703b83a2fd Merge pull request #432 from louis-e/dependabot/cargo/colored-3.0.0
Bump colored from 2.2.0 to 3.0.0
2025-05-01 14:39:49 +02:00
Louis Erbkamm
c7e1b5bf67 Merge pull request #431 from louis-e/dependabot/cargo/flate2-1.1.1
Bump flate2 from 1.0.35 to 1.1.1
2025-05-01 14:39:40 +02:00
Garrett M
b8f45ac178 Merge branch 'louis-e:main' into Update-block-types 2025-05-01 08:34:10 -04:00
Louis Erbkamm
e9133c136a pr-benchmark.yml: fix reference time 2025-05-01 14:23:40 +02:00
Louis Erbkamm
92881cf3b3 pr-benchmark.yml: fix new line 2025-05-01 14:19:42 +02:00
Louis Erbkamm
421fe47ecf pr-benchmark.yml: fix summary 2025-05-01 14:13:55 +02:00
Louis Erbkamm
0c2c99544e pr-benchmark.yml: fix summary 2025-05-01 14:12:22 +02:00
Louis Erbkamm
491716f0fc pr-benchmark.yml: fix summary 2025-05-01 14:10:48 +02:00
Louis Erbkamm
96f9bc736e pr-benchmark.yml: more detailed comment 2025-05-01 14:05:38 +02:00
Louis Erbkamm
ffe694f9d8 pr-benchmark.yml: add detailed comment 2025-05-01 14:00:34 +02:00
Louis Erbkamm
c7b6df92ab Update pr-benchmark.yml 2025-05-01 13:53:13 +02:00
Louis Erbkamm
5b67f8ee84 pr-benchmark.yml: update bbox arg input 2025-05-01 13:49:52 +02:00
Louis Erbkamm
179cb6fa2d pr-benchmark.yml: Create dummy world 2025-05-01 13:46:00 +02:00
Louis Erbkamm
15c8265a21 pr-benchmark.yml: run on command 2025-05-01 13:40:27 +02:00
Louis Erbkamm
7ec0b9aa03 Run pr-benchmark.yml on opened PR 2025-05-01 13:33:51 +02:00
dependabot[bot]
c1ac1774fb Bump once_cell from 1.20.2 to 1.21.3
Bumps [once_cell](https://github.com/matklad/once_cell) from 1.20.2 to 1.21.3.
- [Changelog](https://github.com/matklad/once_cell/blob/master/CHANGELOG.md)
- [Commits](https://github.com/matklad/once_cell/compare/v1.20.2...v1.21.3)

---
updated-dependencies:
- dependency-name: once_cell
  dependency-version: 1.21.3
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-05-01 02:14:14 +00:00
dependabot[bot]
b46cd17ff4 Bump windows from 0.59.0 to 0.61.1
Bumps [windows](https://github.com/microsoft/windows-rs) from 0.59.0 to 0.61.1.
- [Release notes](https://github.com/microsoft/windows-rs/releases)
- [Commits](https://github.com/microsoft/windows-rs/commits)

---
updated-dependencies:
- dependency-name: windows
  dependency-version: 0.61.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-05-01 02:13:54 +00:00
dependabot[bot]
2789a40fd0 Bump colored from 2.2.0 to 3.0.0
Bumps [colored](https://github.com/mackwic/colored) from 2.2.0 to 3.0.0.
- [Release notes](https://github.com/mackwic/colored/releases)
- [Changelog](https://github.com/colored-rs/colored/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mackwic/colored/compare/v2.2.0...v3.0.0)

---
updated-dependencies:
- dependency-name: colored
  dependency-version: 3.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-05-01 02:13:40 +00:00
dependabot[bot]
6f71bc3fdb Bump flate2 from 1.0.35 to 1.1.1
Bumps [flate2](https://github.com/rust-lang/flate2-rs) from 1.0.35 to 1.1.1.
- [Release notes](https://github.com/rust-lang/flate2-rs/releases)
- [Commits](https://github.com/rust-lang/flate2-rs/compare/1.0.35...1.1.1)

---
updated-dependencies:
- dependency-name: flate2
  dependency-version: 1.1.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-05-01 02:13:26 +00:00
Garrett M
7a102dec51 Fix extra match and typo
Fix GRASS to GRASS_BLOCK
Remove ladder type as it would have to have special properties to work properly
2025-04-30 19:24:39 -04:00
Oleg4260
320acac80d More wetland types 2025-04-30 17:33:53 +03:00
Oleg4260
0cad9fa307 fix forest generating over roads 2025-04-30 16:41:18 +03:00
Garrett M
b03202ac71 Update leisure.rs
Fix nature_reserve
Add more leisure values.
2025-04-29 14:11:01 -04:00
Oleg4260
32ae0778e2 Implement wetlands
Implement wetlands

cargo fmt; implement bog

Better bog
2025-04-29 20:49:16 +03:00
Garrett M
faef164abe Fix marina and add more blocks to highways.rs
Remove marina from water. It was making entire marina areas water, which was not intended. Add some block types to highways
2025-04-28 23:39:04 -04:00
Garrett M
d9930c2b44 Merge branch 'louis-e:main' into Update-block-types 2025-04-28 17:35:38 -04:00
Louis Erbkamm
1a0fc291b0 Merge pull request #426 from Oleg4260/main
Fixes for pull/423
2025-04-28 21:21:40 +02:00
Oleg4260
bb14b1da49 fix fmt 2025-04-28 12:55:10 +03:00
Oleg4260
c0edbaa92c cargo fmt 2025-04-28 12:48:49 +03:00
Oleg4260
bf69996427 Fix crash caused by unicode characters in area_name 2025-04-28 12:45:34 +03:00
Oleg4260
1c734cdd7c Fix generation of ground layers, remove unnecessary function 2025-04-28 12:10:57 +03:00
XianlinSheng
b815a3b563 fix clippy, allow the bad-styled floating point values in test 2025-04-28 01:47:38 -04:00
XianlinSheng
32745217a7 support new elevation code 2025-04-28 01:43:09 -04:00
XianlinSheng
11cec0fc15 merge main 2025-04-28 00:39:15 -04:00
XianlinSheng
f9cc2acf11 add tests for operators generation from json, translator results, xzbbox, including a test_utilities.rs for fetching example data 2025-04-28 00:22:57 -04:00
Garrett M
ed529071ae Merge branch 'louis-e:main' into Update-block-types 2025-04-27 21:08:27 -04:00
Louis Erbkamm
9a288e3966 Merge pull request #423 from louis-e/simplify-elevation
Simplify elevation retrieval in each element processor
2025-04-27 23:48:54 +02:00
louis-e
e5f0717838 Fix bedrock layer 2025-04-27 23:39:08 +02:00
louis-e
c258892b45 Fix cargo fmt 2025-04-27 23:23:37 +02:00
louis-e
151ced7625 Assign persistent property to birch leaves 2025-04-27 23:21:38 +02:00
louis-e
73e8bab4a0 Resolve merge conflicts 2025-04-27 23:18:12 +02:00
Garrett M
3dfa2ca62e leisure.rs cargo fmt
Cargo fmt
2025-04-27 16:48:30 -04:00
Louis Erbkamm
f1d3c0b980 Merge pull request #421 from Oleg4260/main
Optimize ground generation + new natural elements
2025-04-27 22:36:52 +02:00
louis-e
bcc986969f Merge branch 'simplify-elevation' of https://github.com/louis-e/arnis into simplify-elevation 2025-04-27 22:28:35 +02:00
Louis Erbkamm
2d07e9c2b9 Fix cargo fmt 2025-04-27 22:27:11 +02:00
Louis Erbkamm
a213bace19 Fix clippy 2025-04-27 22:18:50 +02:00
Louis Erbkamm
7552a99a34 Fix clippy 2025-04-27 22:16:28 +02:00
XianlinSheng
2a52538a1e improve safety for public interfaces of xzbboxes 2025-04-27 16:09:11 -04:00
Louis Erbkamm
ec3f5825b4 Fix formatting 2025-04-27 22:08:09 +02:00
louis-e
1294c3ef3c Fix formatting for CI 2025-04-27 22:06:52 +02:00
Louis Erbkamm
ca2fd0b1c6 Merge branch 'main' into simplify-elevation 2025-04-27 21:58:13 +02:00
louis-e
b5596548db Optimize WorldEditor performance with strategic #[inline] attributes 2025-04-27 21:57:01 +02:00
Oleg4260
6167466b2f Less vegetation in heathland 2025-04-27 22:56:03 +03:00
louis-e
5e18402017 Add location name to world name 2025-04-27 21:47:25 +02:00
Oleg4260
ec76a5f2e2 Add heath and orchard generation 2025-04-27 22:14:49 +03:00
XianlinSheng
369e422b4a change operator into trait; factory method return error-backtracable Result 2025-04-27 14:32:28 -04:00
Oleg4260
349f15807a Final adjustments 2025-04-27 21:27:19 +03:00
Oleg4260
6fdf28ab81 Add beach surface material processing, dead bushes in sand, plants in scrub and grassland 2025-04-27 19:15:30 +03:00
louis-e
c961287290 Adapt code comments 2025-04-27 16:59:56 +02:00
louis-e
1fefb20f71 Fix formatting 2025-04-27 16:52:37 +02:00
louis-e
022c44a7d4 Remove unused code 2025-04-27 16:52:13 +02:00
louis-e
6b8a8ad666 Patch amenities.rs to new relative block setter logic 2025-04-27 16:51:49 +02:00
louis-e
c0e1d0e3b4 Patch buildings.rs to new relative block setter logic 2025-04-27 16:38:17 +02:00
louis-e
fb64d0c360 Add absolute setter support in world_editor.rs 2025-04-27 16:10:13 +02:00
Oleg4260
19cac3ea81 Minor reformatting 2025-04-27 15:18:16 +03:00
Oleg4260
8bad88bdca Refactor editor.check_for_block() 2025-04-27 15:00:42 +03:00
Oleg4260
e62ba6a95a Merge branch 'louis-e:main' into main 2025-04-27 13:46:02 +03:00
Garrett M
d1b18871ce Update leisure generation and fix typo
Fix 'Mincraft' typo (Code still works so not sure what that prefix did)
Add additional types for leisure
2025-04-27 00:07:58 -04:00
XianlinSheng
4d47a22904 add xzbbox validity check in factory 2025-04-26 23:21:15 -04:00
Benjamin Wheeler
d4b74fc48a Move GUI logic to its own file. Simplify main fn. 2025-04-26 23:13:32 -04:00
louis-e
38752f2666 Fix fmt for elevation retrieval simplification 2025-04-27 03:35:52 +02:00
louis-e
77a9c23ed3 Simplify elevation retrieval 2025-04-27 03:32:44 +02:00
XianlinSheng
a991f60d29 fix clippy 2025-04-26 21:07:25 -04:00
XianlinSheng
966241aa52 merge to main 2025-04-26 20:57:36 -04:00
XianlinSheng
e9cc0ced41 xzbbox architecture made compatible for rotation and cropping; improve namings; fix water area dependencies on new xzbbox (add get_min_coords) 2025-04-26 20:38:03 -04:00
Louis Erbkamm
987b8b3d74 Merge pull request #422 from louis-e/simplification-refactoring
Remove winter mode as discussed in issues/415
2025-04-27 01:29:06 +02:00
Louis Erbkamm
f398c7e6b8 Removed dirt reference 2025-04-27 01:26:40 +02:00
louis-e
9a759c39db Fix fmt for winter mode removal 2025-04-27 00:51:36 +02:00
louis-e
856cba162e Remove winter mode as discussed in issues/415 2025-04-27 00:48:56 +02:00
Louis Erbkamm
55d0208a32 Merge pull request #411 from HelleBenjamin/main
Update Finnish translation
2025-04-27 00:01:18 +02:00
Louis Erbkamm
b1d20cbd1a Patch --all-features discussed in pull/417 2025-04-26 23:59:07 +02:00
Louis Erbkamm
cca4d1a361 Merge pull request #417 from benjamin051000/ci-cache
CI: Add cache action to preserve build artifacts.
2025-04-26 23:57:11 +02:00
Oleg4260
ae5a838fa3 Optimize ground generation 2025-04-26 19:05:17 +03:00
Louis Erbkamm
06974e2bf7 Arch Linux AUR package 2025-04-26 16:13:17 +02:00
Louis Erbkamm
b769ff34de Merge pull request #113 from adamperkowski/docs/aur
docs(README): add Arch Linux installation instructions
2025-04-26 16:11:18 +02:00
Louis Erbkamm
0f8e302aff Merge branch 'main' into docs/aur 2025-04-26 16:10:45 +02:00
Louis Erbkamm
597051303c Merge pull request #360 from louis-e/dependabot/cargo/dirs-6.0.0
Bump dirs from 5.0.1 to 6.0.0
2025-04-26 16:06:19 +02:00
Louis Erbkamm
08bdc64999 Merge branch 'main' into dependabot/cargo/dirs-6.0.0 2025-04-26 16:06:12 +02:00
Louis Erbkamm
3723127132 Resolve open discussion in pull/354 2025-04-26 15:43:59 +02:00
Louis Erbkamm
f8a1da1967 Merge pull request #354 from TheComputerGuy96/desktop-file
Add a XDG desktop file
2025-04-26 15:43:09 +02:00
Louis Erbkamm
9352ee62b7 Merge pull request #420 from louis-e/revert-line
Revert to second dirt addition line
2025-04-26 15:19:53 +02:00
Louis Erbkamm
8816af5c75 Revert to second dirt addition line 2025-04-26 15:19:38 +02:00
Louis Erbkamm
2fb09d1fba Merge pull request #377 from benjamin051000/formalize-bbox
Formal BBox struct
2025-04-26 15:00:09 +02:00
Benjamin Wheeler
c3ce8829f3 Update GUI bbox to use comma delim. Add gui bbox errors. 2025-04-25 20:28:11 -04:00
Benjamin Wheeler
a3f0d5e367 Formal bounding box type BBox.
`BBox` represents a *valid* bounding box.

It's only possible to have a BBox object that's valid.
2025-04-25 20:28:06 -04:00
Benjamin Helle
d93b771422 Merge branch 'main' into main 2025-04-24 15:47:41 +03:00
Louis Erbkamm
4271dc3b7d Merge pull request #414 from Oleg4260/main
Minor improvements to farmland code
2025-04-22 22:39:49 +02:00
Oleg4260
6732697f46 Use args.ground_level instead of MIN_Y with terrain enabled 2025-04-22 17:56:12 +03:00
Benjamin Helle
4d94ab98a4 Merge branch 'main' into main 2025-04-22 01:34:39 +03:00
Benjamin Wheeler
2c8418bf90 Add cache action to preserve build artifacts.
Github Copilot made this... so who knows if it actually works.
2025-04-21 18:17:08 -04:00
Oleg4260
a1ed2b9dd2 Clean up farmland code 2025-04-20 23:17:35 +03:00
Oleg4260
9b7cabc549 Fix space between water blocks (meant to be 8) 2025-04-20 16:05:45 +03:00
XianlinSheng
21b0b99d7e improve modulization of map_editing and coordinate_system. make cartesian coordinate_system::cartesian for extension of spherical coordinate submod 2025-04-19 23:58:07 -04:00
Louis Erbkamm
db47f6ab20 Merge pull request #412 from louis-e/revert-improvement
Revert improvement
2025-04-19 15:13:55 +02:00
louis-e
ef261a24e4 Revert benches in leisure, discussion in pull/406 2025-04-19 15:13:22 +02:00
louis-e
898457e06c Revert improvement, discussion in pull/406 2025-04-19 15:10:04 +02:00
Benjamin Helle
0f84c8a38c Update Finnish translation 2025-04-19 15:39:21 +03:00
Benjamin Helle
f416f650c2 Update Finnish translation 2025-04-19 15:38:28 +03:00
XianlinSheng
f39b760aa0 fix redundant namings 2025-04-13 03:05:27 -04:00
XianlinSheng
bfbb8b05a2 Merge updated branch 'main' 2025-04-13 02:30:06 -04:00
XianlinSheng
3173a8f7d8 add map editing into workflow 2025-04-13 02:29:55 -04:00
XianlinSheng
9dac978a69 add map_editing architecture, cancels coordinate restriction starting from 0 2025-04-13 00:43:26 -04:00
Louis Erbkamm
b98c043bb8 Merge pull request #376 from benjamin051000/ci-cargo-test
ci: run cargo test
2025-04-13 00:45:35 +02:00
Louis Erbkamm
2a1233c463 Merge pull request #374 from benjamin051000/fix-terrain-flag
Set `terrain` arg to store true.
2025-04-13 00:44:37 +02:00
Louis Erbkamm
e1869fbbbc Merge pull request #340 from benjamin051000/refactor-block-defs
Change functions returning vecs to global arrays.
2025-04-13 00:43:11 +02:00
Benjamin Wheeler
bfba692aaf Change functions returning vecs to global arrays.
I'm not sure why these were initally functions. I think they are better
off as global arrays, since the function would initialize a new vec
every time its called, whereas this only initializes it once.
2025-04-10 16:57:29 -04:00
Benjamin Wheeler
1382e05e25 Add cargo test to CI 2025-04-10 16:25:02 -04:00
Benjamin Wheeler
642928057a Add unit tests for --winter, --debug, --terrain flags. 2025-04-10 16:23:09 -04:00
Benjamin Wheeler
1749f6a1f2 Set terrain arg to SetTrue.
This was erroneously set to `SetFalse`, which means it's impossible to
enable the terrain from the cli.

According to clap docs, the default action for a bool arg is SetTrue,
and the default value is false. (https://docs.rs/clap/latest/clap/_derive/index.html#arg-types)

So we don't need to provide any additional args here.
2025-04-10 16:23:09 -04:00
Louis Erbkamm
4c08c5fe72 Patch arabic translation 2025-04-10 22:19:35 +02:00
Louis Erbkamm
8a4961a0a6 Merge pull request #287 from Salmonings/main
Add Arabic language
2025-04-10 22:18:43 +02:00
Louis Erbkamm
05569fb0fc fr-FR.json adaptions from pull/318/ 2025-04-10 22:15:47 +02:00
Louis Erbkamm
f203ad1c09 Merge pull request #396 from Phantomwise/translation-french
Add translation for French (France)
2025-04-10 22:13:39 +02:00
Louis Erbkamm
4d123211ee Merge pull request #398 from xCipHanD/ChineseTranslation
Update Chinese translation
2025-04-10 22:10:35 +02:00
Louis Erbkamm
8a191e563d Merge pull request #407 from louis-e/dependabot/cargo/cargo-6f59152c2a
Bump the cargo group with 5 updates
2025-04-10 22:05:07 +02:00
Louis Erbkamm
9c0db6f1c7 Update README.md 2025-04-10 21:59:07 +02:00
dependabot[bot]
a7638d971a Bump the cargo group with 5 updates
Bumps the cargo group with 5 updates:

| Package | From | To |
| --- | --- | --- |
| [tauri-plugin-shell](https://github.com/tauri-apps/plugins-workspace) | `2.2.0` | `2.2.1` |
| [tokio](https://github.com/tokio-rs/tokio) | `1.44.1` | `1.44.2` |
| [crossbeam-channel](https://github.com/crossbeam-rs/crossbeam) | `0.5.14` | `0.5.15` |
| [openssl](https://github.com/sfackler/rust-openssl) | `0.10.70` | `0.10.72` |
| [ring](https://github.com/briansmith/ring) | `0.17.8` | `0.17.14` |


Updates `tauri-plugin-shell` from 2.2.0 to 2.2.1
- [Release notes](https://github.com/tauri-apps/plugins-workspace/releases)
- [Commits](https://github.com/tauri-apps/plugins-workspace/compare/os-v2.2.0...os-v2.2.1)

Updates `tokio` from 1.44.1 to 1.44.2
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.44.1...tokio-1.44.2)

Updates `crossbeam-channel` from 0.5.14 to 0.5.15
- [Release notes](https://github.com/crossbeam-rs/crossbeam/releases)
- [Changelog](https://github.com/crossbeam-rs/crossbeam/blob/master/CHANGELOG.md)
- [Commits](https://github.com/crossbeam-rs/crossbeam/compare/crossbeam-channel-0.5.14...crossbeam-channel-0.5.15)

Updates `openssl` from 0.10.70 to 0.10.72
- [Release notes](https://github.com/sfackler/rust-openssl/releases)
- [Commits](https://github.com/sfackler/rust-openssl/compare/openssl-v0.10.70...openssl-v0.10.72)

Updates `ring` from 0.17.8 to 0.17.14
- [Changelog](https://github.com/briansmith/ring/blob/main/RELEASES.md)
- [Commits](https://github.com/briansmith/ring/commits)

---
updated-dependencies:
- dependency-name: tauri-plugin-shell
  dependency-version: 2.2.1
  dependency-type: direct:production
  dependency-group: cargo
- dependency-name: tokio
  dependency-version: 1.44.2
  dependency-type: direct:production
  dependency-group: cargo
- dependency-name: crossbeam-channel
  dependency-version: 0.5.15
  dependency-type: indirect
  dependency-group: cargo
- dependency-name: openssl
  dependency-version: 0.10.72
  dependency-type: indirect
  dependency-group: cargo
- dependency-name: ring
  dependency-version: 0.17.14
  dependency-type: indirect
  dependency-group: cargo
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-10 19:51:16 +00:00
Louis Erbkamm
fa6a023b7c Merge pull request #406 from louis-e/pull403-adaptions
Minor adaptions for PR 403
2025-04-10 21:50:09 +02:00
Louis Erbkamm
2ac4cacd2d Merge pull request #363 from louis-e/dependabot/cargo/cargo-2c68f0befb
Bump openssl from 0.10.68 to 0.10.70 in the cargo group
2025-04-10 21:49:17 +02:00
Louis Erbkamm
b334212667 Merge pull request #391 from louis-e/dependabot/cargo/tauri-plugin-log-2.2.2
Bump tauri-plugin-log from 2.2.0 to 2.2.2
2025-04-10 21:48:58 +02:00
Louis Erbkamm
dc7f3f973e Merge pull request #402 from louis-e/dependabot/cargo/tokio-1.44.1
Bump tokio from 1.42.0 to 1.44.1
2025-04-10 21:48:42 +02:00
Louis Erbkamm
44f58dcd22 Merge pull request #401 from louis-e/dependabot/cargo/log-0.4.27
Bump log from 0.4.22 to 0.4.27
2025-04-10 21:48:38 +02:00
louis-e
4c1643281d fmt: Fix formatting 2025-04-10 21:47:35 +02:00
louis-e
6e113746d4 Minor adaptions for PR 403 2025-04-10 21:41:35 +02:00
Louis Erbkamm
6a1d6d32ff Merge pull request #403 from Oleg4260/main
Some improvements for the generation
2025-04-10 21:39:09 +02:00
Oleg4260
8d6d10fc47 Remove ugly "benches" 2025-04-09 17:23:18 +03:00
Oleg4260
c022611d08 Add custom layers for some landuse and natural objects, use stone as a marker not to generate dirt 2025-04-07 18:21:57 +03:00
Oleg4260
5a15ba3a62 Clarify comment 2025-04-07 12:34:02 +03:00
Oleg4260
c526f295c3 cargo fmt 2025-04-07 12:23:43 +03:00
Oleg4260
0e0a08cfc9 Remove stone filling under quarries (doesn't work anymore) 2025-04-07 12:22:58 +03:00
Oleg4260
d992e5eb87 Remove BASE_HEIGHT_SCALE, remove scale.sqrt to match X and Z scale 2025-04-07 10:59:56 +03:00
Oleg4260
5c0e24ee73 fix fmt 2025-04-06 18:29:35 +03:00
Oleg4260
9d85de61a3 Replace water grid with dot grid in farmlands 2025-04-06 18:27:42 +03:00
Oleg4260
b23749b330 Change scale to 1.0 2025-04-05 20:56:35 +03:00
Oleg4260
77debbbc20 Fix clippy error 2025-04-05 15:24:25 +03:00
Oleg4260
8970ce5ffe Remove trees from farmlands 2025-04-05 15:06:47 +03:00
Oleg4260
7a36ac9c3f Improve winter mode 2025-04-05 14:40:19 +03:00
Oleg4260
4363dfd558 Add more natural surfaces 2025-04-05 13:22:52 +03:00
Oleg4260
1aac2e3068 Increase max_y to 319 2025-04-05 01:31:59 +03:00
dependabot[bot]
d16cedde9a Bump tokio from 1.42.0 to 1.44.1
Bumps [tokio](https://github.com/tokio-rs/tokio) from 1.42.0 to 1.44.1.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.42.0...tokio-1.44.1)

---
updated-dependencies:
- dependency-name: tokio
  dependency-version: 1.44.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-01 03:04:46 +00:00
dependabot[bot]
59b71ebd84 Bump log from 0.4.22 to 0.4.27
Bumps [log](https://github.com/rust-lang/log) from 0.4.22 to 0.4.27.
- [Release notes](https://github.com/rust-lang/log/releases)
- [Changelog](https://github.com/rust-lang/log/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/log/compare/0.4.22...0.4.27)

---
updated-dependencies:
- dependency-name: log
  dependency-version: 0.4.27
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-01 03:03:02 +00:00
xciphand
2e01c8c710 Update Chinese Translation 2025-03-26 12:03:17 +08:00
Louis Erbkamm
bff58b39fd Fix cargo fmt 2025-03-23 17:14:13 +01:00
Louis Erbkamm
887e622428 Added fillground if wrapping around bedrock generation 2025-03-23 17:11:01 +01:00
Louis Erbkamm
931f03a784 Merge pull request #337 from Oleg4260/main
Added ores generation in quarries + other changes
2025-03-23 17:09:08 +01:00
Oleg4260
c1c43d9244 Fix stone bricks in rural area 2025-03-22 19:25:06 +02:00
Phantomwise
8a84a08316 Add translation for French (France) 2025-03-20 04:25:32 +01:00
Oleg4260
2c72a61324 sync 2025-03-09 23:09:06 +02:00
Oleg4260
bf263a4f8c fix conflict 2025-03-09 22:56:35 +02:00
Louis Erbkamm
50ba0bad6e Merge pull request #346 from Xatresu/hutranslation
Add Hungarian translation
2025-03-09 21:47:44 +01:00
Louis Erbkamm
1d80e6e047 Merge pull request #378 from benjamin051000/clippy-warnings
Fix clippy warnings
2025-03-09 21:43:35 +01:00
Louis Erbkamm
b5e9bb885d Merge pull request #335 from benjamin051000/refactor-tree
Refactor tree generation
2025-03-09 21:40:38 +01:00
dependabot[bot]
665b8f095b Bump tauri-plugin-log from 2.2.0 to 2.2.2
Bumps [tauri-plugin-log](https://github.com/tauri-apps/plugins-workspace) from 2.2.0 to 2.2.2.
- [Release notes](https://github.com/tauri-apps/plugins-workspace/releases)
- [Commits](https://github.com/tauri-apps/plugins-workspace/compare/os-v2.2.0...log-v2.2.2)

---
updated-dependencies:
- dependency-name: tauri-plugin-log
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-03-09 20:33:13 +00:00
Louis Erbkamm
75bee6ca97 Merge pull request #321 from benjamin051000/remove-more-gui-deps
Remove gui-only deps when building cli
2025-03-09 21:31:52 +01:00
Oleg4260
41055825ef Replace iron blocks under railways with gravel 2025-03-08 13:56:34 +02:00
Benjamin Wheeler
6fd3a8eda7 Fix clippy warnings 2025-02-21 22:42:44 -05:00
Oleg4260
c578a436b4 Replace light concrete with dirt path for highway:path 2025-02-11 23:52:10 +02:00
Oleg4260
211ac4ed72 Merge branch 'main' of https://github.com/Oleg4260/arnis 2025-02-04 17:02:12 +02:00
Oleg4260
3d0a1c3c4d cargo fmt 2025-02-04 17:02:10 +02:00
Oleg4260
0c9c8e1366 Merge branch 'main' of https://github.com/Oleg4260/arnis 2025-02-04 17:00:15 +02:00
Oleg4260
0e28d34224 Use editor.fill_blocks() instead of loop 2025-02-04 16:59:09 +02:00
Oleg4260
3b1425cd30 Merge branch 'main' of https://github.com/Oleg4260/arnis 2025-02-04 16:08:20 +02:00
Oleg4260
ce0bce99fb Added feature to fill ground with stone
Trying to fix compilation error
2025-02-04 16:08:09 +02:00
Oleg4260
cde0042b85 Trying to fix compilation error 2025-02-04 00:22:49 +02:00
Oleg4260
622edaff07 Added feature to fill ground with stone 2025-02-04 00:06:09 +02:00
dependabot[bot]
ca760563d1 Bump openssl from 0.10.68 to 0.10.70 in the cargo group
Bumps the cargo group with 1 update: [openssl](https://github.com/sfackler/rust-openssl).


Updates `openssl` from 0.10.68 to 0.10.70
- [Release notes](https://github.com/sfackler/rust-openssl/releases)
- [Commits](https://github.com/sfackler/rust-openssl/compare/openssl-v0.10.68...openssl-v0.10.70)

---
updated-dependencies:
- dependency-name: openssl
  dependency-type: indirect
  dependency-group: cargo
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-02-03 18:51:25 +00:00
dependabot[bot]
f278d629eb Bump dirs from 5.0.1 to 6.0.0
Bumps [dirs](https://github.com/soc/dirs-rs) from 5.0.1 to 6.0.0.
- [Commits](https://github.com/soc/dirs-rs/commits)

---
updated-dependencies:
- dependency-name: dirs
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-02-01 02:40:47 +00:00
Echo J
2c319bae5d Add a XDG desktop file
This allows proper packaging of the application for Linux distros
2025-01-29 20:55:49 +02:00
Xatres
809ff2793d Add files via upload 2025-01-27 03:35:52 +01:00
Benjamin Wheeler
3ba9c58f85 element_processing/tree: Make all trees conform to a struct.
This decouples the data that each tree has with the block-placing
procedure. Now, all the data about a tree is stored in `struct Tree`,
and the `Tree::create()` function handles all paths accordingly.
2025-01-25 23:39:38 -05:00
Benjamin Wheeler
66b7f47e32 element_processing/tree: Update create_tree signature
x, y, z -> (x, y, z)

Also some small variable renames
2025-01-25 23:39:38 -05:00
Benjamin Wheeler
a96911e112 element_processing/tree: DRY on fill calls, use j with y.
This commit is a little messy:
- It reduces repitition of the block fill calls and the snow layer calls
- It also replaces previous usage of `y + i` with `y + j` to keep the
  variable conventions the same.
2025-01-25 23:39:35 -05:00
Benjamin Wheeler
112481f36f Remove gui-only deps when building cli
It looks like these are only GUI dependencies. I still need to test that
it compiles, but these give unused warnings when compiling with the gui
disabled.
2025-01-25 22:03:16 -05:00
Benjamin Wheeler
65cd0d453a element_processing/tree: replace round{1,2,3} with generic round
round takes a parameter which is a reference to an array of patterns.
The patterns are defined at the top of the file as `[(i32, i32, i32)]`.
2025-01-25 21:33:13 -05:00
Benjamin Wheeler
febd1b7a3e element_processing/tree: Use loops to reduce repitition 2025-01-25 21:33:13 -05:00
Oleg4260
6b527855e4 cargo fmt 2025-01-25 20:07:03 +02:00
Oleg4260
cc1e28b80a Added ores generation in quarries 2025-01-25 20:03:16 +02:00
Louis Erbkamm
a969d65ae4 Trigger ci-build.yml only when files in src/ have changed 2025-01-25 14:15:23 +01:00
Louis Erbkamm
acf123488a Merge pull request #333 from Oleg4260/main
Add landuse for quarry and landfills + add one advice in FAQ
2025-01-25 14:10:08 +01:00
Louis Erbkamm
938a2d74ad Merge pull request #334 from wielandb/hedge-fix
Make leaves persistent to stop hedges from decaying
2025-01-25 14:09:02 +01:00
Louis Erbkamm
33144a149c Merge pull request #336 from TheComputerGuy96/lt-update
Update Lithuanian translation
2025-01-25 14:07:18 +01:00
Echo J
fbb0f845cd Update Lithuanian translation 2025-01-25 12:20:30 +02:00
Wieland
c71cd111ca Make leaves persistent 2025-01-24 22:41:30 +01:00
Oleg4260
04d9d5269f Put changes back again (i messed up with merging lmao) 2025-01-24 20:29:43 +02:00
Oleg4260
f53e4d65e3 Merge branch 'main' of https://github.com/Oleg4260/arnis 2025-01-24 20:20:27 +02:00
Oleg4260
c39d6fc1ef Merge branch 'louis-e:main' into main 2025-01-24 20:12:53 +02:00
Oleg4260
a1c69b4cb0 Did cargo fmt 2025-01-24 20:11:10 +02:00
Louis Erbkamm
b57719b0f4 Merge pull request #317 from krvstek/main
Update Polish translation
2025-01-24 17:21:41 +01:00
Louis Erbkamm
893945b98a Merge pull request #324 from Denisskas/main
Update Russian translation
2025-01-24 17:19:19 +01:00
Oleg4260
a57c5f1f1b Add landuse for quarry and landfill 2025-01-23 23:37:28 +02:00
Oleg4260
718389e88d Revert "Replaced iron blocks under railways with gravel"
This reverts commit 3f4536e04f.
2025-01-23 20:50:33 +02:00
Oleg4260
3f4536e04f Replaced iron blocks under railways with gravel 2025-01-23 19:43:57 +02:00
Oleg4260
1f79285e83 Update README.md
I had an issue of the program not opening when I switched to KDE and removed some gtk libraries i don't need, I found out that webkit2gtk-4.1 is required, so I think this should be in the FAQ as this might help others with the same issue
2025-01-23 18:11:45 +02:00
Adham Hakki
31dca8b0b7 Merge branch 'main' into main 2025-01-22 21:26:37 +02:00
Denisskas
54791388d1 Update ru.json 2025-01-22 13:18:47 +04:00
krvstek.
7fa05d3e7b Update Polish translation 2025-01-21 23:02:33 +00:00
dependabot[bot]
b9133664ec Bump actions/upload-artifact from 3 to 4
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 3 to 4.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-01-20 22:45:24 +00:00
dependabot[bot]
032e084265 Bump softprops/action-gh-release from 1 to 2
Bumps [softprops/action-gh-release](https://github.com/softprops/action-gh-release) from 1 to 2.
- [Release notes](https://github.com/softprops/action-gh-release/releases)
- [Changelog](https://github.com/softprops/action-gh-release/blob/master/CHANGELOG.md)
- [Commits](https://github.com/softprops/action-gh-release/compare/v1...v2)

---
updated-dependencies:
- dependency-name: softprops/action-gh-release
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-01-20 22:45:23 +00:00
dependabot[bot]
49202b0f33 Bump actions/download-artifact from 3 to 4
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 3 to 4.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-01-20 22:45:20 +00:00
Adham Hakki
7ae9ac35d1 Add Arabic language
Just love the idea and the project so a little bit of contributing might help! Here's the Arabic locales for the program! Just be careful as Arabic is a RTL language so it might go wrong/weird
2025-01-13 21:32:29 +02:00
dependabot[bot]
1609608ae8 Bump actions/checkout from 3 to 4
Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-01-07 21:27:21 +00:00
Adam Perkowski
8e29b1422e docs(README): add Arch Linux installation instructions 2025-01-01 18:17:26 +01:00
187 changed files with 15610 additions and 17250 deletions

1
.envrc Normal file
View File

@@ -0,0 +1 @@
use flake

2
.gitattributes vendored
View File

@@ -1 +1 @@
gui-src/** linguist-vendored
src/gui/** linguist-vendored

View File

@@ -11,13 +11,13 @@ assignees: ''
A clear and concise description of what the bug is and what you expected to happen.
**Used bbox area**
Please provide your input parameters so we can reproduce the issue. *(For example: 48.133444 11.569462 48.142609 11.584740)*
Please provide your input parameters (BBOX) so we can reproduce the issue. *(For example: 48.133444 11.569462 48.142609 11.584740)*
**Arnis and Minecraft version**
Please tell us what version of Arnis and Minecraft you used.
Please tell us what version of Arnis and Minecraft you used, as well as if you are on Windows, Linux or MacOS.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Additional context**
Add any other context about the problem here. If you used any more custom settings, please provide them here too. If you experienced any issue with the application itself like a crash, please provide the log file which can be found at C:\Users\USERNAME\AppData\Local\com.louisdev.arnis\logs
Add any other context about the problem here. If you used any more custom settings, please provide them here too. Please provide the log file if possible as well, which can be found at C:\Users\USERNAME\AppData\Local\com.louisdev.arnis\logs

View File

@@ -1,35 +1,32 @@
name: CI Build
# Trigger on pull request creation, update, and on pushes to the main branch
# Trigger CI on pull requests when relevant files change, and pushes to main
on:
pull_request:
branches:
- main
paths:
- '.github/**'
- 'src/**'
- 'Cargo.toml'
- 'Cargo.lock'
push:
branches:
- main
workflow_dispatch:
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
lint:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
uses: actions/checkout@v6
- name: Set up Rust
uses: dtolnay/rust-toolchain@v1
with:
toolchain: stable
targets: ${{ matrix.os == 'windows-latest' && 'x86_64-pc-windows-msvc' || 'x86_64-unknown-linux-gnu' || 'x86_64-apple-darwin' }}
components: clippy
components: clippy, rustfmt
- name: Install Linux dependencies
if: matrix.os == 'ubuntu-latest'
run: |
sudo apt update
sudo apt install -y software-properties-common
@@ -39,14 +36,39 @@ jobs:
sudo apt install -y libgtk-3-dev build-essential pkg-config libglib2.0-dev libsoup-3.0-dev libwebkit2gtk-4.1-dev
echo "PKG_CONFIG_PATH=/usr/lib/x86_64-linux-gnu/pkgconfig" >> $GITHUB_ENV
- uses: Swatinem/rust-cache@v2
- name: Check formatting
run: cargo fmt -- --check
- name: Check clippy lints
run: cargo clippy --all-targets --all-features -- -D warnings
- name: Install Rust dependencies
run: cargo fetch
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v6
- name: Build
run: cargo build --release
- name: Set up Rust
uses: dtolnay/rust-toolchain@v1
with:
toolchain: stable
- name: Install Linux dependencies
run: |
sudo apt update
sudo apt install -y software-properties-common
sudo add-apt-repository universe
echo "deb http://archive.ubuntu.com/ubuntu $(lsb_release -sc)-backports main restricted universe multiverse" | sudo tee -a /etc/apt/sources.list
sudo apt update
sudo apt install -y libgtk-3-dev build-essential pkg-config libglib2.0-dev libsoup-3.0-dev libwebkit2gtk-4.1-dev
echo "PKG_CONFIG_PATH=/usr/lib/x86_64-linux-gnu/pkgconfig" >> $GITHUB_ENV
- uses: Swatinem/rust-cache@v2
- name: Build (all targets, all features)
run: cargo build --all-targets --all-features --release
- name: Run unit tests
run: cargo test --all-targets --all-features

141
.github/workflows/pr-benchmark.yml vendored Normal file
View File

@@ -0,0 +1,141 @@
name: PR Benchmark
permissions:
contents: read
pull-requests: write
on:
pull_request:
types: [opened, reopened]
issue_comment:
types: [created]
jobs:
benchmark:
if: |
github.event_name == 'pull_request' ||
(github.event_name == 'issue_comment' &&
github.event.issue.pull_request != null &&
contains(github.event.comment.body, 'retrigger-benchmark'))
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v5
- name: Set up Rust
uses: dtolnay/rust-toolchain@v1
with:
toolchain: stable
- uses: Swatinem/rust-cache@v2
- name: Create dummy Minecraft world directory
run: |
mkdir -p "./world/region"
- name: Build for release
run: cargo build --release --no-default-features
- name: Start timer
id: start_time
run: echo "start_time=$(date +%s)" >> $GITHUB_OUTPUT
- name: Run benchmark command with memory tracking
id: benchmark
run: |
/usr/bin/time -v ./target/release/arnis --path="./world" --terrain --generate-map --bbox="48.125768 11.552296 48.148565 11.593838" 2> benchmark_log.txt
grep "Maximum resident set size" benchmark_log.txt | awk '{print $6}' > peak_mem_kb.txt
peak_kb=$(cat peak_mem_kb.txt)
peak_mb=$((peak_kb / 1024))
echo "peak_memory=${peak_mb}" >> $GITHUB_OUTPUT
- name: End timer and calculate duration
id: end_time
run: |
end_time=$(date +%s)
start_time=${{ steps.start_time.outputs.start_time }}
duration=$((end_time - start_time))
echo "duration=$duration" >> $GITHUB_OUTPUT
- name: Check for map preview
id: map_check
run: |
if [ -f "./world/arnis_world_map.png" ]; then
echo "Map preview generated successfully"
echo "map_exists=true" >> $GITHUB_OUTPUT
else
echo "Map preview not found"
echo "map_exists=false" >> $GITHUB_OUTPUT
fi
- name: Upload map preview as artifact
if: steps.map_check.outputs.map_exists == 'true'
uses: actions/upload-artifact@v4
with:
name: world-map-preview
path: ./world/arnis_world_map.png
retention-days: 60
- name: Format duration and generate summary
id: comment_body
run: |
duration=${{ steps.end_time.outputs.duration }}
minutes=$((duration / 60))
seconds=$((duration % 60))
peak_mem=${{ steps.benchmark.outputs.peak_memory }}
baseline_time=69
diff=$((duration - baseline_time))
abs_diff=${diff#-}
if [ "$diff" -lt -5 ]; then
verdict="✅ This PR **improves generation time**."
elif [ "$abs_diff" -le 4 ]; then
verdict="🟢 Generation time is unchanged."
elif [ "$diff" -le 15 ]; then
verdict="⚠️ This PR **worsens generation time**."
else
verdict="🚨 This PR **drastically worsens generation time**."
fi
baseline_mem=935
mem_annotation=""
if [ "$peak_mem" -gt 2000 ]; then
mem_diff=$((peak_mem - baseline_mem))
mem_percent=$((mem_diff * 100 / baseline_mem))
mem_annotation=" (↗ ${mem_percent}% more)"
fi
# Get current timestamp
benchmark_time=$(date -u "+%Y-%m-%d %H:%M:%S UTC")
run_url="https://github.com/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}"
{
echo "summary<<EOF"
echo "## ⏱️ Benchmark Results"
echo ""
echo "| Metric | Value |"
echo "|--------|-------|"
echo "| Duration | **${minutes}m ${seconds}s** |"
echo "| Peak Memory | **${peak_mem} MB**${mem_annotation} |"
echo "| Baseline | **${baseline_time}s** |"
echo "| Delta | **${diff}s** |"
echo "| Commit | [\`${GITHUB_SHA:0:7}\`](https://github.com/${GITHUB_REPOSITORY}/commit/${GITHUB_SHA}) |"
echo ""
echo "${verdict}"
echo ""
echo "---"
echo ""
echo "📅 **Last benchmark:** ${benchmark_time} | 📥 [Download generated world map](${run_url}#artifacts)"
echo ""
echo "_You can retrigger the benchmark by commenting \`retrigger-benchmark\`._"
echo "EOF"
} >> "$GITHUB_OUTPUT"
- name: Comment build time on PR
uses: thollander/actions-comment-pull-request@v3
with:
message: ${{ steps.comment_body.outputs.summary }}
comment-tag: benchmark-report
env:
GITHUB_TOKEN: ${{ secrets.BENCHMARK_TOKEN }}

View File

@@ -17,16 +17,20 @@ jobs:
target: x86_64-unknown-linux-gnu
binary_name: arnis
asset_name: arnis-linux
- os: macos-latest
- os: macos-13 # Intel runner for x86_64 builds
target: x86_64-apple-darwin
binary_name: arnis
asset_name: arnis-mac
asset_name: arnis-mac-intel
- os: macos-latest # ARM64 runner for ARM64 builds
target: aarch64-apple-darwin
binary_name: arnis
asset_name: arnis-mac-arm64
runs-on: ${{ matrix.os }}
steps:
- name: Checkout code
uses: actions/checkout@v3
uses: actions/checkout@v6
- name: Set up Rust
uses: dtolnay/rust-toolchain@v1
@@ -49,10 +53,10 @@ jobs:
run: cargo fetch
- name: Build
run: cargo build --release
run: cargo build --release --target ${{ matrix.target }}
- name: Rename binary for release
run: mv target/release/${{ matrix.binary_name }} target/release/${{ matrix.asset_name }}
run: mv target/${{ matrix.target }}/release/${{ matrix.binary_name }} target/release/${{ matrix.asset_name }}
- name: Install Windows SDK
if: matrix.os == 'windows-latest'
@@ -83,47 +87,74 @@ jobs:
shell: powershell
- name: Upload artifact
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.os }}-build
name: ${{ matrix.os }}-${{ matrix.target }}-build
path: target/release/${{ matrix.asset_name }}
release:
create-universal-macos:
needs: build
runs-on: macos-latest
steps:
- name: Download macOS Intel build
uses: actions/download-artifact@v5
with:
name: macos-13-x86_64-apple-darwin-build
path: ./intel
- name: Download macOS ARM64 build
uses: actions/download-artifact@v5
with:
name: macos-latest-aarch64-apple-darwin-build
path: ./arm64
- name: Create universal binary
run: |
lipo -create -output arnis-mac-universal ./intel/arnis-mac-intel ./arm64/arnis-mac-arm64
chmod +x arnis-mac-universal
- name: Upload universal binary
uses: actions/upload-artifact@v4
with:
name: macos-universal-build
path: arnis-mac-universal
release:
needs: [build, create-universal-macos]
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
uses: actions/checkout@v6
- name: Download Windows build artifact
uses: actions/download-artifact@v3
uses: actions/download-artifact@v5
with:
name: windows-latest-build
name: windows-latest-x86_64-pc-windows-msvc-build
path: ./builds/windows
- name: Download Linux build artifact
uses: actions/download-artifact@v3
uses: actions/download-artifact@v5
with:
name: ubuntu-latest-build
name: ubuntu-latest-x86_64-unknown-linux-gnu-build
path: ./builds/linux
- name: Download macOS build artifact
uses: actions/download-artifact@v3
- name: Download macOS universal build artifact
uses: actions/download-artifact@v5
with:
name: macos-latest-build
name: macos-universal-build
path: ./builds/macos
- name: Make Linux and macOS binaries executable
run: |
chmod +x ./builds/linux/arnis-linux
chmod +x ./builds/macos/arnis-mac
chmod +x ./builds/macos/arnis-mac-universal
- name: Create GitHub Release
uses: softprops/action-gh-release@v1
uses: softprops/action-gh-release@v2
with:
files: |
builds/windows/arnis-windows.exe
builds/linux/arnis-linux
builds/macos/arnis-mac
builds/macos/arnis-mac-universal
env:
GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }}

View File

@@ -0,0 +1,100 @@
name: Test macOS Build
on:
push:
branches: [ main ]
paths:
- '.github/workflows/release.yml'
- 'src/**'
- 'Cargo.toml'
pull_request:
branches: [ main ]
workflow_dispatch: # Allow manual triggering
jobs:
test-macos-builds:
strategy:
matrix:
include:
- target: x86_64-apple-darwin
asset_name: arnis-mac-intel
- target: aarch64-apple-darwin
asset_name: arnis-mac-arm64
runs-on: macos-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Rust
uses: dtolnay/rust-toolchain@v1
with:
toolchain: stable
targets: ${{ matrix.target }}
- name: Install dependencies
run: cargo fetch
- name: Build for ${{ matrix.target }}
run: cargo build --release --target ${{ matrix.target }}
- name: Rename binary
run: mv target/${{ matrix.target }}/release/arnis target/${{ matrix.target }}/release/${{ matrix.asset_name }}
- name: Check binary architecture
run: |
file target/${{ matrix.target }}/release/${{ matrix.asset_name }}
lipo -info target/${{ matrix.target }}/release/${{ matrix.asset_name }}
- name: Test binary execution (basic check)
run: |
chmod +x target/${{ matrix.target }}/release/${{ matrix.asset_name }}
# Test that it at least shows help/version (don't run full generation)
target/${{ matrix.target }}/release/${{ matrix.asset_name }} --help || echo "Help command completed"
- name: Upload test artifact
uses: actions/upload-artifact@v4
with:
name: test-${{ matrix.target }}-build
path: target/${{ matrix.target }}/release/${{ matrix.asset_name }}
test-universal-binary:
needs: test-macos-builds
runs-on: macos-latest
steps:
- name: Download Intel build
uses: actions/download-artifact@v4
with:
name: test-x86_64-apple-darwin-build
path: ./intel
- name: Download ARM64 build
uses: actions/download-artifact@v4
with:
name: test-aarch64-apple-darwin-build
path: ./arm64
- name: Create and test universal binary
run: |
lipo -create -output arnis-mac-universal ./intel/arnis-mac-intel ./arm64/arnis-mac-arm64
chmod +x arnis-mac-universal
# Verify it's actually universal
echo "=== Universal Binary Info ==="
file arnis-mac-universal
lipo -info arnis-mac-universal
# Test execution
echo "=== Testing Universal Binary ==="
./arnis-mac-universal --help || echo "Universal binary help command completed"
# Check file size (should be sum of both architectures roughly)
echo "=== File Sizes ==="
ls -lah ./intel/arnis-mac-intel ./arm64/arnis-mac-arm64 arnis-mac-universal
- name: Upload universal binary
uses: actions/upload-artifact@v4
with:
name: test-universal-build
path: arnis-mac-universal

5
.gitignore vendored
View File

@@ -1,6 +1,7 @@
/wiki
# Environment files
.env
.envrc
/.direnv
# Build artifacts
@@ -28,6 +29,8 @@ Thumbs.db
/export.json
/parsed_osm_data.txt
/elevation_debug.png
/terrain-tile-cache
/arnis-tile-cache
/gen/
/build/
*.rmeta

1741
Cargo.lock generated
View File

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
[package]
name = "arnis"
version = "2.2.0"
version = "2.3.1"
edition = "2021"
description = "Arnis - Generate real life cities in Minecraft"
homepage = "https://github.com/louis-e/arnis"
@@ -10,40 +10,45 @@ readme = "README.md"
[profile.release]
lto = "thin"
overflow-checks = true
[features]
default = ["gui"]
gui = ["dep:tauri", "dep:tauri-plugin-log", "dep:tauri-plugin-shell"]
gui = ["tauri", "tauri-plugin-log", "tauri-plugin-shell", "tokio", "rfd", "dirs", "tauri-build"]
[build-dependencies]
tauri-build = "2"
tauri-build = {version = "2", optional = true}
[dependencies]
clap = { version = "4.1", features = ["derive"] }
colored = "2.1.0"
dirs = "5.0.1"
fastanvil = "0.31.0"
fastnbt = "2.5.0"
flate2 = "1.0"
base64 = "0.22.1"
clap = { version = "4.5", features = ["derive", "env"] }
colored = "3.0.0"
dirs = {version = "6.0.0", optional = true }
fastanvil = "0.32.0"
fastnbt = "2.6.0"
flate2 = "1.1"
fnv = "1.0.7"
fs2 = "0.4"
geo = "0.29.3"
image = "0.24"
indicatif = "0.17.8"
geo = "0.31.0"
image = "0.25"
indicatif = "0.17.11"
itertools = "0.14.0"
log = "0.4.22"
once_cell = "1.19.0"
log = "0.4.27"
once_cell = "1.21.3"
rand = "0.8.5"
rayon = "1.10.0"
reqwest = { version = "0.12.7", features = ["blocking", "json"] }
rfd = "0.15.1"
semver = "1.0.23"
reqwest = { version = "0.12.15", features = ["blocking", "json"] }
rfd = { version = "0.15.4", optional = true }
semver = "1.0.27"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tauri = { version = "2", optional = true }
tauri-plugin-log = { version = "2.2.0", optional = true }
tauri-plugin-log = { version = "2.6.0", optional = true }
tauri-plugin-shell = { version = "2", optional = true }
tokio = { version = "1.42.0", features = ["full"] }
tokio = { version = "1.48.0", features = ["full"], optional = true }
[target.'cfg(windows)'.dependencies]
windows = { version = "0.59.0", features = ["Win32_System_Console"] }
windows = { version = "0.61.1", features = ["Win32_System_Console"] }
[dev-dependencies]
tempfile = "3.23.0"

121
README.md
View File

@@ -1,110 +1,41 @@
<p align="center">
<img width="456" height="125" src="https://github.com/louis-e/arnis/blob/main/gui-src/images/logo.png?raw=true">
</p>
<img src="assets/git/banner.png" width="100%" alt="Banner">
# Arnis [![CI Build Status](https://github.com/louis-e/arnis/actions/workflows/ci-build.yml/badge.svg)](https://github.com/louis-e/arnis/actions) [<img alt="GitHub Release" src="https://img.shields.io/github/v/release/louis-e/arnis" />](https://github.com/louis-e/arnis/releases) [<img alt="GitHub Downloads (all assets, all releases" src="https://img.shields.io/github/downloads/louis-e/arnis/total" />](https://github.com/louis-e/arnis/releases)
# Arnis [![CI Build Status](https://github.com/louis-e/arnis/actions/workflows/ci-build.yml/badge.svg)](https://github.com/louis-e/arnis/actions) [<img alt="GitHub Release" src="https://img.shields.io/github/v/release/louis-e/arnis" />](https://github.com/louis-e/arnis/releases) [<img alt="GitHub Downloads (all assets, all releases" src="https://img.shields.io/github/downloads/louis-e/arnis/total" />](https://github.com/louis-e/arnis/releases) [![Download here](https://img.shields.io/badge/Download-here-green)](https://github.com/louis-e/arnis/releases) [![Discord](https://img.shields.io/discord/1326192999738249267?label=Discord&color=%237289da)](https://discord.gg/mA2g69Fhxq)
This open source project written in Rust generates any chosen location from the real world in Minecraft Java Edition with a high level of detail.
Arnis creates complex and accurate Minecraft Java Edition worlds that reflect real-world geography, topography, and architecture.
###### ⚠️ This Github page is the official project website. Do not download Arnis from any other website.
This free and open source project is designed to handle large-scale geographic data from the real world and generate detailed Minecraft worlds. The algorithm processes geospatial data from OpenStreetMap as well as elevation data to create an accurate Minecraft representation of terrain and architecture.
Generate your hometown, big cities, and natural landscapes with ease!
## :desktop_computer: Example
![Minecraft Preview](https://github.com/louis-e/arnis/blob/main/gitassets/mc.gif?raw=true)
By leveraging geospatial data from OpenStreetMap and utilizing the powerful capabilities of Rust, Arnis provides an efficient and robust solution for creating complex and accurate Minecraft worlds that reflect real-world geography and architecture.
Arnis is designed to handle large-scale data and generate rich, immersive environments that bring real-world cities, landmarks, and natural features into the Minecraft universe. Whether you're looking to replicate your hometown, explore urban environments, or simply build something unique and realistic, Arnis generates your vision.
![Minecraft Preview](assets/git/preview.jpg)
<i>This Github page and [arnismc.com](https://arnismc.com) are the only official project websites. Do not download Arnis from any other website.</i>
## :keyboard: Usage
<img width="60%" src="https://github.com/louis-e/arnis/blob/main/gitassets/gui.png?raw=true"><br>
<img width="60%" src="assets/git/gui.png"><br>
Download the [latest release](https://github.com/louis-e/arnis/releases/) or [compile](#trophy-open-source) the project on your own.
Choose your area in Arnis using the rectangle tool and select your Minecraft world - then simply click on 'Start Generation'!
The world will always be generated starting from the Minecraft coordinates 0 0 0 (/tp 0 0 0). This is the top left of your selected area.
To generate your world with terrain, make sure to enable the corresponding feature in the generation settings.
Choose your area on the map using the rectangle tool and select your Minecraft world - then simply click on <i>Start Generation</i>!
Additionally, you can customize various generation settings, such as world scale, spawn point, or building interior generation.
Minecraft version 1.16.5 and below is currently not supported, but we are working on it! For the best results, use Minecraft version 1.21.4.
If you choose to select an own world, be aware that Arnis will overwrite certain areas.
## 📚 Documentation
## :floppy_disk: How it works
![CLI Generation](https://github.com/louis-e/arnis/blob/main/gitassets/cli.gif?raw=true)
<img src="assets/git/documentation.png" width="100%" alt="Banner">
The raw data obtained from the API *[(see FAQ)](#question-faq)* includes each element (buildings, walls, fountains, farmlands, etc.) with its respective corner coordinates (nodes) and descriptive tags. When you run Arnis, the following steps are performed automatically to generate a Minecraft world:
#### Processing Pipeline
1. **Fetching Data from the Overpass API:** The script retrieves geospatial data for the desired bounding box from the Overpass API.
2. **Parsing Raw Data:** The raw data is parsed to extract essential information like nodes, ways, and relations. Nodes are converted into Minecraft coordinates, and relations are handled similarly to ways, ensuring all relevant elements are processed correctly. Relations and ways cluster several nodes into one specific object.
3. **Prioritizing and Sorting Elements:** The elements (nodes, ways, relations) are sorted by priority to establish a layering system, which ensures that certain types of elements (e.g., entrances and buildings) are generated in the correct order to avoid conflicts and overlapping structures.
4. **Generating Minecraft World:** The Minecraft world is generated using a series of element processors (generate_buildings, generate_highways, generate_landuse, etc.) that interpret the tags and nodes of each element to place the appropriate blocks in the Minecraft world. These processors handle the logic for creating 3D structures, roads, natural formations, and more, as specified by the processed data.
5. **Generating Ground Layer:** A ground layer is generated based on the provided scale factors to provide a base for the entire Minecraft world. This step ensures all areas have an appropriate foundation (e.g., grass and dirt layers).
6. **Saving the Minecraft World:** All the modified chunks are saved back to the Minecraft region files.
## :question: FAQ
- *Wasn't this written in Python before?*<br>
Yes! Arnis was initially developed in Python, which benefited from Python's open-source friendliness and ease of readability. This is why we strive for clear, well-documented code in the Rust port of this project to find the right balance. I decided to port the project to Rust to learn more about the language and push the algorithm's performance further. We were nearing the limits of optimization in Python, and Rust's capabilities allow for even better performance and efficiency. The old Python implementation is still available in the python-legacy branch.
- *Where does the data come from?*<br>
The geographic data is sourced from OpenStreetMap (OSM)[^1], a free, collaborative mapping project that serves as an open-source alternative to commercial mapping services. The data is accessed via the Overpass API, which queries OSM's database. Other services like Google Maps do not provide data like this, which makes OSM perfect for this project.
- *How does the Minecraft world generation work?*<br>
The script uses the [fastnbt](https://github.com/owengage/fastnbt) cargo package to interact with Minecraft's world format. This library allows Arnis to manipulate Minecraft region files, enabling the generation of real-world locations. The section 'Processing Pipeline' goes a bit further into the details and steps of the generation process itself.
- *Where does the name come from?*<br>
The project is named after the smallest city in Germany, Arnis[^2]. The city's small size made it an ideal test case for developing and debugging the algorithm efficiently.
- *I don't have Minecraft installed but want to generate a world for my kids. How?*<br>
When selecting a world, click on 'Select existing world' and choose a directory. The world will be generated there.
- *Arnis instantly closes again or the window is empty!*<br>
If you're on Windows, please install the [Evergreen Bootstrapper from Microsoft](https://developer.microsoft.com/en-us/microsoft-edge/webview2/?form=MA13LH#download).
- *What Minecraft version should I use?*<br>
Please use Minecraft version 1.21.4 for the best results. Minecraft version 1.16.5 and below is currently not supported, but we are working on it!
- *The generation did finish, but there's nothing in the world!*<br>
Make sure to teleport to the generation starting point (/tp 0 0 0). If there is still nothing, you might need to travel a bit further into the positive X and positive Z direction.
- *What features are in the world generation settings?*<br>
**Terrain:** Make sure to enable this feature to generate your world with elevation data included.<br>
**Winter Mode:** This setting changes the generation style to a snowy theme and adds snow layers to the ground.<br>
**Scale Factor:** The scale factor determines the size of the generated world.<br>
**Custom BBOX Input:** This setting allows you to manually input the bounding box coordinates for the area you want to generate.<br>
**Floodfill-Timeout (Sec):** This setting determines the maximum time the floodfill algorithm is allowed to run before being terminated. Increasing this value may improve the generation of large water areas but may also increase processing time.<br>
**Ground Height:** This setting determines the base height of the generated world and can be adjusted to create different terrain types.
## :memo: ToDo and Known Bugs
Feel free to choose an item from the To-Do or Known Bugs list, or bring your own idea to the table. Bug reports shall be raised as a Github issue. Contributions are highly welcome and appreciated!
- [ ] Fix compilation for Linux
- [ ] Rotate maps (https://github.com/louis-e/arnis/issues/97)
- [ ] Fix coastal cities generation duration time (water_areas.rs)
- [ ] Add street names as signs
- [ ] Add support for older Minecraft versions (<=1.16.5) (https://github.com/louis-e/arnis/issues/124, https://github.com/louis-e/arnis/issues/137)
- [ ] Mapping real coordinates to Minecraft coordinates (https://github.com/louis-e/arnis/issues/29)
- [ ] Add interior to buildings
- [ ] Implement house roof types
- [ ] Add support for inner attribute in multipolygons and multipolygon elements other than buildings
- [ ] Refactor bridges implementation
- [ ] Better code documentation
- [ ] Refactor fountain structure implementation
- [ ] Luanti Support (https://github.com/louis-e/arnis/issues/120)
- [ ] Minecraft Bedrock Edition Support (https://github.com/louis-e/arnis/issues/148)
- [x] Evaluate and implement elevation (https://github.com/louis-e/arnis/issues/66)
- [x] Refactor railway implementation
- [x] Evaluate and implement faster region saving
- [x] Support multipolygons (https://github.com/louis-e/arnis/issues/112, https://github.com/louis-e/arnis/issues/114)
- [x] Memory optimization
- [x] Fix Github Action Workflow for releasing MacOS Binary
- [x] Design and implement a GUI
- [x] Automatic new world creation instead of using an existing world
- [x] Fix faulty empty chunks ([https://github.com/owengage/fastnbt/issues/120](https://github.com/owengage/fastnbt/issues/120)) (workaround found)
- [x] Setup fork of [https://github.com/aaronr/bboxfinder.com](https://github.com/aaronr/bboxfinder.com) for easy bbox picking
Full documentation is available in the [GitHub Wiki](https://github.com/louis-e/arnis/wiki/), covering topics such as technical explanations, FAQs, contribution guidelines and roadmaps.
## :trophy: Open Source
#### Key objectives of this project
- **Modularity**: Ensure that all components (e.g., data fetching, processing, and world generation) are cleanly separated into distinct modules for better maintainability and scalability.
- **Performance Optimization**: Utilize Rusts memory safety and concurrency features to optimize the performance of the world generation process.
- **Performance Optimization**: We aim to keep a good performance and speed of the world generation process.
- **Comprehensive Documentation**: Detailed in-code documentation for a clear structure and logic.
- **User-Friendly Experience**: Focus on making the project easy to use for end users.
- **Cross-Platform Support**: Ensure the project runs smoothly on Windows, macOS, and Linux.
- **Cross-Platform Support**: We want this project to run smoothly on Windows, macOS, and Linux.
#### How to contribute
This project is open source and welcomes contributions from everyone! Whether you're interested in fixing bugs, improving performance, adding new features, or enhancing documentation, your input is valuable. Simply fork the repository, make your changes, and submit a pull request. We encourage discussions and suggestions to ensure the project remains modular, optimized, and easy to use for the community. You can use the parameter --debug to get a more detailed output of the processed values, which can be helpful for debugging and development. Contributions of all levels are appreciated, and your efforts help improve this tool for everyone.
This project is open source and welcomes contributions from everyone! Whether you're interested in fixing bugs, improving performance, adding new features, or enhancing documentation, your input is valuable. Simply fork the repository, make your changes, and submit a pull request. Please respect the above mentioned key objectives. Contributions of all levels are appreciated, and your efforts help improve this tool for everyone.
Build and run it using: ```cargo run --release --no-default-features -- --path="C:/YOUR_PATH/.minecraft/saves/worldname" --bbox="min_lng,min_lat,max_lng,max_lat"```<br>
For the GUI: ```cargo run --release```<br>
Command line Build: ```cargo run --no-default-features -- --terrain --path="C:/YOUR_PATH/.minecraft/saves/worldname" --bbox="min_lat,min_lng,max_lat,max_lng"```<br>
GUI Build: ```cargo run```<br>
After your pull request was merged, I will take care of regularly creating update releases which will include your changes.
@@ -118,6 +49,20 @@ After your pull request was merged, I will take care of regularly creating updat
</picture>
</a>
## :newspaper: Academic & Press Recognition
<img src="assets/git/recognition.png" width="100%" alt="Banner">
Arnis has been recognized in various academic and press publications after gaining a lot of attention in December 2024.
[Floodcraft: Game-based Interactive Learning Environment using Minecraft for Flood Mitigation and Preparedness for K-12 Education](https://www.researchgate.net/publication/384644535_Floodcraft_Game-based_Interactive_Learning_Environment_using_Minecraft_for_Flood_Mitigation_and_Preparedness_for_K-12_Education)
[Hackaday: Bringing OpenStreetMap Data into Minecraft](https://hackaday.com/2024/12/30/bringing-openstreetmap-data-into-minecraft/)
[TomsHardware: Minecraft Tool Lets You Create Scale Replicas of Real-World Locations](https://www.tomshardware.com/video-games/pc-gaming/minecraft-tool-lets-you-create-scale-replicas-of-real-world-locations-arnis-uses-geospatial-data-from-openstreetmap-to-generate-minecraft-maps)
[XDA Developers: Hometown Minecraft Map: Arnis](https://www.xda-developers.com/hometown-minecraft-map-arnis/)
## :copyright: License Information
Copyright (c) 2022-2025 Louis Erbkamm (louis-e)
@@ -133,7 +78,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.[^3]
Download Arnis only from the official source (https://github.com/louis-e/arnis/). Every other website providing a download and claiming to be affiliated with the project is unofficial and may be malicious.
Download Arnis only from the official source https://arnismc.com or https://github.com/louis-e/arnis/. Every other website providing a download and claiming to be affiliated with the project is unofficial and may be malicious.
The logo was made by @nxfx21.

BIN
assets/git/banner.png Normal file
View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

View File

Before

Width:  |  Height:  |  Size: 160 KiB

After

Width:  |  Height:  |  Size: 160 KiB

View File

Before

Width:  |  Height:  |  Size: 1.0 MiB

After

Width:  |  Height:  |  Size: 1.0 MiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

BIN
assets/git/gui.png Normal file
View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 196 KiB

BIN
assets/git/preview.jpg Normal file
View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 790 KiB

BIN
assets/git/recognition.png Normal file
View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 KiB

BIN
assets/icons/128x128.png Normal file
View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
assets/icons/128x128@2x.png Normal file
View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

BIN
assets/icons/32x32.png Normal file
View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

BIN
assets/icons/icon.icns Normal file
View File

Binary file not shown.

BIN
assets/icons/icon.ico Normal file
View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

BIN
assets/icons/icon.png Normal file
View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 258 KiB

BIN
assets/minecraft/icon.png Normal file
View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

60
flake.lock generated Normal file
View File

@@ -0,0 +1,60 @@
{
"nodes": {
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1731533236,
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1755615617,
"narHash": "sha256-HMwfAJBdrr8wXAkbGhtcby1zGFvs+StOp19xNsbqdOg=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "20075955deac2583bb12f07151c2df830ef346b4",
"type": "github"
},
"original": {
"id": "nixpkgs",
"ref": "nixos-unstable",
"type": "indirect"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",
"version": 7
}

36
flake.nix Normal file
View File

@@ -0,0 +1,36 @@
{
inputs = {
flake-utils.url = "github:numtide/flake-utils";
nixpkgs.url = "nixpkgs/nixos-unstable";
};
outputs =
{
flake-utils,
nixpkgs,
...
}:
flake-utils.lib.eachDefaultSystem (
system:
let
pkgs = nixpkgs.legacyPackages.${system};
stdenv = if pkgs.stdenv.isLinux then pkgs.stdenvAdapters.useMoldLinker pkgs.stdenv else pkgs.stdenv;
in
{
devShell = pkgs.mkShell.override { inherit stdenv; } {
buildInputs = with pkgs; [
openssl.dev
pkg-config
wayland
glib
gdk-pixbuf
pango
gtk3
libsoup_3.dev
webkitgtk_4_1.dev
];
};
}
);
}

99
flake/flake.lock generated
View File

@@ -1,99 +0,0 @@
{
"nodes": {
"fenix": {
"inputs": {
"nixpkgs": [
"nixpkgs"
],
"rust-analyzer-src": "rust-analyzer-src"
},
"locked": {
"lastModified": 1724653830,
"narHash": "sha256-88f0KK8h6tGIP4Na5RJDKs0S+7WsGGaCGNkLj/bPV3g=",
"owner": "nix-community",
"repo": "fenix",
"rev": "9ecf5e7d800ace001320da8acadd4a3deb872a83",
"type": "github"
},
"original": {
"owner": "nix-community",
"repo": "fenix",
"type": "github"
}
},
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1710146030,
"narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1724479785,
"narHash": "sha256-pP3Azj5d6M5nmG68Fu4JqZmdGt4S4vqI5f8te+E/FTw=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "d0e1602ddde669d5beb01aec49d71a51937ed7be",
"type": "github"
},
"original": {
"id": "nixpkgs",
"ref": "nixos-unstable",
"type": "indirect"
}
},
"root": {
"inputs": {
"fenix": "fenix",
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs"
}
},
"rust-analyzer-src": {
"flake": false,
"locked": {
"lastModified": 1724586512,
"narHash": "sha256-mrfwk6nO8N2WtCq3sB2zhd2QN1HMKzeSESzOA6lSsQg=",
"owner": "rust-lang",
"repo": "rust-analyzer",
"rev": "7106cd3be50b2a43c1d9f2787bf22d4369c2b25b",
"type": "github"
},
"original": {
"owner": "rust-lang",
"ref": "nightly",
"repo": "rust-analyzer",
"type": "github"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",
"version": 7
}

View File

@@ -1,34 +0,0 @@
{
inputs = {
fenix = {
url = "github:nix-community/fenix";
inputs.nixpkgs.follows = "nixpkgs";
};
flake-utils.url = "github:numtide/flake-utils";
nixpkgs.url = "nixpkgs/nixos-unstable";
};
outputs = { self, fenix, flake-utils, nixpkgs }:
flake-utils.lib.eachDefaultSystem (system:
let
pkgs = nixpkgs.legacyPackages.${system};
fenixPkgs = (fenix.packages.${system}.stable);
in
{
devShell = pkgs.mkShell
{
buildInputs = with pkgs; [
openssl.dev
pkg-config
fenixPkgs.toolchain
wayland
glib
gdk-pixbuf
pango
gtk3
libsoup_3.dev
webkitgtk_4_1.dev
];
};
});
}

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 198 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.7 MiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.5 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.5 KiB

View File

@@ -1,49 +0,0 @@
/* Conditional stylesheet for IE. */
.leaflet-draw-toolbar {
border: 3px solid #999;
}
.leaflet-draw-toolbar a {
background-color: #eee;
}
.leaflet-draw-toolbar a:hover {
background-color: #fff;
}
.leaflet-draw-actions {
left: 32px;
margin-top: 3px;
}
.leaflet-draw-actions li {
display: inline;
zoom: 1;
}
.leaflet-edit-marker-selected {
border: 4px dashed #fe93c2;
}
.leaflet-draw-actions a {
background-color: #999;
}
.leaflet-draw-actions a:hover {
background-color: #a5a5a5;
}
.leaflet-draw-actions-top a {
margin-top: 1px;
}
.leaflet-draw-actions-bottom a {
height: 28px;
line-height: 28px;
}
.leaflet-draw-actions-top.leaflet-draw-actions-bottom a {
height: 27px;
line-height: 27px;
}

View File

@@ -1,51 +0,0 @@
.leaflet-vml-shape {
width: 1px;
height: 1px;
}
.lvml {
behavior: url(#default#VML);
display: inline-block;
position: absolute;
}
.leaflet-control {
display: inline;
}
.leaflet-popup-tip {
width: 21px;
_width: 27px;
margin: 0 auto;
_margin-top: -3px;
filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678);
-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)";
}
.leaflet-popup-tip-container {
margin-top: -1px;
}
.leaflet-popup-content-wrapper, .leaflet-popup-tip {
border: 1px solid #999;
}
.leaflet-popup-content-wrapper {
zoom: 1;
}
.leaflet-control-zoom,
.leaflet-control-layers {
border: 3px solid #999;
}
.leaflet-control-layers-toggle {
}
.leaflet-control-attribution,
.leaflet-control-layers,
.leaflet-control-scale-line {
background: white;
}
.leaflet-zoom-box {
filter: alpha(opacity=50);
}
.leaflet-control-attribution {
border-top: 1px solid #bbb;
border-left: 1px solid #bbb;
}

View File

@@ -1,757 +0,0 @@
/* general typography */
.leaflet-container {
background:#fff;
font:15px/25px 'Helvetica Neue', Arial, Helvetica, sans-serif;
color:#404040;
color:rgba(0,0,0,0.75);
outline:0;
overflow:hidden;
-ms-touch-action:none;
}
.leaflet-container *,
.leaflet-container *:after,
.leaflet-container *:before {
-webkit-box-sizing:border-box;
-moz-box-sizing:border-box;
box-sizing:border-box;
}
.leaflet-container h1,
.leaflet-container h2,
.leaflet-container h3,
.leaflet-container h4,
.leaflet-container h5,
.leaflet-container h6,
.leaflet-container p {
font-size:15px;
line-height:25px;
margin:0 0 10px;
}
.mapbox-small,
.leaflet-control-attribution,
.leaflet-control-scale,
.leaflet-container input,
.leaflet-container textarea,
.leaflet-container label,
.leaflet-container small {
font-size:12px;
line-height:20px;
}
.leaflet-container a {
color:#3887BE;
font-weight:normal;
text-decoration:none;
}
.leaflet-container a:hover { color:#63b6e5; }
.leaflet-container.dark a { color:#63b6e5; }
.leaflet-container.dark a:hover { color:#8fcaec; }
.leaflet-container.dark .mapbox-button,
.leaflet-container .mapbox-button {
background-color:#3887be;
display:inline-block;
height:40px;
line-height:40px;
text-decoration:none;
color:#fff;
font-size:12px;
white-space:nowrap;
text-overflow:ellipsis;
}
.leaflet-container.dark .mapbox-button:hover,
.leaflet-container .mapbox-button:hover {
color:#fff;
background-color:#3bb2d0;
}
/* Base Leaflet
------------------------------------------------------- */
.leaflet-map-pane,
.leaflet-tile,
.leaflet-marker-icon,
.leaflet-marker-shadow,
.leaflet-tile-pane,
.leaflet-tile-container,
.leaflet-overlay-pane,
.leaflet-shadow-pane,
.leaflet-marker-pane,
.leaflet-popup-pane,
.leaflet-overlay-pane svg,
.leaflet-zoom-box,
.leaflet-image-layer,
.leaflet-layer {
position:absolute;
left:0;
top:0;
}
.leaflet-tile,
.leaflet-marker-icon,
.leaflet-marker-shadow {
-webkit-user-drag:none;
-webkit-user-select:none;
-moz-user-select:none;
user-select:none;
}
.leaflet-marker-icon,
.leaflet-marker-shadow {
display: block;
}
.leaflet-tile {
filter:inherit;
visibility:hidden;
}
.leaflet-tile-loaded {
visibility:inherit;
}
.leaflet-zoom-box {
width:0;
height:0;
}
.leaflet-tile-pane { z-index:2; }
.leaflet-objects-pane { z-index:3; }
.leaflet-overlay-pane { z-index:4; }
.leaflet-shadow-pane { z-index:5; }
.leaflet-marker-pane { z-index:6; }
.leaflet-popup-pane { z-index:7; }
.leaflet-control {
position:relative;
z-index:7;
pointer-events:auto;
float:left;
clear:both;
}
.leaflet-right .leaflet-control { float:right; }
.leaflet-top .leaflet-control { margin-top:10px; }
.leaflet-bottom .leaflet-control { margin-bottom:10px; }
.leaflet-left .leaflet-control { margin-left:10px; }
.leaflet-right .leaflet-control { margin-right:10px; }
.leaflet-top,
.leaflet-bottom {
position:absolute;
z-index:1000;
pointer-events:none;
}
.leaflet-top { top:0; }
.leaflet-right { right:0; }
.leaflet-bottom { bottom:0; }
.leaflet-left { left:0; }
/* zoom and fade animations */
.leaflet-fade-anim .leaflet-tile,
.leaflet-fade-anim .leaflet-popup {
opacity:0;
-webkit-transition:opacity 0.2s linear;
-moz-transition:opacity 0.2s linear;
-o-transition:opacity 0.2s linear;
transition:opacity 0.2s linear;
}
.leaflet-fade-anim .leaflet-tile-loaded,
.leaflet-fade-anim .leaflet-map-pane .leaflet-popup {
opacity:1;
}
.leaflet-zoom-anim .leaflet-zoom-animated {
-webkit-transition:-webkit-transform 0.25s cubic-bezier(0,0,0.25,1);
-moz-transition: -moz-transform 0.25s cubic-bezier(0,0,0.25,1);
-o-transition: -o-transform 0.25s cubic-bezier(0,0,0.25,1);
transition: transform 0.25s cubic-bezier(0,0,0.25,1);
}
.leaflet-zoom-anim .leaflet-tile,
.leaflet-pan-anim .leaflet-tile,
.leaflet-touching .leaflet-zoom-animated {
-webkit-transition:none;
-moz-transition:none;
-o-transition:none;
transition:none;
}
.leaflet-zoom-anim .leaflet-zoom-hide { visibility: hidden; }
/* cursors */
.map-clickable,
.leaflet-clickable {
cursor: pointer;
}
.leaflet-popup-pane,
.leaflet-control {
cursor:auto;
}
.leaflet-container {
cursor:-webkit-grab;
cursor: -moz-grab;
}
.leaflet-dragging,
.leaflet-dragging .map-clickable,
.leaflet-dragging .leaflet-clickable,
.leaflet-dragging .leaflet-container {
cursor:move;
cursor:-webkit-grabbing;
cursor: -moz-grabbing;
}
.leaflet-zoom-box {
background:#fff;
border:2px dotted #202020;
opacity:0.5;
}
/* general toolbar styles */
.leaflet-control-layers,
.leaflet-bar {
background-color:#fff;
border:1px solid #999;
border-color:rgba(0,0,0,0.4);
border-radius:3px;
box-shadow:none;
}
.leaflet-bar a,
.leaflet-bar a:hover {
color:#404040;
color:rgba(0,0,0,0.75);
border-bottom:1px solid #ddd;
border-bottom-color:rgba(0,0,0,0.10);
}
.leaflet-bar a:hover,
.leaflet-bar a:active {
background-color:#f8f8f8;
cursor:pointer;
}
.leaflet-bar a:first-child {
border-radius:3px 3px 0 0;
}
.leaflet-bar a:last-child {
border-bottom:none;
border-radius:0 0 3px 3px;
}
.leaflet-bar a:only-of-type {
border-radius:3px;
}
.leaflet-bar .leaflet-disabled {
cursor:default;
opacity:0.75;
}
.leaflet-control-zoom-in,
.leaflet-control-zoom-out {
display:block;
content:'';
text-indent:-999em;
}
.leaflet-control-layers .leaflet-control-layers-list,
.leaflet-control-layers-expanded .leaflet-control-layers-toggle {
display:none;
}
.leaflet-control-layers-expanded .leaflet-control-layers-list {
display:block;
position:relative;
}
.leaflet-control-layers-expanded {
background:#fff;
padding:6px 10px 6px 6px;
color:#404040;
color:rgba(0,0,0,0.75);
}
.leaflet-control-layers-selector {
margin-top:2px;
position:relative;
top:1px;
}
.leaflet-control-layers label {
display: block;
}
.leaflet-control-layers-separator {
height:0;
border-top:1px solid #ddd;
border-top-color:rgba(0,0,0,0.10);
margin:5px -10px 5px -6px;
}
.leaflet-container .leaflet-control-attribution {
background-color:rgba(255,255,255,0.25);
margin:0;
box-shadow:none;
}
.leaflet-control-attribution a:hover,
.map-info-container a:hover {
color:inherit;
text-decoration:underline;
}
.leaflet-control-attribution,
.leaflet-control-scale-line {
padding:0 5px;
}
.leaflet-left .leaflet-control-scale { margin-left:5px; }
.leaflet-bottom .leaflet-control-scale { margin-bottom:5px; }
.leaflet-control-scale-line {
background-color:rgba(255,255,255,0.5);
border:1px solid #999;
border-color:rgba(0,0,0,0.4);
border-top:none;
padding:2px 5px 1px;
white-space:nowrap;
overflow:hidden;
}
.leaflet-control-scale-line:not(:first-child) {
border-top:2px solid #ddd;
border-top-color:rgba(0,0,0,0.10);
border-bottom:none;
margin-top:-2px;
}
.leaflet-control-scale-line:not(:first-child):not(:last-child) {
border-bottom:2px solid #777;
}
/* popup */
.leaflet-popup {
position:absolute;
text-align:center;
pointer-events:none;
}
.leaflet-popup-content-wrapper {
padding:1px;
text-align:left;
pointer-events:all;
}
.leaflet-popup-content {
padding:10px 10px 15px;
margin:0;
line-height:inherit;
}
.leaflet-popup-tip-container {
width:20px;
height:20px;
margin:0 auto;
position:relative;
}
.leaflet-popup-tip {
width:0;
height:0;
margin:0;
border-left:10px solid transparent;
border-right:10px solid transparent;
border-top:10px solid #fff;
box-shadow:none;
}
.leaflet-popup-close-button {
text-indent:-999em;
position:absolute;
top:0;right:0;
pointer-events:all;
}
.leaflet-popup-close-button:hover {
background-color:#f8f8f8;
}
.leaflet-popup-scrolled {
overflow:auto;
border-bottom:1px solid #ddd;
border-top:1px solid #ddd;
}
/* div icon */
.leaflet-div-icon {
background:#fff;
border:1px solid #999;
border-color:rgba(0,0,0,0.4);
}
.leaflet-editing-icon {
border-radius:3px;
}
/* Leaflet + Mapbox
------------------------------------------------------- */
.leaflet-bar a,
.mapbox-icon,
.map-tooltip.closable .close,
.leaflet-control-layers-toggle,
.leaflet-popup-close-button,
.mapbox-button-icon:before {
content:'';
display:inline-block;
width:26px;
height:26px;
vertical-align:middle;
background-repeat:no-repeat;
}
.leaflet-bar a {
display:block;
}
.leaflet-control-zoom-in,
.leaflet-control-zoom-out,
.leaflet-popup-close-button,
.leaflet-control-layers-toggle,
.leaflet-container.dark .map-tooltip .close,
.map-tooltip .close,
.mapbox-icon {
background-image:url(./images/icons-404040.png);
background-repeat:no-repeat;
background-size:26px 260px;
}
.mapbox-button-icon:before,
.leaflet-container.dark .leaflet-control-zoom-in,
.leaflet-container.dark .leaflet-control-zoom-out,
.leaflet-container.dark .leaflet-control-layers-toggle,
.leaflet-container.dark .mapbox-icon {
background-image:url(./images/icons-ffffff.png);
background-size:26px 260px;
}
.leaflet-bar .leaflet-control-zoom-in { background-position:0 0; }
.leaflet-bar .leaflet-control-zoom-out { background-position:0 -26px; }
.map-tooltip .close, .leaflet-popup-close-button { background-position:0 -52px; }
.mapbox-icon-info { background-position:0 -78px; }
.leaflet-control-layers-toggle { background-position:0 -104px; }
.mapbox-icon-share:before, .mapbox-icon-share { background-position:0 -130px; }
.mapbox-icon-geocoder:before, .mapbox-icon-geocoder { background-position:0 -156px; }
.mapbox-icon-facebook:before, .mapbox-icon-facebook { background-position:0 -182px; }
.mapbox-icon-twitter:before, .mapbox-icon-twitter { background-position:0 -208px; }
.mapbox-icon-pinterest:before, .mapbox-icon-pinterest { background-position:0 -234px; }
@media
(-webkit-min-device-pixel-ratio:2),
(min-resolution:192dpi) {
.leaflet-control-zoom-in,
.leaflet-control-zoom-out,
.leaflet-popup-close-button,
.leaflet-control-layers-toggle,
.mapbox-icon {
background-image:url(./images/icons-404040@2x.png);
}
.mapbox-button-icon:before,
.leaflet-container.dark .leaflet-control-zoom-in,
.leaflet-container.dark .leaflet-control-zoom-out,
.leaflet-container.dark .leaflet-control-layers-toggle,
.leaflet-container.dark .mapbox-icon {
background-image:url(./images/icons-ffffff@2x.png);
}
}
.leaflet-popup-content-wrapper,
.map-legends,
.map-tooltip {
background:#fff;
border-radius:3px;
box-shadow:0 1px 2px rgba(0,0,0,0.10);
}
.map-legends,
.map-tooltip {
max-width:300px;
}
.map-legends .map-legend {
padding:10px;
}
.map-tooltip {
z-index:999999;
padding:10px;
min-width:180px;
max-height:400px;
overflow:auto;
opacity:1;
-webkit-transition:opacity 150ms;
-moz-transition:opacity 150ms;
-o-transition:opacity 150ms;
transition:opacity 150ms;
}
.map-tooltip .close {
text-indent:-999em;
overflow:hidden;
display:none;
}
.map-tooltip.closable .close {
position:absolute;
top:0;right:0;
border-radius:3px;
}
.map-tooltip.closable .close:active {
background-color:#f8f8f8;
}
.leaflet-control-interaction {
position:absolute;
top:10px;
right:10px;
width:300px;
}
.leaflet-popup-content .marker-title {
font-weight:bold;
}
.leaflet-control .mapbox-button {
background-color:#fff;
border:1px solid #ddd;
border-color:rgba(0,0,0,0.10);
padding:5px 10px;
border-radius:3px;
}
/* Share modal
------------------------------------------------------- */
.mapbox-modal > div {
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
z-index:-1;
overflow-y:auto;
}
.mapbox-modal.active > div {
z-index:99999;
transition:all .2s, z-index 0 0;
}
.mapbox-modal .mapbox-modal-mask {
background:rgba(0,0,0,0.5);
opacity:0;
}
.mapbox-modal.active .mapbox-modal-mask { opacity:1; }
.mapbox-modal .mapbox-modal-content {
-webkit-transform:translateY(-100%);
-moz-transform:translateY(-100%);
-ms-transform:translateY(-100%);
transform:translateY(-100%);
}
.mapbox-modal.active .mapbox-modal-content {
-webkit-transform:translateY(0);
-moz-transform:translateY(0);
-ms-transform:translateY(0);
transform:translateY(0);
}
.mapbox-modal-body {
position:relative;
background:#fff;
padding:20px;
z-index:1000;
width:50%;
margin:20px 0 20px 25%;
}
.mapbox-share-buttons {
margin:0 0 20px;
}
.mapbox-share-buttons a {
width:33.3333%;
border-left:1px solid #fff;
text-align:center;
border-radius:0;
}
.mapbox-share-buttons a:last-child { border-radius:0 3px 3px 0; }
.mapbox-share-buttons a:first-child { border:none; border-radius:3px 0 0 3px; }
.mapbox-modal input {
width:100%;
height:40px;
padding:10px;
border:1px solid #ddd;
border-color:rgba(0,0,0,0.10);
color:rgba(0,0,0,0.5);
}
/* Info Control
------------------------------------------------------- */
.leaflet-control.mapbox-control-info {
margin:5px 30px 10px 10px;
min-height:26px;
}
.leaflet-control.mapbox-control-info-right {
margin:5px 10px 10px 30px;
}
.mapbox-info-toggle {
background-color:#fff;
background-color:rgba(255,255,255,0.25);
border-radius:50%;
position:absolute;
bottom:0;left:0;
z-index:1;
}
.mapbox-control-info-right .mapbox-info-toggle { left:auto; right:0; }
.mapbox-control-info.active .mapbox-info-toggle { background-color:#fff; }
.mapbox-info-toggle:hover { background-color:rgba(255,255,255,0.5); }
.map-info-container {
background:#fff;
background:rgba(255,255,255,0.75);
padding:3px 5px 3px 15px;
display:none;
position:relative;
bottom:0;
left:13px;
border-radius:3px;
}
.mapbox-control-info.active .map-info-container { display:inline-block; }
.mapbox-control-info-right .map-info-container {
left:auto;
right:13px;
padding:3px 15px 3px 5px;
}
/* Geocoder
------------------------------------------------------- */
.leaflet-control-mapbox-geocoder {
position:relative;
}
.leaflet-control-mapbox-geocoder.searching {
opacity:0.75;
}
.leaflet-control-mapbox-geocoder .leaflet-control-mapbox-geocoder-wrap {
background:#fff;
position:absolute;
border:1px solid #999;
border-color:rgba(0,0,0,0.4);
border-bottom-width:0;
overflow:hidden;
left:26px;
height:27px;
width:0;
top:-1px;
border-radius:0 3px 3px 0;
opacity:0;
-webkit-transition:opacity 100ms;
-moz-transition:opacity 100ms;
-o-transition:opacity 100ms;
transition:opacity 100ms;
}
.leaflet-control-mapbox-geocoder.active .leaflet-control-mapbox-geocoder-wrap {
width:180px;
opacity:1;
}
.leaflet-bar .leaflet-control-mapbox-geocoder-toggle,
.leaflet-bar .leaflet-control-mapbox-geocoder-toggle:hover {
border-bottom:none;
}
.leaflet-control-mapbox-geocoder-toggle {
border-radius:3px;
}
.leaflet-control-mapbox-geocoder.active,
.leaflet-control-mapbox-geocoder.active .leaflet-control-mapbox-geocoder-toggle {
border-top-right-radius:0;
border-bottom-right-radius:0;
}
.leaflet-control-mapbox-geocoder .leaflet-control-mapbox-geocoder-form input {
background:transparent;
border:0;
width:180px;
padding:0 0 0 10px;
height:26px;
outline:none;
}
.leaflet-control-mapbox-geocoder-results {
width:180px;
position:absolute;
left:26px;
top:25px;
border-radius:0 0 3px 3px;
}
.leaflet-control-mapbox-geocoder.active .leaflet-control-mapbox-geocoder-results {
background:#fff;
border:1px solid #999;
border-color:rgba(0,0,0,0.4);
}
.leaflet-control-mapbox-geocoder-results a,
.leaflet-control-mapbox-geocoder-results span {
padding:0 10px;
text-overflow:ellipsis;
white-space:nowrap;
display:block;
width:100%;
font-size:12px;
line-height:26px;
text-align:left;
overflow:hidden;
}
.leaflet-control-mapbox-geocoder-results a:first-child {
border-top:1px solid #999;
border-top-color:rgba(0,0,0,0.4);
border-radius:0;
}
.leaflet-container.dark .leaflet-control .leaflet-control-mapbox-geocoder-results a:hover,
.leaflet-control-mapbox-geocoder-results a:hover {
background:#f8f8f8;
opacity:1;
}
/* Dark Theme
------------------------------------------------------- */
.leaflet-container.dark .leaflet-bar {
background-color:#404040;
border-color:#202020;
border-color:rgba(0,0,0,0.75);
}
.leaflet-container.dark .leaflet-bar a {
color:#404040;
border-color:rgba(0,0,0,0.5);
}
.leaflet-container.dark .leaflet-bar a:active,
.leaflet-container.dark .leaflet-bar a:hover {
background-color:#505050;
}
.leaflet-container.dark .mapbox-info-toggle,
.leaflet-container.dark .map-info-container,
.leaflet-container.dark .leaflet-control-attribution {
background-color:rgba(0,0,0,0.25);
color:#f8f8f8;
}
.leaflet-container.dark .leaflet-bar a.leaflet-disabled,
.leaflet-container.dark .leaflet-control .mapbox-button.disabled {
background-color:#252525;
color:#404040;
}
.leaflet-container.dark .leaflet-control-mapbox-geocoder > div {
border-color:#202020;
border-color:rgba(0,0,0,0.75);
}
.leaflet-container.dark .leaflet-control .leaflet-control-mapbox-geocoder-results a {
border-color:#ddd #202020;
border-color:rgba(0,0,0,0.10) rgba(0,0,0,0.75);
}
.leaflet-container.dark .leaflet-control .leaflet-control-mapbox-geocoder-results span {
border-color:#202020;
border-color:rgba(0,0,0,0.75);
}
/* Larger Screens
------------------------------------------------------- */
@media only screen and (max-width:800px) {
.mapbox-modal-body {
width:83.3333%;
margin-left:8.3333%;
}
}
/* Smaller Screens
------------------------------------------------------- */
@media only screen and (max-width:640px) {
.mapbox-modal-body {
width:100%;
height:100%;
margin:0;
}
}
/* Browser Fixes
------------------------------------------------------- */
/* Map is broken in FF if you have max-width: 100% on tiles */
.leaflet-container img { max-width:none!important; }
/* Stupid Android 2 doesn't understand "max-width: none" properly */
.leaflet-container img.leaflet-image-layer { max-width:15000px!important; }
/* Android chrome makes tiles disappear without this */
.leaflet-tile-container img { -webkit-backface-visibility:hidden; }
/* workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=888319 */
.leaflet-overlay-pane svg { -moz-user-select:none; }
/* Older IEs don't support the translateY property for display animation */
.leaflet-oldie .mapbox-modal .mapbox-modal-content { display:none; }
.leaflet-oldie .mapbox-modal.active .mapbox-modal-content { display:block; }
.map-tooltip { width:280px\8; /* < IE9 */ }

View File

File diff suppressed because one or more lines are too long

View File

@@ -1,151 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="./css/styles.css" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Arnis</title>
<script type="module" src="./js/main.js" defer></script>
<script type="module" src="./js/license.js" defer></script>
</head>
<body>
<main class="container">
<div class="row">
<a href="https://github.com/louis-e/arnis" target="_blank">
<img src="./images/logo.png" id="arnis-logo" class="logo arnis" alt="Arnis Logo" style="width: 35%; height: auto;" />
</a>
</div>
<div class="flex-container">
<!-- Left Box: Map and BBox Input -->
<section class="section map-box" style="margin-bottom: 0; padding-bottom: 0;">
<h2 data-localize="select_location">Select Location</h2>
<span id="bbox-text" style="font-size: 1.0em; display: block; margin-top: -8px; margin-bottom: 3px;" data-localize="zoom_in_and_choose">
Zoom in and choose your area using the rectangle tool
</span>
<iframe src="maps.html" width="100%" height="300" class="map-container" title="Map Picker"></iframe>
<span id="bbox-info"
style="font-size: 0.75em; color: #7bd864; display: block; margin-bottom: 4px; font-weight: bold; min-height: 2em;"></span>
</section>
<!-- Right Box: Directory Selection, Start Button, and Progress Bar -->
<section class="section controls-box">
<div class="controls-content">
<h2 data-localize="select_world">Select World</h2>
<!-- Updated Tooltip Structure -->
<div class="tooltip" style="width: 100%;">
<button type="button" onclick="openWorldPicker()" style="padding: 10px; line-height: 1.2; width: 100%;">
<span id="choose_world">Choose World</span>
<br>
<span id="selected-world" style="font-size: 0.8em; color: #fecc44; display: block; margin-top: 4px;" data-localize="no_world_selected">
No world selected
</span>
</button>
</div>
<div class="button-container">
<button type="button" id="start-button" class="start-button" onclick="startGeneration()" data-localize="start_generation">Start Generation</button>
<button type="button" class="settings-button" onclick="openSettings()">
<i class="gear-icon"></i>
</button>
</div>
<br><br>
<div class="progress-section">
<h2 data-localize="progress">Progress</h2>
<div class="progress-bar-container">
<div class="progress-bar" id="progress-bar"></div>
</div>
<div class="progress-status">
<span id="progress-message"></span>
<span id="progress-detail">0%</span>
</div>
</div>
</div>
</section>
</div>
<!-- World Picker Modal -->
<div id="world-modal" class="modal" style="display: none;">
<div class="modal-content">
<span class="close-button" onclick="closeWorldPicker()">&times;</span>
<h2 data-localize="choose_world_modal_title">Choose World</h2>
<button type="button" id="select-world-button" class="select-world-button" onclick="selectWorld(false)" data-localize="select_existing_world">Select existing world</button>
<button type="button" id="generate-world-button" class="generate-world-button" onclick="selectWorld(true)" data-localize="generate_new_world">Generate new world</button>
</div>
</div>
<!-- Settings Modal -->
<div id="settings-modal" class="modal" style="display: none;">
<div class="modal-content">
<span class="close-button" onclick="closeSettings()">&times;</span>
<h2 data-localize="customization_settings">Customization Settings</h2>
<!-- Terrain Toggle Button -->
<div class="terrain-toggle-container">
<label for="terrain-toggle" data-localize="terrain">Terrain:</label>
<input type="checkbox" id="terrain-toggle" name="terrain-toggle">
</div>
<!-- Winter Mode Toggle Button -->
<div class="winter-toggle-container">
<label for="winter-toggle" data-localize="winter_mode">Winter Mode:</label>
<input type="checkbox" id="winter-toggle" name="winter-toggle">
</div>
<!-- World Scale Slider -->
<div class="scale-slider-container">
<label for="scale-value-slider" data-localize="world_scale">World Scale:</label>
<input type="range" id="scale-value-slider" name="scale-value-slider" min="0.30" max="2.5" step="0.1" value="1">
<span id="slider-value">1.00</span>
</div>
<!-- Bounding Box Input -->
<div class="bbox-input-container">
<label for="bbox-coords" data-localize="custom_bounding_box">Custom Bounding Box:</label>
<input type="text" id="bbox-coords" name="bbox-coords" maxlength="55" style="width: 280px;" placeholder="Format: lat,lng,lat,lng">
</div>
<!-- Floodfill Timeout Input -->
<div class="timeout-input-container">
<label for="floodfill-timeout" data-localize="floodfill_timeout">Floodfill Timeout (sec):</label>
<input type="number" id="floodfill-timeout" name="floodfill-timeout" min="0" step="1" value="20" style="width: 100px;" placeholder="Seconds">
</div><br>
<!-- Ground Level Input -->
<div class="ground-level-input-container">
<label for="ground-level" data-localize="ground_level">Ground Level:</label>
<input type="number" id="ground-level" name="ground-level" min="-64" max="290" value="-62" style="width: 100px;" placeholder="Ground Level">
</div>
<!-- License and Credits Button -->
<button type="button" id="license-button" class="license-button" onclick="openLicense()" data-localize="license_and_credits">License and Credits</button>
</div>
</div>
<!-- License Modal -->
<div id="license-modal" class="modal" style="display: none;">
<div class="modal-content">
<span class="close-button" onclick="closeLicense()">&times;</span>
<h2 data-localize="license_and_credits">License and Credits</h2>
<div id="license-content" style="overflow-y: auto; max-height: 300px; font-size: 0.85em; line-height: 1.3; padding: 10px; border: 1px solid #ccc; border-radius: 4px;">
Loading...
</div>
</div>
</div>
<!-- Footer -->
<footer class="footer">
<a href="https://github.com/louis-e/arnis" target="_blank" class="footer-link" data-localize="footer_text">
© {year} Arnis v{version} by louis-e
</a>
</footer>
</main>
</body>
</html>

View File

@@ -1,508 +0,0 @@
import { licenseText } from './license.js';
let invoke;
if (window.__TAURI__) {
invoke = window.__TAURI__.core.invoke;
} else {
function dummyFunc() {}
window.__TAURI__ = { event: { listen: dummyFunc } };
invoke = dummyFunc;
}
const DEFAULT_LOCALE_PATH = `./locales/en.json`;
// Initialize elements and start the demo progress
window.addEventListener("DOMContentLoaded", async () => {
registerMessageEvent();
window.selectWorld = selectWorld;
window.startGeneration = startGeneration;
setupProgressListener();
initSettings();
initWorldPicker();
handleBboxInput();
const localization = await getLocalization();
await applyLocalization(localization);
initFooter();
await checkForUpdates();
});
/**
* Checks if a JSON response is invalid or falls back to HTML
* @param {Response} response - The fetch response object
* @returns {boolean} True if the response is invalid JSON
*/
function invalidJSON(response) {
// Workaround for Tauri always falling back to index.html for asset loading
return !response.ok || response.headers.get("Content-Type") === "text/html";
}
/**
* Fetches and returns localization data based on user's language
* Falls back to English if requested language is not available
* @returns {Promise<Object>} The localization JSON object
*/
async function getLocalization() {
const lang = navigator.language;
let response = await fetch(`./locales/${lang}.json`);
// Try with only first part of language code
if (invalidJSON(response)) {
response = await fetch(`./locales/${lang.split('-')[0]}.json`);
// Fallback to default English localization
if (invalidJSON(response)) {
response = await fetch(DEFAULT_LOCALE_PATH);
}
}
const localization = await response.json();
return localization;
}
/**
* Updates an HTML element with localized text
* @param {Object} json - Localization data
* @param {Object} elementObject - Object containing element or selector
* @param {string} localizedStringKey - Key for the localized string
*/
async function localizeElement(json, elementObject, localizedStringKey) {
const element =
(!elementObject.element || elementObject.element === "")
? document.querySelector(elementObject.selector) : elementObject.element;
const attribute = localizedStringKey.startsWith("placeholder_") ? "placeholder" : "textContent";
if (element) {
if (localizedStringKey in json) {
element[attribute] = json[localizedStringKey];
} else {
// Fallback to default (English) string
const response = await fetch(DEFAULT_LOCALE_PATH);
const defaultJson = await response.json();
element[attribute] = defaultJson[localizedStringKey];
}
}
}
async function applyLocalization(localization) {
const localizationElements = {
"h2[data-localize='select_location']": "select_location",
"#bbox-text": "zoom_in_and_choose",
"h2[data-localize='select_world']": "select_world",
"span[id='choose_world']": "choose_world",
"#selected-world": "no_world_selected",
"#start-button": "start_generation",
"h2[data-localize='progress']": "progress",
"h2[data-localize='choose_world_modal_title']": "choose_world_modal_title",
"button[data-localize='select_existing_world']": "select_existing_world",
"button[data-localize='generate_new_world']": "generate_new_world",
"h2[data-localize='customization_settings']": "customization_settings",
"label[data-localize='winter_mode']": "winter_mode",
"label[data-localize='world_scale']": "world_scale",
"label[data-localize='custom_bounding_box']": "custom_bounding_box",
"label[data-localize='floodfill_timeout']": "floodfill_timeout",
"label[data-localize='ground_level']": "ground_level",
".footer-link": "footer_text",
"button[data-localize='license_and_credits']": "license_and_credits",
"h2[data-localize='license_and_credits']": "license_and_credits",
// Placeholder strings
"input[id='bbox-coords']": "placeholder_bbox",
"input[id='floodfill-timeout']": "placeholder_floodfill",
"input[id='ground-level']": "placeholder_ground"
};
for (const selector in localizationElements) {
localizeElement(localization, { selector: selector }, localizationElements[selector]);
}
// Update error messages
window.localization = localization;
}
// Function to initialize the footer with the current year and version
async function initFooter() {
const currentYear = new Date().getFullYear();
let version = "x.x.x";
try {
version = await invoke('gui_get_version');
} catch (error) {
console.error("Failed to fetch version:", error);
}
const footerElement = document.querySelector(".footer-link");
if (footerElement) {
footerElement.textContent =
footerElement.textContent
.replace("{year}", currentYear)
.replace("{version}", version);
}
}
// Function to check for updates and display a notification if available
async function checkForUpdates() {
try {
const isUpdateAvailable = await invoke('gui_check_for_updates');
if (isUpdateAvailable) {
const footer = document.querySelector(".footer");
const updateMessage = document.createElement("a");
updateMessage.href = "https://github.com/louis-e/arnis/releases";
updateMessage.target = "_blank";
updateMessage.style.color = "#fecc44";
updateMessage.style.marginTop = "-5px";
updateMessage.style.fontSize = "0.95em";
updateMessage.style.display = "block";
updateMessage.style.textDecoration = "none";
localizeElement(window.localization, { element: updateMessage }, "new_version_available");
footer.style.marginTop = "15px";
footer.appendChild(updateMessage);
}
} catch (error) {
console.error("Failed to check for updates: ", error);
}
}
// Function to register the event listener for bbox updates from iframe
function registerMessageEvent() {
window.addEventListener('message', function (event) {
const bboxText = event.data.bboxText;
if (bboxText) {
console.log("Updated BBOX Coordinates:", bboxText);
displayBboxInfoText(bboxText);
}
});
}
// Function to set up the progress bar listener
function setupProgressListener() {
const progressBar = document.getElementById("progress-bar");
const progressMessage = document.getElementById("progress-message");
const progressDetail = document.getElementById("progress-detail");
window.__TAURI__.event.listen("progress-update", (event) => {
const { progress, message } = event.payload;
if (progress != -1) {
progressBar.style.width = `${progress}%`;
progressDetail.textContent = `${Math.round(progress)}%`;
}
if (message != "") {
progressMessage.textContent = message;
if (message.startsWith("Error!")) {
progressMessage.style.color = "#fa7878";
generationButtonEnabled = true;
} else if (message.startsWith("Done!")) {
progressMessage.style.color = "#7bd864";
generationButtonEnabled = true;
} else {
progressMessage.style.color = "";
}
}
});
}
function initSettings() {
// Settings
const settingsModal = document.getElementById("settings-modal");
const slider = document.getElementById("scale-value-slider");
const sliderValue = document.getElementById("slider-value");
// Open settings modal
function openSettings() {
settingsModal.style.display = "flex";
settingsModal.style.justifyContent = "center";
settingsModal.style.alignItems = "center";
}
// Close settings modal
function closeSettings() {
settingsModal.style.display = "none";
}
window.openSettings = openSettings;
window.closeSettings = closeSettings;
// Update slider value display
slider.addEventListener("input", () => {
sliderValue.textContent = parseFloat(slider.value).toFixed(2);
});
/// License and Credits
function openLicense() {
const licenseModal = document.getElementById("license-modal");
const licenseContent = document.getElementById("license-content");
// Render the license text as HTML
licenseContent.innerHTML = licenseText;
// Show the modal
licenseModal.style.display = "flex";
licenseModal.style.justifyContent = "center";
licenseModal.style.alignItems = "center";
}
function closeLicense() {
const licenseModal = document.getElementById("license-modal");
licenseModal.style.display = "none";
}
window.openLicense = openLicense;
window.closeLicense = closeLicense;
}
function initWorldPicker() {
// World Picker
const worldPickerModal = document.getElementById("world-modal");
// Open world picker modal
function openWorldPicker() {
worldPickerModal.style.display = "flex";
worldPickerModal.style.justifyContent = "center";
worldPickerModal.style.alignItems = "center";
}
// Close world picker modal
function closeWorldPicker() {
worldPickerModal.style.display = "none";
}
window.openWorldPicker = openWorldPicker;
window.closeWorldPicker = closeWorldPicker;
}
/**
* Validates and processes bounding box coordinates input
* Supports both comma and space-separated formats
* Updates the map display when valid coordinates are entered
*/
function handleBboxInput() {
const inputBox = document.getElementById("bbox-coords");
const bboxInfo = document.getElementById("bbox-info");
inputBox.addEventListener("input", function () {
const input = inputBox.value.trim();
if (input === "") {
bboxInfo.textContent = "";
bboxInfo.style.color = "";
selectedBBox = "";
return;
}
// Regular expression to validate bbox input (supports both comma and space-separated formats)
const bboxPattern = /^(-?\d+(\.\d+)?)[,\s](-?\d+(\.\d+)?)[,\s](-?\d+(\.\d+)?)[,\s](-?\d+(\.\d+)?)$/;
if (bboxPattern.test(input)) {
const matches = input.match(bboxPattern);
// Extract coordinates (Lat / Lng order expected)
const lat1 = parseFloat(matches[1]);
const lng1 = parseFloat(matches[3]);
const lat2 = parseFloat(matches[5]);
const lng2 = parseFloat(matches[7]);
// Validate latitude and longitude ranges in the expected Lat / Lng order
if (
lat1 >= -90 && lat1 <= 90 &&
lng1 >= -180 && lng1 <= 180 &&
lat2 >= -90 && lat2 <= 90 &&
lng2 >= -180 && lng2 <= 180
) {
// Input is valid; trigger the event
const bboxText = `${lat1} ${lng1} ${lat2} ${lng2}`;
window.dispatchEvent(new MessageEvent('message', { data: { bboxText } }));
// Show custom bbox on the map
let map_container = document.querySelector('.map-container');
map_container.setAttribute('src', `maps.html#${lat1},${lng1},${lat2},${lng2}`);
map_container.contentWindow.location.reload();
// Update the info text
localizeElement(window.localization, { element: bboxInfo }, "custom_selection_confirmed");
bboxInfo.style.color = "#7bd864";
} else {
// Valid numbers but invalid order or range
localizeElement(window.localization, { element: bboxInfo }, "error_coordinates_out_of_range");
bboxInfo.style.color = "#fecc44";
selectedBBox = "";
}
} else {
// Input doesn't match the required format
localizeElement(window.localization, { element: bboxInfo }, "invalid_format");
bboxInfo.style.color = "#fecc44";
selectedBBox = "";
}
});
}
/**
* Calculates the approximate area of a bounding box in square meters
* Uses the Haversine formula for geodesic calculations
* @param {number} lng1 - First longitude coordinate
* @param {number} lat1 - First latitude coordinate
* @param {number} lng2 - Second longitude coordinate
* @param {number} lat2 - Second latitude coordinate
* @returns {number} Area in square meters
*/
function calculateBBoxSize(lng1, lat1, lng2, lat2) {
// Approximate distance calculation using Haversine formula or geodesic formula
const toRad = (angle) => (angle * Math.PI) / 180;
const R = 6371000; // Earth radius in meters
const latDistance = toRad(lat2 - lat1);
const lngDistance = toRad(lng2 - lng1);
const a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) +
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
Math.sin(lngDistance / 2) * Math.sin(lngDistance / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
// Width and height of the box
const height = R * latDistance;
const width = R * lngDistance;
return Math.abs(width * height);
}
/**
* Normalizes a longitude value to the range [-180, 180]
* @param {number} lon - Longitude value to normalize
* @returns {number} Normalized longitude value
*/
function normalizeLongitude(lon) {
return ((lon + 180) % 360 + 360) % 360 - 180;
}
const threshold1 = 30000000.00;
const threshold2 = 45000000.00;
let selectedBBox = "";
// Function to handle incoming bbox data
function displayBboxInfoText(bboxText) {
let [lng1, lat1, lng2, lat2] = bboxText.split(" ").map(Number);
// Normalize longitudes
lat1 = parseFloat(normalizeLongitude(lat1).toFixed(6));
lat2 = parseFloat(normalizeLongitude(lat2).toFixed(6));
selectedBBox = `${lng1} ${lat1} ${lng2} ${lat2}`;
const bboxInfo = document.getElementById("bbox-info");
// Reset the info text if the bbox is 0,0,0,0
if (lng1 === 0 && lat1 === 0 && lng2 === 0 && lat2 === 0) {
bboxInfo.textContent = "";
selectedBBox = "";
return;
}
// Calculate the size of the selected bbox
const selectedSize = calculateBBoxSize(lng1, lat1, lng2, lat2);
if (selectedSize > threshold2) {
localizeElement(window.localization, { element: bboxInfo }, "area_too_large");
bboxInfo.style.color = "#fa7878";
} else if (selectedSize > threshold1) {
localizeElement(window.localization, { element: bboxInfo }, "area_extensive");
bboxInfo.style.color = "#fecc44";
} else {
localizeElement(window.localization, { element: bboxInfo }, "selection_confirmed");
bboxInfo.style.color = "#7bd864";
}
}
let worldPath = "";
async function selectWorld(generate_new_world) {
try {
const worldName = await invoke('gui_select_world', { generateNew: generate_new_world } );
if (worldName) {
worldPath = worldName;
const lastSegment = worldName.split(/[\\/]/).pop();
document.getElementById('selected-world').textContent = lastSegment;
document.getElementById('selected-world').style.color = "#fecc44";
}
} catch (error) {
handleWorldSelectionError(error);
}
closeWorldPicker();
}
/**
* Handles world selection errors and displays appropriate messages
* @param {number} errorCode - Error code from the backend
*/
function handleWorldSelectionError(errorCode) {
const errorKeys = {
1: "minecraft_directory_not_found",
2: "world_in_use",
3: "failed_to_create_world",
4: "no_world_selected_error"
};
const errorKey = errorKeys[errorCode] || "unknown_error";
const selectedWorld = document.getElementById('selected-world');
localizeElement(window.localization, { element: selectedWorld }, errorKey);
selectedWorld.style.color = "#fa7878";
worldPath = "";
console.error(errorCode);
}
let generationButtonEnabled = true;
/**
* Initiates the world generation process
* Validates required inputs and sends generation parameters to the backend
* @returns {Promise<void>}
*/
async function startGeneration() {
try {
if (generationButtonEnabled === false) {
return;
}
if (!selectedBBox || selectedBBox == "0.000000 0.000000 0.000000 0.000000") {
const bboxInfo = document.getElementById('bbox-info');
localizeElement(window.localization, { element: bboxInfo }, "select_location_first");
bboxInfo.style.color = "#fa7878";
return;
}
if (!worldPath || worldPath === "") {
const selectedWorld = document.getElementById('selected-world');
localizeElement(window.localization, { element: selectedWorld }, "select_minecraft_world_first");
selectedWorld.style.color = "#fa7878";
return;
}
var terrain = document.getElementById("terrain-toggle").checked;
var winter_mode = document.getElementById("winter-toggle").checked;
var scale = parseFloat(document.getElementById("scale-value-slider").value);
var floodfill_timeout = parseInt(document.getElementById("floodfill-timeout").value, 10);
var ground_level = parseInt(document.getElementById("ground-level").value, 10);
// Validate floodfill_timeout and ground_level
floodfill_timeout = isNaN(floodfill_timeout) || floodfill_timeout < 0 ? 20 : floodfill_timeout;
ground_level = isNaN(ground_level) || ground_level < -62 ? 20 : ground_level;
// Pass the bounding box and selected world to the Rust backend
await invoke("gui_start_generation", {
bboxText: selectedBBox,
selectedWorld: worldPath,
worldScale: scale,
groundLevel: ground_level,
winterMode: winter_mode,
floodfillTimeout: floodfill_timeout,
terrainEnabled: terrain
});
console.log("Generation process started.");
generationButtonEnabled = false;
} catch (error) {
console.error("Error starting generation:", error);
generationButtonEnabled = true;
}
}

View File

File diff suppressed because it is too large Load Diff

View File

File diff suppressed because it is too large Load Diff

View File

File diff suppressed because one or more lines are too long

View File

File diff suppressed because one or more lines are too long

View File

File diff suppressed because one or more lines are too long

View File

@@ -1,158 +0,0 @@
(function( definition ) { // execute immeidately
if ( typeof module !== 'undefined' &&
typeof module.exports !== 'undefined' ) {
module.exports = definition();
}
else if ( typeof window === "object" ) {
// example run syntax: BBOX_T( { 'url' : '/js/maps/testdata.js' } );
window.BBOX_T = definition();
}
})( function() {
'use strict';
/*
**
** constructor
**
*/
var TestRunner = function( options ) {
options || ( options = {} );
if( !this || !(this instanceof TestRunner )){
return new TestRunner( options );
}
this.test_url = options.url || "";
this.global_setup(); // execute immediately
};
/*
**
** functions
**
*/
TestRunner.prototype.global_setup = function() {
var self = this; // hold ref to instance
$.ajax({
'url' : this.test_url ,
'dataType' : 'json'
})
.done( function( json_data ) {
self.run_this_mother.call( self, json_data );
})
.fail( function( error ) {
console.log( "The test data didn't load: ", error );
});
};
TestRunner.prototype.single_setup = function() {
this.get_layer_count();
};
TestRunner.prototype.tear_down = function() {
if( this._draw_delete_handler ){
this._draw_delete_handler.off('draw:deleted');
}
};
TestRunner.prototype.run_this_mother = function( json_data ) {
for( var key in json_data ){
console.log( "[ RUNNING ]: test " + json_data[key]['type'] + "->" + "simple=" + json_data[key]['simple'] );
var data = json_data[key]['data'];
if( json_data[key]['type'] === 'geojson' ) {
data = JSON.stringify( data );
}
/*
** run different tests
** the context here is jQuery, so change
** to reference the instance
*/
this.single_setup();
this.test_parsing( data, json_data );
this.test_add2map( json_data );
this.test_deletable( json_data );
this.tear_down();
}
};
TestRunner.prototype.test_deletable = function(identifier){ // TODO: this needs work
var toolbar = null;
// get the right toolbar, depending on attributes
for( var key in drawControl._toolbars ){
var tbar = drawControl._toolbars[key];
if ( !(tbar instanceof L.EditToolbar ) ){
continue;
}
toolbar = tbar; // set the right one;
}
// create delete handler that makes sure things are deleted
this._draw_delete_handler = map.on('draw:deleted', function (e) {
try {
e.layers.eachLayer(function (l) {
drawnItems.removeLayer(l);
});
console.warn( "[ PASSED ]: test_deletable" );
}
catch ( err ) {
console.error( "[ DELETE TEST FAIL ]: ", err.message, identifier );
}
});
// loop through this toolbars featureGroup, delete layers
if ( !toolbar._activeMode ) {
toolbar._modes['remove'].button.click(); // enable deletable
}
for( var indx in toolbar.options['featureGroup']._layers ) {
try {
var lyr = toolbar.options['featureGroup']._layers[indx];
lyr.fire( 'click' ); // triggers delete
}
catch ( err ){
console.error( "[ DELETE TEST FAIL ]: ", err.message, identifier );
}
}
// WTF?
$('a[title="Save changes."]')[0].click(); // disable deletable
};
TestRunner.prototype.test_add2map = function(identifier){
var current_num = Object.keys( map._layers ).length;
if( current_num <= this.num_layers_before_parse ){
console.error( "[ ADD2MAP TEST FAIL ]: ", identifier );
}
else {
console.warn( "[ PASSED ]: test_add2map" );
}
};
TestRunner.prototype.get_layer_count = function(){
this.num_layers_before_parse = Object.keys( map._layers ).length;
};
TestRunner.prototype.test_parsing = function( data, identifier ){
var is_valid = FormatSniffer( { data : data } ).sniff();
if ( !is_valid ) {
console.error( "[ PARSE TEST FAIL ]: ", identifier );
}
else {
console.warn( "[ PASSED ]: test_parsing" );
}
};
return TestRunner; // return class def
});

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

View File

Binary file not shown.

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 221 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 232 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

View File

@@ -1,107 +1,145 @@
use clap::{ArgGroup, Parser};
use colored::Colorize;
use std::path::Path;
use std::process::exit;
use crate::coordinate_system::geographic::LLBBox;
use clap::Parser;
use std::path::PathBuf;
use std::time::Duration;
/// Command-line arguments parser
#[derive(Parser, Debug)]
#[command(author, version, about)]
#[command(group(
ArgGroup::new("location")
.required(true)
.args(&["bbox", "file"])
))]
pub struct Args {
/// Bounding box of the area (min_lng,min_lat,max_lng,max_lat) (required)
#[arg(long, allow_hyphen_values = true)]
pub bbox: Option<String>,
/// Bounding box of the area (min_lat,min_lng,max_lat,max_lng) (required)
#[arg(long, allow_hyphen_values = true, value_parser = LLBBox::from_str)]
pub bbox: LLBBox,
/// JSON file containing OSM data (optional)
#[arg(long)]
#[arg(long, group = "location")]
pub file: Option<String>,
/// JSON file to save OSM data to (optional)
#[arg(long, group = "location")]
pub save_json_file: Option<String>,
/// Path to the Minecraft world (required)
#[arg(long, required = true)]
pub path: String,
#[arg(long, value_parser = validate_minecraft_world_path)]
pub path: PathBuf,
/// Downloader method (requests/curl/wget) (optional)
#[arg(long, default_value = "requests")]
pub downloader: String,
/// World scale to use, in blocks per meter
#[arg(long, default_value = "1.0")]
#[arg(long, default_value_t = 1.0)]
pub scale: f64,
/// Ground level to use in the Minecraft world
#[arg(long, default_value_t = -62)]
pub ground_level: i32,
/// Enable winter mode (default: false)
#[arg(long, default_value_t = false)]
pub winter: bool,
/// Enable terrain (optional)
#[arg(long, default_value_t = false, action = clap::ArgAction::SetFalse)]
#[arg(long)]
pub terrain: bool,
/// Enable interior generation (optional)
#[arg(long, default_value_t = true, action = clap::ArgAction::SetTrue)]
pub interior: bool,
/// Enable roof generation (optional)
#[arg(long, default_value_t = true, action = clap::ArgAction::SetTrue)]
pub roof: bool,
/// Enable filling ground (optional)
#[arg(long, default_value_t = false, action = clap::ArgAction::SetFalse)]
pub fillground: bool,
/// Enable debug mode (optional)
#[arg(long, default_value_t = false, action = clap::ArgAction::SetTrue)]
#[arg(long)]
pub debug: bool,
/// Set floodfill timeout (seconds) (optional)
#[arg(long, value_parser = parse_duration)]
pub timeout: Option<Duration>,
/// Generate a top-down map preview image after world generation (optional)
#[arg(long)]
pub generate_map: bool,
/// Spawn point coordinates (lat, lng)
#[arg(skip)]
pub spawn_point: Option<(f64, f64)>,
}
impl Args {
pub fn run(&self) {
// Validating the world path
let mc_world_path: &Path = Path::new(&self.path);
if !mc_world_path.join("region").exists() {
eprintln!(
"{}",
"Error! No Minecraft world found at the given path"
.red()
.bold()
);
exit(1);
}
// Validating bbox if provided
if let Some(bbox) = &self.bbox {
if !validate_bounding_box(bbox) {
eprintln!("{}", "Error! Invalid bbox input".red().bold());
exit(1);
}
}
fn validate_minecraft_world_path(path: &str) -> Result<PathBuf, String> {
let mc_world_path = PathBuf::from(path);
if !mc_world_path.exists() {
return Err(format!("Path does not exist: {path}"));
}
}
/// Validates the bounding box string
fn validate_bounding_box(bbox: &str) -> bool {
let parts: Vec<&str> = bbox.split(',').collect();
if parts.len() != 4 {
return false;
if !mc_world_path.is_dir() {
return Err(format!("Path is not a directory: {path}"));
}
let min_lng: f64 = parts[0].parse().ok().unwrap_or(0.0);
let min_lat: f64 = parts[1].parse().ok().unwrap_or(0.0);
let max_lng: f64 = parts[2].parse().ok().unwrap_or(0.0);
let max_lat: f64 = parts[3].parse().ok().unwrap_or(0.0);
if !(-180.0..=180.0).contains(&min_lng) || !(-180.0..=180.0).contains(&max_lng) {
return false;
let region = mc_world_path.join("region");
if !region.is_dir() {
return Err(format!("No Minecraft world found at {region:?}"));
}
if !(-90.0..=90.0).contains(&min_lat) || !(-90.0..=90.0).contains(&max_lat) {
return false;
}
min_lng < max_lng && min_lat < max_lat
Ok(mc_world_path)
}
fn parse_duration(arg: &str) -> Result<std::time::Duration, std::num::ParseIntError> {
let seconds = arg.parse()?;
Ok(std::time::Duration::from_secs(seconds))
}
#[cfg(test)]
mod tests {
use super::*;
fn minecraft_tmpdir() -> tempfile::TempDir {
let tmpdir = tempfile::tempdir().unwrap();
// create a `region` directory in the tempdir
let region_path = tmpdir.path().join("region");
std::fs::create_dir(&region_path).unwrap();
tmpdir
}
#[test]
fn test_flags() {
let tmpdir = minecraft_tmpdir();
let tmp_path = tmpdir.path().to_str().unwrap();
// Test that terrain/debug are SetTrue
let cmd = [
"arnis",
"--path",
tmp_path,
"--bbox",
"1,2,3,4",
"--terrain",
"--debug",
];
let args = Args::parse_from(cmd.iter());
assert!(args.debug);
assert!(args.terrain);
let cmd = ["arnis", "--path", tmp_path, "--bbox", "1,2,3,4"];
let args = Args::parse_from(cmd.iter());
assert!(!args.debug);
assert!(!args.terrain);
}
#[test]
fn test_required_options() {
let tmpdir = minecraft_tmpdir();
let tmp_path = tmpdir.path().to_str().unwrap();
let cmd = ["arnis"];
assert!(Args::try_parse_from(cmd.iter()).is_err());
let cmd = ["arnis", "--path", tmp_path, "--bbox", "1,2,3,4"];
assert!(Args::try_parse_from(cmd.iter()).is_ok());
let cmd = ["arnis", "--path", tmp_path, "--file", ""];
assert!(Args::try_parse_from(cmd.iter()).is_err());
// The --gui flag isn't used here, ugh. TODO clean up main.rs and its argparse usage.
// let cmd = ["arnis", "--gui"];
// assert!(Args::try_parse_from(cmd.iter()).is_ok());
}
}

View File

@@ -7,22 +7,93 @@ use std::collections::HashMap;
use crate::colors::RGBTuple;
// Enums for stair properties
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum StairFacing {
North,
East,
South,
West,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum StairShape {
Straight,
InnerLeft,
InnerRight,
OuterLeft,
OuterRight,
}
impl StairFacing {
#[inline(always)]
pub fn as_str(&self) -> &'static str {
match self {
StairFacing::North => "north",
StairFacing::East => "east",
StairFacing::South => "south",
StairFacing::West => "west",
}
}
}
impl StairShape {
#[inline(always)]
pub fn as_str(&self) -> &'static str {
match self {
StairShape::Straight => "straight",
StairShape::InnerLeft => "inner_left",
StairShape::InnerRight => "inner_right",
StairShape::OuterLeft => "outer_left",
StairShape::OuterRight => "outer_right",
}
}
}
// Type definitions for better readability
type ColorTuple = (u8, u8, u8);
type BlockOptions = &'static [Block];
type ColorBlockMapping = (ColorTuple, BlockOptions);
#[derive(Copy, Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Debug)]
pub struct Block {
id: u8,
}
// Extended block with dynamic properties
#[derive(Clone, Debug)]
pub struct BlockWithProperties {
pub block: Block,
pub properties: Option<Value>,
}
impl BlockWithProperties {
pub fn new(block: Block, properties: Option<Value>) -> Self {
Self { block, properties }
}
pub fn simple(block: Block) -> Self {
Self {
block,
properties: None,
}
}
}
impl Block {
#[inline(always)]
const fn new(id: u8) -> Self {
Self { id }
}
#[inline(always)]
pub fn id(&self) -> u8 {
self.id
}
#[inline(always)]
pub fn namespace(&self) -> &str {
"mincraft"
"minecraft"
}
pub fn name(&self) -> &str {
@@ -41,7 +112,7 @@ impl Block {
11 => "chiseled_stone_bricks",
12 => "cobblestone_wall",
13 => "cobblestone",
14 => "cracked_polished_blackstone_bricks",
14 => "polished_blackstone_bricks",
15 => "cracked_stone_bricks",
16 => "crimson_planks",
17 => "cut_sandstone",
@@ -52,11 +123,11 @@ impl Block {
22 => "dirt",
23 => "end_stone_bricks",
24 => "farmland",
25 => "glass_pane",
25 => "glass",
26 => "glowstone",
27 => "granite",
28 => "grass_block",
29 => "tall_grass",
29 => "short_grass",
30 => "gravel",
31 => "gray_concrete",
32 => "gray_terracotta",
@@ -74,7 +145,7 @@ impl Block {
44 => "mossy_cobblestone",
45 => "mud_bricks",
46 => "nether_bricks",
47 => "nether_bricks",
47 => "netherite_block",
48 => "oak_fence",
49 => "oak_leaves",
50 => "oak_log",
@@ -84,7 +155,7 @@ impl Block {
54 => "podzol",
55 => "polished_andesite",
56 => "polished_basalt",
57 => "polished_blackstone_bricks",
57 => "quartz_block",
58 => "polished_blackstone",
59 => "polished_deepslate",
60 => "polished_diorite",
@@ -144,12 +215,75 @@ impl Block {
114 => "andesite_wall",
115 => "stone_brick_wall",
116..=125 => "rail",
126 => "coarse_dirt",
127 => "iron_ore",
128 => "coal_ore",
129 => "gold_ore",
130 => "copper_ore",
131 => "clay",
132 => "dirt_path",
133 => "ice",
134 => "packed_ice",
135 => "mud",
136 => "dead_bush",
137..=138 => "tall_grass",
139 => "crafting_table",
140 => "furnace",
141 => "white_carpet",
142 => "bookshelf",
143 => "oak_pressure_plate",
144 => "oak_stairs",
155 => "chest",
156 => "red_carpet",
157 => "anvil",
158 => "note_block",
159 => "oak_door",
160 => "brewing_stand",
161 => "red_bed", // North head
162 => "red_bed", // North foot
163 => "red_bed", // East head
164 => "red_bed", // East foot
165 => "red_bed", // South head
166 => "red_bed", // South foot
167 => "red_bed", // West head
168 => "red_bed", // West foot
169 => "gray_stained_glass",
170 => "light_gray_stained_glass",
171 => "brown_stained_glass",
172 => "tinted_glass",
173 => "oak_trapdoor",
174 => "brown_concrete",
175 => "black_terracotta",
176 => "brown_terracotta",
177 => "stone_brick_stairs",
178 => "mud_brick_stairs",
179 => "polished_blackstone_brick_stairs",
180 => "brick_stairs",
181 => "polished_granite_stairs",
182 => "end_stone_brick_stairs",
183 => "polished_diorite_stairs",
184 => "smooth_sandstone_stairs",
185 => "quartz_stairs",
186 => "polished_andesite_stairs",
187 => "nether_brick_stairs",
_ => panic!("Invalid id"),
}
}
pub fn properties(&self) -> Option<Value> {
match self.id {
3 => Some(Value::Compound({
let mut map: HashMap<String, Value> = HashMap::new();
map.insert("persistent".to_string(), Value::String("true".to_string()));
map
})),
49 => Some(Value::Compound({
let mut map: HashMap<String, Value> = HashMap::new();
map.insert("persistent".to_string(), Value::String("true".to_string()));
map
})),
105 => Some(Value::Compound({
let mut map: HashMap<String, Value> = HashMap::new();
map.insert("age".to_string(), Value::String("7".to_string()));
@@ -264,11 +398,126 @@ impl Block {
map.insert("shape".to_string(), Value::String("south_west".to_string()));
map
})),
137 => Some(Value::Compound({
let mut map = HashMap::new();
map.insert("half".to_string(), Value::String("lower".to_string()));
map
})),
138 => Some(Value::Compound({
let mut map = HashMap::new();
map.insert("half".to_string(), Value::String("upper".to_string()));
map
})),
// Red bed variations by direction and part
161 => Some(Value::Compound({
let mut map: HashMap<String, Value> = HashMap::new();
map.insert("facing".to_string(), Value::String("north".to_string()));
map.insert("part".to_string(), Value::String("head".to_string()));
map
})),
162 => Some(Value::Compound({
let mut map: HashMap<String, Value> = HashMap::new();
map.insert("facing".to_string(), Value::String("north".to_string()));
map.insert("part".to_string(), Value::String("foot".to_string()));
map
})),
163 => Some(Value::Compound({
let mut map: HashMap<String, Value> = HashMap::new();
map.insert("facing".to_string(), Value::String("east".to_string()));
map.insert("part".to_string(), Value::String("head".to_string()));
map
})),
164 => Some(Value::Compound({
let mut map: HashMap<String, Value> = HashMap::new();
map.insert("facing".to_string(), Value::String("east".to_string()));
map.insert("part".to_string(), Value::String("foot".to_string()));
map
})),
165 => Some(Value::Compound({
let mut map: HashMap<String, Value> = HashMap::new();
map.insert("facing".to_string(), Value::String("south".to_string()));
map.insert("part".to_string(), Value::String("head".to_string()));
map
})),
166 => Some(Value::Compound({
let mut map: HashMap<String, Value> = HashMap::new();
map.insert("facing".to_string(), Value::String("south".to_string()));
map.insert("part".to_string(), Value::String("foot".to_string()));
map
})),
167 => Some(Value::Compound({
let mut map: HashMap<String, Value> = HashMap::new();
map.insert("facing".to_string(), Value::String("west".to_string()));
map.insert("part".to_string(), Value::String("head".to_string()));
map
})),
168 => Some(Value::Compound({
let mut map: HashMap<String, Value> = HashMap::new();
map.insert("facing".to_string(), Value::String("west".to_string()));
map.insert("part".to_string(), Value::String("foot".to_string()));
map
})),
173 => Some(Value::Compound({
let mut map = HashMap::new();
map.insert("half".to_string(), Value::String("top".to_string()));
map
})),
_ => None,
}
}
}
// Cache for stair blocks with properties
use std::sync::Mutex;
#[allow(clippy::type_complexity)]
static STAIR_CACHE: Lazy<Mutex<HashMap<(u8, StairFacing, StairShape), BlockWithProperties>>> =
Lazy::new(|| Mutex::new(HashMap::new()));
// General function to create any stair block with facing and shape properties
pub fn create_stair_with_properties(
base_stair_block: Block,
facing: StairFacing,
shape: StairShape,
) -> BlockWithProperties {
let cache_key = (base_stair_block.id(), facing, shape);
// Check cache first
{
let cache = STAIR_CACHE.lock().unwrap();
if let Some(cached_block) = cache.get(&cache_key) {
return cached_block.clone();
}
}
// Create properties
let mut map = HashMap::new();
map.insert(
"facing".to_string(),
Value::String(facing.as_str().to_string()),
);
// Only add shape if it's not straight (default)
if !matches!(shape, StairShape::Straight) {
map.insert(
"shape".to_string(),
Value::String(shape.as_str().to_string()),
);
}
let properties = Value::Compound(map);
let block_with_props = BlockWithProperties::new(base_stair_block, Some(properties));
// Cache the result
{
let mut cache = STAIR_CACHE.lock().unwrap();
cache.insert(cache_key, block_with_props.clone());
}
block_with_props
}
// Lazy static blocks
pub const ACACIA_PLANKS: Block = Block::new(0);
pub const AIR: Block = Block::new(1);
@@ -284,7 +533,7 @@ pub const CAULDRON: Block = Block::new(10);
pub const CHISELED_STONE_BRICKS: Block = Block::new(11);
pub const COBBLESTONE_WALL: Block = Block::new(12);
pub const COBBLESTONE: Block = Block::new(13);
pub const CRACKED_POLISHED_BLACKSTONE_BRICKS: Block = Block::new(14);
pub const POLISHED_BLACKSTONE_BRICKS: Block = Block::new(14);
pub const CRACKED_STONE_BRICKS: Block = Block::new(15);
pub const CRIMSON_PLANKS: Block = Block::new(16);
pub const CUT_SANDSTONE: Block = Block::new(17);
@@ -317,7 +566,7 @@ pub const MOSS_BLOCK: Block = Block::new(43);
pub const MOSSY_COBBLESTONE: Block = Block::new(44);
pub const MUD_BRICKS: Block = Block::new(45);
pub const NETHER_BRICK: Block = Block::new(46);
pub const NETHER_BRICKS: Block = Block::new(47);
pub const NETHERITE_BLOCK: Block = Block::new(47);
pub const OAK_FENCE: Block = Block::new(48);
pub const OAK_LEAVES: Block = Block::new(49);
pub const OAK_LOG: Block = Block::new(50);
@@ -327,7 +576,7 @@ pub const ORANGE_TERRACOTTA: Block = Block::new(53);
pub const PODZOL: Block = Block::new(54);
pub const POLISHED_ANDESITE: Block = Block::new(55);
pub const POLISHED_BASALT: Block = Block::new(56);
pub const POLISHED_BLACKSTONE_BRICKS: Block = Block::new(57);
pub const QUARTZ_BLOCK: Block = Block::new(57);
pub const POLISHED_BLACKSTONE: Block = Block::new(58);
pub const POLISHED_DEEPSLATE: Block = Block::new(59);
pub const POLISHED_DIORITE: Block = Block::new(60);
@@ -338,7 +587,7 @@ pub const PURPUR_PILLAR: Block = Block::new(64);
pub const QUARTZ_BRICKS: Block = Block::new(65);
pub const RAIL: Block = Block::new(66);
pub const RED_FLOWER: Block = Block::new(67);
pub const RED_NETHER_BRICKS: Block = Block::new(68);
pub const RED_NETHER_BRICK: Block = Block::new(68);
pub const RED_TERRACOTTA: Block = Block::new(69);
pub const RED_WOOL: Block = Block::new(70);
pub const SAND: Block = Block::new(71);
@@ -380,15 +629,12 @@ pub const SNOW_LAYER: Block = Block::new(112);
pub const SIGN: Block = Block::new(113);
pub const ANDESITE_WALL: Block = Block::new(114);
pub const STONE_BRICK_WALL: Block = Block::new(115);
pub const CARROTS: Block = Block::new(105);
pub const DARK_OAK_DOOR_LOWER: Block = Block::new(106);
pub const DARK_OAK_DOOR_UPPER: Block = Block::new(107);
pub const POTATOES: Block = Block::new(108);
pub const WHEAT: Block = Block::new(109);
pub const BEDROCK: Block = Block::new(110);
pub const RAIL_NORTH_SOUTH: Block = Block::new(116);
pub const RAIL_EAST_WEST: Block = Block::new(117);
pub const RAIL_ASCENDING_EAST: Block = Block::new(118);
@@ -399,97 +645,363 @@ pub const RAIL_NORTH_EAST: Block = Block::new(122);
pub const RAIL_NORTH_WEST: Block = Block::new(123);
pub const RAIL_SOUTH_EAST: Block = Block::new(124);
pub const RAIL_SOUTH_WEST: Block = Block::new(125);
pub const COARSE_DIRT: Block = Block::new(126);
pub const IRON_ORE: Block = Block::new(127);
pub const COAL_ORE: Block = Block::new(128);
pub const GOLD_ORE: Block = Block::new(129);
pub const COPPER_ORE: Block = Block::new(130);
pub const CLAY: Block = Block::new(131);
pub const DIRT_PATH: Block = Block::new(132);
pub const ICE: Block = Block::new(133);
pub const PACKED_ICE: Block = Block::new(134);
pub const MUD: Block = Block::new(135);
pub const DEAD_BUSH: Block = Block::new(136);
pub const TALL_GRASS_BOTTOM: Block = Block::new(137);
pub const TALL_GRASS_TOP: Block = Block::new(138);
pub const CRAFTING_TABLE: Block = Block::new(139);
pub const FURNACE: Block = Block::new(140);
pub const WHITE_CARPET: Block = Block::new(141);
pub const BOOKSHELF: Block = Block::new(142);
pub const OAK_PRESSURE_PLATE: Block = Block::new(143);
pub const OAK_STAIRS: Block = Block::new(144);
pub const CHEST: Block = Block::new(155);
pub const RED_CARPET: Block = Block::new(156);
pub const ANVIL: Block = Block::new(157);
pub const NOTE_BLOCK: Block = Block::new(158);
pub const OAK_DOOR: Block = Block::new(159);
pub const BREWING_STAND: Block = Block::new(160);
pub const RED_BED_NORTH_HEAD: Block = Block::new(161);
pub const RED_BED_NORTH_FOOT: Block = Block::new(162);
pub const RED_BED_EAST_HEAD: Block = Block::new(163);
pub const RED_BED_EAST_FOOT: Block = Block::new(164);
pub const RED_BED_SOUTH_HEAD: Block = Block::new(165);
pub const RED_BED_SOUTH_FOOT: Block = Block::new(166);
pub const RED_BED_WEST_HEAD: Block = Block::new(167);
pub const RED_BED_WEST_FOOT: Block = Block::new(168);
pub const GRAY_STAINED_GLASS: Block = Block::new(169);
pub const LIGHT_GRAY_STAINED_GLASS: Block = Block::new(170);
pub const BROWN_STAINED_GLASS: Block = Block::new(171);
pub const TINTED_GLASS: Block = Block::new(172);
pub const OAK_TRAPDOOR: Block = Block::new(173);
pub const BROWN_CONCRETE: Block = Block::new(174);
pub const BLACK_TERRACOTTA: Block = Block::new(175);
pub const BROWN_TERRACOTTA: Block = Block::new(176);
pub const STONE_BRICK_STAIRS: Block = Block::new(177);
pub const MUD_BRICK_STAIRS: Block = Block::new(178);
pub const POLISHED_BLACKSTONE_BRICK_STAIRS: Block = Block::new(179);
pub const BRICK_STAIRS: Block = Block::new(180);
pub const POLISHED_GRANITE_STAIRS: Block = Block::new(181);
pub const END_STONE_BRICK_STAIRS: Block = Block::new(182);
pub const POLISHED_DIORITE_STAIRS: Block = Block::new(183);
pub const SMOOTH_SANDSTONE_STAIRS: Block = Block::new(184);
pub const QUARTZ_STAIRS: Block = Block::new(185);
pub const POLISHED_ANDESITE_STAIRS: Block = Block::new(186);
pub const NETHER_BRICK_STAIRS: Block = Block::new(187);
// Variations for building corners
pub fn building_corner_variations() -> Vec<Block> {
vec![
/// Maps a block to its corresponding stair variant
#[inline]
pub fn get_stair_block_for_material(material: Block) -> Block {
match material {
STONE_BRICKS => STONE_BRICK_STAIRS,
MUD_BRICKS => MUD_BRICK_STAIRS,
OAK_PLANKS => OAK_STAIRS,
POLISHED_ANDESITE => STONE_BRICK_STAIRS,
SMOOTH_STONE => POLISHED_ANDESITE_STAIRS,
OAK_PLANKS => OAK_STAIRS,
ANDESITE => STONE_BRICK_STAIRS,
CHISELED_STONE_BRICKS => STONE_BRICK_STAIRS,
BLACK_TERRACOTTA => POLISHED_BLACKSTONE_BRICK_STAIRS,
BLACKSTONE => POLISHED_BLACKSTONE_BRICK_STAIRS,
BLUE_TERRACOTTA => MUD_BRICK_STAIRS,
BRICK => BRICK_STAIRS,
BROWN_CONCRETE => MUD_BRICK_STAIRS,
BROWN_TERRACOTTA => MUD_BRICK_STAIRS,
DEEPSLATE_BRICKS => STONE_BRICK_STAIRS,
END_STONE_BRICKS => END_STONE_BRICK_STAIRS,
GRAY_CONCRETE => POLISHED_BLACKSTONE_BRICK_STAIRS,
GRAY_TERRACOTTA => MUD_BRICK_STAIRS,
LIGHT_BLUE_TERRACOTTA => STONE_BRICK_STAIRS,
LIGHT_GRAY_CONCRETE => STONE_BRICK_STAIRS,
NETHER_BRICK => NETHER_BRICK_STAIRS,
POLISHED_BLACKSTONE => POLISHED_BLACKSTONE_BRICK_STAIRS,
POLISHED_BLACKSTONE_BRICKS => POLISHED_BLACKSTONE_BRICK_STAIRS,
POLISHED_DEEPSLATE => STONE_BRICK_STAIRS,
POLISHED_GRANITE => POLISHED_GRANITE_STAIRS,
QUARTZ_BLOCK => POLISHED_DIORITE_STAIRS,
QUARTZ_BRICKS => POLISHED_DIORITE_STAIRS,
SANDSTONE => SMOOTH_SANDSTONE_STAIRS,
SMOOTH_SANDSTONE => SMOOTH_SANDSTONE_STAIRS,
WHITE_CONCRETE => QUARTZ_STAIRS,
WHITE_TERRACOTTA => MUD_BRICK_STAIRS,
_ => STONE_BRICK_STAIRS,
}
}
// Window variations for different building types
pub static WINDOW_VARIATIONS: [Block; 7] = [
GLASS,
GRAY_STAINED_GLASS,
LIGHT_GRAY_STAINED_GLASS,
GRAY_STAINED_GLASS,
BROWN_STAINED_GLASS,
WHITE_STAINED_GLASS,
TINTED_GLASS,
];
// Window types for different building styles
pub fn get_window_block_for_building_type(building_type: &str) -> Block {
use rand::Rng;
let mut rng = rand::thread_rng();
match building_type {
"residential" | "house" | "apartment" => {
let residential_windows = [
GLASS,
WHITE_STAINED_GLASS,
LIGHT_GRAY_STAINED_GLASS,
BROWN_STAINED_GLASS,
];
residential_windows[rng.gen_range(0..residential_windows.len())]
}
"hospital" | "school" | "university" => {
let institutional_windows = [GLASS, WHITE_STAINED_GLASS, LIGHT_GRAY_STAINED_GLASS];
institutional_windows[rng.gen_range(0..institutional_windows.len())]
}
"hotel" | "restaurant" => {
let hospitality_windows = [GLASS, WHITE_STAINED_GLASS];
hospitality_windows[rng.gen_range(0..hospitality_windows.len())]
}
"industrial" | "warehouse" => {
let industrial_windows = [
GLASS,
GRAY_STAINED_GLASS,
LIGHT_GRAY_STAINED_GLASS,
BROWN_STAINED_GLASS,
];
industrial_windows[rng.gen_range(0..industrial_windows.len())]
}
_ => WINDOW_VARIATIONS[rng.gen_range(0..WINDOW_VARIATIONS.len())],
}
}
// Random floor block selection
pub fn get_random_floor_block() -> Block {
use rand::Rng;
let mut rng = rand::thread_rng();
let floor_options = [
WHITE_CONCRETE,
GRAY_CONCRETE,
LIGHT_GRAY_CONCRETE,
POLISHED_ANDESITE,
SMOOTH_STONE,
STONE_BRICKS,
COBBLESTONE,
BRICK,
MOSSY_COBBLESTONE,
SANDSTONE,
RED_NETHER_BRICKS,
MUD_BRICKS,
OAK_PLANKS,
];
floor_options[rng.gen_range(0..floor_options.len())]
}
// Define all predefined colors with their blocks
static DEFINED_COLORS: &[ColorBlockMapping] = &[
((233, 107, 57), &[BRICK, NETHER_BRICK]),
(
(18, 12, 13),
&[POLISHED_BLACKSTONE_BRICKS, BLACKSTONE, DEEPSLATE_BRICKS],
),
((76, 127, 153), &[LIGHT_BLUE_TERRACOTTA]),
(
(0, 0, 0),
&[DEEPSLATE_BRICKS, BLACKSTONE, POLISHED_BLACKSTONE],
),
(
(186, 195, 142),
&[
END_STONE_BRICKS,
SANDSTONE,
SMOOTH_SANDSTONE,
LIGHT_GRAY_CONCRETE,
],
),
(
(57, 41, 35),
&[BROWN_TERRACOTTA, BROWN_CONCRETE, MUD_BRICKS, BRICK],
),
(
(112, 108, 138),
&[LIGHT_BLUE_TERRACOTTA, GRAY_TERRACOTTA, GRAY_CONCRETE],
),
(
(122, 92, 66),
&[MUD_BRICKS, BROWN_TERRACOTTA, SANDSTONE, BRICK],
),
((24, 13, 14), &[NETHER_BRICK, BLACKSTONE, DEEPSLATE_BRICKS]),
(
(159, 82, 36),
&[
BROWN_TERRACOTTA,
BRICK,
POLISHED_GRANITE,
BROWN_CONCRETE,
NETHERITE_BLOCK,
POLISHED_DEEPSLATE,
],
),
(
(128, 128, 128),
&[
POLISHED_ANDESITE,
LIGHT_GRAY_CONCRETE,
SMOOTH_STONE,
STONE_BRICKS,
],
),
(
(174, 173, 174),
&[
POLISHED_ANDESITE,
LIGHT_GRAY_CONCRETE,
SMOOTH_STONE,
STONE_BRICKS,
],
),
((141, 101, 142), &[STONE_BRICKS, BRICK, MUD_BRICKS]),
(
(142, 60, 46),
&[
BLACK_TERRACOTTA,
NETHERITE_BLOCK,
NETHER_BRICK,
POLISHED_GRANITE,
POLISHED_DEEPSLATE,
BROWN_TERRACOTTA,
],
),
(
(153, 83, 28),
&[
BLACK_TERRACOTTA,
POLISHED_GRANITE,
BROWN_CONCRETE,
BROWN_TERRACOTTA,
STONE_BRICKS,
],
),
(
(224, 216, 175),
&[
SMOOTH_SANDSTONE,
LIGHT_GRAY_CONCRETE,
POLISHED_ANDESITE,
SMOOTH_STONE,
],
),
(
(188, 182, 179),
&[
SMOOTH_SANDSTONE,
LIGHT_GRAY_CONCRETE,
QUARTZ_BRICKS,
POLISHED_ANDESITE,
SMOOTH_STONE,
],
),
(
(35, 86, 85),
&[
POLISHED_BLACKSTONE_BRICKS,
BLUE_TERRACOTTA,
LIGHT_BLUE_TERRACOTTA,
],
),
(
(255, 255, 255),
&[WHITE_CONCRETE, QUARTZ_BRICKS, QUARTZ_BLOCK],
),
(
(209, 177, 161),
&[
WHITE_TERRACOTTA,
SMOOTH_SANDSTONE,
SMOOTH_STONE,
SANDSTONE,
LIGHT_GRAY_CONCRETE,
],
),
((191, 147, 42), &[SMOOTH_SANDSTONE, SANDSTONE, SMOOTH_STONE]),
];
// Function to randomly select building wall block with alternatives
pub fn get_building_wall_block_for_color(color: RGBTuple) -> Block {
use rand::Rng;
let mut rng = rand::thread_rng();
// Find the closest color match
let closest_color = DEFINED_COLORS
.iter()
.min_by_key(|(defined_color, _)| crate::colors::rgb_distance(&color, defined_color));
if let Some((_, options)) = closest_color {
options[rng.gen_range(0..options.len())]
} else {
// This should never happen, but fallback just in case
get_fallback_building_block()
}
}
// Function to get a random fallback building block when no color attribute is specified
pub fn get_fallback_building_block() -> Block {
use rand::Rng;
let mut rng = rand::thread_rng();
let fallback_options = [
BLACKSTONE,
SMOOTH_QUARTZ,
CHISELED_STONE_BRICKS,
POLISHED_BASALT,
CUT_SANDSTONE,
POLISHED_BLACKSTONE_BRICKS,
ANDESITE,
GRANITE,
DIORITE,
CRACKED_STONE_BRICKS,
PRISMARINE,
BLUE_TERRACOTTA,
BLACK_TERRACOTTA,
BRICK,
BROWN_CONCRETE,
BROWN_TERRACOTTA,
DEEPSLATE_BRICKS,
END_STONE_BRICKS,
GRAY_CONCRETE,
GRAY_TERRACOTTA,
LIGHT_BLUE_TERRACOTTA,
LIGHT_GRAY_CONCRETE,
MUD_BRICKS,
NETHER_BRICK,
POLISHED_ANDESITE,
POLISHED_BLACKSTONE,
POLISHED_BLACKSTONE_BRICKS,
POLISHED_DEEPSLATE,
POLISHED_GRANITE,
QUARTZ_BLOCK,
QUARTZ_BRICKS,
]
SANDSTONE,
SMOOTH_SANDSTONE,
SMOOTH_STONE,
STONE_BRICKS,
WHITE_CONCRETE,
WHITE_TERRACOTTA,
OAK_PLANKS,
];
fallback_options[rng.gen_range(0..fallback_options.len())]
}
// Variations for building walls
pub fn building_wall_variations() -> Vec<Block> {
building_wall_color_map()
.into_iter()
.map(|(_, block)| block)
.collect()
}
// Function to get a random castle wall block
pub fn get_castle_wall_block() -> Block {
use rand::Rng;
let mut rng = rand::thread_rng();
// https://wiki.openstreetmap.org/wiki/Key:building:colour
pub fn building_wall_color_map() -> Vec<(RGBTuple, Block)> {
vec![
((233, 107, 57), BRICK),
((18, 12, 13), CRACKED_POLISHED_BLACKSTONE_BRICKS),
((76, 127, 153), CYAN_CONCRETE),
((0, 0, 0), DEEPSLATE_BRICKS),
((186, 195, 142), END_STONE_BRICKS),
((57, 41, 35), GRAY_TERRACOTTA),
((112, 108, 138), LIGHT_BLUE_TERRACOTTA),
((122, 92, 66), MUD_BRICKS),
((24, 13, 14), NETHER_BRICKS),
((159, 82, 36), ORANGE_TERRACOTTA),
((128, 128, 128), POLISHED_ANDESITE),
((174, 173, 174), POLISHED_DIORITE),
((141, 101, 142), PURPUR_PILLAR),
((142, 60, 46), RED_TERRACOTTA),
((153, 83, 28), SMOOTH_RED_SANDSTONE),
((224, 216, 175), SMOOTH_SANDSTONE),
((188, 182, 179), SMOOTH_STONE),
((35, 86, 85), WARPED_PLANKS),
((255, 255, 255), WHITE_CONCRETE),
((209, 177, 161), WHITE_TERRACOTTA),
((191, 147, 42), YELLOW_TERRACOTTA),
]
}
// Variations for building floors
pub fn building_floor_variations() -> Vec<Block> {
building_wall_color_map()
.into_iter()
.map(|(_, block)| block)
.collect()
}
pub fn building_floor_color_map() -> Vec<(RGBTuple, Block)> {
vec![
((181, 101, 59), ACACIA_PLANKS),
((22, 15, 16), BLACKSTONE),
((104, 51, 74), CRIMSON_PLANKS),
((82, 55, 26), DARK_OAK_PLANKS),
((182, 133, 99), JUNGLE_PLANKS),
((33, 128, 185), LIGHT_BLUE_CONCRETE),
((78, 103, 43), MOSS_BLOCK),
((171, 138, 88), OAK_PLANKS),
((0, 128, 0), OXIDIZED_COPPER),
((18, 12, 13), POLISHED_BLACKSTONE),
((64, 64, 64), POLISHED_DEEPSLATE),
((255, 255, 255), POLISHED_DIORITE),
((143, 96, 79), POLISHED_GRANITE),
((141, 101, 142), PURPUR_BLOCK),
((128, 0, 0), RED_NETHER_BRICKS),
((153, 83, 28), SMOOTH_RED_SANDSTONE),
((128, 96, 57), SPRUCE_PLANKS),
((128, 128, 128), STONE_BRICKS),
((150, 93, 68), TERRACOTTA),
((35, 86, 85), WARPED_PLANKS),
]
let castle_wall_options = [
STONE_BRICKS,
CHISELED_STONE_BRICKS,
CRACKED_STONE_BRICKS,
COBBLESTONE,
MOSSY_COBBLESTONE,
DEEPSLATE_BRICKS,
POLISHED_ANDESITE,
ANDESITE,
SMOOTH_STONE,
BRICK,
];
castle_wall_options[rng.gen_range(0..castle_wall_options.len())]
}

View File

@@ -1,12 +0,0 @@
#[derive(Copy, Clone)]
pub struct XZPoint {
pub x: i32,
pub z: i32,
}
impl XZPoint {
#[inline]
pub fn new(x: i32, z: i32) -> Self {
Self { x, z }
}
}

706
src/clipping.rs Normal file
View File

@@ -0,0 +1,706 @@
// Sutherland-Hodgman polygon clipping and related geometry utilities.
//
// Provides bbox clipping for polygons, polylines, and water rings with
// proper corner insertion for closed shapes.
use crate::coordinate_system::cartesian::{XZBBox, XZPoint};
use crate::osm_parser::ProcessedNode;
use std::collections::HashMap;
/// Clips a way to the bounding box using Sutherland-Hodgman for polygons or
/// simple line clipping for polylines. Preserves endpoint IDs for ring assembly.
pub fn clip_way_to_bbox(nodes: &[ProcessedNode], xzbbox: &XZBBox) -> Vec<ProcessedNode> {
if nodes.is_empty() {
return Vec::new();
}
let is_closed = is_closed_polygon(nodes);
if !is_closed {
return clip_polyline_to_bbox(nodes, xzbbox);
}
// If all nodes are inside the bbox, return unchanged
let has_nodes_outside = nodes
.iter()
.any(|node| !xzbbox.contains(&XZPoint::new(node.x, node.z)));
if !has_nodes_outside {
return nodes.to_vec();
}
let min_x = xzbbox.min_x() as f64;
let min_z = xzbbox.min_z() as f64;
let max_x = xzbbox.max_x() as f64;
let max_z = xzbbox.max_z() as f64;
let mut polygon: Vec<(f64, f64)> = nodes.iter().map(|n| (n.x as f64, n.z as f64)).collect();
polygon = clip_polygon_sutherland_hodgman(polygon, min_x, min_z, max_x, max_z);
if polygon.len() < 3 {
return Vec::new();
}
// Final clamping for floating-point errors
for p in &mut polygon {
p.0 = p.0.clamp(min_x, max_x);
p.1 = p.1.clamp(min_z, max_z);
}
let polygon = remove_consecutive_duplicates(polygon);
if polygon.len() < 3 {
return Vec::new();
}
let polygon = insert_bbox_corners(polygon, min_x, min_z, max_x, max_z);
let polygon = remove_consecutive_duplicates(polygon);
if polygon.len() < 3 {
return Vec::new();
}
let way_id = nodes.first().map(|n| n.id).unwrap_or(0);
assign_node_ids_preserving_endpoints(nodes, polygon, way_id)
}
/// Clips a water polygon ring to bbox using Sutherland-Hodgman (post-ring-merge).
pub fn clip_water_ring_to_bbox(
ring: &[ProcessedNode],
xzbbox: &XZBBox,
) -> Option<Vec<ProcessedNode>> {
if ring.is_empty() {
return None;
}
let min_x = xzbbox.min_x() as f64;
let min_z = xzbbox.min_z() as f64;
let max_x = xzbbox.max_x() as f64;
let max_z = xzbbox.max_z() as f64;
// Check if entire ring is inside bbox
let all_inside = ring.iter().all(|n| {
n.x as f64 >= min_x && n.x as f64 <= max_x && n.z as f64 >= min_z && n.z as f64 <= max_z
});
if all_inside {
return Some(ring.to_vec());
}
// Check if entire ring is outside bbox
if is_ring_outside_bbox(ring, min_x, min_z, max_x, max_z) {
return None;
}
// Convert to f64 coordinates and ensure closed
let mut polygon: Vec<(f64, f64)> = ring.iter().map(|n| (n.x as f64, n.z as f64)).collect();
if !polygon.is_empty() && polygon.first() != polygon.last() {
polygon.push(polygon[0]);
}
// Clip with full-range clamping (water uses simpler approach)
polygon = clip_polygon_sutherland_hodgman_simple(polygon, min_x, min_z, max_x, max_z);
if polygon.len() < 3 {
return None;
}
// Verify all points are within bbox
let all_points_inside = polygon
.iter()
.all(|&(x, z)| x >= min_x && x <= max_x && z >= min_z && z <= max_z);
if !all_points_inside {
eprintln!("ERROR: clip_water_ring_to_bbox produced points outside bbox!");
return None;
}
let polygon = insert_bbox_corners(polygon, min_x, min_z, max_x, max_z);
if polygon.len() < 3 {
return None;
}
// Convert back to ProcessedNode with synthetic IDs
let mut result: Vec<ProcessedNode> = polygon
.iter()
.enumerate()
.map(|(i, &(x, z))| ProcessedNode {
id: 1_000_000_000 + i as u64,
tags: HashMap::new(),
x: x.clamp(min_x, max_x).round() as i32,
z: z.clamp(min_z, max_z).round() as i32,
})
.collect();
// Close the loop by matching first and last ID
if !result.is_empty() {
let first_id = result[0].id;
result.last_mut().unwrap().id = first_id;
}
Some(result)
}
// ============================================================================
// Internal helpers
// ============================================================================
/// Checks if a way forms a closed polygon.
fn is_closed_polygon(nodes: &[ProcessedNode]) -> bool {
if nodes.len() < 3 {
return false;
}
let first = nodes.first().unwrap();
let last = nodes.last().unwrap();
first.id == last.id || (first.x == last.x && first.z == last.z)
}
/// Checks if an entire ring is outside the bbox.
fn is_ring_outside_bbox(
ring: &[ProcessedNode],
min_x: f64,
min_z: f64,
max_x: f64,
max_z: f64,
) -> bool {
let all_left = ring.iter().all(|n| (n.x as f64) < min_x);
let all_right = ring.iter().all(|n| (n.x as f64) > max_x);
let all_top = ring.iter().all(|n| (n.z as f64) < min_z);
let all_bottom = ring.iter().all(|n| (n.z as f64) > max_z);
all_left || all_right || all_top || all_bottom
}
/// Clips a polyline (open path) to the bounding box.
fn clip_polyline_to_bbox(nodes: &[ProcessedNode], xzbbox: &XZBBox) -> Vec<ProcessedNode> {
if nodes.is_empty() {
return Vec::new();
}
let min_x = xzbbox.min_x() as f64;
let min_z = xzbbox.min_z() as f64;
let max_x = xzbbox.max_x() as f64;
let max_z = xzbbox.max_z() as f64;
let mut result = Vec::new();
for i in 0..nodes.len() {
let current = &nodes[i];
let current_point = (current.x as f64, current.z as f64);
let current_inside = point_in_bbox(current_point, min_x, min_z, max_x, max_z);
if current_inside {
result.push(current.clone());
}
if i + 1 < nodes.len() {
let next = &nodes[i + 1];
let next_point = (next.x as f64, next.z as f64);
let next_inside = point_in_bbox(next_point, min_x, min_z, max_x, max_z);
if current_inside != next_inside {
// One endpoint inside, one outside, find single intersection
let intersections =
find_bbox_intersections(current_point, next_point, min_x, min_z, max_x, max_z);
for intersection in intersections {
let synthetic_id = nodes[0]
.id
.wrapping_mul(10000000)
.wrapping_add(result.len() as u64);
result.push(ProcessedNode {
id: synthetic_id,
x: intersection.0.round() as i32,
z: intersection.1.round() as i32,
tags: HashMap::new(),
});
}
} else if !current_inside && !next_inside {
// Both endpoints outside, segment might still cross through bbox
let mut intersections =
find_bbox_intersections(current_point, next_point, min_x, min_z, max_x, max_z);
if intersections.len() >= 2 {
// Sort intersections by distance from current point
intersections.sort_by(|a, b| {
let dist_a =
(a.0 - current_point.0).powi(2) + (a.1 - current_point.1).powi(2);
let dist_b =
(b.0 - current_point.0).powi(2) + (b.1 - current_point.1).powi(2);
dist_a
.partial_cmp(&dist_b)
.unwrap_or(std::cmp::Ordering::Equal)
});
for intersection in intersections {
let synthetic_id = nodes[0]
.id
.wrapping_mul(10000000)
.wrapping_add(result.len() as u64);
result.push(ProcessedNode {
id: synthetic_id,
x: intersection.0.round() as i32,
z: intersection.1.round() as i32,
tags: HashMap::new(),
});
}
}
}
}
}
// Preserve endpoint IDs where possible
if result.len() >= 2 {
let tolerance = 50.0;
if let Some(first_orig) = nodes.first() {
if matches_endpoint(
(result[0].x as f64, result[0].z as f64),
first_orig,
tolerance,
) {
result[0].id = first_orig.id;
}
}
if let Some(last_orig) = nodes.last() {
let last_idx = result.len() - 1;
if matches_endpoint(
(result[last_idx].x as f64, result[last_idx].z as f64),
last_orig,
tolerance,
) {
result[last_idx].id = last_orig.id;
}
}
}
result
}
/// Sutherland-Hodgman polygon clipping with edge-specific clamping.
fn clip_polygon_sutherland_hodgman(
mut polygon: Vec<(f64, f64)>,
min_x: f64,
min_z: f64,
max_x: f64,
max_z: f64,
) -> Vec<(f64, f64)> {
// Edges: bottom, right, top, left (counter-clockwise traversal)
let bbox_edges = [
(min_x, min_z, max_x, min_z, 0), // Bottom: clamp z
(max_x, min_z, max_x, max_z, 1), // Right: clamp x
(max_x, max_z, min_x, max_z, 2), // Top: clamp z
(min_x, max_z, min_x, min_z, 3), // Left: clamp x
];
for (edge_x1, edge_z1, edge_x2, edge_z2, edge_idx) in bbox_edges {
if polygon.is_empty() {
break;
}
let mut clipped = Vec::new();
let is_closed = !polygon.is_empty() && polygon.first() == polygon.last();
let edge_count = if is_closed {
polygon.len().saturating_sub(1)
} else {
polygon.len()
};
for i in 0..edge_count {
let current = polygon[i];
let next = polygon.get(i + 1).copied().unwrap_or(polygon[0]);
let current_inside = point_inside_edge(current, edge_x1, edge_z1, edge_x2, edge_z2);
let next_inside = point_inside_edge(next, edge_x1, edge_z1, edge_x2, edge_z2);
if next_inside {
if !current_inside {
if let Some(mut intersection) = line_edge_intersection(
current.0, current.1, next.0, next.1, edge_x1, edge_z1, edge_x2, edge_z2,
) {
// Clamp to current edge only
match edge_idx {
0 => intersection.1 = min_z,
1 => intersection.0 = max_x,
2 => intersection.1 = max_z,
3 => intersection.0 = min_x,
_ => {}
}
clipped.push(intersection);
}
}
clipped.push(next);
} else if current_inside {
if let Some(mut intersection) = line_edge_intersection(
current.0, current.1, next.0, next.1, edge_x1, edge_z1, edge_x2, edge_z2,
) {
match edge_idx {
0 => intersection.1 = min_z,
1 => intersection.0 = max_x,
2 => intersection.1 = max_z,
3 => intersection.0 = min_x,
_ => {}
}
clipped.push(intersection);
}
}
}
polygon = clipped;
}
polygon
}
/// Sutherland-Hodgman with full bbox clamping (simpler, for water rings).
fn clip_polygon_sutherland_hodgman_simple(
mut polygon: Vec<(f64, f64)>,
min_x: f64,
min_z: f64,
max_x: f64,
max_z: f64,
) -> Vec<(f64, f64)> {
let bbox_edges = [
(min_x, min_z, max_x, min_z),
(max_x, min_z, max_x, max_z),
(max_x, max_z, min_x, max_z),
(min_x, max_z, min_x, min_z),
];
for (edge_x1, edge_z1, edge_x2, edge_z2) in bbox_edges {
if polygon.is_empty() {
break;
}
let mut clipped = Vec::new();
for i in 0..(polygon.len().saturating_sub(1)) {
let current = polygon[i];
let next = polygon[i + 1];
let current_inside = point_inside_edge(current, edge_x1, edge_z1, edge_x2, edge_z2);
let next_inside = point_inside_edge(next, edge_x1, edge_z1, edge_x2, edge_z2);
if next_inside {
if !current_inside {
if let Some(mut intersection) = line_edge_intersection(
current.0, current.1, next.0, next.1, edge_x1, edge_z1, edge_x2, edge_z2,
) {
intersection.0 = intersection.0.clamp(min_x, max_x);
intersection.1 = intersection.1.clamp(min_z, max_z);
clipped.push(intersection);
}
}
clipped.push(next);
} else if current_inside {
if let Some(mut intersection) = line_edge_intersection(
current.0, current.1, next.0, next.1, edge_x1, edge_z1, edge_x2, edge_z2,
) {
intersection.0 = intersection.0.clamp(min_x, max_x);
intersection.1 = intersection.1.clamp(min_z, max_z);
clipped.push(intersection);
}
}
}
polygon = clipped;
}
polygon
}
/// Checks if point is inside bbox.
fn point_in_bbox(point: (f64, f64), min_x: f64, min_z: f64, max_x: f64, max_z: f64) -> bool {
point.0 >= min_x && point.0 <= max_x && point.1 >= min_z && point.1 <= max_z
}
/// Checks if point is on the "inside" side of an edge (cross product test).
fn point_inside_edge(
point: (f64, f64),
edge_x1: f64,
edge_z1: f64,
edge_x2: f64,
edge_z2: f64,
) -> bool {
let edge_dx = edge_x2 - edge_x1;
let edge_dz = edge_z2 - edge_z1;
let point_dx = point.0 - edge_x1;
let point_dz = point.1 - edge_z1;
(edge_dx * point_dz - edge_dz * point_dx) >= 0.0
}
/// Finds intersection between a line segment and an edge.
#[allow(clippy::too_many_arguments)]
fn line_edge_intersection(
line_x1: f64,
line_z1: f64,
line_x2: f64,
line_z2: f64,
edge_x1: f64,
edge_z1: f64,
edge_x2: f64,
edge_z2: f64,
) -> Option<(f64, f64)> {
let line_dx = line_x2 - line_x1;
let line_dz = line_z2 - line_z1;
let edge_dx = edge_x2 - edge_x1;
let edge_dz = edge_z2 - edge_z1;
let denom = line_dx * edge_dz - line_dz * edge_dx;
if denom.abs() < 1e-10 {
return None;
}
let dx = edge_x1 - line_x1;
let dz = edge_z1 - line_z1;
let t = (dx * edge_dz - dz * edge_dx) / denom;
if (0.0..=1.0).contains(&t) {
Some((line_x1 + t * line_dx, line_z1 + t * line_dz))
} else {
None
}
}
/// Finds intersections between a line segment and bbox edges.
fn find_bbox_intersections(
start: (f64, f64),
end: (f64, f64),
min_x: f64,
min_z: f64,
max_x: f64,
max_z: f64,
) -> Vec<(f64, f64)> {
let mut intersections = Vec::new();
let bbox_edges = [
(min_x, min_z, max_x, min_z),
(max_x, min_z, max_x, max_z),
(max_x, max_z, min_x, max_z),
(min_x, max_z, min_x, min_z),
];
for (edge_x1, edge_z1, edge_x2, edge_z2) in bbox_edges {
if let Some(intersection) = line_edge_intersection(
start.0, start.1, end.0, end.1, edge_x1, edge_z1, edge_x2, edge_z2,
) {
let on_edge = point_in_bbox(intersection, min_x, min_z, max_x, max_z)
&& ((intersection.0 == min_x || intersection.0 == max_x)
|| (intersection.1 == min_z || intersection.1 == max_z));
if on_edge {
intersections.push(intersection);
}
}
}
intersections
}
/// Returns which bbox edge a point lies on: 0=bottom, 1=right, 2=top, 3=left, -1=interior.
fn get_bbox_edge(point: (f64, f64), min_x: f64, min_z: f64, max_x: f64, max_z: f64) -> i32 {
let eps = 0.5;
let on_left = (point.0 - min_x).abs() < eps;
let on_right = (point.0 - max_x).abs() < eps;
let on_bottom = (point.1 - min_z).abs() < eps;
let on_top = (point.1 - max_z).abs() < eps;
// Handle corners (assign to edge in counter-clockwise order)
if on_bottom && on_left {
return 3;
}
if on_bottom && on_right {
return 0;
}
if on_top && on_right {
return 1;
}
if on_top && on_left {
return 2;
}
if on_bottom {
return 0;
}
if on_right {
return 1;
}
if on_top {
return 2;
}
if on_left {
return 3;
}
-1
}
/// Returns corners to insert when traversing from edge1 to edge2 via shorter path.
fn get_corners_between_edges(
edge1: i32,
edge2: i32,
min_x: f64,
min_z: f64,
max_x: f64,
max_z: f64,
) -> Vec<(f64, f64)> {
if edge1 == edge2 || edge1 < 0 || edge2 < 0 {
return Vec::new();
}
let corners = [
(max_x, min_z), // 0: bottom-right
(max_x, max_z), // 1: top-right
(min_x, max_z), // 2: top-left
(min_x, min_z), // 3: bottom-left
];
let ccw_dist = ((edge2 - edge1 + 4) % 4) as usize;
let cw_dist = ((edge1 - edge2 + 4) % 4) as usize;
// Opposite edges: don't insert corners
if ccw_dist == 2 && cw_dist == 2 {
return Vec::new();
}
let mut result = Vec::new();
if ccw_dist <= cw_dist {
let mut current = edge1;
for _ in 0..ccw_dist {
result.push(corners[current as usize]);
current = (current + 1) % 4;
}
} else {
let mut current = edge1;
for _ in 0..cw_dist {
current = (current + 4 - 1) % 4;
result.push(corners[current as usize]);
}
}
result
}
/// Inserts bbox corners where polygon transitions between different bbox edges.
fn insert_bbox_corners(
polygon: Vec<(f64, f64)>,
min_x: f64,
min_z: f64,
max_x: f64,
max_z: f64,
) -> Vec<(f64, f64)> {
if polygon.len() < 3 {
return polygon;
}
let mut result = Vec::with_capacity(polygon.len() + 4);
for i in 0..polygon.len() {
let current = polygon[i];
let next = polygon[(i + 1) % polygon.len()];
result.push(current);
let edge1 = get_bbox_edge(current, min_x, min_z, max_x, max_z);
let edge2 = get_bbox_edge(next, min_x, min_z, max_x, max_z);
if edge1 >= 0 && edge2 >= 0 && edge1 != edge2 {
for corner in get_corners_between_edges(edge1, edge2, min_x, min_z, max_x, max_z) {
result.push(corner);
}
}
}
result
}
/// Removes consecutive duplicate points (within epsilon tolerance).
fn remove_consecutive_duplicates(polygon: Vec<(f64, f64)>) -> Vec<(f64, f64)> {
if polygon.is_empty() {
return polygon;
}
let eps = 0.1;
let mut result: Vec<(f64, f64)> = Vec::with_capacity(polygon.len());
for p in &polygon {
if let Some(last) = result.last() {
if (p.0 - last.0).abs() < eps && (p.1 - last.1).abs() < eps {
continue;
}
}
result.push(*p);
}
// Check first/last duplicates for closed polygons
if result.len() > 1 {
let first = result.first().unwrap();
let last = result.last().unwrap();
if (first.0 - last.0).abs() < eps && (first.1 - last.1).abs() < eps {
result.pop();
}
}
result
}
/// Checks if a clipped coordinate matches an original endpoint.
fn matches_endpoint(coord: (f64, f64), endpoint: &ProcessedNode, tolerance: f64) -> bool {
let dx = (coord.0 - endpoint.x as f64).abs();
let dz = (coord.1 - endpoint.z as f64).abs();
dx * dx + dz * dz < tolerance * tolerance
}
/// Assigns node IDs to clipped coordinates, preserving original endpoint IDs.
fn assign_node_ids_preserving_endpoints(
original_nodes: &[ProcessedNode],
clipped_coords: Vec<(f64, f64)>,
way_id: u64,
) -> Vec<ProcessedNode> {
if clipped_coords.is_empty() {
return Vec::new();
}
let original_first = original_nodes.first();
let original_last = original_nodes.last();
let tolerance = 50.0;
let last_index = clipped_coords.len() - 1;
clipped_coords
.into_iter()
.enumerate()
.map(|(i, coord)| {
let is_first = i == 0;
let is_last = i == last_index;
if is_first || is_last {
if let Some(first) = original_first {
if matches_endpoint(coord, first, tolerance) {
return ProcessedNode {
id: first.id,
x: coord.0.round() as i32,
z: coord.1.round() as i32,
tags: HashMap::new(),
};
}
}
if let Some(last) = original_last {
if matches_endpoint(coord, last, tolerance) {
return ProcessedNode {
id: last.id,
x: coord.0.round() as i32,
z: coord.1.round() as i32,
tags: HashMap::new(),
};
}
}
}
ProcessedNode {
id: way_id.wrapping_mul(10000000).wrapping_add(i as u64),
x: coord.0.round() as i32,
z: coord.1.round() as i32,
tags: HashMap::new(),
}
})
.collect()
}

View File

@@ -32,16 +32,16 @@ fn full_hex_color_to_rgb_tuple(text: &str) -> Option<RGBTuple> {
fn short_hex_color_to_rgb_tuple(text: &str) -> Option<RGBTuple> {
if text.len() != 4
|| !text.starts_with("#")
|| text.chars().skip(1).all(|c: char| c.is_ascii_hexdigit())
|| !text.chars().skip(1).all(|c: char| c.is_ascii_hexdigit())
{
return None;
}
let r: u8 = u8::from_str_radix(&text[1..2], 16).unwrap();
let r: u8 = r | r << 4;
let r: u8 = r | (r << 4);
let g: u8 = u8::from_str_radix(&text[2..3], 16).unwrap();
let g: u8 = g | g << 4;
let g: u8 = g | (g << 4);
let b: u8 = u8::from_str_radix(&text[3..4], 16).unwrap();
let b: u8 = b | b << 4;
let b: u8 = b | (b << 4);
Some((r, g, b))
}

View File

@@ -0,0 +1,7 @@
mod xzbbox;
mod xzpoint;
mod xzvector;
pub use xzbbox::XZBBox;
pub use xzpoint::XZPoint;
pub use xzvector::XZVector;

View File

@@ -0,0 +1,4 @@
mod rectangle;
mod xzbbox_enum;
pub use xzbbox_enum::XZBBox;

View File

@@ -0,0 +1,112 @@
use crate::coordinate_system::cartesian::{XZPoint, XZVector};
use std::fmt;
use std::ops::{Add, AddAssign, Sub, SubAssign};
/// An underlying shape of XZBBox enum.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct XZBBoxRect {
/// The "bottom-left" vertex of the rectangle
min: XZPoint,
/// The "top-right" vertex of the rectangle
max: XZPoint,
}
impl XZBBoxRect {
pub fn new(min: XZPoint, max: XZPoint) -> Result<Self, String> {
let blockx_ge_1 = max.x - min.x >= 0;
let blockz_ge_1 = max.z - min.z >= 0;
if !blockx_ge_1 {
return Err(format!(
"Invalid XZBBox::Rect: max.x should >= min.x, but encountered {} -> {}",
min.x, max.x
));
}
if !blockz_ge_1 {
return Err(format!(
"Invalid XZBBox::Rect: max.z should >= min.z, but encountered {} -> {}",
min.z, max.z
));
}
Ok(Self { min, max })
}
pub fn min(&self) -> XZPoint {
self.min
}
pub fn max(&self) -> XZPoint {
self.max
}
/// Total number of blocks covered in this 2D bbox
pub fn total_blocks(&self) -> u64 {
(self.total_blocks_x() as u64) * (self.total_blocks_z() as u64)
}
/// Total number of blocks covered in x direction
pub fn total_blocks_x(&self) -> u32 {
let nx = self.max.x - self.min.x + 1;
nx as u32
}
/// Total number of blocks covered in z direction
pub fn total_blocks_z(&self) -> u32 {
let nz = self.max.z - self.min.z + 1;
nz as u32
}
/// Check whether an XZPoint is covered
pub fn contains(&self, xzpoint: &XZPoint) -> bool {
xzpoint.x >= self.min.x
&& xzpoint.x <= self.max.x
&& xzpoint.z >= self.min.z
&& xzpoint.z <= self.max.z
}
}
impl fmt::Display for XZBBoxRect {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Rect({} -> {})", self.min, self.max)
}
}
// below are associated +- operators
impl Add<XZVector> for XZBBoxRect {
type Output = XZBBoxRect;
fn add(self, other: XZVector) -> Self {
Self {
min: self.min + other,
max: self.max + other,
}
}
}
impl AddAssign<XZVector> for XZBBoxRect {
fn add_assign(&mut self, other: XZVector) {
self.min += other;
self.max += other;
}
}
impl Sub<XZVector> for XZBBoxRect {
type Output = XZBBoxRect;
fn sub(self, other: XZVector) -> Self {
Self {
min: self.min - other,
max: self.max - other,
}
}
}
impl SubAssign<XZVector> for XZBBoxRect {
fn sub_assign(&mut self, other: XZVector) {
self.min -= other;
self.max -= other;
}
}

View File

@@ -0,0 +1,202 @@
use super::rectangle::XZBBoxRect;
use crate::coordinate_system::cartesian::{XZPoint, XZVector};
use std::fmt;
use std::ops::{Add, AddAssign, Sub, SubAssign};
/// Bounding Box in minecraft XZ space with varied shapes.
#[derive(Clone, Debug)]
pub enum XZBBox {
Rect(XZBBoxRect),
}
impl XZBBox {
/// Construct rectangle shape bbox from the x and z lengths of the world, originated at (0, 0)
pub fn rect_from_xz_lengths(length_x: f64, length_z: f64) -> Result<Self, String> {
let lenx_ge_0 = length_x >= 0.0;
let lenz_ge_0 = length_z >= 0.0;
let lenx_overflow = length_x > i32::MAX as f64;
let lenz_overflow = length_z > i32::MAX as f64;
if !lenx_ge_0 {
return Err(format!(
"Invalid XZBBox::Rect from xz lengths: length x should >=0 , but encountered {length_x}"
));
}
if !lenz_ge_0 {
return Err(format!(
"Invalid XZBBox::Rect from xz lengths: length z should >=0 , but encountered {length_x}"
));
}
if lenx_overflow {
return Err(format!(
"Invalid XZBBox::Rect from xz lengths: length x too large for i32: {length_x}"
));
}
if lenz_overflow {
return Err(format!(
"Invalid XZBBox::Rect from xz lengths: length z too large for i32: {length_z}"
));
}
Ok(Self::Rect(XZBBoxRect::new(
XZPoint { x: 0, z: 0 },
XZPoint {
x: length_x as i32,
z: length_z as i32,
},
)?))
}
/// Check whether an XZPoint is covered
pub fn contains(&self, xzpoint: &XZPoint) -> bool {
match self {
Self::Rect(r) => r.contains(xzpoint),
}
}
/// Return the circumscribed rectangle of the current XZBBox shape
pub fn bounding_rect(&self) -> XZBBoxRect {
match self {
Self::Rect(r) => *r,
}
}
/// Return the min x in all covered blocks
pub fn min_x(&self) -> i32 {
self.bounding_rect().min().x
}
/// Return the max x in all covered blocks
pub fn max_x(&self) -> i32 {
self.bounding_rect().max().x
}
/// Return the min z in all covered blocks
pub fn min_z(&self) -> i32 {
self.bounding_rect().min().z
}
/// Return the max z in all covered blocks
pub fn max_z(&self) -> i32 {
self.bounding_rect().max().z
}
}
impl fmt::Display for XZBBox {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Rect(r) => write!(f, "XZBBox::{r}"),
}
}
}
// below are associated +- operators
impl Add<XZVector> for XZBBox {
type Output = XZBBox;
fn add(self, other: XZVector) -> XZBBox {
match self {
Self::Rect(r) => Self::Rect(r + other),
}
}
}
impl AddAssign<XZVector> for XZBBox {
fn add_assign(&mut self, other: XZVector) {
match self {
Self::Rect(r) => *r += other,
}
}
}
impl Sub<XZVector> for XZBBox {
type Output = XZBBox;
fn sub(self, other: XZVector) -> XZBBox {
match self {
Self::Rect(r) => Self::Rect(r - other),
}
}
}
impl SubAssign<XZVector> for XZBBox {
fn sub_assign(&mut self, other: XZVector) {
match self {
Self::Rect(r) => *r -= other,
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_valid_inputs() {
// 2 * 2
let obj = XZBBox::rect_from_xz_lengths(1.0, 1.0);
assert!(obj.is_ok());
let obj = obj.unwrap();
assert_eq!(obj.bounding_rect().total_blocks_x(), 2);
assert_eq!(obj.bounding_rect().total_blocks_z(), 2);
assert_eq!(obj.bounding_rect().total_blocks(), 4);
assert_eq!(obj.min_x(), 0);
assert_eq!(obj.max_x(), 1);
assert_eq!(obj.min_z(), 0);
assert_eq!(obj.max_z(), 1);
// edge cases
// 1 * 2
let obj = XZBBox::rect_from_xz_lengths(0.0, 1.0);
assert!(obj.is_ok());
let obj = obj.unwrap();
assert_eq!(obj.bounding_rect().total_blocks_x(), 1);
assert_eq!(obj.bounding_rect().total_blocks_z(), 2);
assert_eq!(obj.bounding_rect().total_blocks(), 2);
assert_eq!(obj.min_x(), 0);
assert_eq!(obj.max_x(), 0);
assert_eq!(obj.min_z(), 0);
assert_eq!(obj.max_z(), 1);
// 2 * 1
let obj = XZBBox::rect_from_xz_lengths(1.0, 0.0);
assert!(obj.is_ok());
let obj = obj.unwrap();
assert_eq!(obj.bounding_rect().total_blocks_x(), 2);
assert_eq!(obj.bounding_rect().total_blocks_z(), 1);
assert_eq!(obj.bounding_rect().total_blocks(), 2);
assert_eq!(obj.min_x(), 0);
assert_eq!(obj.max_x(), 1);
assert_eq!(obj.min_z(), 0);
assert_eq!(obj.max_z(), 0);
// normal case
let obj = XZBBox::rect_from_xz_lengths(123.4, 322.5);
assert!(obj.is_ok());
let obj = obj.unwrap();
assert_eq!(obj.bounding_rect().total_blocks_x(), 124);
assert_eq!(obj.bounding_rect().total_blocks_z(), 323);
assert_eq!(obj.bounding_rect().total_blocks(), 124 * 323);
assert_eq!(obj.min_x(), 0);
assert_eq!(obj.max_x(), 123);
assert_eq!(obj.min_z(), 0);
assert_eq!(obj.max_z(), 322);
}
#[test]
#[allow(clippy::excessive_precision)]
fn test_invalid_inputs() {
assert!(XZBBox::rect_from_xz_lengths(-1.0, 1.5).is_err());
assert!(XZBBox::rect_from_xz_lengths(1323.5, -3287238791.395).is_err());
assert!(XZBBox::rect_from_xz_lengths(-239928341323.29389498, -3287238791.938395).is_err());
assert!(XZBBox::rect_from_xz_lengths(-0.1, 1.5).is_err());
assert!(XZBBox::rect_from_xz_lengths(-0.5, 1.5).is_err());
assert!(XZBBox::rect_from_xz_lengths(123948761293874123.2398, -0.5).is_err());
assert!(XZBBox::rect_from_xz_lengths(i32::MAX as f64 + 10.0, -0.5).is_err());
assert!(XZBBox::rect_from_xz_lengths(0.2, i32::MAX as f64 + 10.0).is_err());
}
}

View File

@@ -0,0 +1,70 @@
use super::xzvector::XZVector;
use serde::Deserialize;
use std::fmt;
use std::ops::{Add, AddAssign, Sub, SubAssign};
#[derive(Debug, Deserialize, Copy, Clone, PartialEq)]
pub struct XZPoint {
pub x: i32,
pub z: i32,
}
impl XZPoint {
pub fn new(x: i32, z: i32) -> Self {
Self { x, z }
}
}
impl fmt::Display for XZPoint {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "XZPoint({}, {})", self.x, self.z)
}
}
// below are associated +- operators
impl Add<XZVector> for XZPoint {
type Output = XZPoint;
fn add(self, other: XZVector) -> XZPoint {
XZPoint {
x: self.x + other.dx,
z: self.z + other.dz,
}
}
}
impl AddAssign<XZVector> for XZPoint {
fn add_assign(&mut self, other: XZVector) {
self.x += other.dx;
self.z += other.dz;
}
}
impl Sub for XZPoint {
type Output = XZVector;
fn sub(self, other: XZPoint) -> XZVector {
XZVector {
dx: self.x - other.x,
dz: self.z - other.z,
}
}
}
impl Sub<XZVector> for XZPoint {
type Output = XZPoint;
fn sub(self, other: XZVector) -> XZPoint {
XZPoint {
x: self.x - other.dx,
z: self.z - other.dz,
}
}
}
impl SubAssign<XZVector> for XZPoint {
fn sub_assign(&mut self, other: XZVector) {
self.x -= other.dx;
self.z -= other.dz;
}
}

View File

@@ -0,0 +1,56 @@
use serde::Deserialize;
use std::fmt;
use std::ops::{Add, AddAssign, Sub, SubAssign};
/// Vector between two points in minecraft xz space.
#[derive(Debug, Deserialize, Copy, Clone, PartialEq)]
pub struct XZVector {
/// Increment in x direction
pub dx: i32,
/// Increment in z direction
pub dz: i32,
}
impl fmt::Display for XZVector {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "XZVector({}, {})", self.dx, self.dz)
}
}
// below are associated +- operators
impl Add for XZVector {
type Output = XZVector;
fn add(self, other: XZVector) -> XZVector {
XZVector {
dx: self.dx + other.dx,
dz: self.dz + other.dz,
}
}
}
impl AddAssign for XZVector {
fn add_assign(&mut self, other: XZVector) {
self.dx += other.dx;
self.dz += other.dz;
}
}
impl Sub for XZVector {
type Output = XZVector;
fn sub(self, other: XZVector) -> XZVector {
XZVector {
dx: self.dx - other.dx,
dz: self.dz - other.dz,
}
}
}
impl SubAssign for XZVector {
fn sub_assign(&mut self, other: XZVector) {
self.dx -= other.dx;
self.dz -= other.dz;
}
}

View File

@@ -0,0 +1,125 @@
use super::llpoint::LLPoint;
/// A checked Bounding Box.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct LLBBox {
/// The "bottom-left" vertex of the rectangle
min: LLPoint,
/// The "top-right" vertex of the rectangle
max: LLPoint,
}
impl LLBBox {
pub fn new(min_lat: f64, min_lng: f64, max_lat: f64, max_lng: f64) -> Result<Self, String> {
if min_lng >= max_lng {
return Err(format!(
"Invalid LLBBox: min_lng {min_lng} >= max_lng {max_lng}"
));
}
if min_lat >= max_lat {
return Err(format!(
"Invalid LLBBox: min_lat {min_lat} >= max_lat {max_lat}"
));
}
let min = LLPoint::new(min_lat, min_lng)?;
let max = LLPoint::new(max_lat, max_lng)?;
Ok(Self { min, max })
}
pub fn from_str(s: &str) -> Result<Self, String> {
let [min_lat, min_lng, max_lat, max_lng]: [f64; 4] = s
.split([',', ' '])
.map(|e| e.parse().unwrap())
.collect::<Vec<_>>()
.try_into()
.unwrap();
// So, the GUI does Lat/Lng and no GDAL (comma-sep values), which is the exact opposite of
// what bboxfinder.com does. :facepalm: (bboxfinder is wrong here: Lat comes first!)
// DO NOT MODIFY THIS! It's correct. The CLI/GUI is passing you the numbers incorrectly.
Self::new(min_lat, min_lng, max_lat, max_lng)
}
pub fn min(&self) -> LLPoint {
self.min
}
pub fn max(&self) -> LLPoint {
self.max
}
pub fn contains(&self, llpoint: &LLPoint) -> bool {
llpoint.lat() >= self.min().lat()
&& llpoint.lat() <= self.max().lat()
&& llpoint.lng() >= self.min().lng()
&& llpoint.lng() <= self.max().lng()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_valid_input() {
assert!(LLBBox::new(0., 0., 1., 1.).is_ok());
assert!(LLBBox::new(1., 2., 3., 4.).is_ok());
// Arnis, Germany
assert!(LLBBox::new(54.627053, 9.927928, 54.634902, 9.937563).is_ok());
// Royal Observatory Greenwich, London, UK
assert!(LLBBox::new(51.470000, -0.015000, 51.480000, 0.015000).is_ok());
// The Bund, Shanghai, China
assert!(LLBBox::new(31.23256, 121.46768, 31.24993, 121.50394).is_ok());
// Santa Monica, Los Angeles, US
assert!(LLBBox::new(34.00348, -118.51226, 34.02033, -118.47600).is_ok());
// Sydney Opera House, Sydney, Australia
assert!(LLBBox::new(-33.861035, 151.204137, -33.852597, 151.222268).is_ok());
}
#[test]
fn test_from_str_commas() {
const ARNIS_STR: &str = "9.927928,54.627053,9.937563,54.634902";
let bbox_result = LLBBox::from_str(ARNIS_STR);
assert!(bbox_result.is_ok());
let arnis_correct: LLBBox = LLBBox {
min: LLPoint::new(9.927928, 54.627053).unwrap(),
max: LLPoint::new(9.937563, 54.634902).unwrap(),
};
assert_eq!(bbox_result.unwrap(), arnis_correct);
}
#[test]
fn test_from_str_spaces() {
const ARNIS_SPACE_STR: &str = "9.927928 54.627053 9.937563 54.634902";
let bbox_result = LLBBox::from_str(ARNIS_SPACE_STR);
assert!(bbox_result.is_ok());
let arnis_correct: LLBBox = LLBBox {
min: LLPoint::new(9.927928, 54.627053).unwrap(),
max: LLPoint::new(9.937563, 54.634902).unwrap(),
};
assert_eq!(bbox_result.unwrap(), arnis_correct);
}
#[test]
fn test_out_of_order() {
// Violates values in vals_in_order
assert!(LLBBox::new(0., 0., 0., 0.).is_err());
assert!(LLBBox::new(1., 0., 0., 1.).is_err());
assert!(LLBBox::new(0., 1., 1., 0.).is_err());
}
}

View File

@@ -0,0 +1,60 @@
/// Bounds-checked longitude and latitude.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct LLPoint {
lat: f64,
lng: f64,
}
impl LLPoint {
pub fn new(lat: f64, lng: f64) -> Result<Self, String> {
let lat_in_range = (-90.0..=90.0).contains(&lat);
let lng_in_range = (-180.0..=180.0).contains(&lng);
if !lat_in_range {
return Err(format!("Latitude {lat} not in range -90.0..=90.0"));
}
if !lng_in_range {
return Err(format!("Longitude {lng} not in range -180.0..=180.0"));
}
Ok(Self { lat, lng })
}
pub fn lat(&self) -> f64 {
self.lat
}
pub fn lng(&self) -> f64 {
self.lng
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_valid_input() {
assert!(LLPoint::new(0., 0.).is_ok());
// latitude extremes
assert!(LLPoint::new(-90.0, 0.).is_ok());
assert!(LLPoint::new(90.0, 0.).is_ok());
// longitude extremes
assert!(LLPoint::new(0., -180.0).is_ok());
assert!(LLPoint::new(0., 180.0).is_ok());
}
#[test]
fn test_out_of_bounds() {
// latitude out-of-bounds
assert!(LLPoint::new(-91., 0.).is_err());
assert!(LLPoint::new(91., 0.).is_err());
// longitude out-of-bounds
assert!(LLPoint::new(0., -181.).is_err());
assert!(LLPoint::new(0., 181.).is_err());
}
}

View File

@@ -0,0 +1,5 @@
mod llbbox;
mod llpoint;
pub use llbbox::LLBBox;
pub use llpoint::LLPoint;

View File

@@ -0,0 +1,3 @@
pub mod cartesian;
pub mod geographic;
pub mod transformation;

View File

@@ -0,0 +1,185 @@
use super::cartesian::{XZBBox, XZPoint};
use super::geographic::{LLBBox, LLPoint};
/// Transform geographic space (within llbbox) to a local tangential cartesian space (within xzbbox)
pub struct CoordTransformer {
len_lat: f64,
len_lng: f64,
scale_factor_x: f64,
scale_factor_z: f64,
min_lat: f64,
min_lng: f64,
}
impl CoordTransformer {
pub fn scale_factor_x(&self) -> f64 {
self.scale_factor_x
}
pub fn scale_factor_z(&self) -> f64 {
self.scale_factor_z
}
pub fn llbbox_to_xzbbox(
llbbox: &LLBBox,
scale: f64,
) -> Result<(CoordTransformer, XZBBox), String> {
let err_header = "Construct LLBBox to XZBBox transformation failed".to_string();
if scale <= 0.0 {
return Err(format!("{}: scale <= 0.0", &err_header));
}
let (scale_factor_z, scale_factor_x) = geo_distance(llbbox.min(), llbbox.max());
let scale_factor_z: f64 = scale_factor_z.floor() * scale;
let scale_factor_x: f64 = scale_factor_x.floor() * scale;
let xzbbox = XZBBox::rect_from_xz_lengths(scale_factor_x, scale_factor_z)
.map_err(|e| format!("{}:\n{}", &err_header, e))?;
Ok((
Self {
len_lat: llbbox.max().lat() - llbbox.min().lat(),
len_lng: llbbox.max().lng() - llbbox.min().lng(),
scale_factor_x,
scale_factor_z,
min_lat: llbbox.min().lat(),
min_lng: llbbox.min().lng(),
},
xzbbox,
))
}
pub fn transform_point(&self, llpoint: LLPoint) -> XZPoint {
// Calculate the relative position within the bounding box
let rel_x: f64 = (llpoint.lng() - self.min_lng) / self.len_lng;
let rel_z: f64 = 1.0 - (llpoint.lat() - self.min_lat) / self.len_lat;
// Apply scaling factors for each dimension and convert to Minecraft coordinates
let x: i32 = (rel_x * self.scale_factor_x) as i32;
let z: i32 = (rel_z * self.scale_factor_z) as i32;
XZPoint::new(x, z)
}
}
// (lat meters, lon meters)
#[inline]
pub fn geo_distance(a: LLPoint, b: LLPoint) -> (f64, f64) {
let z: f64 = lat_distance(a.lat(), b.lat());
// distance between two lons depends on their latitude. In this case we'll just average them
let x: f64 = lon_distance((a.lat() + b.lat()) / 2.0, a.lng(), b.lng());
(z, x)
}
// Haversine but optimized for a latitude delta of 0
// returns meters
fn lon_distance(lat: f64, lon1: f64, lon2: f64) -> f64 {
const R: f64 = 6_371_000.0;
let d_lon: f64 = (lon2 - lon1).to_radians();
let a: f64 =
lat.to_radians().cos() * lat.to_radians().cos() * (d_lon / 2.0).sin() * (d_lon / 2.0).sin();
let c: f64 = 2.0 * a.sqrt().atan2((1.0 - a).sqrt());
R * c
}
// Haversine but optimized for a longitude delta of 0
// returns meters
fn lat_distance(lat1: f64, lat2: f64) -> f64 {
const R: f64 = 6_371_000.0;
let d_lat: f64 = (lat2 - lat1).to_radians();
let a: f64 = (d_lat / 2.0).sin() * (d_lat / 2.0).sin();
let c: f64 = 2.0 * a.sqrt().atan2((1.0 - a).sqrt());
R * c
}
// copied legacy code
// Function to convert latitude and longitude to Minecraft coordinates.
// Function to convert latitude and longitude to Minecraft coordinates.
#[cfg(test)]
pub fn lat_lon_to_minecraft_coords(
lat: f64,
lon: f64,
bbox: LLBBox, // (min_lon, min_lat, max_lon, max_lat)
scale_factor_z: f64,
scale_factor_x: f64,
) -> (i32, i32) {
// Calculate the relative position within the bounding box
let rel_x: f64 = (lon - bbox.min().lng()) / (bbox.max().lng() - bbox.min().lng());
let rel_z: f64 = 1.0 - (lat - bbox.min().lat()) / (bbox.max().lat() - bbox.min().lat());
// Apply scaling factors for each dimension and convert to Minecraft coordinates
let x: i32 = (rel_x * scale_factor_x) as i32;
let z: i32 = (rel_z * scale_factor_z) as i32;
(x, z)
}
#[cfg(test)]
mod test {
use super::*;
use crate::test_utilities::get_llbbox_arnis;
fn test_llxztransform_one_scale_one_factor(
scale: f64,
test_latfactor: f64,
test_lngfactor: f64,
) {
let llbbox = get_llbbox_arnis();
let llpoint = LLPoint::new(
llbbox.min().lat() + (llbbox.max().lat() - llbbox.min().lat()) * test_latfactor,
llbbox.min().lng() + (llbbox.max().lng() - llbbox.min().lng()) * test_lngfactor,
)
.unwrap();
let (transformer, xzbbox_new) = CoordTransformer::llbbox_to_xzbbox(&llbbox, scale).unwrap();
// legacy xzbbox creation
let (scale_factor_z, scale_factor_x) = geo_distance(llbbox.min(), llbbox.max());
let scale_factor_z: f64 = scale_factor_z.floor() * scale;
let scale_factor_x: f64 = scale_factor_x.floor() * scale;
let xzbbox_old = XZBBox::rect_from_xz_lengths(scale_factor_x, scale_factor_z).unwrap();
// legacy coord transform
let (x, z) = lat_lon_to_minecraft_coords(
llpoint.lat(),
llpoint.lng(),
llbbox,
scale_factor_z,
scale_factor_x,
);
// new coord transform
let xzpoint = transformer.transform_point(llpoint);
assert_eq!(x, xzpoint.x);
assert_eq!(z, xzpoint.z);
assert_eq!(xzbbox_new.min_x(), xzbbox_old.min_x());
assert_eq!(xzbbox_new.max_x(), xzbbox_old.max_x());
assert_eq!(xzbbox_new.min_z(), xzbbox_old.min_z());
assert_eq!(xzbbox_new.max_z(), xzbbox_old.max_z());
}
// this ensures that transformer.transform_point == legacy lat_lon_to_minecraft_coords
#[test]
pub fn test_llxztransform() {
test_llxztransform_one_scale_one_factor(1.0, 0.5, 0.5);
test_llxztransform_one_scale_one_factor(3.0, 0.1, 0.2);
test_llxztransform_one_scale_one_factor(10.0, -1.2, 2.0);
test_llxztransform_one_scale_one_factor(0.4, 0.3, -0.2);
test_llxztransform_one_scale_one_factor(0.1, 0.2, 0.7);
}
// this ensures that invalid inputs can be handled correctly
#[test]
pub fn test_invalid_construct() {
let llbbox = get_llbbox_arnis();
let obj = CoordTransformer::llbbox_to_xzbbox(&llbbox, 0.0);
assert!(obj.is_err());
let obj = CoordTransformer::llbbox_to_xzbbox(&llbbox, -1.2);
assert!(obj.is_err());
}
}

View File

@@ -1,32 +1,39 @@
use crate::args::Args;
use crate::block_definitions::{DIRT, GRASS_BLOCK, SNOW_BLOCK};
use crate::cartesian::XZPoint;
use crate::block_definitions::{BEDROCK, DIRT, GRASS_BLOCK, STONE};
use crate::coordinate_system::cartesian::XZBBox;
use crate::coordinate_system::geographic::LLBBox;
use crate::element_processing::*;
use crate::ground::Ground;
use crate::map_renderer;
use crate::osm_parser::ProcessedElement;
use crate::progress::emit_gui_progress_update;
use crate::progress::{emit_gui_progress_update, emit_map_preview_ready};
#[cfg(feature = "gui")]
use crate::telemetry::{send_log, LogLevel};
use crate::world_editor::WorldEditor;
use colored::Colorize;
use indicatif::{ProgressBar, ProgressStyle};
const MIN_Y: i32 = -64;
pub const MIN_Y: i32 = -64;
pub fn generate_world(
elements: Vec<ProcessedElement>,
xzbbox: XZBBox,
llbbox: LLBBox,
ground: Ground,
args: &Args,
scale_factor_x: f64,
scale_factor_z: f64,
) -> Result<(), String> {
let region_dir: String = format!("{}/region", args.path);
let mut editor: WorldEditor = WorldEditor::new(&region_dir, scale_factor_x, scale_factor_z);
let mut editor: WorldEditor = WorldEditor::new(args.path.clone(), &xzbbox, llbbox);
println!("{} Processing data...", "[3/5]".bold());
if args.terrain {
emit_gui_progress_update(10.0, "Fetching elevation...");
}
let ground: Ground = Ground::new(args);
println!("{} Processing data...", "[4/7]".bold());
emit_gui_progress_update(11.0, "Processing terrain...");
// Build highway connectivity map once before processing
let highway_connectivity = highways::build_highway_connectivity_map(&elements);
// Set ground reference in the editor to enable elevation-aware block placement
editor.set_ground(&ground);
println!("{} Processing terrain...", "[5/7]".bold());
emit_gui_progress_update(25.0, "Processing terrain...");
// Process data
let elements_count: usize = elements.len();
@@ -36,8 +43,8 @@ pub fn generate_world(
.unwrap()
.progress_chars("█▓░"));
let progress_increment_prcs: f64 = 49.0 / elements_count as f64;
let mut current_progress_prcs: f64 = 11.0;
let progress_increment_prcs: f64 = 45.0 / elements_count as f64;
let mut current_progress_prcs: f64 = 25.0;
let mut last_emitted_progress: f64 = current_progress_prcs;
for element in &elements {
@@ -61,56 +68,83 @@ pub fn generate_world(
match element {
ProcessedElement::Way(way) => {
if way.tags.contains_key("building") || way.tags.contains_key("building:part") {
buildings::generate_buildings(&mut editor, way, &ground, args, None);
buildings::generate_buildings(&mut editor, way, args, None);
} else if way.tags.contains_key("highway") {
highways::generate_highways(&mut editor, element, &ground, args);
highways::generate_highways(&mut editor, element, args, &highway_connectivity);
} else if way.tags.contains_key("landuse") {
landuse::generate_landuse(&mut editor, way, &ground, args);
landuse::generate_landuse(&mut editor, way, args);
} else if way.tags.contains_key("natural") {
natural::generate_natural(&mut editor, element, &ground, args);
natural::generate_natural(&mut editor, element, args);
} else if way.tags.contains_key("amenity") {
amenities::generate_amenities(&mut editor, element, &ground, args);
amenities::generate_amenities(&mut editor, element, args);
} else if way.tags.contains_key("leisure") {
leisure::generate_leisure(&mut editor, way, &ground, args);
leisure::generate_leisure(&mut editor, way, args);
} else if way.tags.contains_key("barrier") {
barriers::generate_barriers(&mut editor, element, &ground);
} else if way.tags.contains_key("waterway") {
waterways::generate_waterways(&mut editor, way, &ground);
barriers::generate_barriers(&mut editor, element);
} else if let Some(val) = way.tags.get("waterway") {
if val == "dock" {
// docks count as water areas
water_areas::generate_water_area_from_way(&mut editor, way, &xzbbox);
} else {
waterways::generate_waterways(&mut editor, way);
}
} else if way.tags.contains_key("bridge") {
//bridges::generate_bridges(&mut editor, way, ground_level); // TODO FIX
} else if way.tags.contains_key("railway") {
railways::generate_railways(&mut editor, way, &ground);
railways::generate_railways(&mut editor, way);
} else if way.tags.contains_key("roller_coaster") {
railways::generate_roller_coaster(&mut editor, way);
} else if way.tags.contains_key("aeroway") || way.tags.contains_key("area:aeroway")
{
highways::generate_aeroway(&mut editor, way, &ground);
highways::generate_aeroway(&mut editor, way, args);
} else if way.tags.get("service") == Some(&"siding".to_string()) {
highways::generate_siding(&mut editor, way, &ground);
highways::generate_siding(&mut editor, way);
} else if way.tags.contains_key("man_made") {
man_made::generate_man_made(&mut editor, element, args);
}
}
ProcessedElement::Node(node) => {
if node.tags.contains_key("door") || node.tags.contains_key("entrance") {
doors::generate_doors(&mut editor, node, &ground);
doors::generate_doors(&mut editor, node);
} else if node.tags.contains_key("natural")
&& node.tags.get("natural") == Some(&"tree".to_string())
{
natural::generate_natural(&mut editor, element, &ground, args);
natural::generate_natural(&mut editor, element, args);
} else if node.tags.contains_key("amenity") {
amenities::generate_amenities(&mut editor, element, &ground, args);
amenities::generate_amenities(&mut editor, element, args);
} else if node.tags.contains_key("barrier") {
barriers::generate_barriers(&mut editor, element, &ground);
barriers::generate_barrier_nodes(&mut editor, node);
} else if node.tags.contains_key("highway") {
highways::generate_highways(&mut editor, element, &ground, args);
highways::generate_highways(&mut editor, element, args, &highway_connectivity);
} else if node.tags.contains_key("tourism") {
tourisms::generate_tourisms(&mut editor, node, &ground);
tourisms::generate_tourisms(&mut editor, node);
} else if node.tags.contains_key("man_made") {
man_made::generate_man_made_nodes(&mut editor, node);
}
}
ProcessedElement::Relation(rel) => {
if rel.tags.contains_key("building") || rel.tags.contains_key("building:part") {
buildings::generate_building_from_relation(&mut editor, rel, &ground, args);
} else if rel.tags.contains_key("water") {
water_areas::generate_water_areas(&mut editor, rel, &ground);
buildings::generate_building_from_relation(&mut editor, rel, args);
} else if rel.tags.contains_key("water")
|| rel
.tags
.get("natural")
.map(|val| val == "water" || val == "bay")
.unwrap_or(false)
{
water_areas::generate_water_areas_from_relation(&mut editor, rel, &xzbbox);
} else if rel.tags.contains_key("natural") {
natural::generate_natural_from_relation(&mut editor, rel, args);
} else if rel.tags.contains_key("landuse") {
landuse::generate_landuse_from_relation(&mut editor, rel, args);
} else if rel.tags.get("leisure") == Some(&"park".to_string()) {
leisure::generate_leisure_from_relation(&mut editor, rel, &ground, args);
leisure::generate_leisure_from_relation(&mut editor, rel, args);
} else if rel.tags.contains_key("man_made") {
man_made::generate_man_made(
&mut editor,
&ProcessedElement::Relation(rel.clone()),
args,
);
}
}
}
@@ -119,14 +153,14 @@ pub fn generate_world(
process_pb.finish();
// Generate ground layer
let total_blocks: u64 = (scale_factor_x as i32 + 1) as u64 * (scale_factor_z as i32 + 1) as u64;
let total_blocks: u64 = xzbbox.bounding_rect().total_blocks();
let desired_updates: u64 = 1500;
let batch_size: u64 = (total_blocks / desired_updates).max(1);
let mut block_counter: u64 = 0;
println!("{} Generating ground...", "[4/5]".bold());
emit_gui_progress_update(60.0, "Generating ground...");
println!("{} Generating ground...", "[6/7]".bold());
emit_gui_progress_update(70.0, "Generating ground...");
let ground_pb: ProgressBar = ProgressBar::new(total_blocks);
ground_pb.set_style(
@@ -136,77 +170,51 @@ pub fn generate_world(
.progress_chars("█▓░"),
);
let mut gui_progress_grnd: f64 = 60.0;
let mut gui_progress_grnd: f64 = 70.0;
let mut last_emitted_progress: f64 = gui_progress_grnd;
let total_iterations_grnd: f64 = (scale_factor_x + 1.0) * (scale_factor_z + 1.0);
let progress_increment_grnd: f64 = 30.0 / total_iterations_grnd;
let total_iterations_grnd: f64 = total_blocks as f64;
let progress_increment_grnd: f64 = 20.0 / total_iterations_grnd;
let groundlayer_block = if args.winter { SNOW_BLOCK } else { GRASS_BLOCK };
let groundlayer_block = GRASS_BLOCK;
// Differentiate between terrain and non-terrain generation
if ground.elevation_enabled {
// Pre-calculate ground levels for all points
let mut ground_levels: Vec<Vec<i32>> = Vec::with_capacity(scale_factor_x as usize + 1);
for x in 0..=(scale_factor_x as i32) {
let mut row = Vec::with_capacity(scale_factor_z as usize + 1);
for z in 0..=(scale_factor_z as i32) {
row.push(ground.level(XZPoint::new(x, z)));
for x in xzbbox.min_x()..=xzbbox.max_x() {
for z in xzbbox.min_z()..=xzbbox.max_z() {
// Add default dirt and grass layer if there isn't a stone layer already
if !editor.check_for_block(x, 0, z, Some(&[STONE])) {
editor.set_block(groundlayer_block, x, 0, z, None, None);
editor.set_block(DIRT, x, -1, z, None, None);
editor.set_block(DIRT, x, -2, z, None, None);
}
ground_levels.push(row);
}
// Process blocks in larger batches
for x in 0..=(scale_factor_x as i32) {
for z in 0..=(scale_factor_z as i32) {
let ground_level = ground_levels[x as usize][z as usize];
// Find the highest block in this column
let max_y = (MIN_Y..ground_level)
.find(|y: &i32| editor.block_at(x, *y, z))
.unwrap_or(ground_level)
.min(ground_level);
// Set blocks in a single batch
editor.set_block(groundlayer_block, x, max_y, z, None, None);
editor.set_block(DIRT, x, max_y - 1, z, None, None);
editor.set_block(DIRT, x, max_y - 2, z, None, None);
block_counter += 1;
if block_counter % batch_size == 0 {
ground_pb.inc(batch_size);
}
gui_progress_grnd += progress_increment_grnd;
if (gui_progress_grnd - last_emitted_progress).abs() > 0.25 {
emit_gui_progress_update(gui_progress_grnd, "");
last_emitted_progress = gui_progress_grnd;
}
// Fill underground with stone
if args.fillground {
// Fill from bedrock+1 to 3 blocks below ground with stone
editor.fill_blocks_absolute(
STONE,
x,
MIN_Y + 1,
z,
x,
editor.get_absolute_y(x, -3, z),
z,
None,
None,
);
}
}
// Generate a bedrock level at MIN_Y
editor.set_block_absolute(BEDROCK, x, MIN_Y, z, None, Some(&[BEDROCK]));
// Set blocks at spawn location
for x in 0..=20 {
for z in 0..=20 {
editor.set_block(groundlayer_block, x, -62, z, None, None);
block_counter += 1;
// Use manual % check since is_multiple_of() is unstable on stable Rust
#[allow(clippy::manual_is_multiple_of)]
if block_counter % batch_size == 0 {
ground_pb.inc(batch_size);
}
}
} else {
for x in 0..=(scale_factor_x as i32) {
for z in 0..=(scale_factor_z as i32) {
let ground_level = ground.level(XZPoint::new(x, z));
editor.set_block(groundlayer_block, x, ground_level, z, None, None);
editor.set_block(DIRT, x, ground_level - 1, z, None, None);
block_counter += 1;
if block_counter % batch_size == 0 {
ground_pb.inc(batch_size);
}
gui_progress_grnd += progress_increment_grnd;
if (gui_progress_grnd - last_emitted_progress).abs() > 0.25 {
emit_gui_progress_update(gui_progress_grnd, "");
last_emitted_progress = gui_progress_grnd;
}
gui_progress_grnd += progress_increment_grnd;
if (gui_progress_grnd - last_emitted_progress).abs() > 0.25 {
emit_gui_progress_update(gui_progress_grnd, "");
last_emitted_progress = gui_progress_grnd;
}
}
}
@@ -229,7 +237,83 @@ pub fn generate_world(
// Save world
editor.save();
// Update player spawn Y coordinate based on terrain height after generation
#[cfg(feature = "gui")]
if let Some(spawn_coords) = &args.spawn_point {
use crate::gui::update_player_spawn_y_after_generation;
let bbox_string = format!(
"{},{},{},{}",
args.bbox.min().lng(),
args.bbox.min().lat(),
args.bbox.max().lng(),
args.bbox.max().lat()
);
if let Err(e) = update_player_spawn_y_after_generation(
&args.path,
Some(*spawn_coords),
bbox_string,
args.scale,
&ground,
) {
let warning_msg = format!("Failed to update spawn point Y coordinate: {}", e);
eprintln!("Warning: {}", warning_msg);
#[cfg(feature = "gui")]
send_log(LogLevel::Warning, &warning_msg);
}
}
emit_gui_progress_update(100.0, "Done! World generation completed.");
println!("{}", "Done! World generation completed.".green().bold());
// Generate top-down map preview:
// - Always for GUI mode (non-blocking, runs in background)
// - Only when --generate-map flag is set for CLI mode (blocking, waits for completion)
#[cfg(feature = "gui")]
let should_generate_map = true;
#[cfg(not(feature = "gui"))]
let should_generate_map = args.generate_map;
if should_generate_map {
let world_path = args.path.clone();
let bounds = (
xzbbox.min_x(),
xzbbox.max_x(),
xzbbox.min_z(),
xzbbox.max_z(),
);
let map_thread = std::thread::spawn(move || {
// Use catch_unwind to prevent any panic from affecting the application
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
map_renderer::render_world_map(&world_path, bounds.0, bounds.1, bounds.2, bounds.3)
}));
match result {
Ok(Ok(_path)) => {
// Notify the GUI that the map preview is ready
emit_map_preview_ready();
}
Ok(Err(e)) => {
eprintln!("Warning: Failed to generate map preview: {}", e);
}
Err(_) => {
eprintln!("Warning: Map preview generation panicked unexpectedly");
}
}
});
// In CLI mode, wait for map generation to complete before exiting
// In GUI mode, let it run in background to keep UI responsive
#[cfg(not(feature = "gui"))]
{
let _ = map_thread.join();
}
// In GUI mode, we don't join, let the thread run in background
#[cfg(feature = "gui")]
drop(map_thread);
}
Ok(())
}

View File

@@ -1,18 +1,12 @@
use crate::args::Args;
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::cartesian::XZPoint;
use crate::coordinate_system::cartesian::XZPoint;
use crate::floodfill::flood_fill_area;
use crate::ground::Ground;
use crate::osm_parser::ProcessedElement;
use crate::world_editor::WorldEditor;
pub fn generate_amenities(
editor: &mut WorldEditor,
element: &ProcessedElement,
ground: &Ground,
args: &Args,
) {
pub fn generate_amenities(editor: &mut WorldEditor, element: &ProcessedElement, args: &Args) {
// Skip if 'layer' or 'level' is negative in the tags
if let Some(layer) = element.tags().get("layer") {
if layer.parse::<i32>().unwrap_or(0) < 0 {
@@ -35,15 +29,13 @@ pub fn generate_amenities(
"waste_disposal" | "waste_basket" => {
// Place a cauldron for waste disposal or waste basket
if let Some(pt) = first_node {
editor.set_block(CAULDRON, pt.x, ground.level(pt) + 1, pt.z, None, None);
editor.set_block(CAULDRON, pt.x, 1, pt.z, None, None);
}
}
"vending_machine" | "atm" => {
if let Some(pt) = first_node {
let y = ground.level(pt);
editor.set_block(IRON_BLOCK, pt.x, y + 1, pt.z, None, None);
editor.set_block(IRON_BLOCK, pt.x, y + 2, pt.z, None, None);
editor.set_block(IRON_BLOCK, pt.x, 1, pt.z, None, None);
editor.set_block(IRON_BLOCK, pt.x, 2, pt.z, None, None);
}
}
"bicycle_parking" => {
@@ -54,61 +46,50 @@ pub fn generate_amenities(
.nodes()
.map(|n: &crate::osm_parser::ProcessedNode| (n.x, n.z))
.collect();
let floor_area: Vec<(i32, i32)> =
flood_fill_area(&polygon_coords, args.timeout.as_ref());
let pts: Vec<_> = floor_area.iter().map(|c| XZPoint::new(c.0, c.1)).collect();
if pts.is_empty() {
if polygon_coords.is_empty() {
return;
}
let y_min = ground.min_level(pts.iter().cloned()).unwrap();
let roof_y = ground.max_level(pts.iter().cloned()).unwrap() + 5;
let floor_area: Vec<(i32, i32)> =
flood_fill_area(&polygon_coords, args.timeout.as_ref());
// Fill the floor area
for (x, z) in floor_area.iter() {
editor.set_block(ground_block, *x, y_min, *z, None, None);
editor.set_block(ground_block, *x, 0, *z, None, None);
}
// Place fences and roof slabs at each corner node directly
// Place fences and roof slabs at each corner node
for node in element.nodes() {
let x: i32 = node.x;
let z: i32 = node.z;
let pt = XZPoint::new(x, z);
let y = ground.level(pt);
editor.set_block(ground_block, x, y, z, None, None);
for cur_y in (y_min + 1)..roof_y {
editor.set_block(OAK_FENCE, x, cur_y, z, None, None);
// Set ground block and fences
editor.set_block(ground_block, x, 0, z, None, None);
for y in 1..=4 {
editor.set_block(OAK_FENCE, x, y, z, None, None);
}
editor.set_block(roof_block, x, roof_y, z, None, None);
editor.set_block(roof_block, x, 5, z, None, None);
}
// Flood fill the roof area
for (x, z) in floor_area.iter() {
editor.set_block(roof_block, *x, roof_y, *z, None, None);
editor.set_block(roof_block, *x, 5, *z, None, None);
}
}
"bench" => {
// Place a bench
if let Some(pt) = first_node {
let y = ground.level(pt) + 1;
editor.set_block(SMOOTH_STONE, pt.x, y, pt.z, None, None);
editor.set_block(OAK_LOG, pt.x + 1, y, pt.z, None, None);
editor.set_block(OAK_LOG, pt.x - 1, y, pt.z, None, None);
}
}
"vending" => {
// Place vending machine blocks
if let Some(pt) = first_node {
let y = ground.level(pt);
editor.set_block(IRON_BLOCK, pt.x, y + 1, pt.z, None, None);
editor.set_block(IRON_BLOCK, pt.x, y + 2, pt.z, None, None);
// 50% chance to 90 degrees rotate the bench using if
if rand::random::<bool>() {
editor.set_block(SMOOTH_STONE, pt.x, 1, pt.z, None, None);
editor.set_block(OAK_LOG, pt.x + 1, 1, pt.z, None, None);
editor.set_block(OAK_LOG, pt.x - 1, 1, pt.z, None, None);
} else {
editor.set_block(SMOOTH_STONE, pt.x, 1, pt.z, None, None);
editor.set_block(OAK_LOG, pt.x, 1, pt.z + 1, None, None);
editor.set_block(OAK_LOG, pt.x, 1, pt.z - 1, None, None);
}
}
}
"shelter" => {
@@ -126,24 +107,15 @@ pub fn generate_amenities(
let x: i32 = node.x;
let z: i32 = node.z;
let Some(y) = ground.min_level(element.nodes().map(|n| n.xz())) else {
return;
};
for fence_height in 1..=4 {
editor.set_block(OAK_FENCE, x, y + fence_height, z, None, None);
editor.set_block(OAK_FENCE, x, fence_height, z, None, None);
}
editor.set_block(roof_block, x, y + 5, z, None, None);
editor.set_block(roof_block, x, 5, z, None, None);
}
// Flood fill the roof area
let Some(y) = ground.min_level(element.nodes().map(|n| n.xz())) else {
return;
};
let roof_height: i32 = y + 5;
for (x, z) in roof_area.iter() {
editor.set_block(roof_block, *x, roof_height, *z, None, None);
editor.set_block(roof_block, *x, 5, *z, None, None);
}
}
"parking" | "fountain" => {
@@ -160,15 +132,13 @@ pub fn generate_amenities(
for node in element.nodes() {
let pt: XZPoint = node.xz();
let y = ground.level(pt);
if let Some(prev) = previous_node {
// Create borders for fountain or parking area
let prev_y = ground.level(prev);
let bresenham_points: Vec<(i32, i32, i32)> =
bresenham_line(prev.x, prev_y, prev.z, pt.x, y, pt.z);
for (bx, by, bz) in bresenham_points {
editor.set_block(block_type, bx, by, bz, Some(&[BLACK_CONCRETE]), None);
bresenham_line(prev.x, 0, prev.z, pt.x, 0, pt.z);
for (bx, _, bz) in bresenham_points {
editor.set_block(block_type, bx, 0, bz, Some(&[BLACK_CONCRETE]), None);
// Decorative border around fountains
if amenity_type == "fountain" {
@@ -178,7 +148,7 @@ pub fn generate_amenities(
editor.set_block(
LIGHT_GRAY_CONCRETE,
bx + dx,
by,
0,
bz + dz,
None,
None,
@@ -204,27 +174,84 @@ pub fn generate_amenities(
flood_fill_area(&polygon_coords, args.timeout.as_ref());
for (x, z) in flood_area {
let pt = XZPoint::new(x, z);
let y = ground.level(pt);
editor.set_block(
block_type,
x,
y,
0,
z,
Some(&[BLACK_CONCRETE, GRAY_CONCRETE]),
None,
);
// Add parking spot markings
if amenity_type == "parking" && (x + z) % 8 == 0 && (x * z) % 32 != 0 {
editor.set_block(
LIGHT_GRAY_CONCRETE,
x,
y,
z,
Some(&[BLACK_CONCRETE, GRAY_CONCRETE]),
None,
);
// Enhanced parking space markings
if amenity_type == "parking" {
// Create defined parking spaces with realistic layout
let space_width = 4; // Width of each parking space
let space_length = 6; // Length of each parking space
let lane_width = 5; // Width of driving lanes
// Calculate which "zone" this coordinate falls into
let zone_x = x / space_width;
let zone_z = z / (space_length + lane_width);
let local_x = x % space_width;
let local_z = z % (space_length + lane_width);
// Create parking space boundaries (only within parking areas, not in driving lanes)
if local_z < space_length {
// We're in a parking space area, not in the driving lane
if local_x == 0 {
// Vertical parking space lines (only on the left edge)
editor.set_block(
LIGHT_GRAY_CONCRETE,
x,
0,
z,
Some(&[BLACK_CONCRETE, GRAY_CONCRETE]),
None,
);
} else if local_z == 0 {
// Horizontal parking space lines (only on the top edge)
editor.set_block(
LIGHT_GRAY_CONCRETE,
x,
0,
z,
Some(&[BLACK_CONCRETE, GRAY_CONCRETE]),
None,
);
}
} else if local_z == space_length {
// Bottom edge of parking spaces (border with driving lane)
editor.set_block(
LIGHT_GRAY_CONCRETE,
x,
0,
z,
Some(&[BLACK_CONCRETE, GRAY_CONCRETE]),
None,
);
} else if local_z > space_length && local_z < space_length + lane_width
{
// Driving lane - use darker concrete
editor.set_block(
BLACK_CONCRETE,
x,
0,
z,
Some(&[GRAY_CONCRETE]),
None,
);
}
// Add light posts at parking space outline corners
if local_x == 0 && local_z == 0 && zone_x % 3 == 0 && zone_z % 2 == 0 {
// Light posts at regular intervals on parking space corners
editor.set_block(COBBLESTONE_WALL, x, 1, z, None, None);
for dy in 2..=4 {
editor.set_block(OAK_FENCE, x, dy, z, None, None);
}
editor.set_block(GLOWSTONE, x, 5, z, None, None);
}
}
}
}

View File

@@ -1,29 +1,17 @@
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::cartesian::XZPoint;
use crate::ground::Ground;
use crate::osm_parser::ProcessedElement;
use crate::osm_parser::{ProcessedElement, ProcessedNode};
use crate::world_editor::WorldEditor;
pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement, ground: &Ground) {
pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement) {
// Default values
let mut barrier_material: Block = COBBLESTONE_WALL;
let mut barrier_height: i32 = 2;
match element.tags().get("barrier").map(|s| s.as_str()) {
Some("bollard") => {
if let ProcessedElement::Node(node) = element {
editor.set_block(
COBBLESTONE_WALL,
node.x,
ground.level(node.xz()) + 1,
node.z,
None,
None,
);
// Place bollard
}
return;
barrier_material = COBBLESTONE_WALL;
barrier_height = 1;
}
Some("kerb") => {
// Ignore kerbs
@@ -40,8 +28,11 @@ pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement, g
barrier_material = STONE_BRICK_WALL;
barrier_height = 1;
}
Some("chain_link" | "metal" | "wire" | "barbed_wire" | "corrugated_metal") => {
barrier_material = STONE_BRICK_WALL;
Some(
"chain_link" | "metal" | "wire" | "barbed_wire" | "corrugated_metal"
| "electric" | "metal_bars",
) => {
barrier_material = STONE_BRICK_WALL; // IRON_BARS
barrier_height = 2;
}
Some("slatted" | "paling") => {
@@ -52,8 +43,8 @@ pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement, g
barrier_material = OAK_FENCE;
barrier_height = 2;
}
Some("concrete") => {
barrier_material = ANDESITE_WALL;
Some("concrete" | "stone") => {
barrier_material = STONE_BRICK_WALL;
barrier_height = 2;
}
Some("glass") => {
@@ -63,6 +54,10 @@ pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement, g
_ => {}
}
}
Some("wall") => {
barrier_material = STONE_BRICK_WALL;
barrier_height = 3;
}
_ => {}
}
// Tagged material takes priority over inferred
@@ -70,6 +65,12 @@ pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement, g
if barrier_mat == "brick" {
barrier_material = BRICK;
}
if barrier_mat == "concrete" {
barrier_material = LIGHT_GRAY_CONCRETE;
}
if barrier_mat == "metal" {
barrier_material = STONE_BRICK_WALL; // IRON_BARS
}
}
if let ProcessedElement::Way(way) = element {
@@ -78,7 +79,7 @@ pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement, g
.tags()
.get("height")
.and_then(|height: &String| height.parse::<f32>().ok())
.map(|height: f32| f32::min(3.0, height).round() as i32)
.map(|height: f32| height.round() as i32)
.unwrap_or(barrier_height);
// Process nodes to create the barrier wall
@@ -96,24 +97,75 @@ pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement, g
for (bx, _, bz) in bresenham_points {
// Build the barrier wall to the specified height
let ground_level = ground.level(XZPoint::new(bx, bz));
for y in (ground_level + 1)..=(ground_level + wall_height) {
for y in 1..=wall_height {
editor.set_block(barrier_material, bx, y, bz, None, None);
// Barrier wall
}
// Add an optional top to the barrier if the height is more than 1
if wall_height > 1 {
editor.set_block(
STONE_BRICK_SLAB,
bx,
ground_level + wall_height + 1,
bz,
None,
None,
); // Top of the barrier
editor.set_block(STONE_BRICK_SLAB, bx, wall_height + 1, bz, None, None);
}
}
}
}
}
pub fn generate_barrier_nodes(editor: &mut WorldEditor<'_>, node: &ProcessedNode) {
match node.tags.get("barrier").map(|s| s.as_str()) {
Some("bollard") => {
editor.set_block(COBBLESTONE_WALL, node.x, 1, node.z, None, None);
}
Some("stile" | "gate" | "swing_gate" | "lift_gate") => {
/*editor.set_block(
OAK_TRAPDOOR,
node.x,
1,
node.z,
Some(&[
COBBLESTONE_WALL,
OAK_FENCE,
STONE_BRICK_WALL,
OAK_LEAVES,
STONE_BRICK_SLAB,
]),
None,
);
editor.set_block(
AIR,
node.x,
2,
node.z,
Some(&[
COBBLESTONE_WALL,
OAK_FENCE,
STONE_BRICK_WALL,
OAK_LEAVES,
STONE_BRICK_SLAB,
]),
None,
);
editor.set_block(
AIR,
node.x,
3,
node.z,
Some(&[
COBBLESTONE_WALL,
OAK_FENCE,
STONE_BRICK_WALL,
OAK_LEAVES,
STONE_BRICK_SLAB,
]),
None,
);*/
}
Some("block") => {
editor.set_block(STONE, node.x, 1, node.z, None, None);
}
Some("entrance") => {
editor.set_block(AIR, node.x, 1, node.z, None, None);
}
None => {}
_ => {}
}
}

View File

@@ -1,19 +1,18 @@
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
//use crate::ground::Ground;
use crate::osm_parser::ProcessedWay;
use crate::world_editor::WorldEditor;
// TODO FIX
#[allow(dead_code)]
pub fn generate_bridges(editor: &mut WorldEditor, element: &ProcessedWay, ground_level: i32) {
pub fn generate_bridges(editor: &mut WorldEditor, element: &ProcessedWay) {
if let Some(_bridge_type) = element.tags.get("bridge") {
let bridge_height = 3; // Fixed height
for i in 1..element.nodes.len() {
let prev = &element.nodes[i - 1];
let cur = &element.nodes[i];
let points = bresenham_line(prev.x, ground_level, prev.z, cur.x, ground_level, cur.z);
let points = bresenham_line(prev.x, 0, prev.z, cur.x, 0, cur.z);
let total_length = points.len();
let ramp_length = 6; // Length of ramp at each end
@@ -30,11 +29,9 @@ pub fn generate_bridges(editor: &mut WorldEditor, element: &ProcessedWay, ground
bridge_height
};
let bridge_y = ground_level + height as i32;
// Place bridge blocks
for dx in -2..=2 {
editor.set_block(LIGHT_GRAY_CONCRETE, *x + dx, bridge_y, *z, None, None);
editor.set_block(LIGHT_GRAY_CONCRETE, *x + dx, height as i32, *z, None, None);
}
}
}

View File

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,8 @@
use crate::block_definitions::*;
use crate::cartesian::XZPoint;
use crate::ground::Ground;
use crate::osm_parser::ProcessedNode;
use crate::world_editor::WorldEditor;
pub fn generate_doors(editor: &mut WorldEditor, element: &ProcessedNode, ground: &Ground) {
pub fn generate_doors(editor: &mut WorldEditor, element: &ProcessedNode) {
// Check if the element is a door or entrance
if element.tags.contains_key("door") || element.tags.contains_key("entrance") {
// Check for the "level" tag and skip doors that are not at ground level
@@ -19,12 +17,9 @@ pub fn generate_doors(editor: &mut WorldEditor, element: &ProcessedNode, ground:
let x: i32 = element.x;
let z: i32 = element.z;
// Calculate the dynamic ground level
let ground_level = ground.level(XZPoint::new(x, z));
// Set the ground block and the door blocks
editor.set_block(GRAY_CONCRETE, x, ground_level, z, None, None);
editor.set_block(DARK_OAK_DOOR_LOWER, x, ground_level + 1, z, None, None);
editor.set_block(DARK_OAK_DOOR_UPPER, x, ground_level + 2, z, None, None);
editor.set_block(GRAY_CONCRETE, x, 0, z, None, None);
editor.set_block(DARK_OAK_DOOR_LOWER, x, 1, z, None, None);
editor.set_block(DARK_OAK_DOOR_UPPER, x, 2, z, None, None);
}
}

View File

@@ -1,29 +1,83 @@
use crate::args::Args;
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::cartesian::XZPoint;
use crate::coordinate_system::cartesian::XZPoint;
use crate::floodfill::flood_fill_area;
use crate::ground::Ground;
use crate::osm_parser::{ProcessedElement, ProcessedWay};
use crate::world_editor::WorldEditor;
use std::collections::HashMap;
/// Type alias for highway connectivity map
pub type HighwayConnectivityMap = HashMap<(i32, i32), Vec<i32>>;
/// Generates highways with elevation support based on layer tags and connectivity analysis
pub fn generate_highways(
editor: &mut WorldEditor,
element: &ProcessedElement,
ground: &Ground,
args: &Args,
highway_connectivity: &HighwayConnectivityMap,
) {
generate_highways_internal(editor, element, args, highway_connectivity);
}
/// Build a connectivity map for highway endpoints to determine where slopes are needed.
pub fn build_highway_connectivity_map(elements: &[ProcessedElement]) -> HighwayConnectivityMap {
let mut connectivity_map: HashMap<(i32, i32), Vec<i32>> = HashMap::new();
for element in elements {
if let ProcessedElement::Way(way) = element {
if way.tags.contains_key("highway") {
let layer_value = way
.tags
.get("layer")
.and_then(|layer| layer.parse::<i32>().ok())
.unwrap_or(0);
// Treat negative layers as ground level (0) for connectivity
let layer_value = if layer_value < 0 { 0 } else { layer_value };
// Add connectivity for start and end nodes
if !way.nodes.is_empty() {
let start_node = &way.nodes[0];
let end_node = &way.nodes[way.nodes.len() - 1];
let start_coord = (start_node.x, start_node.z);
let end_coord = (end_node.x, end_node.z);
connectivity_map
.entry(start_coord)
.or_default()
.push(layer_value);
connectivity_map
.entry(end_coord)
.or_default()
.push(layer_value);
}
}
}
}
connectivity_map
}
/// Internal function that generates highways with connectivity context for elevation handling
fn generate_highways_internal(
editor: &mut WorldEditor,
element: &ProcessedElement,
args: &Args,
highway_connectivity: &HashMap<(i32, i32), Vec<i32>>, // Maps node coordinates to list of layers that connect to this node
) {
if let Some(highway_type) = element.tags().get("highway") {
if highway_type == "street_lamp" {
// Handle street lamps
if let ProcessedElement::Node(first_node) = element {
let x: i32 = first_node.x;
let y: i32 = ground.level(first_node.xz());
let z: i32 = first_node.z;
for dy in 1..=4 {
editor.set_block(OAK_FENCE, x, y + dy, z, None, None);
editor.set_block(COBBLESTONE_WALL, x, 1, z, None, None);
for dy in 2..=4 {
editor.set_block(OAK_FENCE, x, dy, z, None, None);
}
editor.set_block(GLOWSTONE, x, y + 5, z, None, None);
editor.set_block(GLOWSTONE, x, 5, z, None, None);
}
} else if highway_type == "crossing" {
// Handle traffic signals for crossings
@@ -31,20 +85,15 @@ pub fn generate_highways(
if crossing_type == "traffic_signals" {
if let ProcessedElement::Node(node) = element {
let x: i32 = node.x;
let y: i32 = ground.level(node.xz());
let z: i32 = node.z;
for dy in 1..=3 {
editor.set_block(COBBLESTONE_WALL, x, y + dy, z, None, None);
editor.set_block(COBBLESTONE_WALL, x, dy, z, None, None);
}
editor.set_block(GREEN_WOOL, x, y + 4, z, None, None);
editor.set_block(YELLOW_WOOL, x, y + 5, z, None, None);
editor.set_block(RED_WOOL, x, y + 6, z, None, None);
if args.winter {
editor.set_block(SNOW_LAYER, x, y + 7, z, None, None);
}
editor.set_block(GREEN_WOOL, x, 4, z, None, None);
editor.set_block(YELLOW_WOOL, x, 5, z, None, None);
editor.set_block(RED_WOOL, x, 6, z, None, None);
}
}
}
@@ -52,14 +101,13 @@ pub fn generate_highways(
// Handle bus stops
if let ProcessedElement::Node(node) = element {
let x = node.x;
let y = ground.level(node.xz());
let z = node.z;
for dy in 1..=3 {
editor.set_block(COBBLESTONE_WALL, x, y + dy, z, None, None);
editor.set_block(COBBLESTONE_WALL, x, dy, z, None, None);
}
editor.set_block(WHITE_WOOL, x, y + 4, z, None, None);
editor.set_block(WHITE_WOOL, x + 1, y + 4, z, None, None);
editor.set_block(WHITE_WOOL, x, 4, z, None, None);
editor.set_block(WHITE_WOOL, x + 1, 4, z, None, None);
}
} else if element
.tags()
@@ -81,14 +129,8 @@ pub fn generate_highways(
"wood" => OAK_PLANKS,
"asphalt" => BLACK_CONCRETE,
"gravel" | "fine_gravel" => GRAVEL,
"grass" => {
if args.winter {
SNOW_BLOCK
} else {
GRASS_BLOCK
}
}
"dirt" => DIRT,
"grass" => GRASS_BLOCK,
"dirt" | "ground" | "earth" => DIRT,
"sand" => SAND,
"concrete" => LIGHT_GRAY_CONCRETE,
_ => STONE, // Default to stone for unknown surfaces
@@ -105,28 +147,27 @@ pub fn generate_highways(
flood_fill_area(&polygon_coords, args.timeout.as_ref());
for (x, z) in filled_area {
editor.set_block(
surface_block,
x,
ground.level(XZPoint::new(x, z)),
z,
None,
None,
);
editor.set_block(surface_block, x, 0, z, None, None);
}
} else {
let mut previous_node: Option<(i32, i32)> = None;
let mut block_type = BLACK_CONCRETE;
let mut block_range: i32 = 2;
let mut add_stripe = false;
let mut add_outline = false;
let scale_factor = args.scale;
// Skip if 'layer' or 'level' is negative in the tags
if let Some(layer) = element.tags().get("layer") {
if layer.parse::<i32>().unwrap_or(0) < 0 {
return;
}
}
// Parse the layer value for elevation calculation
let layer_value = element
.tags()
.get("layer")
.and_then(|layer| layer.parse::<i32>().ok())
.unwrap_or(0);
// Treat negative layers as ground level (0)
let layer_value = if layer_value < 0 { 0 } else { layer_value };
// Skip if 'level' is negative in the tags (indoor mapping)
if let Some(level) = element.tags().get("level") {
if level.parse::<i32>().unwrap_or(0) < 0 {
return;
@@ -140,13 +181,17 @@ pub fn generate_highways(
block_range = 1;
}
"path" => {
block_type = LIGHT_GRAY_CONCRETE;
block_type = DIRT_PATH;
block_range = 1;
}
"motorway" | "primary" => {
"motorway" | "primary" | "trunk" => {
block_range = 5;
add_stripe = true;
}
"secondary" => {
block_range = 4;
add_stripe = true;
}
"tertiary" => {
add_stripe = true;
}
@@ -157,14 +202,32 @@ pub fn generate_highways(
block_type = GRAY_CONCRETE;
block_range = 2;
}
"secondary_link" | "tertiary_link" => {
//Exit ramps, sliproads
block_type = BLACK_CONCRETE;
block_range = 1;
}
"escape" => {
// Sand trap for vehicles on mountainous roads
block_type = SAND;
block_range = 1;
}
"steps" => {
//TODO: Add correct stairs respecting height, step_count, etc.
block_type = GRAY_CONCRETE;
block_range = 1;
}
_ => {
if let Some(lanes) = element.tags().get("lanes") {
if lanes == "2" {
block_range = 3;
add_stripe = true;
add_outline = true;
} else if lanes != "1" {
block_range = 4;
add_stripe = true;
add_outline = true;
}
}
}
@@ -174,7 +237,44 @@ pub fn generate_highways(
return;
};
if scale_factor < 1.0 {
block_range = ((block_range as f64) * scale_factor).floor() as i32;
}
// Calculate elevation based on layer
const LAYER_HEIGHT_STEP: i32 = 6; // Each layer is 6 blocks higher/lower
let base_elevation = layer_value * LAYER_HEIGHT_STEP;
// Check if we need slopes at start and end
let needs_start_slope =
should_add_slope_at_node(&way.nodes[0], layer_value, highway_connectivity);
let needs_end_slope = should_add_slope_at_node(
&way.nodes[way.nodes.len() - 1],
layer_value,
highway_connectivity,
);
// Calculate total way length for slope distribution
let total_way_length = calculate_way_length(way);
// Check if this is a short isolated elevated segment - if so, treat as ground level
let is_short_isolated_elevated =
needs_start_slope && needs_end_slope && layer_value > 0 && total_way_length <= 35;
// Override elevation and slopes for short isolated segments
let (effective_elevation, effective_start_slope, effective_end_slope) =
if is_short_isolated_elevated {
(0, false, false) // Treat as ground level
} else {
(base_elevation, needs_start_slope, needs_end_slope)
};
let slope_length = (total_way_length as f32 * 0.35).clamp(15.0, 50.0) as usize; // 35% of way length, max 50 blocks, min 15 blocks
// Iterate over nodes to create the highway
let mut segment_index = 0;
let total_segments = way.nodes.len() - 1;
for node in &way.nodes {
if let Some(prev) = previous_node {
let (x1, z1) = prev;
@@ -182,17 +282,30 @@ pub fn generate_highways(
let z2: i32 = node.z;
// Generate the line of coordinates between the two nodes
// we don't care about the y because it's going to get overwritten
// I'm not sure if we'll keep it this way
let bresenham_points: Vec<(i32, i32, i32)> =
bresenham_line(x1, 0, z1, x2, 0, z2);
// Calculate elevation for this segment
let segment_length = bresenham_points.len();
// Variables to manage dashed line pattern
let mut stripe_length: i32 = 0;
let dash_length: i32 = 5; // Length of the solid part of the stripe
let gap_length: i32 = 5; // Length of the gap part of the stripe
let dash_length: i32 = (5.0 * scale_factor).ceil() as i32;
let gap_length: i32 = (5.0 * scale_factor).ceil() as i32;
for (point_index, (x, _, z)) in bresenham_points.iter().enumerate() {
// Calculate Y elevation for this point based on slopes and layer
let current_y = calculate_point_elevation(
segment_index,
point_index,
segment_length,
total_segments,
effective_elevation,
effective_start_slope,
effective_end_slope,
slope_length,
);
for (x, _, z) in bresenham_points {
// Draw the road surface for the entire width
for dx in -block_range..=block_range {
for dz in -block_range..=block_range {
@@ -210,7 +323,7 @@ pub fn generate_highways(
editor.set_block(
WHITE_CONCRETE,
set_x,
ground.level(XZPoint::new(set_x, set_z)),
current_y,
set_z,
Some(&[BLACK_CONCRETE]),
None,
@@ -219,7 +332,7 @@ pub fn generate_highways(
editor.set_block(
BLACK_CONCRETE,
set_x,
ground.level(XZPoint::new(set_x, set_z)),
current_y,
set_z,
None,
None,
@@ -229,7 +342,7 @@ pub fn generate_highways(
editor.set_block(
WHITE_CONCRETE,
set_x,
ground.level(XZPoint::new(set_x, set_z)),
current_y,
set_z,
Some(&[BLACK_CONCRETE]),
None,
@@ -238,7 +351,7 @@ pub fn generate_highways(
editor.set_block(
BLACK_CONCRETE,
set_x,
ground.level(XZPoint::new(set_x, set_z)),
current_y,
set_z,
None,
None,
@@ -248,24 +361,80 @@ pub fn generate_highways(
editor.set_block(
block_type,
set_x,
ground.level(XZPoint::new(set_x, set_z)),
current_y,
set_z,
None,
Some(&[BLACK_CONCRETE, WHITE_CONCRETE]),
);
}
// Add stone brick foundation underneath elevated highways for thickness
if effective_elevation > 0 && current_y > 0 {
// Add 1 layer of stone bricks underneath the highway surface
editor.set_block(
STONE_BRICKS,
set_x,
current_y - 1,
set_z,
None,
None,
);
}
// Add support pillars for elevated highways
if effective_elevation != 0 && current_y > 0 {
add_highway_support_pillar(
editor,
set_x,
current_y,
set_z,
dx,
dz,
block_range,
);
}
}
}
// Add light gray concrete outline for multi-lane roads
if add_outline {
// Left outline
for dz in -block_range..=block_range {
let outline_x = x - block_range - 1;
let outline_z = z + dz;
editor.set_block(
LIGHT_GRAY_CONCRETE,
outline_x,
current_y,
outline_z,
None,
None,
);
}
// Right outline
for dz in -block_range..=block_range {
let outline_x = x + block_range + 1;
let outline_z = z + dz;
editor.set_block(
LIGHT_GRAY_CONCRETE,
outline_x,
current_y,
outline_z,
None,
None,
);
}
}
// Add a dashed white line in the middle for larger roads
if add_stripe {
if stripe_length < dash_length {
let stripe_x: i32 = x;
let stripe_z: i32 = z;
let stripe_x: i32 = *x;
let stripe_z: i32 = *z;
editor.set_block(
WHITE_CONCRETE,
stripe_x,
ground.level(XZPoint::new(stripe_x, stripe_z)),
current_y,
stripe_z,
Some(&[BLACK_CONCRETE]),
None,
@@ -279,6 +448,8 @@ pub fn generate_highways(
}
}
}
segment_index += 1;
}
previous_node = Some((node.x, node.z));
}
@@ -286,8 +457,133 @@ pub fn generate_highways(
}
}
/// Helper function to determine if a slope should be added at a specific node
fn should_add_slope_at_node(
node: &crate::osm_parser::ProcessedNode,
current_layer: i32,
highway_connectivity: &HashMap<(i32, i32), Vec<i32>>,
) -> bool {
let node_coord = (node.x, node.z);
// If we don't have connectivity information, always add slopes for non-zero layers
if highway_connectivity.is_empty() {
return current_layer != 0;
}
// Check if there are other highways at different layers connected to this node
if let Some(connected_layers) = highway_connectivity.get(&node_coord) {
// Count how many ways are at the same layer as current way
let same_layer_count = connected_layers
.iter()
.filter(|&&layer| layer == current_layer)
.count();
// If this is the only way at this layer connecting to this node, we need a slope
// (unless we're at ground level and connecting to ground level ways)
if same_layer_count <= 1 {
return current_layer != 0;
}
// If there are multiple ways at the same layer, don't add slope
false
} else {
// No other highways connected, add slope if not at ground level
current_layer != 0
}
}
/// Helper function to calculate the total length of a way in blocks
fn calculate_way_length(way: &ProcessedWay) -> usize {
let mut total_length = 0;
let mut previous_node: Option<&crate::osm_parser::ProcessedNode> = None;
for node in &way.nodes {
if let Some(prev) = previous_node {
let dx = (node.x - prev.x).abs();
let dz = (node.z - prev.z).abs();
total_length += ((dx * dx + dz * dz) as f32).sqrt() as usize;
}
previous_node = Some(node);
}
total_length
}
/// Calculate the Y elevation for a specific point along the highway
#[allow(clippy::too_many_arguments)]
fn calculate_point_elevation(
segment_index: usize,
point_index: usize,
segment_length: usize,
total_segments: usize,
base_elevation: i32,
needs_start_slope: bool,
needs_end_slope: bool,
slope_length: usize,
) -> i32 {
// If no slopes needed, return base elevation
if !needs_start_slope && !needs_end_slope {
return base_elevation;
}
// Calculate total distance from start
let total_distance_from_start = segment_index * segment_length + point_index;
let total_way_length = total_segments * segment_length;
// Ensure we have reasonable values
if total_way_length == 0 || slope_length == 0 {
return base_elevation;
}
// Start slope calculation - gradual rise from ground level
if needs_start_slope && total_distance_from_start <= slope_length {
let slope_progress = total_distance_from_start as f32 / slope_length as f32;
let elevation_offset = (base_elevation as f32 * slope_progress) as i32;
return elevation_offset;
}
// End slope calculation - gradual descent to ground level
if needs_end_slope
&& total_distance_from_start >= (total_way_length.saturating_sub(slope_length))
{
let distance_from_end = total_way_length - total_distance_from_start;
let slope_progress = distance_from_end as f32 / slope_length as f32;
let elevation_offset = (base_elevation as f32 * slope_progress) as i32;
return elevation_offset;
}
// Middle section at full elevation
base_elevation
}
/// Add support pillars for elevated highways
fn add_highway_support_pillar(
editor: &mut WorldEditor,
x: i32,
highway_y: i32,
z: i32,
dx: i32,
dz: i32,
_block_range: i32, // Keep for future use
) {
// Only add pillars at specific intervals and positions
if dx == 0 && dz == 0 && (x + z) % 8 == 0 {
// Add pillar from ground to highway level
for y in 1..highway_y {
editor.set_block(STONE_BRICKS, x, y, z, None, None);
}
// Add pillar base
for base_dx in -1..=1 {
for base_dz in -1..=1 {
editor.set_block(STONE_BRICKS, x + base_dx, 0, z + base_dz, None, None);
}
}
}
}
/// Generates a siding using stone brick slabs
pub fn generate_siding(editor: &mut WorldEditor, element: &ProcessedWay, ground: &Ground) {
pub fn generate_siding(editor: &mut WorldEditor, element: &ProcessedWay) {
let mut previous_node: Option<XZPoint> = None;
let siding_block: Block = STONE_BRICK_SLAB;
@@ -306,16 +602,8 @@ pub fn generate_siding(editor: &mut WorldEditor, element: &ProcessedWay, ground:
);
for (bx, _, bz) in bresenham_points {
let ground_level = ground.level(XZPoint::new(bx, bz)) + 1;
if !editor.check_for_block(
bx,
ground_level - 1,
bz,
None,
Some(&[BLACK_CONCRETE, WHITE_CONCRETE]),
) {
editor.set_block(siding_block, bx, ground_level, bz, None, None);
if !editor.check_for_block(bx, 0, bz, Some(&[BLACK_CONCRETE, WHITE_CONCRETE])) {
editor.set_block(siding_block, bx, 1, bz, None, None);
}
}
}
@@ -325,7 +613,7 @@ pub fn generate_siding(editor: &mut WorldEditor, element: &ProcessedWay, ground:
}
/// Generates an aeroway
pub fn generate_aeroway(editor: &mut WorldEditor, way: &ProcessedWay, ground: &Ground) {
pub fn generate_aeroway(editor: &mut WorldEditor, way: &ProcessedWay, args: &Args) {
let mut previous_node: Option<(i32, i32)> = None;
let surface_block = LIGHT_GRAY_CONCRETE;
@@ -335,14 +623,14 @@ pub fn generate_aeroway(editor: &mut WorldEditor, way: &ProcessedWay, ground: &G
let x2 = node.x;
let z2 = node.z;
let points = bresenham_line(x1, 0, z1, x2, 0, z2);
let way_width: i32 = (12.0 * args.scale).ceil() as i32;
for (x, _, z) in points {
for dx in -12..=12 {
for dz in -12..=12 {
for dx in -way_width..=way_width {
for dz in -way_width..=way_width {
let set_x = x + dx;
let set_z = z + dz;
let y = ground.level(XZPoint::new(set_x, set_z));
editor.set_block(surface_block, set_x, y, set_z, None, None);
editor.set_block(surface_block, set_x, 0, set_z, None, None);
}
}
}

View File

@@ -1,56 +1,47 @@
use crate::args::Args;
use crate::block_definitions::*;
use crate::cartesian::XZPoint;
use crate::element_processing::tree::create_tree;
use crate::element_processing::tree::Tree;
use crate::floodfill::flood_fill_area;
use crate::ground::Ground;
use crate::osm_parser::ProcessedWay;
use crate::osm_parser::{ProcessedMemberRole, ProcessedRelation, ProcessedWay};
use crate::world_editor::WorldEditor;
use rand::Rng;
pub fn generate_landuse(
editor: &mut WorldEditor,
element: &ProcessedWay,
ground: &Ground,
args: &Args,
) {
pub fn generate_landuse(editor: &mut WorldEditor, element: &ProcessedWay, args: &Args) {
// Determine block type based on landuse tag
let binding: String = "".to_string();
let landuse_tag: &String = element.tags.get("landuse").unwrap_or(&binding);
let block_type = match landuse_tag.as_str() {
"greenfield" | "meadow" | "grass" => {
if args.winter {
SNOW_BLOCK
} else {
GRASS_BLOCK
}
}
"greenfield" | "meadow" | "grass" | "orchard" | "forest" => GRASS_BLOCK,
"farmland" => FARMLAND,
"forest" => {
if args.winter {
SNOW_BLOCK
} else {
"cemetery" => PODZOL,
"construction" => COARSE_DIRT,
"traffic_island" => STONE_BLOCK_SLAB,
"residential" => {
let residential_tag = element.tags.get("residential").unwrap_or(&binding);
if residential_tag == "rural" {
GRASS_BLOCK
} else {
STONE_BRICKS
}
}
"cemetery" => PODZOL,
"beach" => SAND,
"construction" => DIRT,
"traffic_island" => STONE_BLOCK_SLAB,
"residential" => STONE_BRICKS,
"commercial" => SMOOTH_STONE,
"education" => LIGHT_GRAY_CONCRETE,
"education" => POLISHED_ANDESITE,
"religious" => POLISHED_ANDESITE,
"industrial" => COBBLESTONE,
"military" => GRAY_CONCRETE,
"railway" => GRAVEL,
_ => {
if args.winter {
SNOW_BLOCK
"landfill" => {
// Gravel if man_made = spoil_heap or heap, coarse dirt else
let manmade_tag = element.tags.get("man_made").unwrap_or(&binding);
if manmade_tag == "spoil_heap" || manmade_tag == "heap" {
GRAVEL
} else {
GRASS_BLOCK
COARSE_DIRT
}
}
"quarry" => STONE,
_ => GRASS_BLOCK,
};
// Get the area of the landuse element
@@ -60,13 +51,12 @@ pub fn generate_landuse(
let mut rng: rand::prelude::ThreadRng = rand::thread_rng();
for (x, z) in floor_area {
let ground_level = ground.level(XZPoint::new(x, z));
if landuse_tag == "traffic_island" {
editor.set_block(block_type, x, ground_level + 1, z, None, None);
editor.set_block(block_type, x, 1, z, None, None);
} else if landuse_tag == "construction" || landuse_tag == "railway" {
editor.set_block(block_type, x, ground_level, z, None, Some(&[SPONGE]));
editor.set_block(block_type, x, 0, z, None, Some(&[SPONGE]));
} else {
editor.set_block(block_type, x, ground_level, z, None, None);
editor.set_block(block_type, x, 0, z, None, None);
}
// Add specific features for different landuse types
@@ -76,197 +66,93 @@ pub fn generate_landuse(
let random_choice: i32 = rng.gen_range(0..100);
if random_choice < 15 {
// Place graves
if editor.check_for_block(x, ground_level, z, Some(&[PODZOL]), None) {
if editor.check_for_block(x, 0, z, Some(&[PODZOL])) {
if rng.gen_bool(0.5) {
editor.set_block(
COBBLESTONE,
x - 1,
ground_level + 1,
z,
None,
None,
);
editor.set_block(
STONE_BRICK_SLAB,
x - 1,
ground_level + 2,
z,
None,
None,
);
editor.set_block(
STONE_BRICK_SLAB,
x,
ground_level + 1,
z,
None,
None,
);
editor.set_block(
STONE_BRICK_SLAB,
x + 1,
ground_level + 1,
z,
None,
None,
);
editor.set_block(COBBLESTONE, x - 1, 1, z, None, None);
editor.set_block(STONE_BRICK_SLAB, x - 1, 2, z, None, None);
editor.set_block(STONE_BRICK_SLAB, x, 1, z, None, None);
editor.set_block(STONE_BRICK_SLAB, x + 1, 1, z, None, None);
} else {
editor.set_block(
COBBLESTONE,
x,
ground_level + 1,
z - 1,
None,
None,
);
editor.set_block(
STONE_BRICK_SLAB,
x,
ground_level + 2,
z - 1,
None,
None,
);
editor.set_block(
STONE_BRICK_SLAB,
x,
ground_level + 1,
z,
None,
None,
);
editor.set_block(
STONE_BRICK_SLAB,
x,
ground_level + 1,
z + 1,
None,
None,
);
editor.set_block(COBBLESTONE, x, 1, z - 1, None, None);
editor.set_block(STONE_BRICK_SLAB, x, 2, z - 1, None, None);
editor.set_block(STONE_BRICK_SLAB, x, 1, z, None, None);
editor.set_block(STONE_BRICK_SLAB, x, 1, z + 1, None, None);
}
}
} else if random_choice < 30 {
if editor.check_for_block(x, ground_level, z, Some(&[PODZOL]), None) {
editor.set_block(RED_FLOWER, x, ground_level + 1, z, None, None);
if editor.check_for_block(x, 0, z, Some(&[PODZOL])) {
editor.set_block(RED_FLOWER, x, 1, z, None, None);
}
} else if random_choice < 33 {
create_tree(
editor,
x,
ground_level + 1,
z,
rng.gen_range(1..=3),
args.winter,
);
Tree::create(editor, (x, 1, z));
} else if random_choice < 35 {
editor.set_block(OAK_LEAVES, x, 1, z, None, None);
}
}
}
"forest" => {
if !editor.check_for_block(x, ground_level, z, None, Some(&[WATER])) {
let random_choice: i32 = rng.gen_range(0..21);
if editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK])) {
let random_choice: i32 = rng.gen_range(0..30);
if random_choice == 20 {
create_tree(
editor,
x,
ground_level + 1,
z,
rng.gen_range(1..=3),
args.winter,
);
Tree::create(editor, (x, 1, z));
} else if random_choice == 2 {
let flower_block: Block = match rng.gen_range(1..=4) {
1 => RED_FLOWER,
2 => BLUE_FLOWER,
3 => YELLOW_FLOWER,
let flower_block: Block = match rng.gen_range(1..=5) {
1 => OAK_LEAVES,
2 => RED_FLOWER,
3 => BLUE_FLOWER,
4 => YELLOW_FLOWER,
_ => WHITE_FLOWER,
};
editor.set_block(flower_block, x, ground_level + 1, z, None, None);
} else if random_choice <= 1 {
editor.set_block(GRASS, x, ground_level + 1, z, None, None);
editor.set_block(flower_block, x, 1, z, None, None);
} else if random_choice <= 12 {
editor.set_block(GRASS, x, 1, z, None, None);
}
}
}
"farmland" => {
// Check if the current block is not water or another undesired block
if !editor.check_for_block(x, ground_level, z, None, Some(&[WATER])) {
if x % 15 == 0 || z % 15 == 0 {
// Place water on the edges
editor.set_block(WATER, x, ground_level, z, Some(&[FARMLAND]), None);
editor.set_block(
AIR,
x,
ground_level + 1,
z,
Some(&[GRASS, WHEAT, CARROTS, POTATOES]),
None,
);
} else {
// Set the block below as farmland
editor.set_block(FARMLAND, x, ground_level, z, None, None);
// If a random condition is met, place a special object
if rng.gen_range(0..76) == 0 {
let special_choice: i32 = rng.gen_range(1..=10);
if special_choice <= 2 {
create_tree(
editor,
x,
ground_level + 1,
z,
rng.gen_range(1..=3),
args.winter,
);
} else if special_choice <= 6 {
editor.set_block(
HAY_BALE,
x,
ground_level + 1,
z,
None,
Some(&[SPONGE]),
);
} else {
editor.set_block(
OAK_LEAVES,
x,
ground_level + 1,
z,
None,
Some(&[SPONGE]),
);
}
if !editor.check_for_block(x, 0, z, Some(&[WATER])) {
if x % 9 == 0 && z % 9 == 0 {
// Place water in dot pattern
editor.set_block(WATER, x, 0, z, Some(&[FARMLAND]), None);
} else if rng.gen_range(0..76) == 0 {
let special_choice: i32 = rng.gen_range(1..=10);
if special_choice <= 4 {
editor.set_block(HAY_BALE, x, 1, z, None, Some(&[SPONGE]));
} else {
// Set crops only if the block below is farmland
if editor.check_for_block(x, ground_level, z, Some(&[FARMLAND]), None) {
let crop_choice = [WHEAT, CARROTS, POTATOES][rng.gen_range(0..3)];
editor.set_block(crop_choice, x, ground_level + 1, z, None, None);
}
editor.set_block(OAK_LEAVES, x, 1, z, None, Some(&[SPONGE]));
}
} else {
// Set crops only if the block below is farmland
if editor.check_for_block(x, 0, z, Some(&[FARMLAND])) {
let crop_choice = [WHEAT, CARROTS, POTATOES][rng.gen_range(0..3)];
editor.set_block(crop_choice, x, 1, z, None, None);
}
}
}
}
"construction" => {
let random_choice: i32 = rng.gen_range(0..1501);
if random_choice < 6 {
editor.set_block(SCAFFOLDING, x, ground_level + 1, z, None, None);
if random_choice < 15 {
editor.set_block(SCAFFOLDING, x, 1, z, None, None);
if random_choice < 2 {
editor.set_block(SCAFFOLDING, x, ground_level + 2, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 3, z, None, None);
editor.set_block(SCAFFOLDING, x, 2, z, None, None);
editor.set_block(SCAFFOLDING, x, 3, z, None, None);
} else if random_choice < 4 {
editor.set_block(SCAFFOLDING, x, ground_level + 2, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 3, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 4, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 1, z + 1, None, None);
editor.set_block(SCAFFOLDING, x, 2, z, None, None);
editor.set_block(SCAFFOLDING, x, 3, z, None, None);
editor.set_block(SCAFFOLDING, x, 4, z, None, None);
editor.set_block(SCAFFOLDING, x, 1, z + 1, None, None);
} else {
editor.set_block(SCAFFOLDING, x, ground_level + 2, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 3, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 4, z, None, None);
editor.set_block(SCAFFOLDING, x, ground_level + 5, z, None, None);
editor.set_block(SCAFFOLDING, x - 1, ground_level + 1, z, None, None);
editor.set_block(SCAFFOLDING, x + 1, ground_level + 1, z - 1, None, None);
editor.set_block(SCAFFOLDING, x, 2, z, None, None);
editor.set_block(SCAFFOLDING, x, 3, z, None, None);
editor.set_block(SCAFFOLDING, x, 4, z, None, None);
editor.set_block(SCAFFOLDING, x, 5, z, None, None);
editor.set_block(SCAFFOLDING, x - 1, 1, z, None, None);
editor.set_block(SCAFFOLDING, x + 1, 1, z - 1, None, None);
}
} else if random_choice < 30 {
let construction_items: [Block; 11] = [
} else if random_choice < 55 {
let construction_items: [Block; 13] = [
OAK_LOG,
COBBLESTONE,
GRAVEL,
@@ -278,64 +164,105 @@ pub fn generate_landuse(
OAK_PLANKS,
DIRT,
BRICK,
CRAFTING_TABLE,
FURNACE,
];
editor.set_block(
construction_items[rng.gen_range(0..construction_items.len())],
x,
ground_level + 1,
1,
z,
None,
None,
);
} else if random_choice < 35 {
if random_choice < 30 {
editor.set_block(DIRT, x, ground_level + 1, z, None, None);
editor.set_block(DIRT, x, ground_level + 2, z, None, None);
editor.set_block(DIRT, x + 1, ground_level + 1, z, None, None);
editor.set_block(DIRT, x, ground_level + 1, z + 1, None, None);
} else if random_choice < 65 {
if random_choice < 60 {
editor.set_block(DIRT, x, 1, z, None, None);
editor.set_block(DIRT, x, 2, z, None, None);
editor.set_block(DIRT, x + 1, 1, z, None, None);
editor.set_block(DIRT, x, 1, z + 1, None, None);
} else {
editor.set_block(DIRT, x, ground_level + 1, z, None, None);
editor.set_block(DIRT, x, ground_level + 2, z, None, None);
editor.set_block(DIRT, x - 1, ground_level + 1, z, None, None);
editor.set_block(DIRT, x, ground_level + 1, z - 1, None, None);
editor.set_block(DIRT, x, 1, z, None, None);
editor.set_block(DIRT, x, 2, z, None, None);
editor.set_block(DIRT, x - 1, 1, z, None, None);
editor.set_block(DIRT, x, 1, z - 1, None, None);
}
} else if random_choice < 150 {
editor.set_block(AIR, x, ground_level, z, None, Some(&[SPONGE]));
} else if random_choice < 100 {
editor.set_block(GRAVEL, x, 0, z, None, Some(&[SPONGE]));
} else if random_choice < 115 {
editor.set_block(SAND, x, 0, z, None, Some(&[SPONGE]));
} else if random_choice < 125 {
editor.set_block(DIORITE, x, 0, z, None, Some(&[SPONGE]));
} else if random_choice < 145 {
editor.set_block(BRICK, x, 0, z, None, Some(&[SPONGE]));
} else if random_choice < 155 {
editor.set_block(GRANITE, x, 0, z, None, Some(&[SPONGE]));
} else if random_choice < 180 {
editor.set_block(ANDESITE, x, 0, z, None, Some(&[SPONGE]));
} else if random_choice < 565 {
editor.set_block(COBBLESTONE, x, 0, z, None, Some(&[SPONGE]));
}
}
"grass" => {
if rng.gen_range(1..=7) != 1
&& editor.check_for_block(
x,
ground_level,
z,
Some(&[GRASS_BLOCK, SNOW_BLOCK]),
None,
)
{
editor.set_block(GRASS, x, ground_level + 1, z, None, None);
if editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK])) {
match rng.gen_range(0..200) {
0 => editor.set_block(OAK_LEAVES, x, 1, z, None, None),
1..=170 => editor.set_block(GRASS, x, 1, z, None, None),
_ => {}
}
}
}
"greenfield" => {
if editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK])) {
match rng.gen_range(0..200) {
0 => editor.set_block(OAK_LEAVES, x, 1, z, None, None),
1..=17 => editor.set_block(GRASS, x, 1, z, None, None),
_ => {}
}
}
}
"meadow" => {
if editor.check_for_block(
x,
ground_level,
z,
Some(&[GRASS_BLOCK, SNOW_BLOCK]),
None,
) {
if editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK])) {
let random_choice: i32 = rng.gen_range(0..1001);
if random_choice < 5 {
create_tree(
editor,
x,
ground_level + 1,
z,
rng.gen_range(1..=3),
args.winter,
);
Tree::create(editor, (x, 1, z));
} else if random_choice < 6 {
editor.set_block(RED_FLOWER, x, 1, z, None, None);
} else if random_choice < 9 {
editor.set_block(OAK_LEAVES, x, 1, z, None, None);
} else if random_choice < 800 {
editor.set_block(GRASS, x, ground_level + 1, z, None, None);
editor.set_block(GRASS, x, 1, z, None, None);
}
}
}
"orchard" => {
if x % 18 == 0 && z % 10 == 0 {
Tree::create(editor, (x, 1, z));
} else if editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK])) {
match rng.gen_range(0..100) {
0 => editor.set_block(OAK_LEAVES, x, 1, z, None, None),
1..=20 => editor.set_block(GRASS, x, 1, z, None, None),
_ => {}
}
}
}
"quarry" => {
// Add stone layer under it
editor.set_block(STONE, x, -1, z, Some(&[STONE]), None);
editor.set_block(STONE, x, -2, z, Some(&[STONE]), None);
// Generate ore blocks
if let Some(resource) = element.tags.get("resource") {
let ore_block = match resource.as_str() {
"iron_ore" => IRON_ORE,
"coal" => COAL_ORE,
"copper" => COPPER_ORE,
"gold" => GOLD_ORE,
"clay" | "kaolinite" => CLAY,
_ => STONE,
};
let random_choice: i32 = rng.gen_range(0..100 + editor.get_absolute_y(x, 0, z)); // The deeper it is the more resources are there
if random_choice < 5 {
editor.set_block(ore_block, x, 0, z, Some(&[STONE]), None);
}
}
}
@@ -343,3 +270,39 @@ pub fn generate_landuse(
}
}
}
pub fn generate_landuse_from_relation(
editor: &mut WorldEditor,
rel: &ProcessedRelation,
args: &Args,
) {
if rel.tags.contains_key("landuse") {
// Generate individual ways with their original tags
for member in &rel.members {
if member.role == ProcessedMemberRole::Outer {
generate_landuse(editor, &member.way.clone(), args);
}
}
// Combine all outer ways into one with relation tags
let mut combined_nodes = Vec::new();
for member in &rel.members {
if member.role == ProcessedMemberRole::Outer {
combined_nodes.extend(member.way.nodes.clone());
}
}
// Only process if we have nodes
if !combined_nodes.is_empty() {
// Create combined way with relation tags
let combined_way = ProcessedWay {
id: rel.id,
nodes: combined_nodes,
tags: rel.tags.clone(),
};
// Generate landuse area from combined way
generate_landuse(editor, &combined_way, args);
}
}
}

View File

@@ -1,20 +1,13 @@
use crate::args::Args;
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::cartesian::XZPoint;
use crate::element_processing::tree::create_tree;
use crate::element_processing::tree::Tree;
use crate::floodfill::flood_fill_area;
use crate::ground::Ground;
use crate::osm_parser::{ProcessedMemberRole, ProcessedRelation, ProcessedWay};
use crate::world_editor::WorldEditor;
use rand::Rng;
pub fn generate_leisure(
editor: &mut WorldEditor,
element: &ProcessedWay,
ground: &Ground,
args: &Args,
) {
pub fn generate_leisure(editor: &mut WorldEditor, element: &ProcessedWay, args: &Args) {
if let Some(leisure_type) = element.tags.get("leisure") {
let mut previous_node: Option<(i32, i32)> = None;
let mut corner_addup: (i32, i32, i32) = (0, 0, 0);
@@ -22,40 +15,31 @@ pub fn generate_leisure(
// Determine block type based on leisure type
let block_type: Block = match leisure_type.as_str() {
"park" => {
if args.winter {
SNOW_BLOCK
} else {
GRASS_BLOCK
}
"park" | "nature_reserve" | "garden" | "disc_golf_course" | "golf_course" => {
GRASS_BLOCK
}
"playground" | "recreation_ground" | "pitch" => {
"schoolyard" => BLACK_CONCRETE,
"playground" | "recreation_ground" | "pitch" | "beach_resort" | "dog_park" => {
if let Some(surface) = element.tags.get("surface") {
match surface.as_str() {
"clay" => TERRACOTTA,
"sand" => SAND,
"tartan" => RED_TERRACOTTA,
"grass" => GRASS_BLOCK,
"dirt" => DIRT,
"pebblestone" | "cobblestone" | "unhewn_cobblestone" => COBBLESTONE,
_ => GREEN_STAINED_HARDENED_CLAY,
}
} else {
GREEN_STAINED_HARDENED_CLAY
}
}
"garden" => {
if args.winter {
SNOW_BLOCK
} else {
GRASS_BLOCK
}
}
"swimming_pool" => WATER,
_ => {
if args.winter {
SNOW_BLOCK
} else {
GRASS_BLOCK
}
}
"swimming_pool" | "swimming_area" => WATER, //Swimming area: Area in a larger body of water for swimming
"bathing_place" => SMOOTH_SANDSTONE, // Could be sand or concrete
"outdoor_seating" => SMOOTH_STONE, //Usually stone or stone bricks
"water_park" | "slipway" => LIGHT_GRAY_CONCRETE, // Water park area, not the pool. Usually is concrete
"ice_rink" => PACKED_ICE, // TODO: Ice for Ice Rink, needs building defined
_ => GRASS_BLOCK,
};
// Process leisure area nodes
@@ -68,7 +52,7 @@ pub fn generate_leisure(
editor.set_block(
block_type,
bx,
ground.level(XZPoint::new(bx, bz)),
0,
bz,
Some(&[
GRASS_BLOCK,
@@ -101,47 +85,37 @@ pub fn generate_leisure(
flood_fill_area(&polygon_coords, args.timeout.as_ref());
for (x, z) in filled_area {
let ground_level = ground.level(XZPoint::new(x, z));
editor.set_block(block_type, x, ground_level, z, Some(&[GRASS_BLOCK]), None);
editor.set_block(block_type, x, 0, z, Some(&[GRASS_BLOCK]), None);
// Add decorative elements for parks and gardens
if matches!(leisure_type.as_str(), "park" | "garden")
&& editor.check_for_block(x, ground_level, z, Some(&[GRASS_BLOCK]), None)
if matches!(leisure_type.as_str(), "park" | "garden" | "nature_reserve")
&& editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK]))
{
let mut rng: rand::prelude::ThreadRng = rand::thread_rng();
let random_choice: i32 = rng.gen_range(0..1000);
match random_choice {
0 => {
// Benches
editor.set_block(OAK_LOG, x, ground_level + 1, z, None, None);
editor.set_block(OAK_LOG, x + 1, ground_level + 1, z, None, None);
editor.set_block(OAK_LOG, x - 1, ground_level + 1, z, None, None);
}
1..=30 => {
0..30 => {
// Flowers
let flower_choice = match rng.gen_range(0..4) {
0 => RED_FLOWER,
1 => YELLOW_FLOWER,
2 => BLUE_FLOWER,
let flower_choice = match random_choice {
0..10 => RED_FLOWER,
10..20 => YELLOW_FLOWER,
20..30 => BLUE_FLOWER,
_ => WHITE_FLOWER,
};
editor.set_block(flower_choice, x, ground_level + 1, z, None, None);
editor.set_block(flower_choice, x, 1, z, None, None);
}
31..=70 => {
30..90 => {
// Grass
editor.set_block(GRASS, x, ground_level + 1, z, None, None);
editor.set_block(GRASS, x, 1, z, None, None);
}
71..=80 => {
90..105 => {
// Oak leaves
editor.set_block(OAK_LEAVES, x, 1, z, None, None);
}
105..120 => {
// Tree
create_tree(
editor,
x,
ground_level + 1,
z,
rng.gen_range(1..=3),
args.winter,
);
Tree::create(editor, (x, 1, z));
}
_ => {}
}
@@ -153,36 +127,38 @@ pub fn generate_leisure(
let random_choice: i32 = rng.gen_range(0..5000);
match random_choice {
0..=10 => {
0..10 => {
// Swing set
for y in 1..=4 {
editor.set_block(OAK_FENCE, x - 1, ground_level + y, z, None, None);
editor.set_block(OAK_FENCE, x + 1, ground_level + y, z, None, None);
for y in 1..=3 {
editor.set_block(OAK_FENCE, x - 1, y, z, None, None);
editor.set_block(OAK_FENCE, x + 1, y, z, None, None);
}
editor.set_block(OAK_FENCE, x, ground_level + 4, z, None, None);
editor.set_block(STONE_BLOCK_SLAB, x, ground_level + 2, z, None, None);
editor.set_block(OAK_PLANKS, x - 1, 4, z, None, None);
editor.set_block(OAK_SLAB, x, 4, z, None, None);
editor.set_block(OAK_PLANKS, x + 1, 4, z, None, None);
editor.set_block(STONE_BLOCK_SLAB, x, 2, z, None, None);
}
11..=20 => {
10..20 => {
// Slide
editor.set_block(OAK_SLAB, x, ground_level + 1, z, None, None);
editor.set_block(OAK_SLAB, x + 1, ground_level + 2, z, None, None);
editor.set_block(OAK_SLAB, x + 2, ground_level + 3, z, None, None);
editor.set_block(OAK_SLAB, x, 1, z, None, None);
editor.set_block(OAK_SLAB, x + 1, 2, z, None, None);
editor.set_block(OAK_SLAB, x + 2, 3, z, None, None);
editor.set_block(OAK_PLANKS, x + 2, ground_level + 2, z, None, None);
editor.set_block(OAK_PLANKS, x + 2, ground_level + 1, z, None, None);
editor.set_block(OAK_PLANKS, x + 2, 2, z, None, None);
editor.set_block(OAK_PLANKS, x + 2, 1, z, None, None);
editor.set_block(LADDER, x + 2, ground_level + 2, z - 1, None, None);
editor.set_block(LADDER, x + 2, ground_level + 1, z - 1, None, None);
editor.set_block(LADDER, x + 2, 2, z - 1, None, None);
editor.set_block(LADDER, x + 2, 1, z - 1, None, None);
}
21..=30 => {
20..30 => {
// Sandpit
editor.fill_blocks(
SAND,
x - 3,
ground_level,
0,
z - 3,
x + 3,
ground_level,
0,
z + 3,
Some(&[GREEN_STAINED_HARDENED_CLAY]),
None,
@@ -199,14 +175,13 @@ pub fn generate_leisure(
pub fn generate_leisure_from_relation(
editor: &mut WorldEditor,
rel: &ProcessedRelation,
ground: &Ground,
args: &Args,
) {
if rel.tags.get("leisure") == Some(&"park".to_string()) {
// First generate individual ways with their original tags
for member in &rel.members {
if member.role == ProcessedMemberRole::Outer {
generate_leisure(editor, &member.way, ground, args);
generate_leisure(editor, &member.way, args);
}
}
@@ -226,6 +201,6 @@ pub fn generate_leisure_from_relation(
};
// Generate leisure area from combined way
generate_leisure(editor, &combined_way, ground, args);
generate_leisure(editor, &combined_way, args);
}
}

View File

@@ -0,0 +1,256 @@
use crate::args::Args;
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::osm_parser::{ProcessedElement, ProcessedNode};
use crate::world_editor::WorldEditor;
pub fn generate_man_made(editor: &mut WorldEditor, element: &ProcessedElement, _args: &Args) {
// Skip if 'layer' or 'level' is negative in the tags
if let Some(layer) = element.tags().get("layer") {
if layer.parse::<i32>().unwrap_or(0) < 0 {
return;
}
}
if let Some(level) = element.tags().get("level") {
if level.parse::<i32>().unwrap_or(0) < 0 {
return;
}
}
if let Some(man_made_type) = element.tags().get("man_made") {
match man_made_type.as_str() {
"pier" => generate_pier(editor, element),
"antenna" => generate_antenna(editor, element),
"chimney" => generate_chimney(editor, element),
"water_well" => generate_water_well(editor, element),
"water_tower" => generate_water_tower(editor, element),
"mast" => generate_antenna(editor, element),
_ => {} // Unknown man_made type, ignore
}
}
}
/// Generate a pier structure with OAK_SLAB planks and OAK_LOG support pillars
fn generate_pier(editor: &mut WorldEditor, element: &ProcessedElement) {
if let ProcessedElement::Way(way) = element {
let nodes = &way.nodes;
if nodes.len() < 2 {
return;
}
// Extract pier dimensions from tags
let pier_width = element
.tags()
.get("width")
.and_then(|w| w.parse::<i32>().ok())
.unwrap_or(3); // Default 3 blocks wide
let pier_height = 1; // Pier deck height above ground
let support_spacing = 4; // Support pillars every 4 blocks
// Generate the pier walkway using bresenham line algorithm
for i in 0..nodes.len() - 1 {
let start_node = &nodes[i];
let end_node = &nodes[i + 1];
let line_points =
bresenham_line(start_node.x, 0, start_node.z, end_node.x, 0, end_node.z);
for (index, (center_x, _y, center_z)) in line_points.iter().enumerate() {
// Create pier deck (3 blocks wide)
let half_width = pier_width / 2;
for x in (center_x - half_width)..=(center_x + half_width) {
for z in (center_z - half_width)..=(center_z + half_width) {
editor.set_block(OAK_SLAB, x, pier_height, z, None, None);
}
}
// Add support pillars every few blocks
if index % support_spacing == 0 {
let half_width = pier_width / 2;
// Place support pillars at the edges of the pier
let support_positions = [
(center_x - half_width, center_z), // Left side
(center_x + half_width, center_z), // Right side
];
for (pillar_x, pillar_z) in support_positions {
// Support pillars going down from pier level
editor.set_block(OAK_LOG, pillar_x, 0, *pillar_z, None, None);
}
}
}
}
}
}
/// Generate an antenna/radio tower
fn generate_antenna(editor: &mut WorldEditor, element: &ProcessedElement) {
if let Some(first_node) = element.nodes().next() {
let x = first_node.x;
let z = first_node.z;
// Extract antenna configuration from tags
let height = match element.tags().get("height") {
Some(h) => h.parse::<i32>().unwrap_or(20).min(40), // Max 40 blocks
None => match element.tags().get("tower:type").map(|s| s.as_str()) {
Some("communication") => 20,
Some("cellular") => 15,
_ => 20,
},
};
// Build the main tower pole
editor.set_block(IRON_BLOCK, x, 3, z, None, None);
for y in 4..height {
editor.set_block(IRON_BARS, x, y, z, None, None);
}
// Add structural supports every 7 blocks
for y in (7..height).step_by(7) {
editor.set_block(IRON_BLOCK, x, y, z, Some(&[IRON_BARS]), None);
let support_positions = [(1, 0), (-1, 0), (0, 1), (0, -1)];
for (dx, dz) in support_positions {
editor.set_block(IRON_BLOCK, x + dx, y, z + dz, None, None);
}
}
// Equipment housing at base
editor.fill_blocks(
GRAY_CONCRETE,
x - 1,
1,
z - 1,
x + 1,
2,
z + 1,
Some(&[GRAY_CONCRETE]),
None,
);
}
}
/// Generate a chimney structure
fn generate_chimney(editor: &mut WorldEditor, element: &ProcessedElement) {
if let Some(first_node) = element.nodes().next() {
let x = first_node.x;
let z = first_node.z;
let height = 25;
// Build 3x3 brick chimney with hole in the middle
for y in 0..height {
for dx in -1..=1 {
for dz in -1..=1 {
// Skip center block to create hole
if dx == 0 && dz == 0 {
continue;
}
editor.set_block(BRICK, x + dx, y, z + dz, None, None);
}
}
}
}
}
/// Generate a water well structure
fn generate_water_well(editor: &mut WorldEditor, element: &ProcessedElement) {
if let Some(first_node) = element.nodes().next() {
let x = first_node.x;
let z = first_node.z;
// Build stone well structure (3x3 base with water in center)
for dx in -1..=1 {
for dz in -1..=1 {
if dx == 0 && dz == 0 {
// Water in the center
editor.set_block(WATER, x, -1, z, None, None);
editor.set_block(WATER, x, 0, z, None, None);
} else {
// Stone well walls
editor.set_block(STONE_BRICKS, x + dx, 0, z + dz, None, None);
editor.set_block(STONE_BRICKS, x + dx, 1, z + dz, None, None);
}
}
}
// Add wooden well frame structure
editor.fill_blocks(OAK_LOG, x - 2, 1, z, x - 2, 4, z, None, None);
editor.fill_blocks(OAK_LOG, x + 2, 1, z, x + 2, 4, z, None, None);
// Crossbeam with pulley system
editor.set_block(OAK_SLAB, x - 1, 5, z, None, None);
editor.set_block(OAK_FENCE, x, 4, z, None, None);
editor.set_block(OAK_SLAB, x, 5, z, None, None);
editor.set_block(OAK_SLAB, x + 1, 5, z, None, None);
// Bucket hanging from center
editor.set_block(IRON_BLOCK, x, 3, z, None, None);
}
}
/// Generate a water tower structure
fn generate_water_tower(editor: &mut WorldEditor, element: &ProcessedElement) {
if let Some(first_node) = element.nodes().next() {
let x = first_node.x;
let z = first_node.z;
let tower_height = 20;
let tank_height = 6;
// Build support legs (4 corner pillars)
let leg_positions = [(-2, -2), (2, -2), (-2, 2), (2, 2)];
for (dx, dz) in leg_positions {
for y in 0..tower_height {
editor.set_block(IRON_BLOCK, x + dx, y, z + dz, None, None);
}
}
// Add cross-bracing every 5 blocks for stability
for y in (5..tower_height).step_by(5) {
// Horizontal bracing
for dx in -1..=1 {
editor.set_block(SMOOTH_STONE, x + dx, y, z - 2, None, None);
editor.set_block(SMOOTH_STONE, x + dx, y, z + 2, None, None);
}
for dz in -1..=1 {
editor.set_block(SMOOTH_STONE, x - 2, y, z + dz, None, None);
editor.set_block(SMOOTH_STONE, x + 2, y, z + dz, None, None);
}
}
// Build water tank at the top - simple rectangular tank
editor.fill_blocks(
POLISHED_ANDESITE,
x - 3,
tower_height,
z - 3,
x + 3,
tower_height + tank_height,
z + 3,
None,
None,
);
// Add polished andesite pipe going down from the tank
for y in 0..tower_height {
editor.set_block(POLISHED_ANDESITE, x, y, z, None, None);
}
}
}
/// Generate man_made structures for node elements
pub fn generate_man_made_nodes(editor: &mut WorldEditor, node: &ProcessedNode) {
if let Some(man_made_type) = node.tags.get("man_made") {
let element = ProcessedElement::Node(node.clone());
match man_made_type.as_str() {
"antenna" => generate_antenna(editor, &element),
"chimney" => generate_chimney(editor, &element),
"water_well" => generate_water_well(editor, &element),
"water_tower" => generate_water_tower(editor, &element),
"mast" => generate_antenna(editor, &element),
_ => {} // Unknown man_made type, ignore
}
}
}

View File

@@ -6,8 +6,10 @@ pub mod doors;
pub mod highways;
pub mod landuse;
pub mod leisure;
pub mod man_made;
pub mod natural;
pub mod railways;
pub mod subprocessor;
pub mod tourisms;
pub mod tree;
pub mod water_areas;

View File

@@ -1,66 +1,48 @@
use crate::args::Args;
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::cartesian::XZPoint;
use crate::element_processing::tree::create_tree;
use crate::element_processing::tree::Tree;
use crate::floodfill::flood_fill_area;
use crate::ground::Ground;
use crate::osm_parser::ProcessedElement;
use crate::osm_parser::{ProcessedElement, ProcessedMemberRole, ProcessedRelation, ProcessedWay};
use crate::world_editor::WorldEditor;
use rand::Rng;
pub fn generate_natural(
editor: &mut WorldEditor,
element: &ProcessedElement,
ground: &Ground,
args: &Args,
) {
pub fn generate_natural(editor: &mut WorldEditor, element: &ProcessedElement, args: &Args) {
if let Some(natural_type) = element.tags().get("natural") {
if natural_type == "tree" {
if let ProcessedElement::Node(node) = element {
let x: i32 = node.x;
let z: i32 = node.z;
let mut rng: rand::prelude::ThreadRng = rand::thread_rng();
create_tree(
editor,
x,
ground.level(node.xz()) + 1,
z,
rng.gen_range(1..=3),
args.winter,
);
Tree::create(editor, (x, 1, z));
}
} else {
let mut previous_node: Option<(i32, i32)> = None;
let mut corner_addup: (i32, i32, i32) = (0, 0, 0);
let mut current_natural: Vec<(i32, i32)> = vec![];
let binding: String = "".to_string();
// Determine block type based on natural tag
let block_type: Block = match natural_type.as_str() {
"scrub" | "grassland" | "wood" => {
if args.winter {
SNOW_BLOCK
} else {
GRASS_BLOCK
}
}
"beach" | "sand" => SAND,
"tree_row" => {
if args.winter {
SNOW_BLOCK
} else {
GRASS_BLOCK
}
}
"wetland" | "water" => WATER,
_ => {
if args.winter {
SNOW_BLOCK
} else {
GRASS_BLOCK
"scrub" | "grassland" | "wood" | "heath" | "tree_row" => GRASS_BLOCK,
"sand" | "dune" => SAND,
"beach" | "shoal" => {
let surface = element.tags().get("natural").unwrap_or(&binding);
match surface.as_str() {
"gravel" => GRAVEL,
_ => SAND,
}
}
"water" | "reef" => WATER,
"bare_rock" => STONE,
"blockfield" => COBBLESTONE,
"glacier" => PACKED_ICE,
"mud" | "wetland" => MUD,
"mountain_range" => COBBLESTONE,
"saddle" | "ridge" => STONE,
"shrubbery" | "tundra" | "hill" => GRASS_BLOCK,
"cliff" => STONE,
_ => GRASS_BLOCK,
};
let ProcessedElement::Way(way) = element else {
@@ -77,14 +59,7 @@ pub fn generate_natural(
let bresenham_points: Vec<(i32, i32, i32)> =
bresenham_line(prev.0, 0, prev.1, x, 0, z);
for (bx, _, bz) in bresenham_points {
editor.set_block(
block_type,
bx,
ground.level(XZPoint::new(bx, bz)),
bz,
None,
None,
);
editor.set_block(block_type, bx, 0, bz, None, None);
}
current_natural.push((x, z));
@@ -107,33 +82,400 @@ pub fn generate_natural(
let mut rng: rand::prelude::ThreadRng = rand::thread_rng();
for (x, z) in filled_area {
let y = ground.level(XZPoint::new(x, z));
editor.set_block(block_type, x, y, z, None, None);
// Generate elements for "wood" and "tree_row"
if natural_type == "wood" || natural_type == "tree_row" {
if editor.check_for_block(x, y, z, None, Some(&[WATER])) {
continue;
editor.set_block(block_type, x, 0, z, None, None);
// Generate custom layer instead of dirt, must be stone on the lowest level
match natural_type.as_str() {
"beach" | "sand" | "dune" | "shoal" => {
editor.set_block(SAND, x, 0, z, None, None);
}
let random_choice: i32 = rng.gen_range(0..26);
if random_choice == 25 {
create_tree(editor, x, y + 1, z, rng.gen_range(1..=3), args.winter);
} else if random_choice == 2 {
let flower_block = match rng.gen_range(1..=4) {
1 => RED_FLOWER,
2 => BLUE_FLOWER,
3 => YELLOW_FLOWER,
_ => WHITE_FLOWER,
};
editor.set_block(flower_block, x, y + 1, z, None, None);
} else if random_choice <= 1 {
editor.set_block(GRASS, x, y + 1, z, None, None);
"glacier" => {
editor.set_block(PACKED_ICE, x, 0, z, None, None);
editor.set_block(STONE, x, -1, z, None, None);
}
"bare_rock" => {
editor.set_block(STONE, x, 0, z, None, None);
}
_ => {}
}
// Generate surface elements
if editor.check_for_block(x, 0, z, Some(&[WATER])) {
continue;
}
match natural_type.as_str() {
"grassland" => {
if !editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK])) {
continue;
}
if rng.gen_bool(0.6) {
editor.set_block(GRASS, x, 1, z, None, None);
}
}
"heath" => {
if !editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK])) {
continue;
}
let random_choice = rng.gen_range(0..500);
if random_choice < 33 {
if random_choice <= 2 {
editor.set_block(COBBLESTONE, x, 0, z, None, None);
} else if random_choice < 6 {
editor.set_block(OAK_LEAVES, x, 1, z, None, None);
} else {
editor.set_block(GRASS, x, 1, z, None, None);
}
}
}
"scrub" => {
if !editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK])) {
continue;
}
let random_choice = rng.gen_range(0..500);
if random_choice == 0 {
Tree::create(editor, (x, 1, z));
} else if random_choice == 1 {
let flower_block = match rng.gen_range(1..=4) {
1 => RED_FLOWER,
2 => BLUE_FLOWER,
3 => YELLOW_FLOWER,
_ => WHITE_FLOWER,
};
editor.set_block(flower_block, x, 1, z, None, None);
} else if random_choice < 40 {
editor.set_block(OAK_LEAVES, x, 1, z, None, None);
if random_choice < 15 {
editor.set_block(OAK_LEAVES, x, 2, z, None, None);
}
} else if random_choice < 300 {
if random_choice < 250 {
editor.set_block(GRASS, x, 1, z, None, None);
} else {
editor.set_block(TALL_GRASS_BOTTOM, x, 1, z, None, None);
editor.set_block(TALL_GRASS_TOP, x, 2, z, None, None);
}
}
}
"tree_row" | "wood" => {
if !editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK])) {
continue;
}
let random_choice: i32 = rng.gen_range(0..30);
if random_choice == 0 {
Tree::create(editor, (x, 1, z));
} else if random_choice == 1 {
let flower_block = match rng.gen_range(1..=4) {
1 => RED_FLOWER,
2 => BLUE_FLOWER,
3 => YELLOW_FLOWER,
_ => WHITE_FLOWER,
};
editor.set_block(flower_block, x, 1, z, None, None);
} else if random_choice <= 12 {
editor.set_block(GRASS, x, 1, z, None, None);
}
}
"sand" => {
if editor.check_for_block(x, 0, z, Some(&[SAND]))
&& rng.gen_range(0..100) == 1
{
editor.set_block(DEAD_BUSH, x, 1, z, None, None);
}
}
"shoal" => {
if rng.gen_bool(0.05) {
editor.set_block(WATER, x, 0, z, Some(&[SAND, GRAVEL]), None);
}
}
"wetland" => {
if let Some(wetland_type) = element.tags().get("wetland") {
// Wetland without water blocks
if matches!(wetland_type.as_str(), "wet_meadow" | "fen") {
if rng.gen_bool(0.3) {
editor.set_block(GRASS_BLOCK, x, 0, z, Some(&[MUD]), None);
}
editor.set_block(GRASS, x, 1, z, None, None);
continue;
}
// All the other types of wetland
if rng.gen_bool(0.3) {
editor.set_block(
WATER,
x,
0,
z,
Some(&[MUD, GRASS_BLOCK]),
None,
);
continue;
}
if !editor.check_for_block(x, 0, z, Some(&[MUD, MOSS_BLOCK])) {
continue;
}
match wetland_type.as_str() {
"reedbed" => {
editor.set_block(TALL_GRASS_BOTTOM, x, 1, z, None, None);
editor.set_block(TALL_GRASS_TOP, x, 2, z, None, None);
}
"swamp" | "mangrove" => {
// TODO implement mangrove
let random_choice: i32 = rng.gen_range(0..40);
if random_choice == 0 {
Tree::create(editor, (x, 1, z));
} else if random_choice < 35 {
editor.set_block(GRASS, x, 1, z, None, None);
}
}
"bog" => {
if rng.gen_bool(0.2) {
editor.set_block(
MOSS_BLOCK,
x,
0,
z,
Some(&[MUD]),
None,
);
}
if rng.gen_bool(0.15) {
editor.set_block(GRASS, x, 1, z, None, None);
}
}
"tidalflat" => {
continue; // No vegetation here
}
_ => {
editor.set_block(GRASS, x, 1, z, None, None);
}
}
} else {
// Generic natural=wetland without wetland=... tag
if rng.gen_bool(0.3) {
editor.set_block(WATER, x, 0, z, Some(&[MUD]), None);
continue;
}
editor.set_block(GRASS, x, 1, z, None, None);
}
}
"mountain_range" => {
// Create block clusters instead of random placement
let cluster_chance = rng.gen_range(0..1000);
if cluster_chance < 50 {
// 5% chance to start a new cluster
let cluster_block = match rng.gen_range(0..7) {
0 => DIRT,
1 => STONE,
2 => GRAVEL,
3 => GRANITE,
4 => DIORITE,
5 => ANDESITE,
_ => GRASS_BLOCK,
};
// Generate cluster size (5-10 blocks radius)
let cluster_size = rng.gen_range(5..=10);
// Create cluster around current position
for dx in -(cluster_size as i32)..=(cluster_size as i32) {
for dz in -(cluster_size as i32)..=(cluster_size as i32) {
let cluster_x = x + dx;
let cluster_z = z + dz;
// Use distance to create more natural cluster shape
let distance = ((dx * dx + dz * dz) as f32).sqrt();
if distance <= cluster_size as f32 {
// Probability decreases with distance from center
let place_prob = 1.0 - (distance / cluster_size as f32);
if rng.gen::<f32>() < place_prob {
editor.set_block(
cluster_block,
cluster_x,
0,
cluster_z,
None,
None,
);
// Add vegetation on grass blocks
if cluster_block == GRASS_BLOCK {
let vegetation_chance = rng.gen_range(0..100);
if vegetation_chance == 0 {
// 1% chance for rare trees
Tree::create(
editor,
(cluster_x, 1, cluster_z),
);
} else if vegetation_chance < 15 {
// 15% chance for grass
editor.set_block(
GRASS, cluster_x, 1, cluster_z, None,
None,
);
} else if vegetation_chance < 25 {
// 10% chance for oak leaves
editor.set_block(
OAK_LEAVES, cluster_x, 1, cluster_z,
None, None,
);
}
}
}
}
}
}
}
}
"saddle" => {
// Saddle areas - lowest point between peaks, mix of stone and grass
let terrain_chance = rng.gen_range(0..100);
if terrain_chance < 30 {
// 30% chance for exposed stone
editor.set_block(STONE, x, 0, z, None, None);
} else if terrain_chance < 50 {
// 20% chance for gravel/rocky terrain
editor.set_block(GRAVEL, x, 0, z, None, None);
} else {
// 50% chance for grass
editor.set_block(GRASS_BLOCK, x, 0, z, None, None);
if rng.gen_bool(0.4) {
// 40% chance for grass on top
editor.set_block(GRASS, x, 1, z, None, None);
}
}
}
"ridge" => {
// Ridge areas - elevated crest, mostly rocky with some vegetation
let ridge_chance = rng.gen_range(0..100);
if ridge_chance < 60 {
// 60% chance for stone/rocky terrain
let rock_type = match rng.gen_range(0..4) {
0 => STONE,
1 => COBBLESTONE,
2 => GRANITE,
_ => ANDESITE,
};
editor.set_block(rock_type, x, 0, z, None, None);
} else {
// 40% chance for grass with sparse vegetation
editor.set_block(GRASS_BLOCK, x, 0, z, None, None);
let vegetation_chance = rng.gen_range(0..100);
if vegetation_chance < 20 {
// 20% chance for grass
editor.set_block(GRASS, x, 1, z, None, None);
} else if vegetation_chance < 25 {
// 5% chance for small shrubs
editor.set_block(OAK_LEAVES, x, 1, z, None, None);
}
}
}
"shrubbery" => {
// Manicured shrubs and decorative vegetation
editor.set_block(OAK_LEAVES, x, 1, z, None, None);
editor.set_block(OAK_LEAVES, x, 2, z, None, None);
}
"tundra" => {
// Treeless habitat with low vegetation, mosses, lichens
if !editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK])) {
continue;
}
let tundra_chance = rng.gen_range(0..100);
if tundra_chance < 40 {
// 40% chance for grass (sedges, grasses)
editor.set_block(GRASS, x, 1, z, None, None);
} else if tundra_chance < 60 {
// 20% chance for moss
editor.set_block(MOSS_BLOCK, x, 0, z, Some(&[GRASS_BLOCK]), None);
} else if tundra_chance < 70 {
// 10% chance for dead bush (lichens)
editor.set_block(DEAD_BUSH, x, 1, z, None, None);
}
// 30% chance for bare ground (no surface block)
}
"cliff" => {
// Cliff areas - predominantly stone with minimal vegetation
let cliff_chance = rng.gen_range(0..100);
if cliff_chance < 90 {
// 90% chance for stone variants
let stone_type = match rng.gen_range(0..4) {
0 => STONE,
1 => COBBLESTONE,
2 => ANDESITE,
_ => DIORITE,
};
editor.set_block(stone_type, x, 0, z, None, None);
} else {
// 10% chance for gravel/loose rock
editor.set_block(GRAVEL, x, 0, z, None, None);
}
}
"hill" => {
// Hill areas - elevated terrain with sparse trees and mostly grass
if !editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK])) {
continue;
}
let hill_chance = rng.gen_range(0..1000);
if hill_chance == 0 {
// 0.1% chance for rare trees
Tree::create(editor, (x, 1, z));
} else if hill_chance < 50 {
// 5% chance for flowers
let flower_block = match rng.gen_range(1..=4) {
1 => RED_FLOWER,
2 => BLUE_FLOWER,
3 => YELLOW_FLOWER,
_ => WHITE_FLOWER,
};
editor.set_block(flower_block, x, 1, z, None, None);
} else if hill_chance < 600 {
// 55% chance for grass
editor.set_block(GRASS, x, 1, z, None, None);
} else if hill_chance < 650 {
// 5% chance for tall grass
editor.set_block(TALL_GRASS_BOTTOM, x, 1, z, None, None);
editor.set_block(TALL_GRASS_TOP, x, 2, z, None, None);
}
// 35% chance for bare grass block
}
_ => {}
}
}
}
}
}
}
pub fn generate_natural_from_relation(
editor: &mut WorldEditor,
rel: &ProcessedRelation,
args: &Args,
) {
if rel.tags.contains_key("natural") {
// Generate individual ways with their original tags
for member in &rel.members {
if member.role == ProcessedMemberRole::Outer {
generate_natural(editor, &ProcessedElement::Way(member.way.clone()), args);
}
}
// Combine all outer ways into one with relation tags
let mut combined_nodes = Vec::new();
for member in &rel.members {
if member.role == ProcessedMemberRole::Outer {
combined_nodes.extend(member.way.nodes.clone());
}
}
// Only process if we have nodes
if !combined_nodes.is_empty() {
// Create combined way with relation tags
let combined_way = ProcessedWay {
id: rel.id,
nodes: combined_nodes,
tags: rel.tags.clone(),
};
// Generate natural area from combined way
generate_natural(editor, &ProcessedElement::Way(combined_way), args);
}
}
}

View File

@@ -1,11 +1,9 @@
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::cartesian::XZPoint;
use crate::ground::Ground;
use crate::osm_parser::ProcessedWay;
use crate::world_editor::WorldEditor;
pub fn generate_railways(editor: &mut WorldEditor, element: &ProcessedWay, ground: &Ground) {
pub fn generate_railways(editor: &mut WorldEditor, element: &ProcessedWay) {
if let Some(railway_type) = element.tags.get("railway") {
if [
"proposed",
@@ -41,9 +39,8 @@ pub fn generate_railways(editor: &mut WorldEditor, element: &ProcessedWay, groun
for j in 0..smoothed_points.len() {
let (bx, _, bz) = smoothed_points[j];
let ground_level = ground.level(XZPoint::new(bx, bz));
editor.set_block(IRON_BLOCK, bx, ground_level, bz, None, None);
editor.set_block(GRAVEL, bx, 0, bz, None, None);
let prev = if j > 0 {
Some(smoothed_points[j - 1])
@@ -62,10 +59,10 @@ pub fn generate_railways(editor: &mut WorldEditor, element: &ProcessedWay, groun
next.map(|(x, _, z)| (x, z)),
);
editor.set_block(rail_block, bx, ground_level + 1, bz, None, None);
editor.set_block(rail_block, bx, 1, bz, None, None);
if bx % 4 == 0 {
editor.set_block(OAK_LOG, bx, ground_level, bz, None, None);
editor.set_block(OAK_LOG, bx, 0, bz, None, None);
}
}
}
@@ -177,3 +174,71 @@ fn determine_rail_direction(
(None, None) => RAIL_NORTH_SOUTH,
}
}
pub fn generate_roller_coaster(editor: &mut WorldEditor, element: &ProcessedWay) {
if let Some(roller_coaster) = element.tags.get("roller_coaster") {
if roller_coaster == "track" {
// Check if it's indoor (skip if yes)
if let Some(indoor) = element.tags.get("indoor") {
if indoor == "yes" {
return;
}
}
// Check if layer is negative (skip if yes)
if let Some(layer) = element.tags.get("layer") {
if let Ok(layer_value) = layer.parse::<i32>() {
if layer_value < 0 {
return;
}
}
}
let elevation_height = 4; // 4 blocks in the air
let pillar_interval = 6; // Support pillars every 6 blocks
for i in 1..element.nodes.len() {
let prev_node = element.nodes[i - 1].xz();
let cur_node = element.nodes[i].xz();
let points = bresenham_line(prev_node.x, 0, prev_node.z, cur_node.x, 0, cur_node.z);
let smoothed_points = smooth_diagonal_rails(&points);
for j in 0..smoothed_points.len() {
let (bx, _, bz) = smoothed_points[j];
// Place track foundation at elevation height
editor.set_block(IRON_BLOCK, bx, elevation_height, bz, None, None);
let prev = if j > 0 {
Some(smoothed_points[j - 1])
} else {
None
};
let next = if j < smoothed_points.len() - 1 {
Some(smoothed_points[j + 1])
} else {
None
};
let rail_block = determine_rail_direction(
(bx, bz),
prev.map(|(x, _, z)| (x, z)),
next.map(|(x, _, z)| (x, z)),
);
// Place rail on top of the foundation
editor.set_block(rail_block, bx, elevation_height + 1, bz, None, None);
// Place support pillars every pillar_interval blocks
if bx % pillar_interval == 0 && bz % pillar_interval == 0 {
// Create a pillar from ground level up to the track
for y in 1..elevation_height {
editor.set_block(IRON_BLOCK, bx, y, bz, None, None);
}
}
}
}
}
}
}

View File

@@ -0,0 +1,303 @@
use crate::block_definitions::*;
use crate::world_editor::WorldEditor;
use std::collections::HashSet;
/// Interior layout for building ground floors (1st layer above floor)
#[rustfmt::skip]
const INTERIOR1_LAYER1: [[char; 23]; 23] = [
['1', 'U', ' ', 'W', 'C', ' ', ' ', ' ', 'S', 'S', 'W', 'B', 'T', 'T', 'B', 'W', '7', '8', ' ', ' ', ' ', ' ', 'W',],
['2', ' ', ' ', 'W', 'F', ' ', ' ', ' ', 'U', 'U', 'W', 'B', 'T', 'T', 'B', 'W', '7', '8', ' ', ' ', ' ', 'B', 'W',],
[' ', ' ', ' ', 'W', 'F', ' ', ' ', ' ', ' ', ' ', 'W', 'B', 'T', 'T', 'B', 'W', 'W', 'W', 'D', 'W', 'W', 'W', 'W',],
['W', 'W', 'D', 'W', 'L', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'A', 'W', ' ', ' ', ' ', ' ', ' ', ' ', 'W',],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'D', ' ', ' ', ' ', ' ', ' ', ' ', 'W',],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W', 'W', 'W', 'W', 'D', 'W', 'W', 'W', 'W', 'D', 'W', 'W', ' ', ' ', 'D',],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W', 'B', 'B', 'B', ' ', ' ', 'J', 'W', ' ', ' ', ' ', 'B', 'W', 'W', 'W',],
['W', 'W', 'W', 'W', 'D', 'W', ' ', ' ', 'W', 'T', 'S', 'S', 'T', ' ', ' ', 'W', 'S', 'S', ' ', 'B', 'W', 'W', 'W',],
[' ', ' ', ' ', ' ', ' ', 'W', ' ', ' ', 'W', 'T', 'T', 'T', 'T', ' ', ' ', 'W', 'U', 'U', ' ', 'B', 'W', ' ', ' ',],
[' ', ' ', ' ', ' ', ' ', 'W', ' ', ' ', 'D', 'T', 'T', 'T', 'T', ' ', 'B', 'W', ' ', ' ', ' ', 'B', 'W', ' ', ' ',],
['L', ' ', 'A', 'L', 'W', 'W', ' ', ' ', 'W', 'J', 'U', 'U', ' ', ' ', 'B', 'W', 'W', 'D', 'W', 'W', 'W', ' ', ' ',],
['W', 'W', 'W', 'W', 'W', 'W', ' ', ' ', 'W', 'W', 'W', 'W', 'W', 'D', 'W', 'W', ' ', ' ', 'W', 'C', 'C', 'W', 'W',],
['B', 'B', ' ', 'W', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'D', ' ', ' ', 'W', ' ', ' ', 'W', 'W',],
[' ', ' ', ' ', 'D', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'D', ' ', ' ', ' ', ' ', ' ', ' ', 'D',],
[' ', '6', ' ', 'W', ' ', ' ', 'W', 'W', 'W', 'W', 'W', 'D', 'W', 'W', 'D', 'W', ' ', ' ', ' ', ' ', ' ', ' ', 'W',],
['U', '5', ' ', 'W', ' ', ' ', 'W', 'C', 'F', 'F', ' ', ' ', 'W', ' ', ' ', 'W', 'W', 'D', 'W', 'W', ' ', ' ', 'W',],
['W', 'W', 'W', 'W', ' ', ' ', 'W', ' ', ' ', ' ', ' ', ' ', 'W', 'L', ' ', 'W', 'A', ' ', 'B', 'W', ' ', ' ', 'W',],
['B', ' ', ' ', ' ', ' ', ' ', 'D', ' ', ' ', ' ', ' ', ' ', 'W', ' ', ' ', 'W', ' ', ' ', 'B', 'W', 'J', ' ', 'W',],
[' ', ' ', ' ', ' ', ' ', ' ', 'W', ' ', ' ', ' ', ' ', ' ', ' ', 'W', ' ', 'W', 'U', ' ', ' ', 'W', 'B', ' ', 'D',],
['J', ' ', ' ', 'C', 'B', 'B', 'W', 'L', 'F', ' ', 'W', 'F', ' ', 'W', 'L', 'W', '7', '8', ' ', 'W', 'B', ' ', 'W',],
['B', ' ', ' ', 'B', 'W', 'W', 'W', 'W', 'W', ' ', 'W', 'A', ' ', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'C', ' ', 'W',],
['B', ' ', ' ', 'B', 'W', ' ', ' ', ' ', 'D', ' ', 'W', 'C', ' ', ' ', 'W', 'W', 'B', 'B', 'B', 'B', 'W', 'D', 'W',],
['W', 'W', 'D', 'W', 'C', ' ', ' ', ' ', 'W', 'W', 'W', 'B', 'T', 'T', 'B', 'W', ' ', ' ', ' ', ' ', ' ', ' ', 'W',],
];
/// Interior layout for building ground floors (2nd layer above floor)
#[rustfmt::skip]
const INTERIOR1_LAYER2: [[char; 23]; 23] = [
[' ', 'P', ' ', 'W', ' ', ' ', ' ', ' ', ' ', ' ', 'W', 'B', ' ', ' ', 'B', 'W', ' ', ' ', ' ', ' ', ' ', ' ', 'W',],
[' ', ' ', ' ', 'W', ' ', ' ', ' ', ' ', 'P', 'P', 'W', 'B', ' ', ' ', 'B', 'W', ' ', ' ', ' ', ' ', ' ', 'B', 'W',],
[' ', ' ', ' ', 'W', ' ', ' ', ' ', ' ', ' ', ' ', 'W', 'B', ' ', ' ', 'B', 'W', 'W', 'W', 'D', 'W', 'W', 'W', 'W',],
['W', 'W', 'D', 'W', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W', ' ', ' ', ' ', ' ', ' ', ' ', 'W',],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'D', ' ', ' ', ' ', ' ', ' ', ' ', 'W',],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W', 'W', 'W', 'W', 'D', 'W', 'W', 'W', 'W', 'D', 'W', 'W', ' ', ' ', 'D',],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W', 'B', 'B', 'B', ' ', ' ', ' ', 'W', ' ', ' ', ' ', 'B', 'W', 'W', 'W',],
['W', 'W', 'W', 'W', 'D', 'W', ' ', ' ', 'W', ' ', ' ', ' ', ' ', ' ', ' ', 'W', ' ', ' ', ' ', 'B', 'W', 'W', 'W',],
[' ', ' ', ' ', ' ', ' ', 'W', ' ', ' ', 'W', ' ', ' ', ' ', ' ', ' ', ' ', 'W', 'P', 'P', ' ', 'B', 'W', ' ', ' ',],
[' ', ' ', ' ', ' ', ' ', 'W', ' ', ' ', 'D', ' ', ' ', ' ', ' ', ' ', 'B', 'W', ' ', ' ', ' ', 'B', 'W', ' ', ' ',],
[' ', ' ', ' ', ' ', 'W', 'W', ' ', ' ', 'W', ' ', 'P', 'P', ' ', ' ', 'B', 'W', 'W', 'D', 'W', 'W', 'W', ' ', ' ',],
['W', 'W', 'W', 'W', 'W', 'W', ' ', ' ', 'W', 'W', 'W', 'W', 'W', 'D', 'W', 'W', ' ', ' ', 'W', 'C', 'C', 'W', 'W',],
['B', 'B', ' ', 'W', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'D', ' ', ' ', 'W', ' ', ' ', 'W', 'W',],
[' ', ' ', ' ', 'D', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'D', ' ', ' ', ' ', ' ', ' ', ' ', 'D',],
[' ', ' ', ' ', 'W', ' ', ' ', 'W', 'W', 'W', 'W', 'W', 'D', 'W', 'W', 'D', 'W', ' ', ' ', ' ', ' ', ' ', ' ', 'W',],
['P', ' ', ' ', 'W', ' ', ' ', 'W', 'N', ' ', ' ', ' ', ' ', 'W', ' ', ' ', 'W', 'W', 'D', 'W', 'W', ' ', ' ', 'W',],
['W', 'W', 'W', 'W', ' ', ' ', 'W', ' ', ' ', ' ', ' ', ' ', 'W', ' ', ' ', 'W', ' ', ' ', 'B', 'W', ' ', ' ', 'W',],
['B', ' ', ' ', ' ', ' ', ' ', 'D', ' ', ' ', ' ', ' ', ' ', 'W', ' ', ' ', 'W', ' ', ' ', 'C', 'W', ' ', ' ', 'W',],
[' ', ' ', ' ', ' ', ' ', ' ', 'W', ' ', ' ', ' ', ' ', ' ', ' ', 'W', ' ', 'W', 'P', ' ', ' ', 'W', 'B', ' ', 'D',],
[' ', ' ', ' ', ' ', 'B', 'B', 'W', ' ', ' ', ' ', 'W', ' ', ' ', 'W', 'P', 'W', ' ', ' ', ' ', 'W', 'B', ' ', 'W',],
['B', ' ', ' ', 'B', 'W', 'W', 'W', 'W', 'W', ' ', 'W', ' ', ' ', 'W', 'W', 'W', 'W', 'W', 'W', 'W', ' ', ' ', 'W',],
['B', ' ', ' ', 'B', 'W', ' ', ' ', ' ', 'D', ' ', 'W', 'N', ' ', ' ', 'W', 'W', 'B', 'B', 'B', 'B', 'W', 'D', 'W',],
['W', 'W', 'D', 'W', ' ', ' ', ' ', ' ', 'W', 'W', 'W', 'B', ' ', ' ', 'B', 'W', ' ', ' ', ' ', ' ', ' ', ' ', 'W',],
];
/// Interior layout for building level floors (1nd layer above floor)
#[rustfmt::skip]
const INTERIOR2_LAYER1: [[char; 23]; 23] = [
['W', 'W', 'W', 'D', 'W', 'W', 'W', 'W', 'W', ' ', ' ', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'D', 'W', 'W', 'W',],
['U', ' ', ' ', ' ', ' ', ' ', 'C', 'W', 'L', ' ', ' ', 'L', 'W', 'A', 'A', 'W', ' ', ' ', ' ', ' ', ' ', 'L', 'W',],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W', ' ', ' ', ' ', ' ', 'W', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W',],
[' ', ' ', 'W', 'W', 'W', ' ', ' ', 'W', ' ', ' ', ' ', ' ', 'W', ' ', ' ', ' ', ' ', ' ', 'S', 'S', 'S', ' ', 'W',],
[' ', ' ', 'W', 'F', ' ', ' ', ' ', 'W', 'C', ' ', ' ', ' ', ' ', ' ', ' ', 'W', 'J', ' ', 'U', 'U', 'U', ' ', 'D',],
['U', ' ', 'W', 'F', ' ', ' ', ' ', 'W', ' ', ' ', ' ', ' ', 'W', ' ', ' ', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W',],
['U', ' ', 'W', 'F', ' ', ' ', ' ', 'D', ' ', ' ', 'T', 'T', 'W', ' ', ' ', ' ', ' ', ' ', 'U', 'W', ' ', 'L', 'W',],
[' ', ' ', 'W', 'W', 'W', ' ', ' ', 'W', ' ', ' ', 'T', 'J', 'W', ' ', ' ', ' ', ' ', ' ', ' ', 'W', ' ', ' ', 'W',],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W', 'W', 'W', 'W', 'W', 'W', 'D', 'W', 'W', 'W', ' ', ' ', 'W', 'L', ' ', 'W',],
['J', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W', 'C', ' ', ' ', ' ', 'B', 'W', ' ', ' ', 'W', ' ', ' ', 'W',],
['W', 'W', 'W', 'W', 'W', 'L', ' ', ' ', ' ', ' ', 'W', 'C', ' ', ' ', ' ', 'B', 'W', ' ', ' ', 'W', 'W', 'D', 'W',],
[' ', 'A', 'B', 'B', 'W', 'W', 'W', 'W', ' ', ' ', 'W', ' ', ' ', ' ', ' ', 'B', 'W', ' ', ' ', ' ', ' ', ' ', 'W',],
[' ', ' ', ' ', 'B', 'W', 'L', ' ', ' ', ' ', ' ', 'W', 'L', ' ', ' ', 'B', 'W', 'W', 'B', 'B', 'W', ' ', ' ', 'W',],
[' ', ' ', ' ', 'B', 'W', ' ', ' ', ' ', ' ', ' ', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', ' ', ' ', 'D',],
[' ', ' ', ' ', ' ', 'D', ' ', ' ', 'U', ' ', ' ', ' ', 'D', ' ', ' ', 'F', 'F', 'W', 'A', 'A', 'W', ' ', ' ', 'W',],
[' ', ' ', ' ', ' ', 'W', ' ', ' ', 'U', ' ', ' ', 'W', 'W', ' ', ' ', ' ', ' ', 'C', ' ', ' ', 'W', ' ', ' ', 'W',],
['C', ' ', ' ', ' ', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', ' ', ' ', ' ', ' ', 'L', ' ', ' ', 'W', 'W', 'D', 'W',],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'D', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W',],
['L', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W', 'L', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W',],
['W', 'W', 'W', 'W', 'W', 'W', ' ', ' ', 'U', 'U', ' ', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', ' ', 'W',],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'U', 'U', ' ', 'W', 'B', ' ', 'U', 'U', 'B', ' ', ' ', ' ', ' ', ' ', 'W',],
['S', 'S', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W', 'B', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'B', ' ', 'W',],
['U', 'U', ' ', ' ', ' ', 'L', 'B', 'B', 'B', ' ', ' ', 'W', 'B', 'B', 'B', 'B', 'B', 'B', 'B', ' ', 'B', 'D', 'W',],
];
/// Interior layout for building level floors (2nd layer above floor)
#[rustfmt::skip]
const INTERIOR2_LAYER2: [[char; 23]; 23] = [
['W', 'W', 'W', 'D', 'W', 'W', 'W', 'W', 'W', ' ', ' ', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'D', 'W', 'W', 'W',],
['P', ' ', ' ', ' ', ' ', ' ', ' ', 'W', 'E', ' ', ' ', 'E', 'W', ' ', ' ', 'W', ' ', ' ', ' ', ' ', ' ', 'E', 'W',],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W', ' ', ' ', ' ', ' ', 'W', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W',],
[' ', ' ', 'W', 'W', 'W', ' ', ' ', 'W', ' ', ' ', ' ', ' ', 'W', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W',],
[' ', ' ', 'W', 'F', ' ', ' ', ' ', 'W', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W', ' ', ' ', 'P', 'P', 'P', ' ', 'D',],
['P', ' ', 'W', 'F', ' ', ' ', ' ', 'W', ' ', ' ', ' ', ' ', 'W', ' ', ' ', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W',],
['P', ' ', 'W', 'F', ' ', ' ', ' ', 'D', ' ', ' ', ' ', ' ', 'W', ' ', ' ', ' ', ' ', ' ', 'P', 'W', ' ', 'P', 'W',],
[' ', ' ', 'W', 'W', 'W', ' ', ' ', 'W', ' ', ' ', ' ', ' ', 'W', ' ', ' ', ' ', ' ', ' ', ' ', 'W', ' ', ' ', 'W',],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W', 'W', 'W', 'W', 'W', 'W', 'D', 'W', 'W', 'W', ' ', ' ', 'W', ' ', ' ', 'W',],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W', 'P', ' ', ' ', ' ', 'B', 'W', ' ', ' ', 'W', ' ', ' ', 'W',],
['W', 'W', 'W', 'W', 'W', 'E', ' ', ' ', ' ', ' ', 'W', 'P', ' ', ' ', ' ', 'B', 'W', ' ', ' ', 'W', 'W', 'D', 'W',],
[' ', ' ', 'B', 'B', 'W', 'W', 'W', 'W', ' ', ' ', 'W', ' ', ' ', ' ', ' ', 'B', 'W', ' ', ' ', ' ', ' ', ' ', 'W',],
[' ', ' ', ' ', 'B', 'W', 'E', ' ', ' ', ' ', ' ', 'W', 'E', ' ', ' ', 'B', 'W', 'W', 'B', 'B', 'W', ' ', ' ', 'W',],
[' ', ' ', ' ', 'B', 'W', ' ', ' ', ' ', ' ', ' ', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', ' ', ' ', 'D',],
[' ', ' ', ' ', ' ', 'D', ' ', ' ', 'P', ' ', ' ', ' ', 'D', ' ', ' ', ' ', ' ', 'W', ' ', ' ', 'W', ' ', ' ', 'W',],
[' ', ' ', ' ', ' ', 'W', ' ', ' ', 'P', ' ', ' ', 'W', 'W', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W', ' ', ' ', 'W',],
[' ', ' ', ' ', ' ', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', ' ', ' ', ' ', ' ', 'E', ' ', ' ', 'W', 'W', 'D', 'W',],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'D', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W',],
['E', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W', 'E', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W',],
['W', 'W', 'W', 'W', 'W', 'W', ' ', ' ', 'P', 'P', ' ', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', ' ', 'W',],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'P', 'P', ' ', 'W', 'B', ' ', 'P', 'P', 'B', ' ', ' ', ' ', ' ', ' ', 'W',],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'W', 'B', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'B', ' ', 'W',],
['P', 'P', ' ', ' ', ' ', 'E', 'B', 'B', 'B', ' ', ' ', 'W', 'B', 'B', 'B', 'B', 'B', 'B', 'B', ' ', 'B', ' ', 'D',],
];
/// Maps interior layout characters to actual block types for different floor layers
#[inline(always)]
pub fn get_interior_block(c: char, is_layer2: bool, wall_block: Block) -> Option<Block> {
match c {
' ' => None, // Nothing
'W' => Some(wall_block), // Use the building's wall block for interior walls
'U' => Some(OAK_FENCE), // Oak Fence
'S' => Some(OAK_STAIRS), // Oak Stairs
'B' => Some(BOOKSHELF), // Bookshelf
'C' => Some(CRAFTING_TABLE), // Crafting Table
'F' => Some(FURNACE), // Furnace
'1' => Some(RED_BED_NORTH_HEAD), // Bed North Head
'2' => Some(RED_BED_NORTH_FOOT), // Bed North Foot
'3' => Some(RED_BED_EAST_HEAD), // Bed East Head
'4' => Some(RED_BED_EAST_FOOT), // Bed East Foot
'5' => Some(RED_BED_SOUTH_HEAD), // Bed South Head
'6' => Some(RED_BED_SOUTH_FOOT), // Bed South Foot
'7' => Some(RED_BED_WEST_HEAD), // Bed West Head
'8' => Some(RED_BED_WEST_FOOT), // Bed West Foot
// 'H' => Some(CHEST), // Chest
'L' => Some(CAULDRON), // Cauldron
'A' => Some(ANVIL), // Anvil
'P' => Some(OAK_PRESSURE_PLATE), // Pressure Plate
'D' => {
// Use different door types for different layers
if is_layer2 {
Some(DARK_OAK_DOOR_UPPER)
} else {
Some(DARK_OAK_DOOR_LOWER)
}
}
'J' => Some(NOTE_BLOCK), // Note block
'G' => Some(GLOWSTONE), // Glowstone
'N' => Some(BREWING_STAND), // Brewing Stand
'T' => Some(WHITE_CARPET), // White Carpet
'E' => Some(OAK_LEAVES), // Oak Leaves
_ => None, // Default case for unknown characters
}
}
/// Generates interior layouts inside buildings at each floor level
#[allow(clippy::too_many_arguments)]
pub fn generate_building_interior(
editor: &mut WorldEditor,
floor_area: &[(i32, i32)],
min_x: i32,
min_z: i32,
max_x: i32,
max_z: i32,
start_y_offset: i32,
building_height: i32,
wall_block: Block,
floor_levels: &[i32],
args: &crate::args::Args,
element: &crate::osm_parser::ProcessedWay,
abs_terrain_offset: i32,
) {
// Skip interior generation for very small buildings
let width = max_x - min_x + 1;
let depth = max_z - min_z + 1;
if width < 8 || depth < 8 {
return; // Building too small for interior
}
// For efficiency, create a HashSet of floor area coordinates
let floor_area_set: HashSet<(i32, i32)> = floor_area.iter().cloned().collect();
// Add buffer around edges to avoid placing furniture too close to walls
let buffer = 2;
let interior_min_x = min_x + buffer;
let interior_min_z = min_z + buffer;
let interior_max_x = max_x - buffer;
let interior_max_z = max_z - buffer;
// Generate interiors for each floor
for (floor_index, &floor_y) in floor_levels.iter().enumerate() {
// Store wall and door positions for this floor to extend them to the ceiling
let mut wall_positions = Vec::new();
let mut door_positions = Vec::new();
// Determine the floor extension height (ceiling) - either next floor or roof
let current_floor_ceiling = if floor_index < floor_levels.len() - 1 {
// For intermediate floors, extend walls up to just below the next floor
floor_levels[floor_index + 1] - 1
} else {
// Last floor ceiling depends on roof generation
if args.roof
&& element.tags.contains_key("roof:shape")
&& element.tags.get("roof:shape").unwrap() != "flat"
{
// When roof generation is enabled with non-flat roofs, stop at building height (no extra ceiling)
start_y_offset + building_height
} else {
// When roof generation is disabled or flat roof, extend to building top + 1 (includes ceiling)
start_y_offset + building_height + 1
}
};
// Choose the appropriate interior pattern based on floor number
let (layer1, layer2) = if floor_index == 0 {
// Ground floor uses INTERIOR1 patterns
(&INTERIOR1_LAYER1, &INTERIOR1_LAYER2)
} else {
// Upper floors use INTERIOR2 patterns
(&INTERIOR2_LAYER1, &INTERIOR2_LAYER2)
};
// Get dimensions for the selected pattern
let pattern_height = layer1.len() as i32;
let pattern_width = layer1[0].len() as i32;
// Calculate Y offset - place interior 1 block above floor level consistently
let y_offset = 1;
// Create a seamless repeating pattern across the interior of this floor
for z in interior_min_z..=interior_max_z {
for x in interior_min_x..=interior_max_x {
// Skip if outside the building's floor area
if !floor_area_set.contains(&(x, z)) {
continue;
}
// Map the world coordinates to pattern coordinates using modulo
// This creates a seamless tiling effect across the entire building
// Add floor_index offset to create variation between floors
let pattern_x = ((x - interior_min_x + floor_index as i32) % pattern_width
+ pattern_width)
% pattern_width;
let pattern_z = ((z - interior_min_z + floor_index as i32) % pattern_height
+ pattern_height)
% pattern_height;
// Access the pattern arrays safely
let cell1 = layer1[pattern_z as usize][pattern_x as usize];
let cell2 = layer2[pattern_z as usize][pattern_x as usize];
// Place first layer blocks
if let Some(block) = get_interior_block(cell1, false, wall_block) {
editor.set_block_absolute(
block,
x,
floor_y + y_offset + abs_terrain_offset,
z,
None,
None,
);
// If this is a wall in layer 1, add to wall positions to extend later
if cell1 == 'W' {
wall_positions.push((x, z));
}
// If this is a door in layer 1, add to door positions to add wall above later
else if cell1 == 'D' {
door_positions.push((x, z));
}
}
// Place second layer blocks
if let Some(block) = get_interior_block(cell2, true, wall_block) {
editor.set_block_absolute(
block,
x,
floor_y + y_offset + abs_terrain_offset + 1,
z,
None,
None,
);
}
}
}
// Extend walls all the way to the next floor ceiling or roof
for (x, z) in &wall_positions {
for y in (floor_y + y_offset + 2)..=current_floor_ceiling {
editor.set_block_absolute(wall_block, *x, y + abs_terrain_offset, *z, None, None);
}
}
// Add wall blocks above doors all the way to the ceiling/next floor
for (x, z) in &door_positions {
for y in (floor_y + y_offset + 2)..=current_floor_ceiling {
editor.set_block_absolute(wall_block, *x, y + abs_terrain_offset, *z, None, None);
}
}
}
}

View File

@@ -0,0 +1 @@
pub mod buildings_interior;

View File

@@ -1,10 +1,8 @@
use crate::block_definitions::*;
use crate::cartesian::XZPoint;
use crate::ground::Ground;
use crate::osm_parser::ProcessedNode;
use crate::world_editor::WorldEditor;
pub fn generate_tourisms(editor: &mut WorldEditor, element: &ProcessedNode, ground: &Ground) {
pub fn generate_tourisms(editor: &mut WorldEditor, element: &ProcessedNode) {
// Skip if 'layer' or 'level' is negative in the tags
if let Some(layer) = element.tags.get("layer") {
if layer.parse::<i32>().unwrap_or(0) < 0 {
@@ -22,15 +20,14 @@ pub fn generate_tourisms(editor: &mut WorldEditor, element: &ProcessedNode, grou
let x: i32 = element.x;
let z: i32 = element.z;
// Calculate the dynamic ground level
let ground_level = ground.level(XZPoint::new(x, z));
if tourism_type == "information" {
if let Some("board") = element.tags.get("information").map(|x: &String| x.as_str()) {
// Draw an information board
// TODO draw a sign with text
editor.set_block(COBBLESTONE_WALL, x, ground_level + 1, z, None, None);
editor.set_block(OAK_PLANKS, x, ground_level + 2, z, None, None);
if let Some(info_type) = element.tags.get("information").map(|x: &String| x.as_str()) {
if info_type != "office" && info_type != "visitor_centre" {
// Draw an information board
// TODO draw a sign with text if provided
editor.set_block(COBBLESTONE_WALL, x, 1, z, None, None);
editor.set_block(OAK_PLANKS, x, 2, z, None, None);
}
}
}
}

View File

@@ -1,166 +1,342 @@
use crate::block_definitions::*;
use crate::world_editor::WorldEditor;
use rand::Rng;
/// Helper function to set blocks in a circular pattern around a central point.
fn round1(editor: &mut WorldEditor, material: Block, x: i32, y: i32, z: i32) {
editor.set_block(material, x - 2, y, z, None, None);
editor.set_block(material, x + 2, y, z, None, None);
editor.set_block(material, x, y, z - 2, None, None);
editor.set_block(material, x, y, z + 2, None, None);
editor.set_block(material, x - 1, y, z - 1, None, None);
editor.set_block(material, x + 1, y, z + 1, None, None);
editor.set_block(material, x + 1, y, z - 1, None, None);
editor.set_block(material, x - 1, y, z + 1, None, None);
}
type Coord = (i32, i32, i32);
/// Helper function to set blocks in a wider circular pattern.
fn round2(editor: &mut WorldEditor, material: Block, x: i32, y: i32, z: i32) {
editor.set_block(material, x + 3, y, z, None, None);
editor.set_block(material, x + 2, y, z - 1, None, None);
editor.set_block(material, x + 2, y, z + 1, None, None);
editor.set_block(material, x + 1, y, z - 2, None, None);
editor.set_block(material, x + 1, y, z + 2, None, None);
editor.set_block(material, x - 3, y, z, None, None);
editor.set_block(material, x - 2, y, z - 1, None, None);
editor.set_block(material, x - 2, y, z + 1, None, None);
editor.set_block(material, x - 1, y, z + 2, None, None);
editor.set_block(material, x - 1, y, z - 2, None, None);
editor.set_block(material, x, y, z - 3, None, None);
editor.set_block(material, x, y, z + 3, None, None);
}
// TODO all this data would probably be better suited in a TOML file or something.
/// Helper function to set blocks in a more scattered circular pattern.
fn round3(editor: &mut WorldEditor, material: Block, x: i32, y: i32, z: i32) {
editor.set_block(material, x + 3, y, z - 1, None, None);
editor.set_block(material, x + 3, y, z + 1, None, None);
editor.set_block(material, x + 2, y, z - 2, None, None);
editor.set_block(material, x + 2, y, z + 2, None, None);
editor.set_block(material, x + 1, y, z - 3, None, None);
editor.set_block(material, x + 1, y, z + 3, None, None);
editor.set_block(material, x - 3, y, z - 1, None, None);
editor.set_block(material, x - 3, y, z + 1, None, None);
editor.set_block(material, x - 2, y, z - 2, None, None);
editor.set_block(material, x - 2, y, z + 2, None, None);
editor.set_block(material, x - 1, y, z + 3, None, None);
editor.set_block(material, x - 1, y, z - 3, None, None);
}
/// A circular pattern around a central point.
#[rustfmt::skip]
const ROUND1_PATTERN: [Coord; 8] = [
(-2, 0, 0),
(2, 0, 0),
(0, 0, -2),
(0, 0, 2),
(-1, 0, -1),
(1, 0, 1),
(1, 0, -1),
(-1, 0, 1),
];
/// Function to create different types of trees.
pub fn create_tree(editor: &mut WorldEditor, x: i32, y: i32, z: i32, typetree: u8, snow: bool) {
let mut blacklist: Vec<Block> = Vec::new();
blacklist.extend(building_corner_variations());
blacklist.extend(building_wall_variations());
blacklist.extend(building_floor_variations());
blacklist.push(WATER);
/// A wider circular pattern.
const ROUND2_PATTERN: [Coord; 12] = [
(3, 0, 0),
(2, 0, -1),
(2, 0, 1),
(1, 0, -2),
(1, 0, 2),
(-3, 0, 0),
(-2, 0, -1),
(-2, 0, 1),
(-1, 0, 2),
(-1, 0, -2),
(0, 0, -3),
(0, 0, 3),
];
if editor.check_for_block(x, y - 1, z, None, Some(&blacklist)) {
return;
}
/// A more scattered circular pattern.
const ROUND3_PATTERN: [Coord; 12] = [
(3, 0, -1),
(3, 0, 1),
(2, 0, -2),
(2, 0, 2),
(1, 0, -3),
(1, 0, 3),
(-3, 0, -1),
(-3, 0, 1),
(-2, 0, -2),
(-2, 0, 2),
(-1, 0, 3),
(-1, 0, -3),
];
match typetree {
1 => {
// Oak tree
editor.fill_blocks(OAK_LOG, x, y, z, x, y + 8, z, None, None);
editor.fill_blocks(OAK_LEAVES, x - 1, y + 3, z, x - 1, y + 9, z, None, None);
editor.fill_blocks(OAK_LEAVES, x + 1, y + 3, z, x + 1, y + 9, z, None, None);
editor.fill_blocks(OAK_LEAVES, x, y + 3, z - 1, x, y + 9, z - 1, None, None);
editor.fill_blocks(OAK_LEAVES, x, y + 3, z + 1, x, y + 9, z + 1, None, None);
editor.fill_blocks(OAK_LEAVES, x, y + 9, z, x, y + 10, z, None, None);
round1(editor, OAK_LEAVES, x, y + 8, z);
round1(editor, OAK_LEAVES, x, y + 7, z);
round1(editor, OAK_LEAVES, x, y + 6, z);
round1(editor, OAK_LEAVES, x, y + 5, z);
round1(editor, OAK_LEAVES, x, y + 4, z);
round1(editor, OAK_LEAVES, x, y + 3, z);
round2(editor, OAK_LEAVES, x, y + 7, z);
round2(editor, OAK_LEAVES, x, y + 6, z);
round2(editor, OAK_LEAVES, x, y + 5, z);
round2(editor, OAK_LEAVES, x, y + 4, z);
round3(editor, OAK_LEAVES, x, y + 6, z);
round3(editor, OAK_LEAVES, x, y + 5, z);
/// Used for iterating over each of the round patterns
const ROUND_PATTERNS: [&[Coord]; 3] = [&ROUND1_PATTERN, &ROUND2_PATTERN, &ROUND3_PATTERN];
if snow {
editor.set_block(SNOW_LAYER, x, y + 11, z, None, None);
editor.set_block(SNOW_LAYER, x + 1, y + 10, z, None, None);
editor.set_block(SNOW_LAYER, x - 1, y + 10, z, None, None);
editor.set_block(SNOW_LAYER, x, y + 10, z - 1, None, None);
editor.set_block(SNOW_LAYER, x, y + 10, z + 1, None, None);
round1(editor, SNOW_LAYER, x, y + 9, z);
round1(editor, SNOW_LAYER, x, y + 8, z);
round1(editor, SNOW_LAYER, x, y + 7, z);
round1(editor, SNOW_LAYER, x, y + 6, z);
round2(editor, SNOW_LAYER, x, y + 8, z);
round2(editor, SNOW_LAYER, x, y + 7, z);
round2(editor, SNOW_LAYER, x, y + 6, z);
round2(editor, SNOW_LAYER, x, y + 5, z);
round3(editor, SNOW_LAYER, x, y + 7, z);
round3(editor, SNOW_LAYER, x, y + 6, z);
}
}
2 => {
// Spruce tree
editor.fill_blocks(SPRUCE_LOG, x, y, z, x, y + 9, z, None, None);
editor.fill_blocks(BIRCH_LEAVES, x - 1, y + 3, z, x - 1, y + 10, z, None, None);
editor.fill_blocks(BIRCH_LEAVES, x + 1, y + 3, z, x + 1, y + 10, z, None, None);
editor.fill_blocks(BIRCH_LEAVES, x, y + 3, z - 1, x, y + 10, z - 1, None, None);
editor.fill_blocks(BIRCH_LEAVES, x, y + 3, z + 1, x, y + 10, z + 1, None, None);
editor.set_block(BIRCH_LEAVES, x, y + 10, z, None, None);
round1(editor, BIRCH_LEAVES, x, y + 9, z);
round1(editor, BIRCH_LEAVES, x, y + 7, z);
round1(editor, BIRCH_LEAVES, x, y + 6, z);
round1(editor, BIRCH_LEAVES, x, y + 4, z);
round1(editor, BIRCH_LEAVES, x, y + 3, z);
round2(editor, BIRCH_LEAVES, x, y + 6, z);
round2(editor, BIRCH_LEAVES, x, y + 3, z);
//////////////////////////////////////////////////
if snow {
editor.set_block(SNOW_LAYER, x, y + 11, z, None, None);
editor.set_block(SNOW_LAYER, x + 1, y + 11, z, None, None);
editor.set_block(SNOW_LAYER, x - 1, y + 11, z, None, None);
editor.set_block(SNOW_LAYER, x, y + 11, z - 1, None, None);
editor.set_block(SNOW_LAYER, x, y + 11, z + 1, None, None);
round1(editor, SNOW_LAYER, x, y + 10, z);
round1(editor, SNOW_LAYER, x, y + 8, z);
round1(editor, SNOW_LAYER, x, y + 7, z);
round1(editor, SNOW_LAYER, x, y + 5, z);
round1(editor, SNOW_LAYER, x, y + 4, z);
round2(editor, SNOW_LAYER, x, y + 7, z);
round2(editor, SNOW_LAYER, x, y + 4, z);
}
}
3 => {
// Birch tree
editor.fill_blocks(BIRCH_LOG, x, y, z, x, y + 6, z, None, None);
editor.fill_blocks(BIRCH_LEAVES, x - 1, y + 2, z, x - 1, y + 7, z, None, None);
editor.fill_blocks(BIRCH_LEAVES, x + 1, y + 2, z, x + 1, y + 7, z, None, None);
editor.fill_blocks(BIRCH_LEAVES, x, y + 2, z - 1, x, y + 7, z - 1, None, None);
editor.fill_blocks(BIRCH_LEAVES, x, y + 2, z + 1, x, y + 7, z + 1, None, None);
editor.fill_blocks(BIRCH_LEAVES, x, y + 7, z, x, y + 8, z, None, None);
round1(editor, BIRCH_LEAVES, x, y + 6, z);
round1(editor, BIRCH_LEAVES, x, y + 5, z);
round1(editor, BIRCH_LEAVES, x, y + 4, z);
round1(editor, BIRCH_LEAVES, x, y + 3, z);
round1(editor, BIRCH_LEAVES, x, y + 2, z);
round2(editor, BIRCH_LEAVES, x, y + 2, z);
round2(editor, BIRCH_LEAVES, x, y + 3, z);
round2(editor, BIRCH_LEAVES, x, y + 4, z);
const OAK_LEAVES_FILL: [(Coord, Coord); 5] = [
((-1, 3, 0), (-1, 9, 0)),
((1, 3, 0), (1, 9, 0)),
((0, 3, -1), (0, 9, -1)),
((0, 3, 1), (0, 9, 1)),
((0, 9, 0), (0, 10, 0)),
];
if snow {
editor.set_block(SNOW_LAYER, x, y + 9, z, None, None);
editor.set_block(SNOW_LAYER, x + 1, y + 8, z, None, None);
editor.set_block(SNOW_LAYER, x - 1, y + 8, z, None, None);
editor.set_block(SNOW_LAYER, x, y + 8, z - 1, None, None);
editor.set_block(SNOW_LAYER, x, y + 8, z + 1, None, None);
round1(editor, SNOW_LAYER, x, y + 7, z);
round1(editor, SNOW_LAYER, x, y + 6, z);
round1(editor, SNOW_LAYER, x, y + 5, z);
round1(editor, SNOW_LAYER, x, y + 4, z);
round1(editor, SNOW_LAYER, x, y + 3, z);
round2(editor, SNOW_LAYER, x, y + 3, z);
round2(editor, SNOW_LAYER, x, y + 4, z);
round2(editor, SNOW_LAYER, x, y + 5, z);
}
}
_ => {} // Do nothing if typetree is not recognized
const SPRUCE_LEAVES_FILL: [(Coord, Coord); 6] = [
((-1, 3, 0), (-1, 10, 0)),
((0, 3, -1), (0, 10, -1)),
((1, 3, 0), (1, 10, 0)),
((0, 3, -1), (0, 10, -1)),
((0, 3, 1), (0, 10, 1)),
((0, 11, 0), (0, 11, 0)),
];
const BIRCH_LEAVES_FILL: [(Coord, Coord); 5] = [
((-1, 2, 0), (-1, 7, 0)),
((1, 2, 0), (1, 7, 0)),
((0, 2, -1), (0, 7, -1)),
((0, 2, 1), (0, 7, 1)),
((0, 7, 0), (0, 8, 0)),
];
//////////////////////////////////////////////////
/// Helper function to set blocks in various patterns.
fn round(editor: &mut WorldEditor, material: Block, (x, y, z): Coord, block_pattern: &[Coord]) {
for (i, j, k) in block_pattern {
editor.set_block(material, x + i, y + j, z + k, None, None);
}
}
pub enum TreeType {
Oak,
Spruce,
Birch,
}
// TODO what should be moved in, and what should be referenced?
pub struct Tree<'a> {
// kind: TreeType, // NOTE: Not actually necessary to store!
log_block: Block,
log_height: i32,
leaves_block: Block,
leaves_fill: &'a [(Coord, Coord)],
round_ranges: [Vec<i32>; 3],
}
impl Tree<'_> {
pub fn create(editor: &mut WorldEditor, (x, y, z): Coord) {
let mut blacklist: Vec<Block> = Vec::new();
blacklist.extend(Self::get_building_wall_blocks());
blacklist.extend(Self::get_building_floor_blocks());
blacklist.extend(Self::get_structural_blocks());
blacklist.extend(Self::get_functional_blocks());
blacklist.push(WATER);
let mut rng = rand::thread_rng();
let tree = Self::get_tree(match rng.gen_range(1..=3) {
1 => TreeType::Oak,
2 => TreeType::Spruce,
3 => TreeType::Birch,
_ => unreachable!(),
});
// Build the logs
editor.fill_blocks(
tree.log_block,
x,
y,
z,
x,
y + tree.log_height,
z,
None,
Some(&blacklist),
);
// Fill in the leaves
for ((i1, j1, k1), (i2, j2, k2)) in tree.leaves_fill {
editor.fill_blocks(
tree.leaves_block,
x + i1,
y + j1,
z + k1,
x + i2,
y + j2,
z + k2,
None,
None,
);
}
// Do the three rounds
for (round_range, round_pattern) in tree.round_ranges.iter().zip(ROUND_PATTERNS) {
for offset in round_range {
round(editor, tree.leaves_block, (x, y + offset, z), round_pattern);
}
}
}
fn get_tree(kind: TreeType) -> Self {
match kind {
TreeType::Oak => Self {
// kind,
log_block: OAK_LOG,
log_height: 8,
leaves_block: OAK_LEAVES,
leaves_fill: &OAK_LEAVES_FILL,
round_ranges: [
(3..=8).rev().collect(),
(4..=7).rev().collect(),
(5..=6).rev().collect(),
],
},
TreeType::Spruce => Self {
// kind,
log_block: SPRUCE_LOG,
log_height: 9,
leaves_block: BIRCH_LEAVES, // TODO Is this correct?
leaves_fill: &SPRUCE_LEAVES_FILL,
// TODO can I omit the third empty vec? May cause issues with iter zip
round_ranges: [vec![9, 7, 6, 4, 3], vec![6, 3], vec![]],
},
TreeType::Birch => Self {
// kind,
log_block: BIRCH_LOG,
log_height: 6,
leaves_block: BIRCH_LEAVES,
leaves_fill: &BIRCH_LEAVES_FILL,
round_ranges: [(2..=6).rev().collect(), (2..=4).collect(), vec![]],
},
} // match
} // fn get_tree
/// Get all possible building wall blocks
fn get_building_wall_blocks() -> Vec<Block> {
vec![
BLACKSTONE,
BLACK_TERRACOTTA,
BRICK,
BROWN_CONCRETE,
BROWN_TERRACOTTA,
DEEPSLATE_BRICKS,
END_STONE_BRICKS,
GRAY_CONCRETE,
GRAY_TERRACOTTA,
LIGHT_BLUE_TERRACOTTA,
LIGHT_GRAY_CONCRETE,
MUD_BRICKS,
NETHER_BRICK,
NETHERITE_BLOCK,
POLISHED_ANDESITE,
POLISHED_BLACKSTONE,
POLISHED_BLACKSTONE_BRICKS,
POLISHED_DEEPSLATE,
POLISHED_GRANITE,
QUARTZ_BLOCK,
QUARTZ_BRICKS,
SANDSTONE,
SMOOTH_SANDSTONE,
SMOOTH_STONE,
STONE_BRICKS,
WHITE_CONCRETE,
WHITE_TERRACOTTA,
ORANGE_TERRACOTTA,
GREEN_STAINED_HARDENED_CLAY,
BLUE_TERRACOTTA,
YELLOW_TERRACOTTA,
BLACK_CONCRETE,
WHITE_CONCRETE,
GRAY_CONCRETE,
LIGHT_GRAY_CONCRETE,
BROWN_CONCRETE,
RED_CONCRETE,
ORANGE_TERRACOTTA,
YELLOW_CONCRETE,
LIME_CONCRETE,
GREEN_STAINED_HARDENED_CLAY,
CYAN_CONCRETE,
LIGHT_BLUE_CONCRETE,
BLUE_CONCRETE,
PURPLE_CONCRETE,
MAGENTA_CONCRETE,
RED_TERRACOTTA,
]
}
/// Get all possible building floor blocks
fn get_building_floor_blocks() -> Vec<Block> {
vec![
GRAY_CONCRETE,
LIGHT_GRAY_CONCRETE,
WHITE_CONCRETE,
SMOOTH_STONE,
POLISHED_ANDESITE,
STONE_BRICKS,
]
}
/// Get structural blocks (fences, walls, stairs, slabs, rails, etc.)
fn get_structural_blocks() -> Vec<Block> {
vec![
// Fences
OAK_FENCE,
// Walls
COBBLESTONE_WALL,
ANDESITE_WALL,
STONE_BRICK_WALL,
// Stairs
OAK_STAIRS,
// Slabs
OAK_SLAB,
STONE_BLOCK_SLAB,
STONE_BRICK_SLAB,
// Rails
RAIL,
RAIL_NORTH_SOUTH,
RAIL_EAST_WEST,
RAIL_ASCENDING_EAST,
RAIL_ASCENDING_WEST,
RAIL_ASCENDING_NORTH,
RAIL_ASCENDING_SOUTH,
RAIL_NORTH_EAST,
RAIL_NORTH_WEST,
RAIL_SOUTH_EAST,
RAIL_SOUTH_WEST,
// Doors and trapdoors
OAK_DOOR,
DARK_OAK_DOOR_LOWER,
DARK_OAK_DOOR_UPPER,
OAK_TRAPDOOR,
// Ladders
LADDER,
]
}
/// Get functional blocks (furniture, decorative items, etc.)
fn get_functional_blocks() -> Vec<Block> {
vec![
// Furniture and functional blocks
CHEST,
CRAFTING_TABLE,
FURNACE,
ANVIL,
BREWING_STAND,
NOTE_BLOCK,
BOOKSHELF,
CAULDRON,
// Beds
RED_BED_NORTH_HEAD,
RED_BED_NORTH_FOOT,
RED_BED_EAST_HEAD,
RED_BED_EAST_FOOT,
RED_BED_SOUTH_HEAD,
RED_BED_SOUTH_FOOT,
RED_BED_WEST_HEAD,
RED_BED_WEST_FOOT,
// Pressure plates and signs
OAK_PRESSURE_PLATE,
SIGN,
// Glass blocks (windows)
GLASS,
WHITE_STAINED_GLASS,
GRAY_STAINED_GLASS,
LIGHT_GRAY_STAINED_GLASS,
BROWN_STAINED_GLASS,
TINTED_GLASS,
// Carpets
WHITE_CARPET,
RED_CARPET,
// Other structural/building blocks
IRON_BARS,
IRON_BLOCK,
SCAFFOLDING,
BEDROCK,
]
}
} // impl Tree

View File

@@ -1,22 +1,47 @@
use geo::orient::{Direction, Orient};
use geo::{Contains, Intersects, LineString, Point, Polygon, Rect};
use std::time::Instant;
use crate::clipping::clip_water_ring_to_bbox;
use crate::{
block_definitions::WATER,
cartesian::XZPoint,
ground::Ground,
osm_parser::{ProcessedMemberRole, ProcessedNode, ProcessedRelation},
coordinate_system::cartesian::{XZBBox, XZPoint},
osm_parser::{ProcessedMemberRole, ProcessedNode, ProcessedRelation, ProcessedWay},
world_editor::WorldEditor,
};
pub fn generate_water_areas(
pub fn generate_water_area_from_way(
editor: &mut WorldEditor,
element: &ProcessedRelation,
ground: &Ground,
element: &ProcessedWay,
_xzbbox: &XZBBox,
) {
let start_time = Instant::now();
if !element.tags.contains_key("water") {
let outers = [element.nodes.clone()];
if !verify_closed_rings(&outers) {
println!("Skipping way {} due to invalid polygon", element.id);
return;
}
generate_water_areas(editor, &outers, &[], start_time);
}
pub fn generate_water_areas_from_relation(
editor: &mut WorldEditor,
element: &ProcessedRelation,
xzbbox: &XZBBox,
) {
let start_time = Instant::now();
// Check if this is a water relation (either with water tag or natural=water)
let is_water = element.tags.contains_key("water")
|| element
.tags
.get("natural")
.map(|val| val == "water" || val == "bay")
.unwrap_or(false);
if !is_water {
return;
}
@@ -37,36 +62,135 @@ pub fn generate_water_areas(
}
}
merge_loopy_loops(&mut outers);
if !verify_loopy_loops(&outers) {
// Preserve OSM-defined outer/inner roles without modification
merge_way_segments(&mut outers);
// Clip assembled rings to bbox (must happen after merging to preserve ring connectivity)
outers = outers
.into_iter()
.filter_map(|ring| clip_water_ring_to_bbox(&ring, xzbbox))
.collect();
merge_way_segments(&mut inners);
inners = inners
.into_iter()
.filter_map(|ring| clip_water_ring_to_bbox(&ring, xzbbox))
.collect();
if !verify_closed_rings(&outers) {
// For clipped multipolygons, some loops may not close perfectly
// Instead of force-closing with straight lines (which creates wedges),
// filter out unclosed loops and only render the properly closed ones
// Filter: Keep only loops that are already closed OR can be closed within 1 block
outers.retain(|loop_nodes| {
if loop_nodes.len() < 3 {
return false;
}
let first = &loop_nodes[0];
let last = loop_nodes.last().unwrap();
let dx = (first.x - last.x).abs();
let dz = (first.z - last.z).abs();
// Keep if already closed by ID or endpoints are within 1 block
first.id == last.id || (dx <= 1 && dz <= 1)
});
// Now close the remaining loops that are within 1 block tolerance
for loop_nodes in outers.iter_mut() {
let first = loop_nodes[0].clone();
let last_idx = loop_nodes.len() - 1;
if loop_nodes[0].id != loop_nodes[last_idx].id {
// Endpoints are close (within tolerance), close the loop
loop_nodes.push(first);
}
}
// If no valid outer loops remain, skip the relation
if outers.is_empty() {
return;
}
// Verify again after filtering and closing
if !verify_closed_rings(&outers) {
println!("Skipping relation {} due to invalid polygon", element.id);
return;
}
}
merge_way_segments(&mut inners);
if !verify_closed_rings(&inners) {
println!("Skipping relation {} due to invalid polygon", element.id);
return;
}
merge_loopy_loops(&mut inners);
if !verify_loopy_loops(&inners) {
return;
}
let (max_x, max_z) = editor.get_max_coords();
let outers: Vec<Vec<XZPoint>> = outers
.iter()
.map(|x| x.iter().map(|y| y.xz()).collect::<Vec<_>>())
.collect();
let inners: Vec<Vec<XZPoint>> = inners
.iter()
.map(|x| x.iter().map(|y| y.xz()).collect::<Vec<_>>())
.collect();
inverse_floodfill(max_x, max_z, outers, inners, editor, ground, start_time);
generate_water_areas(editor, &outers, &inners, start_time);
}
// Merges ways that share nodes into full loops
fn merge_loopy_loops(loops: &mut Vec<Vec<ProcessedNode>>) {
fn generate_water_areas(
editor: &mut WorldEditor,
outers: &[Vec<ProcessedNode>],
inners: &[Vec<ProcessedNode>],
start_time: Instant,
) {
// Calculate polygon bounding box to limit fill area
let mut poly_min_x = i32::MAX;
let mut poly_min_z = i32::MAX;
let mut poly_max_x = i32::MIN;
let mut poly_max_z = i32::MIN;
for outer in outers {
for node in outer {
poly_min_x = poly_min_x.min(node.x);
poly_min_z = poly_min_z.min(node.z);
poly_max_x = poly_max_x.max(node.x);
poly_max_z = poly_max_z.max(node.z);
}
}
// If no valid bounds, nothing to fill
if poly_min_x == i32::MAX || poly_max_x == i32::MIN {
return;
}
// Clamp to world bounds just in case
let (world_min_x, world_min_z) = editor.get_min_coords();
let (world_max_x, world_max_z) = editor.get_max_coords();
let min_x = poly_min_x.max(world_min_x);
let min_z = poly_min_z.max(world_min_z);
let max_x = poly_max_x.min(world_max_x);
let max_z = poly_max_z.min(world_max_z);
let outers_xz: Vec<Vec<XZPoint>> = outers
.iter()
.map(|x| x.iter().map(|y| y.xz()).collect::<Vec<_>>())
.collect();
let inners_xz: Vec<Vec<XZPoint>> = inners
.iter()
.map(|x| x.iter().map(|y| y.xz()).collect::<Vec<_>>())
.collect();
inverse_floodfill(
min_x, min_z, max_x, max_z, outers_xz, inners_xz, editor, start_time,
);
}
/// Merges way segments that share endpoints into closed rings.
fn merge_way_segments(rings: &mut Vec<Vec<ProcessedNode>>) {
let mut removed: Vec<usize> = vec![];
let mut merged: Vec<Vec<ProcessedNode>> = vec![];
for i in 0..loops.len() {
for j in 0..loops.len() {
// Match nodes by ID or proximity (handles synthetic nodes from bbox clipping)
let nodes_match = |a: &ProcessedNode, b: &ProcessedNode| -> bool {
if a.id == b.id {
return true;
}
let dx = (a.x - b.x).abs();
let dz = (a.z - b.z).abs();
dx <= 1 && dz <= 1
};
for i in 0..rings.len() {
for j in 0..rings.len() {
if i == j {
continue;
}
@@ -75,20 +199,29 @@ fn merge_loopy_loops(loops: &mut Vec<Vec<ProcessedNode>>) {
continue;
}
let x: &Vec<ProcessedNode> = &loops[i];
let y: &Vec<ProcessedNode> = &loops[j];
let x: &Vec<ProcessedNode> = &rings[i];
let y: &Vec<ProcessedNode> = &rings[j];
// it's looped already
if x[0].id == x.last().unwrap().id {
// Skip empty rings (can happen after clipping)
if x.is_empty() || y.is_empty() {
continue;
}
// it's looped already
if y[0].id == y.last().unwrap().id {
let x_first = &x[0];
let x_last = x.last().unwrap();
let y_first = &y[0];
let y_last = y.last().unwrap();
// Skip already-closed rings
if nodes_match(x_first, x_last) {
continue;
}
if x[0].id == y[0].id {
if nodes_match(y_first, y_last) {
continue;
}
if nodes_match(x_first, y_first) {
removed.push(i);
removed.push(j);
@@ -96,7 +229,7 @@ fn merge_loopy_loops(loops: &mut Vec<Vec<ProcessedNode>>) {
x.reverse();
x.extend(y.iter().skip(1).cloned());
merged.push(x);
} else if x.last().unwrap().id == y.last().unwrap().id {
} else if nodes_match(x_last, y_last) {
removed.push(i);
removed.push(j);
@@ -104,7 +237,7 @@ fn merge_loopy_loops(loops: &mut Vec<Vec<ProcessedNode>>) {
x.extend(y.iter().rev().skip(1).cloned());
merged.push(x);
} else if x[0].id == y.last().unwrap().id {
} else if nodes_match(x_first, y_last) {
removed.push(i);
removed.push(j);
@@ -112,6 +245,14 @@ fn merge_loopy_loops(loops: &mut Vec<Vec<ProcessedNode>>) {
y.extend(x.iter().skip(1).cloned());
merged.push(y);
} else if nodes_match(x_last, y_first) {
removed.push(i);
removed.push(j);
let mut x: Vec<ProcessedNode> = x.clone();
x.extend(y.iter().skip(1).cloned());
merged.push(x);
}
}
}
@@ -119,24 +260,35 @@ fn merge_loopy_loops(loops: &mut Vec<Vec<ProcessedNode>>) {
removed.sort();
for r in removed.iter().rev() {
loops.remove(*r);
rings.remove(*r);
}
let merged_len: usize = merged.len();
for m in merged {
loops.push(m);
rings.push(m);
}
if merged_len > 0 {
merge_loopy_loops(loops);
merge_way_segments(rings);
}
}
fn verify_loopy_loops(loops: &[Vec<ProcessedNode>]) -> bool {
let mut valid: bool = true;
for l in loops {
if l[0].id != l.last().unwrap().id {
eprintln!("WARN: Disconnected loop");
/// Verifies all rings are properly closed (first node matches last).
fn verify_closed_rings(rings: &[Vec<ProcessedNode>]) -> bool {
let mut valid = true;
for ring in rings {
let first = &ring[0];
let last = ring.last().unwrap();
// Check if ring is closed (by ID or proximity)
let is_closed = first.id == last.id || {
let dx = (first.x - last.x).abs();
let dz = (first.z - last.z).abs();
dx <= 1 && dz <= 1
};
if !is_closed {
eprintln!("WARN: Disconnected ring");
valid = false;
}
}
@@ -147,18 +299,18 @@ fn verify_loopy_loops(loops: &[Vec<ProcessedNode>]) -> bool {
// Water areas are absolutely huge. We can't easily flood fill the entire thing.
// Instead, we'll iterate over all the blocks in our MC world, and check if each
// one is in the river or not
#[allow(clippy::too_many_arguments)]
fn inverse_floodfill(
min_x: i32,
min_z: i32,
max_x: i32,
max_z: i32,
outers: Vec<Vec<XZPoint>>,
inners: Vec<Vec<XZPoint>>,
editor: &mut WorldEditor,
ground: &Ground,
start_time: Instant,
) {
let min_x: i32 = 0;
let min_z: i32 = 0;
// Convert to geo Polygons with normalized winding order
let inners: Vec<_> = inners
.into_iter()
.map(|x| {
@@ -170,6 +322,7 @@ fn inverse_floodfill(
),
vec![],
)
.orient(Direction::Default)
})
.collect();
@@ -184,6 +337,7 @@ fn inverse_floodfill(
),
vec![],
)
.orient(Direction::Default)
})
.collect();
@@ -193,7 +347,6 @@ fn inverse_floodfill(
&outers,
&inners,
editor,
ground,
start_time,
);
}
@@ -204,7 +357,6 @@ fn inverse_floodfill_recursive(
outers: &[Polygon],
inners: &[Polygon],
editor: &mut WorldEditor,
ground: &Ground,
start_time: Instant,
) {
// Check if we've exceeded 25 seconds
@@ -212,15 +364,16 @@ fn inverse_floodfill_recursive(
println!("Water area generation exceeded 25 seconds, continuing anyway");
}
const ITERATIVE_THRES: i32 = 10_000;
const ITERATIVE_THRES: i64 = 10_000;
if min.0 > max.0 || min.1 > max.1 {
return;
}
if (max.0 - min.0) * (max.1 - min.1) < ITERATIVE_THRES {
let ground_level = ground.level(XZPoint::new(min.0, min.1));
inverse_floodfill_iterative(min, max, ground_level, outers, inners, editor);
// Multiply as i64 to avoid overflow; in release builds where unchecked math is
// enabled, this could cause the rest of this code to end up in an infinite loop.
if ((max.0 - min.0) as i64) * ((max.1 - min.1) as i64) < ITERATIVE_THRES {
inverse_floodfill_iterative(min, max, 0, outers, inners, editor);
return;
}
@@ -242,8 +395,7 @@ fn inverse_floodfill_recursive(
if outers.iter().any(|outer: &Polygon| outer.contains(&rect))
&& !inners.iter().any(|inner: &Polygon| inner.intersects(&rect))
{
let ground_level = ground.level(XZPoint::new(min_x, min_z));
rect_fill(min_x, max_x, min_z, max_z, ground_level, editor);
rect_fill(min_x, max_x, min_z, max_z, 0, editor);
continue;
}
@@ -265,7 +417,6 @@ fn inverse_floodfill_recursive(
&outers_intersects,
&inners_intersects,
editor,
ground,
start_time,
);
}

View File

@@ -1,14 +1,11 @@
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::cartesian::XZPoint;
use crate::ground::Ground;
use crate::osm_parser::ProcessedWay;
use crate::world_editor::WorldEditor;
pub fn generate_waterways(editor: &mut WorldEditor, element: &ProcessedWay, ground: &Ground) {
if let Some(_waterway_type) = element.tags.get("waterway") {
let mut previous_node: Option<XZPoint> = None;
let mut waterway_width: i32 = 4; // Default waterway width
pub fn generate_waterways(editor: &mut WorldEditor, element: &ProcessedWay) {
if let Some(waterway_type) = element.tags.get("waterway") {
let (mut waterway_width, waterway_depth) = get_waterway_dimensions(waterway_type);
// Check for custom width in tags
if let Some(width_str) = element.tags.get("width") {
@@ -20,42 +17,99 @@ pub fn generate_waterways(editor: &mut WorldEditor, element: &ProcessedWay, grou
});
}
// Process nodes to create waterways
for node in &element.nodes {
let current_node = node.xz();
// Skip layers below the ground level
if matches!(
element.tags.get("layer").map(|s| s.as_str()),
Some("-1") | Some("-2") | Some("-3")
) {
return;
}
if let Some(prev) = previous_node {
// Skip layers below the ground level
if !matches!(
element.tags.get("layer").map(|s| s.as_str()),
Some("-1") | Some("-2") | Some("-3")
) {
// Draw a line between the current and previous node
let bresenham_points: Vec<(i32, i32, i32)> =
bresenham_line(prev.x, 0, prev.z, current_node.x, 0, current_node.z);
// Process consecutive node pairs to create waterways
// Use windows(2) to avoid connecting last node back to first
for nodes_pair in element.nodes.windows(2) {
let prev_node = nodes_pair[0].xz();
let current_node = nodes_pair[1].xz();
for (bx, _, bz) in bresenham_points {
let ground_level = ground.level(XZPoint::new(bx, bz));
// Draw a line between the current and previous node
let bresenham_points: Vec<(i32, i32, i32)> = bresenham_line(
prev_node.x,
0,
prev_node.z,
current_node.x,
0,
current_node.z,
);
for x in (bx - waterway_width / 2)..=(bx + waterway_width / 2) {
for z in (bz - waterway_width / 2)..=(bz + waterway_width / 2) {
// Set water block at the ground level
editor.set_block(WATER, x, ground_level, z, None, None);
// Clear vegetation above the water
editor.set_block(
AIR,
x,
ground_level + 1,
z,
Some(&[GRASS, WHEAT, CARROTS, POTATOES]),
None,
);
}
}
}
}
for (bx, _, bz) in bresenham_points {
// Create water channel with proper depth and sloped banks
create_water_channel(editor, bx, bz, waterway_width, waterway_depth);
}
}
}
}
/// Determines width and depth based on waterway type
fn get_waterway_dimensions(waterway_type: &str) -> (i32, i32) {
match waterway_type {
"river" => (8, 3), // Large rivers: 8 blocks wide, 3 blocks deep
"canal" => (6, 2), // Canals: 6 blocks wide, 2 blocks deep
"stream" => (3, 2), // Streams: 3 blocks wide, 2 blocks deep
"fairway" => (12, 3), // Shipping fairways: 12 blocks wide, 3 blocks deep
"flowline" => (2, 1), // Water flow lines: 2 blocks wide, 1 block deep
"brook" => (2, 1), // Small brooks: 2 blocks wide, 1 block deep
"ditch" => (2, 1), // Ditches: 2 blocks wide, 1 block deep
"drain" => (1, 1), // Drainage: 1 block wide, 1 block deep
_ => (4, 2), // Default: 4 blocks wide, 2 blocks deep
}
}
/// Creates a water channel with proper depth and sloped banks
fn create_water_channel(
editor: &mut WorldEditor,
center_x: i32,
center_z: i32,
width: i32,
depth: i32,
) {
let half_width = width / 2;
for x in (center_x - half_width - 1)..=(center_x + half_width + 1) {
for z in (center_z - half_width - 1)..=(center_z + half_width + 1) {
let dx = (x - center_x).abs();
let dz = (z - center_z).abs();
let distance_from_center = dx.max(dz);
if distance_from_center <= half_width {
// Main water channel
for y in (1 - depth)..=0 {
editor.set_block(WATER, x, y, z, None, None);
}
// Place one layer of dirt below the water channel
editor.set_block(DIRT, x, -depth, z, None, None);
// Clear vegetation above the water
editor.set_block(AIR, x, 1, z, Some(&[GRASS, WHEAT, CARROTS, POTATOES]), None);
} else if distance_from_center == half_width + 1 && depth > 1 {
// Create sloped banks (one block interval slopes)
let slope_depth = (depth - 1).max(1);
for y in (1 - slope_depth)..=0 {
if y == 0 {
// Surface level - place water or air
editor.set_block(WATER, x, y, z, None, None);
} else {
// Below surface - dig out for slope
editor.set_block(AIR, x, y, z, None, None);
}
}
// Place one layer of dirt below the sloped areas
editor.set_block(DIRT, x, -slope_depth, z, None, None);
// Clear vegetation above sloped areas
editor.set_block(AIR, x, 1, z, Some(&[GRASS, WHEAT, CARROTS, POTATOES]), None);
}
previous_node = Some(current_node);
}
}
}

607
src/elevation_data.rs Normal file
View File

@@ -0,0 +1,607 @@
use crate::coordinate_system::{geographic::LLBBox, transformation::geo_distance};
#[cfg(feature = "gui")]
use crate::telemetry::{send_log, LogLevel};
use image::Rgb;
use std::path::Path;
/// Maximum Y coordinate in Minecraft (build height limit)
const MAX_Y: i32 = 319;
/// Scale factor for converting real elevation to Minecraft heights
const BASE_HEIGHT_SCALE: f64 = 0.7;
/// AWS S3 Terrarium tiles endpoint (no API key required)
const AWS_TERRARIUM_URL: &str =
"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png";
/// Terrarium format offset for height decoding
const TERRARIUM_OFFSET: f64 = 32768.0;
/// Minimum zoom level for terrain tiles
const MIN_ZOOM: u8 = 10;
/// Maximum zoom level for terrain tiles
const MAX_ZOOM: u8 = 15;
/// Holds processed elevation data and metadata
#[derive(Clone)]
pub struct ElevationData {
/// Height values in Minecraft Y coordinates
pub(crate) heights: Vec<Vec<i32>>,
/// Width of the elevation grid
pub(crate) width: usize,
/// Height of the elevation grid
pub(crate) height: usize,
}
/// Calculates appropriate zoom level for the given bounding box
fn calculate_zoom_level(bbox: &LLBBox) -> u8 {
let lat_diff: f64 = (bbox.max().lat() - bbox.min().lat()).abs();
let lng_diff: f64 = (bbox.max().lng() - bbox.min().lng()).abs();
let max_diff: f64 = lat_diff.max(lng_diff);
let zoom: u8 = (-max_diff.log2() + 20.0) as u8;
zoom.clamp(MIN_ZOOM, MAX_ZOOM)
}
fn lat_lng_to_tile(lat: f64, lng: f64, zoom: u8) -> (u32, u32) {
let lat_rad: f64 = lat.to_radians();
let n: f64 = 2.0_f64.powi(zoom as i32);
let x: u32 = ((lng + 180.0) / 360.0 * n).floor() as u32;
let y: u32 = ((1.0 - lat_rad.tan().asinh() / std::f64::consts::PI) / 2.0 * n).floor() as u32;
(x, y)
}
/// Downloads a tile from AWS Terrain Tiles service
fn download_tile(
client: &reqwest::blocking::Client,
tile_x: u32,
tile_y: u32,
zoom: u8,
tile_path: &Path,
) -> Result<image::ImageBuffer<Rgb<u8>, Vec<u8>>, Box<dyn std::error::Error>> {
println!("Fetching tile x={tile_x},y={tile_y},z={zoom} from AWS Terrain Tiles");
let url: String = AWS_TERRARIUM_URL
.replace("{z}", &zoom.to_string())
.replace("{x}", &tile_x.to_string())
.replace("{y}", &tile_y.to_string());
let response: reqwest::blocking::Response = client.get(&url).send()?;
response.error_for_status_ref()?;
let bytes = response.bytes()?;
std::fs::write(tile_path, &bytes)?;
let img: image::DynamicImage = image::load_from_memory(&bytes)?;
Ok(img.to_rgb8())
}
pub fn fetch_elevation_data(
bbox: &LLBBox,
scale: f64,
ground_level: i32,
) -> Result<ElevationData, Box<dyn std::error::Error>> {
let (base_scale_z, base_scale_x) = geo_distance(bbox.min(), bbox.max());
// Apply same floor() and scale operations as CoordTransformer.llbbox_to_xzbbox()
let scale_factor_z: f64 = base_scale_z.floor() * scale;
let scale_factor_x: f64 = base_scale_x.floor() * scale;
// Calculate zoom and tiles
let zoom: u8 = calculate_zoom_level(bbox);
let tiles: Vec<(u32, u32)> = get_tile_coordinates(bbox, zoom);
// Match grid dimensions with Minecraft world size
let grid_width: usize = scale_factor_x as usize;
let grid_height: usize = scale_factor_z as usize;
// Initialize height grid with proper dimensions
let mut height_grid: Vec<Vec<f64>> = vec![vec![f64::NAN; grid_width]; grid_height];
let mut extreme_values_found = Vec::new(); // Track extreme values for debugging
let client: reqwest::blocking::Client = reqwest::blocking::Client::new();
let tile_cache_dir = Path::new("./arnis-tile-cache");
if !tile_cache_dir.exists() {
std::fs::create_dir_all(tile_cache_dir)?;
}
// Fetch and process each tile
for (tile_x, tile_y) in &tiles {
// Check if tile is already cached
let tile_path = tile_cache_dir.join(format!("z{zoom}_x{tile_x}_y{tile_y}.png"));
let rgb_img: image::ImageBuffer<Rgb<u8>, Vec<u8>> = if tile_path.exists() {
// Check if the cached file has a reasonable size (PNG files should be at least a few KB)
let file_size = match std::fs::metadata(&tile_path) {
Ok(metadata) => metadata.len(),
Err(_) => 0,
};
if file_size < 1000 {
eprintln!(
"Warning: Cached tile at {} appears to be too small ({} bytes). Refetching tile.",
tile_path.display(),
file_size
);
#[cfg(feature = "gui")]
send_log(
LogLevel::Warning,
"Cached tile appears to be too small. Refetching tile.",
);
// Remove the potentially corrupted file
if let Err(remove_err) = std::fs::remove_file(&tile_path) {
eprintln!(
"Warning: Failed to remove corrupted tile file: {}",
remove_err
);
#[cfg(feature = "gui")]
send_log(
LogLevel::Warning,
"Failed to remove corrupted tile file during refetching.",
);
}
// Re-download the tile
download_tile(&client, *tile_x, *tile_y, zoom, &tile_path)?
} else {
println!(
"Loading cached tile x={tile_x},y={tile_y},z={zoom} from {}",
tile_path.display()
);
// Try to load cached tile, but handle corruption gracefully
match image::open(&tile_path) {
Ok(img) => img.to_rgb8(),
Err(e) => {
eprintln!(
"Cached tile at {} is corrupted or invalid: {}. Re-downloading...",
tile_path.display(),
e
);
#[cfg(feature = "gui")]
send_log(
LogLevel::Warning,
"Cached tile is corrupted or invalid. Re-downloading...",
);
// Remove the corrupted file
if let Err(remove_err) = std::fs::remove_file(&tile_path) {
eprintln!(
"Warning: Failed to remove corrupted tile file: {}",
remove_err
);
#[cfg(feature = "gui")]
send_log(
LogLevel::Warning,
"Failed to remove corrupted tile file during re-download.",
);
}
// Re-download the tile
download_tile(&client, *tile_x, *tile_y, zoom, &tile_path)?
}
}
}
} else {
// Download the tile for the first time
download_tile(&client, *tile_x, *tile_y, zoom, &tile_path)?
};
// Only process pixels that fall within the requested bbox
for (y, row) in rgb_img.rows().enumerate() {
for (x, pixel) in row.enumerate() {
// Convert tile pixel coordinates back to geographic coordinates
let pixel_lng = ((*tile_x as f64 + x as f64 / 256.0) / (2.0_f64.powi(zoom as i32)))
* 360.0
- 180.0;
let pixel_lat_rad = std::f64::consts::PI
* (1.0
- 2.0 * (*tile_y as f64 + y as f64 / 256.0) / (2.0_f64.powi(zoom as i32)));
let pixel_lat = pixel_lat_rad.sinh().atan().to_degrees();
// Skip pixels outside the requested bounding box
if pixel_lat < bbox.min().lat()
|| pixel_lat > bbox.max().lat()
|| pixel_lng < bbox.min().lng()
|| pixel_lng > bbox.max().lng()
{
continue;
}
// Map geographic coordinates to grid coordinates
let rel_x = (pixel_lng - bbox.min().lng()) / (bbox.max().lng() - bbox.min().lng());
let rel_y =
1.0 - (pixel_lat - bbox.min().lat()) / (bbox.max().lat() - bbox.min().lat());
let scaled_x = (rel_x * grid_width as f64).round() as usize;
let scaled_y = (rel_y * grid_height as f64).round() as usize;
if scaled_y >= grid_height || scaled_x >= grid_width {
continue;
}
// Decode Terrarium format: (R * 256 + G + B/256) - 32768
let height: f64 =
(pixel[0] as f64 * 256.0 + pixel[1] as f64 + pixel[2] as f64 / 256.0)
- TERRARIUM_OFFSET;
// Track extreme values for debugging
if !(-1000.0..=10000.0).contains(&height) {
extreme_values_found
.push((tile_x, tile_y, x, y, pixel[0], pixel[1], pixel[2], height));
if extreme_values_found.len() <= 5 {
// Only log first 5 extreme values
eprintln!("Extreme value found: tile({tile_x},{tile_y}) pixel({x},{y}) RGB({},{},{}) = {height}m",
pixel[0], pixel[1], pixel[2]);
}
}
height_grid[scaled_y][scaled_x] = height;
}
}
}
// Report on extreme values found
if !extreme_values_found.is_empty() {
eprintln!(
"Found {} total extreme elevation values during tile processing",
extreme_values_found.len()
);
eprintln!("This may indicate corrupted tile data or areas with invalid elevation data");
}
// Fill in any NaN values by interpolating from nearest valid values
fill_nan_values(&mut height_grid);
// Filter extreme outliers that might be due to corrupted tile data
filter_elevation_outliers(&mut height_grid);
// Calculate blur sigma based on grid resolution
// Reference points for tuning:
const SMALL_GRID_REF: f64 = 100.0; // Reference grid size
const SMALL_SIGMA_REF: f64 = 15.0; // Sigma for 100x100 grid
const LARGE_GRID_REF: f64 = 1000.0; // Reference grid size
const LARGE_SIGMA_REF: f64 = 7.0; // Sigma for 1000x1000 grid
let grid_size: f64 = (grid_width.min(grid_height) as f64).max(1.0);
let sigma: f64 = if grid_size <= SMALL_GRID_REF {
// Linear scaling for small grids
SMALL_SIGMA_REF * (grid_size / SMALL_GRID_REF)
} else {
// Logarithmic scaling for larger grids
let ln_small: f64 = SMALL_GRID_REF.ln();
let ln_large: f64 = LARGE_GRID_REF.ln();
let log_grid_size: f64 = grid_size.ln();
let t: f64 = (log_grid_size - ln_small) / (ln_large - ln_small);
SMALL_SIGMA_REF + t * (LARGE_SIGMA_REF - SMALL_SIGMA_REF)
};
/* eprintln!(
"Grid: {}x{}, Blur sigma: {:.2}",
grid_width, grid_height, sigma
); */
// Continue with the existing blur and conversion to Minecraft heights...
let blurred_heights: Vec<Vec<f64>> = apply_gaussian_blur(&height_grid, sigma);
let mut mc_heights: Vec<Vec<i32>> = Vec::with_capacity(blurred_heights.len());
// Find min/max in raw data
let mut min_height: f64 = f64::MAX;
let mut max_height: f64 = f64::MIN;
let mut extreme_low_count = 0;
let mut extreme_high_count = 0;
for row in &blurred_heights {
for &height in row {
min_height = min_height.min(height);
max_height = max_height.max(height);
// Count extreme values that might indicate data issues
if height < -1000.0 {
extreme_low_count += 1;
}
if height > 10000.0 {
extreme_high_count += 1;
}
}
}
eprintln!("Height data range: {min_height} to {max_height} m");
if extreme_low_count > 0 {
eprintln!(
"WARNING: Found {extreme_low_count} pixels with extremely low elevations (< -1000m)"
);
}
if extreme_high_count > 0 {
eprintln!(
"WARNING: Found {extreme_high_count} pixels with extremely high elevations (> 10000m)"
);
}
let height_range: f64 = max_height - min_height;
// Apply scale factor to height scaling
let mut height_scale: f64 = BASE_HEIGHT_SCALE * scale.sqrt(); // sqrt to make height scaling less extreme
let mut scaled_range: f64 = height_range * height_scale;
// Adaptive scaling: ensure we don't exceed reasonable Y range
let available_y_range = (MAX_Y - ground_level) as f64;
let safety_margin = 0.9; // Use 90% of available range
let max_allowed_range = available_y_range * safety_margin;
if scaled_range > max_allowed_range {
let adjustment_factor = max_allowed_range / scaled_range;
height_scale *= adjustment_factor;
scaled_range = height_range * height_scale;
eprintln!(
"Height range too large, applying scaling adjustment factor: {adjustment_factor:.3}"
);
eprintln!("Adjusted scaled range: {scaled_range:.1} blocks");
}
// Convert to scaled Minecraft Y coordinates
for row in blurred_heights {
let mc_row: Vec<i32> = row
.iter()
.map(|&h| {
// Scale the height differences
let relative_height: f64 = (h - min_height) / height_range;
let scaled_height: f64 = relative_height * scaled_range;
// With terrain enabled, ground_level is used as the MIN_Y for terrain
((ground_level as f64 + scaled_height).round() as i32).clamp(ground_level, MAX_Y)
})
.collect();
mc_heights.push(mc_row);
}
let mut min_block_height: i32 = i32::MAX;
let mut max_block_height: i32 = i32::MIN;
for row in &mc_heights {
for &height in row {
min_block_height = min_block_height.min(height);
max_block_height = max_block_height.max(height);
}
}
eprintln!("Minecraft height data range: {min_block_height} to {max_block_height} blocks");
Ok(ElevationData {
heights: mc_heights,
width: grid_width,
height: grid_height,
})
}
fn get_tile_coordinates(bbox: &LLBBox, zoom: u8) -> Vec<(u32, u32)> {
// Convert lat/lng to tile coordinates
let (x1, y1) = lat_lng_to_tile(bbox.min().lat(), bbox.min().lng(), zoom);
let (x2, y2) = lat_lng_to_tile(bbox.max().lat(), bbox.max().lng(), zoom);
let mut tiles: Vec<(u32, u32)> = Vec::new();
for x in x1.min(x2)..=x1.max(x2) {
for y in y1.min(y2)..=y1.max(y2) {
tiles.push((x, y));
}
}
tiles
}
fn apply_gaussian_blur(heights: &[Vec<f64>], sigma: f64) -> Vec<Vec<f64>> {
let kernel_size: usize = (sigma * 3.0).ceil() as usize * 2 + 1;
let kernel: Vec<f64> = create_gaussian_kernel(kernel_size, sigma);
// Apply blur
let mut blurred: Vec<Vec<f64>> = heights.to_owned();
// Horizontal pass
for row in blurred.iter_mut() {
let mut temp: Vec<f64> = row.clone();
for (i, val) in temp.iter_mut().enumerate() {
let mut sum: f64 = 0.0;
let mut weight_sum: f64 = 0.0;
for (j, k) in kernel.iter().enumerate() {
let idx: i32 = i as i32 + j as i32 - kernel_size as i32 / 2;
if idx >= 0 && idx < row.len() as i32 {
sum += row[idx as usize] * k;
weight_sum += k;
}
}
*val = sum / weight_sum;
}
*row = temp;
}
// Vertical pass
let height: usize = blurred.len();
let width: usize = blurred[0].len();
for x in 0..width {
let temp: Vec<_> = blurred
.iter()
.take(height)
.map(|row: &Vec<f64>| row[x])
.collect();
for (y, row) in blurred.iter_mut().enumerate().take(height) {
let mut sum: f64 = 0.0;
let mut weight_sum: f64 = 0.0;
for (j, k) in kernel.iter().enumerate() {
let idx: i32 = y as i32 + j as i32 - kernel_size as i32 / 2;
if idx >= 0 && idx < height as i32 {
sum += temp[idx as usize] * k;
weight_sum += k;
}
}
row[x] = sum / weight_sum;
}
}
blurred
}
fn create_gaussian_kernel(size: usize, sigma: f64) -> Vec<f64> {
let mut kernel: Vec<f64> = vec![0.0; size];
let center: f64 = size as f64 / 2.0;
for (i, value) in kernel.iter_mut().enumerate() {
let x: f64 = i as f64 - center;
*value = (-x * x / (2.0 * sigma * sigma)).exp();
}
let sum: f64 = kernel.iter().sum();
for k in kernel.iter_mut() {
*k /= sum;
}
kernel
}
fn fill_nan_values(height_grid: &mut [Vec<f64>]) {
let height: usize = height_grid.len();
let width: usize = height_grid[0].len();
let mut changes_made: bool = true;
while changes_made {
changes_made = false;
for y in 0..height {
for x in 0..width {
if height_grid[y][x].is_nan() {
let mut sum: f64 = 0.0;
let mut count: i32 = 0;
// Check neighboring cells
for dy in -1..=1 {
for dx in -1..=1 {
let ny: i32 = y as i32 + dy;
let nx: i32 = x as i32 + dx;
if ny >= 0 && ny < height as i32 && nx >= 0 && nx < width as i32 {
let val: f64 = height_grid[ny as usize][nx as usize];
if !val.is_nan() {
sum += val;
count += 1;
}
}
}
}
if count > 0 {
height_grid[y][x] = sum / count as f64;
changes_made = true;
}
}
}
}
}
}
fn filter_elevation_outliers(height_grid: &mut [Vec<f64>]) {
let height = height_grid.len();
let width = height_grid[0].len();
// Collect all valid height values to calculate statistics
let mut all_heights: Vec<f64> = Vec::new();
for row in height_grid.iter() {
for &h in row {
if !h.is_nan() && h.is_finite() {
all_heights.push(h);
}
}
}
if all_heights.is_empty() {
return;
}
// Sort to find percentiles
all_heights.sort_by(|a, b| a.partial_cmp(b).unwrap());
let len = all_heights.len();
// Use 1st and 99th percentiles to define reasonable bounds
let p1_idx = (len as f64 * 0.01) as usize;
let p99_idx = (len as f64 * 0.99) as usize;
let min_reasonable = all_heights[p1_idx];
let max_reasonable = all_heights[p99_idx];
eprintln!("Filtering outliers outside range: {min_reasonable:.1}m to {max_reasonable:.1}m");
let mut outliers_filtered = 0;
// Replace outliers with NaN, then fill them using interpolation
for row in height_grid.iter_mut().take(height) {
for h in row.iter_mut().take(width) {
if !h.is_nan() && (*h < min_reasonable || *h > max_reasonable) {
*h = f64::NAN;
outliers_filtered += 1;
}
}
}
if outliers_filtered > 0 {
eprintln!("Filtered {outliers_filtered} elevation outliers, interpolating replacements...");
// Re-run the NaN filling to interpolate the filtered values
fill_nan_values(height_grid);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_terrarium_height_decoding() {
// Test known Terrarium RGB values
// Sea level (0m) in Terrarium format should be (128, 0, 0) = 32768 - 32768 = 0
let sea_level_pixel = [128, 0, 0];
let height = (sea_level_pixel[0] as f64 * 256.0
+ sea_level_pixel[1] as f64
+ sea_level_pixel[2] as f64 / 256.0)
- TERRARIUM_OFFSET;
assert_eq!(height, 0.0);
// Test simple case: height of 1000m
// 1000 + 32768 = 33768 = 131 * 256 + 232
let test_pixel = [131, 232, 0];
let height =
(test_pixel[0] as f64 * 256.0 + test_pixel[1] as f64 + test_pixel[2] as f64 / 256.0)
- TERRARIUM_OFFSET;
assert_eq!(height, 1000.0);
// Test below sea level (-100m)
// -100 + 32768 = 32668 = 127 * 256 + 156
let below_sea_pixel = [127, 156, 0];
let height = (below_sea_pixel[0] as f64 * 256.0
+ below_sea_pixel[1] as f64
+ below_sea_pixel[2] as f64 / 256.0)
- TERRARIUM_OFFSET;
assert_eq!(height, -100.0);
}
#[test]
fn test_aws_url_generation() {
let url = AWS_TERRARIUM_URL
.replace("{z}", "15")
.replace("{x}", "17436")
.replace("{y}", "11365");
assert_eq!(
url,
"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/15/17436/11365.png"
);
}
#[test]
#[ignore] // This test requires internet connection, run with --ignored
fn test_aws_tile_fetch() {
use reqwest::blocking::Client;
let client = Client::new();
let url = "https://s3.amazonaws.com/elevation-tiles-prod/terrarium/15/17436/11365.png";
let response = client.get(url).send();
assert!(response.is_ok());
let response = response.unwrap();
assert!(response.status().is_success());
assert!(response
.headers()
.get("content-type")
.unwrap()
.to_str()
.unwrap()
.contains("image"));
}
}

View File

@@ -3,8 +3,8 @@ use itertools::Itertools;
use std::collections::{HashSet, VecDeque};
use std::time::{Duration, Instant};
/// Perform a flood-fill to find the area inside a polygon.
/// Returns a vector of (x, z) coordinates representing the filled area.
/// Main flood fill function with automatic algorithm selection
/// Chooses the best algorithm based on polygon size and complexity
pub fn flood_fill_area(
polygon_coords: &[(i32, i32)],
timeout: Option<&Duration>,
@@ -13,8 +13,6 @@ pub fn flood_fill_area(
return vec![]; // Not a valid polygon
}
let start_time: Instant = Instant::now();
// Calculate bounding box of the polygon using itertools
let (min_x, max_x) = polygon_coords
.iter()
@@ -29,73 +27,184 @@ pub fn flood_fill_area(
.into_option()
.unwrap();
let mut filled_area: Vec<(i32, i32)> = Vec::new();
let mut visited: HashSet<(i32, i32)> = HashSet::new();
let area = (max_x - min_x + 1) as i64 * (max_z - min_z + 1) as i64;
// Convert input to a geo::Polygon for efficient point-in-polygon testing
// For small and medium areas, use optimized flood fill with span filling
if area < 50000 {
optimized_flood_fill_area(polygon_coords, timeout, min_x, max_x, min_z, max_z)
} else {
// For larger areas, use original flood fill with grid sampling
original_flood_fill_area(polygon_coords, timeout, min_x, max_x, min_z, max_z)
}
}
/// Optimized flood fill for larger polygons with multi-seed detection for complex shapes like U-shapes
fn optimized_flood_fill_area(
polygon_coords: &[(i32, i32)],
timeout: Option<&Duration>,
min_x: i32,
max_x: i32,
min_z: i32,
max_z: i32,
) -> Vec<(i32, i32)> {
let start_time = Instant::now();
let mut filled_area = Vec::new();
let mut global_visited = HashSet::new();
// Create polygon for containment testing
let exterior_coords: Vec<(f64, f64)> = polygon_coords
.iter()
.map(|&(x, z)| (x as f64, z as f64))
.collect::<Vec<_>>();
let exterior: LineString = LineString::from(exterior_coords); // Create LineString from coordinates
let polygon: Polygon<f64> = Polygon::new(exterior, vec![]); // Create Polygon using LineString
.collect();
let exterior = LineString::from(exterior_coords);
let polygon = Polygon::new(exterior, vec![]);
// Determine safe step sizes for grid sampling
let step_x: i32 = ((max_x - min_x) / 10).max(1); // Ensure step is at least 1
let step_z: i32 = ((max_z - min_z) / 10).max(1); // Ensure step is at least 1
// Optimized step sizes: larger steps for efficiency, but still catch U-shapes
let width = max_x - min_x + 1;
let height = max_z - min_z + 1;
let step_x = (width / 6).clamp(1, 8); // Balance between coverage and speed
let step_z = (height / 6).clamp(1, 8);
// Sample multiple starting points within the bounding box
let mut candidate_points: VecDeque<(i32, i32)> = VecDeque::new();
for x in (min_x..=max_x).step_by(step_x as usize) {
for z in (min_z..=max_z).step_by(step_z as usize) {
candidate_points.push_back((x, z));
}
}
// Pre-allocate queue with reasonable capacity to avoid reallocations
let mut queue = VecDeque::with_capacity(1024);
// Attempt flood-fill from each candidate point
while let Some((start_x, start_z)) = candidate_points.pop_front() {
if let Some(timeout) = timeout {
if &start_time.elapsed() > timeout {
eprintln!("Floodfill timeout");
break;
}
}
if polygon.contains(&Point::new(start_x as f64, start_z as f64)) {
// Start flood-fill from the valid interior point
let mut queue: VecDeque<(i32, i32)> = VecDeque::new();
queue.push_back((start_x, start_z));
visited.insert((start_x, start_z));
while let Some((x, z)) = queue.pop_front() {
for z in (min_z..=max_z).step_by(step_z as usize) {
for x in (min_x..=max_x).step_by(step_x as usize) {
// Fast timeout check, only every few iterations
if filled_area.len() % 100 == 0 {
if let Some(timeout) = timeout {
if &start_time.elapsed() > timeout {
eprintln!("Floodfill timeout");
break;
if start_time.elapsed() > *timeout {
return filled_area;
}
}
}
if polygon.contains(&Point::new(x as f64, z as f64)) {
filled_area.push((x, z));
// Skip if already visited or not inside polygon
if global_visited.contains(&(x, z))
|| !polygon.contains(&Point::new(x as f64, z as f64))
{
continue;
}
// Check adjacent points
for (nx, nz) in [(x - 1, z), (x + 1, z), (x, z - 1), (x, z + 1)].iter() {
if *nx >= min_x
&& *nx <= max_x
&& *nz >= min_z
&& *nz <= max_z
&& !visited.contains(&(*nx, *nz))
{
visited.insert((*nx, *nz));
// Start flood fill from this seed point
queue.clear(); // Reuse queue instead of creating new one
queue.push_back((x, z));
global_visited.insert((x, z));
while let Some((curr_x, curr_z)) = queue.pop_front() {
// Add current point to filled area
filled_area.push((curr_x, curr_z));
// Check all four directions with optimized bounds checking
let neighbors = [
(curr_x - 1, curr_z),
(curr_x + 1, curr_z),
(curr_x, curr_z - 1),
(curr_x, curr_z + 1),
];
for (nx, nz) in neighbors.iter() {
if *nx >= min_x
&& *nx <= max_x
&& *nz >= min_z
&& *nz <= max_z
&& !global_visited.contains(&(*nx, *nz))
{
// Only check polygon containment for unvisited points
if polygon.contains(&Point::new(*nx as f64, *nz as f64)) {
global_visited.insert((*nx, *nz));
queue.push_back((*nx, *nz));
}
}
}
}
}
}
filled_area
}
/// Original flood fill algorithm with enhanced multi-seed detection for complex shapes
fn original_flood_fill_area(
polygon_coords: &[(i32, i32)],
timeout: Option<&Duration>,
min_x: i32,
max_x: i32,
min_z: i32,
max_z: i32,
) -> Vec<(i32, i32)> {
let start_time = Instant::now();
let mut filled_area: Vec<(i32, i32)> = Vec::new();
let mut global_visited: HashSet<(i32, i32)> = HashSet::new();
// Convert input to a geo::Polygon for efficient point-in-polygon testing
let exterior_coords: Vec<(f64, f64)> = polygon_coords
.iter()
.map(|&(x, z)| (x as f64, z as f64))
.collect::<Vec<_>>();
let exterior: LineString = LineString::from(exterior_coords);
let polygon: Polygon<f64> = Polygon::new(exterior, vec![]);
// Optimized step sizes for large polygons - coarser sampling for speed
let width = max_x - min_x + 1;
let height = max_z - min_z + 1;
let step_x: i32 = (width / 8).clamp(1, 12); // Cap max step size for coverage
let step_z: i32 = (height / 8).clamp(1, 12);
// Pre-allocate queue and reserve space for filled_area
let mut queue: VecDeque<(i32, i32)> = VecDeque::with_capacity(2048);
filled_area.reserve(1000); // Reserve space to reduce reallocations
// Scan for multiple seed points to handle U-shapes and concave polygons
for z in (min_z..=max_z).step_by(step_z as usize) {
for x in (min_x..=max_x).step_by(step_x as usize) {
// Reduced timeout checking frequency for better performance
// Use manual % check since is_multiple_of() is unstable on stable Rust
if let Some(timeout) = timeout {
if &start_time.elapsed() > timeout {
return filled_area;
}
}
// Skip if already processed or not inside polygon
if global_visited.contains(&(x, z))
|| !polygon.contains(&Point::new(x as f64, z as f64))
{
continue;
}
// Start flood-fill from this seed point
queue.clear(); // Reuse queue
queue.push_back((x, z));
global_visited.insert((x, z));
while let Some((curr_x, curr_z)) = queue.pop_front() {
// Only check polygon containment once per point when adding to filled_area
if polygon.contains(&Point::new(curr_x as f64, curr_z as f64)) {
filled_area.push((curr_x, curr_z));
// Check adjacent points with optimized iteration
let neighbors = [
(curr_x - 1, curr_z),
(curr_x + 1, curr_z),
(curr_x, curr_z - 1),
(curr_x, curr_z + 1),
];
for (nx, nz) in neighbors.iter() {
if *nx >= min_x
&& *nx <= max_x
&& *nz >= min_z
&& *nz <= max_z
&& !global_visited.contains(&(*nx, *nz))
{
global_visited.insert((*nx, *nz));
queue.push_back((*nx, *nz));
}
}
}
}
if !filled_area.is_empty() {
break; // Exit if a valid area has been flood-filled
}
}
}

View File

@@ -1,63 +1,44 @@
use crate::cartesian::XZPoint;
use crate::args::Args;
use crate::coordinate_system::{cartesian::XZPoint, geographic::LLBBox};
use crate::elevation_data::{fetch_elevation_data, ElevationData};
use crate::progress::emit_gui_progress_update;
use colored::Colorize;
use image::{Rgb, RgbImage};
/// Minimum Y coordinate in Minecraft (bedrock level)
const MIN_Y: i32 = -62;
/// Maximum Y coordinate in Minecraft (build height limit)
const MAX_Y: i32 = 256;
/// Scale factor for converting real elevation to Minecraft heights
const BASE_HEIGHT_SCALE: f64 = 0.6;
/// Mapbox API access token for terrain data
const MAPBOX_PUBKEY: &str =
"pk.eyJ1IjoiY3Vnb3MiLCJhIjoiY2p4Nm43MzA3MDFmZDQwcGxsMjB4Z3hnNiJ9.SQbnMASwdqZe6G4n6OMvVw";
/// Minimum zoom level for terrain tiles
const MIN_ZOOM: u8 = 10;
/// Maximum zoom level for terrain tiles
const MAX_ZOOM: u8 = 15;
/// Represents terrain data and elevation settings
#[derive(Clone)]
pub struct Ground {
pub elevation_enabled: bool,
ground_level: i32,
elevation_data: Option<ElevationData>,
}
/// Holds processed elevation data and metadata
#[derive(Clone)]
struct ElevationData {
/// Height values in Minecraft Y coordinates
heights: Vec<Vec<i32>>,
/// Width of the elevation grid
width: usize,
/// Height of the elevation grid
height: usize,
}
impl Ground {
pub fn new(args: &crate::args::Args) -> Self {
let mut elevation_enabled: bool = args.terrain;
let elevation_data: Option<ElevationData> = if elevation_enabled && args.bbox.is_some() {
match Self::fetch_elevation_data(args.bbox.as_deref().unwrap(), args.scale) {
Ok(data) => {
if args.debug {
Self::save_debug_image(&data.heights, "elevation_debug");
}
Some(data)
}
Err(e) => {
eprintln!("Warning: Failed to fetch elevation data: {}", e);
elevation_enabled = false;
None
pub fn new_flat(ground_level: i32) -> Self {
Self {
elevation_enabled: false,
ground_level,
elevation_data: None,
}
}
pub fn new_enabled(bbox: &LLBBox, scale: f64, ground_level: i32) -> Self {
match fetch_elevation_data(bbox, scale, ground_level) {
Ok(elevation_data) => Self {
elevation_enabled: true,
ground_level,
elevation_data: Some(elevation_data),
},
Err(e) => {
eprintln!("Failed to fetch elevation data: {}", e);
emit_gui_progress_update(15.0, "Elevation unavailable, using flat ground");
// Graceful fallback: disable elevation and keep provided ground_level
Self {
elevation_enabled: false,
ground_level,
elevation_data: None,
}
}
} else {
None
};
Self {
elevation_enabled,
ground_level: args.ground_level,
elevation_data,
}
}
@@ -73,6 +54,7 @@ impl Ground {
self.interpolate_height(x_ratio, z_ratio, data)
}
#[allow(unused)]
#[inline(always)]
pub fn min_level<I: Iterator<Item = XZPoint>>(&self, coords: I) -> Option<i32> {
if !self.elevation_enabled {
@@ -81,6 +63,7 @@ impl Ground {
coords.map(|c: XZPoint| self.level(c)).min()
}
#[allow(unused)]
#[inline(always)]
pub fn max_level<I: Iterator<Item = XZPoint>>(&self, coords: I) -> Option<i32> {
if !self.elevation_enabled {
@@ -105,280 +88,12 @@ impl Ground {
data.heights[z][x]
}
/// Calculates appropriate zoom level for the given bounding box
fn calculate_zoom_level(bbox: (f64, f64, f64, f64)) -> u8 {
let lat_diff: f64 = (bbox.2 - bbox.0).abs();
let lng_diff: f64 = (bbox.3 - bbox.1).abs();
let max_diff: f64 = lat_diff.max(lng_diff);
let zoom: u8 = (-max_diff.log2() + 20.0) as u8;
zoom.clamp(MIN_ZOOM, MAX_ZOOM)
}
fn lat_lng_to_tile(lat: f64, lng: f64, zoom: u8) -> (u32, u32) {
let lat_rad: f64 = lat.to_radians();
let n: f64 = 2.0_f64.powi(zoom as i32);
let x: u32 = ((lng + 180.0) / 360.0 * n).floor() as u32;
let y: u32 =
((1.0 - lat_rad.tan().asinh() / std::f64::consts::PI) / 2.0 * n).floor() as u32;
(x, y)
}
fn fetch_elevation_data(
bbox_str: &str,
scale: f64,
) -> Result<ElevationData, Box<dyn std::error::Error>> {
let coords: Vec<f64> = bbox_str
.split_whitespace()
.map(|s: &str| s.parse::<f64>())
.collect::<Result<Vec<f64>, _>>()?;
let (min_lat, min_lng, max_lat, max_lng) = (coords[0], coords[1], coords[2], coords[3]);
// Use OSM parser's scale calculation and apply user scale factor
let (scale_factor_z, scale_factor_x) =
crate::osm_parser::geo_distance(min_lat, max_lat, min_lng, max_lng);
let scale_factor_x: f64 = scale_factor_x * scale;
let scale_factor_z: f64 = scale_factor_z * scale;
// Calculate zoom and tiles
let zoom: u8 = Self::calculate_zoom_level((min_lat, min_lng, max_lat, max_lng));
let tiles: Vec<(u32, u32)> =
Self::get_tile_coordinates(min_lat, min_lng, max_lat, max_lng, zoom);
// Calculate tile boundaries
let x_min: &u32 = tiles.iter().map(|(x, _)| x).min().unwrap();
let x_max: &u32 = tiles.iter().map(|(x, _)| x).max().unwrap();
let y_min: &u32 = tiles.iter().map(|(_, y)| y).min().unwrap();
let y_max: &u32 = tiles.iter().map(|(_, y)| y).max().unwrap();
// Match grid dimensions with Minecraft world size
let grid_width: usize = scale_factor_x.round() as usize;
let grid_height: usize = scale_factor_z.round() as usize;
// Calculate total tile dimensions
let total_tile_width: u32 = (x_max - x_min + 1) * 256;
let total_tile_height: u32 = (y_max - y_min + 1) * 256;
// Calculate scaling factors to match the desired grid dimensions
let x_scale: f64 = grid_width as f64 / total_tile_width as f64;
let y_scale: f64 = grid_height as f64 / total_tile_height as f64;
// Initialize height grid with proper dimensions
let mut height_grid: Vec<Vec<f64>> = vec![vec![f64::NAN; grid_width]; grid_height];
let client: reqwest::blocking::Client = reqwest::blocking::Client::new();
let access_token: &str = MAPBOX_PUBKEY;
// Fetch and process each tile
for (tile_x, tile_y) in &tiles {
let url: String = format!(
"https://api.mapbox.com/v4/mapbox.terrain-rgb/{}/{}/{}.pngraw?access_token={}",
zoom, tile_x, tile_y, access_token
);
let response: reqwest::blocking::Response = client.get(&url).send()?;
let img: image::DynamicImage = image::load_from_memory(&response.bytes()?)?;
let rgb_img: image::ImageBuffer<Rgb<u8>, Vec<u8>> = img.to_rgb8();
// Calculate position in the scaled grid
let base_x: f64 = ((*tile_x - x_min) * 256) as f64;
let base_y: f64 = ((*tile_y - y_min) * 256) as f64;
// Process tile data with scaling
for (y, row) in rgb_img.rows().enumerate() {
for (x, pixel) in row.enumerate() {
let scaled_x: usize = ((base_x + x as f64) * x_scale) as usize;
let scaled_y: usize = ((base_y + y as f64) * y_scale) as usize;
if scaled_y >= grid_height || scaled_x >= grid_width {
continue;
}
let height: f64 = -10000.0
+ ((pixel[0] as f64 * 256.0 * 256.0
+ pixel[1] as f64 * 256.0
+ pixel[2] as f64)
* 0.1);
height_grid[scaled_y][scaled_x] = height;
}
}
}
// Fill in any NaN values by interpolating from nearest valid values
Self::fill_nan_values(&mut height_grid);
// Continue with the existing blur and conversion to Minecraft heights...
let blurred_heights: Vec<Vec<f64>> = Self::apply_gaussian_blur(&height_grid, 1.0);
let mut mc_heights: Vec<Vec<i32>> = Vec::with_capacity(blurred_heights.len());
// Find min/max in raw data
let mut min_height: f64 = f64::MAX;
let mut max_height: f64 = f64::MIN;
for row in &blurred_heights {
for &height in row {
min_height = min_height.min(height);
max_height = max_height.max(height);
}
}
let height_range: f64 = max_height - min_height;
// Apply scale factor to height scaling
let height_scale: f64 = BASE_HEIGHT_SCALE * scale.sqrt(); // sqrt to make height scaling less extreme
let scaled_range: f64 = height_range * height_scale;
// Convert to scaled Minecraft Y coordinates
for row in blurred_heights {
let mc_row: Vec<i32> = row
.iter()
.map(|&h| {
// Scale the height differences
let relative_height: f64 = (h - min_height) / height_range;
let scaled_height: f64 = relative_height * scaled_range;
((MIN_Y as f64 + scaled_height).round() as i32).clamp(MIN_Y, MAX_Y)
})
.collect();
mc_heights.push(mc_row);
}
Ok(ElevationData {
heights: mc_heights,
width: grid_width,
height: grid_height,
})
}
fn get_tile_coordinates(
min_lat: f64,
min_lng: f64,
max_lat: f64,
max_lng: f64,
zoom: u8,
) -> Vec<(u32, u32)> {
// Convert lat/lng to tile coordinates
let (x1, y1) = Self::lat_lng_to_tile(min_lat, min_lng, zoom);
let (x2, y2) = Self::lat_lng_to_tile(max_lat, max_lng, zoom);
let mut tiles: Vec<(u32, u32)> = Vec::new();
for x in x1.min(x2)..=x1.max(x2) {
for y in y1.min(y2)..=y1.max(y2) {
tiles.push((x, y));
}
}
tiles
}
fn apply_gaussian_blur(heights: &[Vec<f64>], sigma: f64) -> Vec<Vec<f64>> {
let kernel_size: usize = (sigma * 3.0).ceil() as usize * 2 + 1;
let kernel: Vec<f64> = Self::create_gaussian_kernel(kernel_size, sigma);
// Apply blur
let mut blurred: Vec<Vec<f64>> = heights.to_owned();
// Horizontal pass
for row in blurred.iter_mut() {
let mut temp: Vec<f64> = row.clone();
for (i, val) in temp.iter_mut().enumerate() {
let mut sum: f64 = 0.0;
let mut weight_sum: f64 = 0.0;
for (j, k) in kernel.iter().enumerate() {
let idx: i32 = i as i32 + j as i32 - kernel_size as i32 / 2;
if idx >= 0 && idx < row.len() as i32 {
sum += row[idx as usize] * k;
weight_sum += k;
}
}
*val = sum / weight_sum;
}
*row = temp;
}
// Vertical pass
let height: usize = blurred.len();
let width: usize = blurred[0].len();
for x in 0..width {
let temp: Vec<_> = blurred
.iter()
.take(height)
.map(|row: &Vec<f64>| row[x])
.collect();
for (y, row) in blurred.iter_mut().enumerate().take(height) {
let mut sum: f64 = 0.0;
let mut weight_sum: f64 = 0.0;
for (j, k) in kernel.iter().enumerate() {
let idx: i32 = y as i32 + j as i32 - kernel_size as i32 / 2;
if idx >= 0 && idx < height as i32 {
sum += temp[idx as usize] * k;
weight_sum += k;
}
}
row[x] = sum / weight_sum;
}
}
blurred
}
fn create_gaussian_kernel(size: usize, sigma: f64) -> Vec<f64> {
let mut kernel: Vec<f64> = vec![0.0; size];
let center: f64 = size as f64 / 2.0;
for (i, value) in kernel.iter_mut().enumerate() {
let x: f64 = i as f64 - center;
*value = (-x * x / (2.0 * sigma * sigma)).exp();
}
let sum: f64 = kernel.iter().sum();
for k in kernel.iter_mut() {
*k /= sum;
}
kernel
}
fn fill_nan_values(height_grid: &mut [Vec<f64>]) {
let height: usize = height_grid.len();
let width: usize = height_grid[0].len();
let mut changes_made: bool = true;
while changes_made {
changes_made = false;
for y in 0..height {
for x in 0..width {
if height_grid[y][x].is_nan() {
let mut sum: f64 = 0.0;
let mut count: i32 = 0;
// Check neighboring cells
for dy in -1..=1 {
for dx in -1..=1 {
let ny: i32 = y as i32 + dy;
let nx: i32 = x as i32 + dx;
if ny >= 0 && ny < height as i32 && nx >= 0 && nx < width as i32 {
let val: f64 = height_grid[ny as usize][nx as usize];
if !val.is_nan() {
sum += val;
count += 1;
}
}
}
}
if count > 0 {
height_grid[y][x] = sum / count as f64;
changes_made = true;
}
}
}
}
}
}
fn save_debug_image(heights: &Vec<Vec<i32>>, filename: &str) {
fn save_debug_image(&self, filename: &str) {
let heights = &self
.elevation_data
.as_ref()
.expect("Elevation data not available")
.heights;
if heights.is_empty() || heights[0].is_empty() {
return;
}
@@ -412,13 +127,26 @@ impl Ground {
// Ensure filename has .png extension
let filename: String = if !filename.ends_with(".png") {
format!("{}.png", filename)
format!("{filename}.png")
} else {
filename.to_string()
};
if let Err(e) = img.save(&filename) {
eprintln!("Failed to save debug image: {}", e);
eprintln!("Failed to save debug image: {e}");
}
}
}
pub fn generate_ground_data(args: &Args) -> Ground {
if args.terrain {
println!("{} Fetching elevation...", "[3/7]".bold());
emit_gui_progress_update(15.0, "Fetching elevation...");
let ground = Ground::new_enabled(&args.bbox, args.scale, args.ground_level);
if args.debug {
ground.save_debug_image("elevation_debug");
}
return ground;
}
Ground::new_flat(args.ground_level)
}

909
src/gui.rs Normal file
View File

@@ -0,0 +1,909 @@
use crate::args::Args;
use crate::coordinate_system::cartesian::XZPoint;
use crate::coordinate_system::geographic::{LLBBox, LLPoint};
use crate::coordinate_system::transformation::CoordTransformer;
use crate::data_processing;
use crate::ground::{self, Ground};
use crate::map_transformation;
use crate::osm_parser;
use crate::progress;
use crate::retrieve_data;
use crate::telemetry::{self, send_log, LogLevel};
use crate::version_check;
use fastnbt::Value;
use flate2::read::GzDecoder;
use fs2::FileExt;
use log::LevelFilter;
use rfd::FileDialog;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::{env, fs, io::Write};
use tauri_plugin_log::{Builder as LogBuilder, Target, TargetKind};
/// Manages the session.lock file for a Minecraft world directory
struct SessionLock {
file: fs::File,
path: PathBuf,
}
impl SessionLock {
/// Creates and locks a session.lock file in the specified world directory
fn acquire(world_path: &Path) -> Result<Self, String> {
let session_lock_path = world_path.join("session.lock");
// Create or open the session.lock file
let file = fs::File::create(&session_lock_path)
.map_err(|e| format!("Failed to create session.lock file: {e}"))?;
// Write the snowman character (U+2603) as specified by Minecraft format
let snowman_bytes = "".as_bytes(); // This is UTF-8 encoded E2 98 83
(&file)
.write_all(snowman_bytes)
.map_err(|e| format!("Failed to write to session.lock file: {e}"))?;
// Acquire an exclusive lock on the file
file.try_lock_exclusive()
.map_err(|e| format!("Failed to acquire lock on session.lock file: {e}"))?;
Ok(SessionLock {
file,
path: session_lock_path,
})
}
}
impl Drop for SessionLock {
fn drop(&mut self) {
// Release the lock and remove the session.lock file
let _ = self.file.unlock();
let _ = fs::remove_file(&self.path);
}
}
pub fn run_gui() {
// Launch the UI
println!("Launching UI...");
// Install panic hook for crash reporting
telemetry::install_panic_hook();
// Workaround WebKit2GTK issue with NVIDIA drivers and graphics issues
// Source: https://github.com/tauri-apps/tauri/issues/10702
#[cfg(target_os = "linux")]
unsafe {
// Disable problematic GPU features that cause map loading issues
env::set_var("WEBKIT_DISABLE_DMABUF_RENDERER", "1");
env::set_var("WEBKIT_DISABLE_COMPOSITING_MODE", "1");
// Force software rendering for better compatibility
env::set_var("LIBGL_ALWAYS_SOFTWARE", "1");
env::set_var("GALLIUM_DRIVER", "softpipe");
// Note: Removed sandbox disabling for security reasons
// Note: Removed Qt WebEngine flags as they don't apply to Tauri
}
tauri::Builder::default()
.plugin(
LogBuilder::default()
.level(LevelFilter::Warn)
.targets([
Target::new(TargetKind::LogDir {
file_name: Some("arnis".into()),
}),
Target::new(TargetKind::Stdout),
])
.build(),
)
.plugin(tauri_plugin_shell::init())
.invoke_handler(tauri::generate_handler![
gui_select_world,
gui_start_generation,
gui_get_version,
gui_check_for_updates,
gui_get_world_map_data
])
.setup(|app| {
let app_handle = app.handle();
let main_window = tauri::Manager::get_webview_window(app_handle, "main")
.expect("Failed to get main window");
progress::set_main_window(main_window);
Ok(())
})
.run(tauri::generate_context!())
.expect("Error while starting the application UI (Tauri)");
}
#[tauri::command]
fn gui_select_world(generate_new: bool) -> Result<String, i32> {
// Determine the default Minecraft 'saves' directory based on the OS
let default_dir: Option<PathBuf> = if cfg!(target_os = "windows") {
env::var("APPDATA")
.ok()
.map(|appdata: String| PathBuf::from(appdata).join(".minecraft").join("saves"))
} else if cfg!(target_os = "macos") {
dirs::home_dir().map(|home: PathBuf| {
home.join("Library/Application Support/minecraft")
.join("saves")
})
} else if cfg!(target_os = "linux") {
dirs::home_dir().map(|home| {
let flatpak_path = home.join(".var/app/com.mojang.Minecraft/.minecraft/saves");
if flatpak_path.exists() {
flatpak_path
} else {
home.join(".minecraft/saves")
}
})
} else {
None
};
if generate_new {
// Handle new world generation
if let Some(default_path) = &default_dir {
if default_path.exists() {
// Call create_new_world and return the result
create_new_world(default_path).map_err(|_| 1) // Error code 1: Minecraft directory not found
} else {
Err(1) // Error code 1: Minecraft directory not found
}
} else {
Err(1) // Error code 1: Minecraft directory not found
}
} else {
// Handle existing world selection
// Open the directory picker dialog
let dialog: FileDialog = FileDialog::new();
let dialog: FileDialog = if let Some(start_dir) = default_dir.filter(|dir| dir.exists()) {
dialog.set_directory(start_dir)
} else {
dialog
};
if let Some(path) = dialog.pick_folder() {
// Check if the "region" folder exists within the selected directory
if path.join("region").exists() {
// Check the 'session.lock' file
let session_lock_path = path.join("session.lock");
if session_lock_path.exists() {
// Try to acquire a lock on the session.lock file
if let Ok(file) = fs::File::open(&session_lock_path) {
if fs2::FileExt::try_lock_shared(&file).is_err() {
return Err(2); // Error code 2: The selected world is currently in use
} else {
// Release the lock immediately
let _ = fs2::FileExt::unlock(&file);
}
}
}
return Ok(path.display().to_string());
} else {
// No Minecraft directory found, generating new world in custom user selected directory
return create_new_world(&path).map_err(|_| 3); // Error code 3: Failed to create new world
}
}
// If no folder was selected, return an error message
Err(4) // Error code 4: No world selected
}
}
fn create_new_world(base_path: &Path) -> Result<String, String> {
// Generate a unique world name with proper counter
// Check for both "Arnis World X" and "Arnis World X: Location" patterns
let mut counter: i32 = 1;
let unique_name: String = loop {
let candidate_name: String = format!("Arnis World {counter}");
let candidate_path: PathBuf = base_path.join(&candidate_name);
// Check for exact match (no location suffix)
let exact_match_exists = candidate_path.exists();
// Check for worlds with location suffix (Arnis World X: Location)
let location_pattern = format!("Arnis World {counter}: ");
let location_match_exists = fs::read_dir(base_path)
.map(|entries| {
entries
.filter_map(Result::ok)
.filter_map(|entry| entry.file_name().into_string().ok())
.any(|name| name.starts_with(&location_pattern))
})
.unwrap_or(false);
if !exact_match_exists && !location_match_exists {
break candidate_name;
}
counter += 1;
};
let new_world_path: PathBuf = base_path.join(&unique_name);
// Create the new world directory structure
fs::create_dir_all(new_world_path.join("region"))
.map_err(|e| format!("Failed to create world directory: {e}"))?;
// Copy the region template file
const REGION_TEMPLATE: &[u8] = include_bytes!("../assets/minecraft/region.template");
let region_path = new_world_path.join("region").join("r.0.0.mca");
fs::write(&region_path, REGION_TEMPLATE)
.map_err(|e| format!("Failed to create region file: {e}"))?;
// Add the level.dat file
const LEVEL_TEMPLATE: &[u8] = include_bytes!("../assets/minecraft/level.dat");
// Decompress the gzipped level.template
let mut decoder = GzDecoder::new(LEVEL_TEMPLATE);
let mut decompressed_data = Vec::new();
decoder
.read_to_end(&mut decompressed_data)
.map_err(|e| format!("Failed to decompress level.template: {e}"))?;
// Parse the decompressed NBT data
let mut level_data: Value = fastnbt::from_bytes(&decompressed_data)
.map_err(|e| format!("Failed to parse level.dat template: {e}"))?;
// Modify the LevelName, LastPlayed and player position fields
if let Value::Compound(ref mut root) = level_data {
if let Some(Value::Compound(ref mut data)) = root.get_mut("Data") {
// Update LevelName
data.insert("LevelName".to_string(), Value::String(unique_name.clone()));
// Update LastPlayed to the current Unix time in milliseconds
let current_time = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|e| format!("Failed to get current time: {e}"))?;
let current_time_millis = current_time.as_millis() as i64;
data.insert("LastPlayed".to_string(), Value::Long(current_time_millis));
// Update player position and rotation
if let Some(Value::Compound(ref mut player)) = data.get_mut("Player") {
if let Some(Value::List(ref mut pos)) = player.get_mut("Pos") {
if let Value::Double(ref mut x) = pos.get_mut(0).unwrap() {
*x = -5.0;
}
if let Value::Double(ref mut y) = pos.get_mut(1).unwrap() {
*y = -61.0;
}
if let Value::Double(ref mut z) = pos.get_mut(2).unwrap() {
*z = -5.0;
}
}
if let Some(Value::List(ref mut rot)) = player.get_mut("Rotation") {
if let Value::Float(ref mut x) = rot.get_mut(0).unwrap() {
*x = -45.0;
}
}
}
}
}
// Serialize the updated NBT data back to bytes
let serialized_level_data: Vec<u8> = fastnbt::to_bytes(&level_data)
.map_err(|e| format!("Failed to serialize updated level.dat: {e}"))?;
// Compress the serialized data back to gzip
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
encoder
.write_all(&serialized_level_data)
.map_err(|e| format!("Failed to compress updated level.dat: {e}"))?;
let compressed_level_data = encoder
.finish()
.map_err(|e| format!("Failed to finalize compression for level.dat: {e}"))?;
// Write the level.dat file
fs::write(new_world_path.join("level.dat"), compressed_level_data)
.map_err(|e| format!("Failed to create level.dat file: {e}"))?;
// Add the icon.png file
const ICON_TEMPLATE: &[u8] = include_bytes!("../assets/minecraft/icon.png");
fs::write(new_world_path.join("icon.png"), ICON_TEMPLATE)
.map_err(|e| format!("Failed to create icon.png file: {e}"))?;
Ok(new_world_path.display().to_string())
}
/// Adds localized area name to the world name in level.dat
fn add_localized_world_name(world_path: PathBuf, bbox: &LLBBox) -> PathBuf {
// Only proceed if the path exists
if !world_path.exists() {
return world_path;
}
// Check the level.dat file first to get the current name
let level_path = world_path.join("level.dat");
if !level_path.exists() {
return world_path;
}
// Try to read the current world name from level.dat
let Ok(level_data) = std::fs::read(&level_path) else {
return world_path;
};
let mut decoder = GzDecoder::new(level_data.as_slice());
let mut decompressed_data = Vec::new();
if decoder.read_to_end(&mut decompressed_data).is_err() {
return world_path;
}
let Ok(Value::Compound(ref root)) = fastnbt::from_bytes::<Value>(&decompressed_data) else {
return world_path;
};
let Some(Value::Compound(ref data)) = root.get("Data") else {
return world_path;
};
let Some(Value::String(current_name)) = data.get("LevelName") else {
return world_path;
};
// Only modify if it's an Arnis world and doesn't already have an area name
if !current_name.starts_with("Arnis World ") || current_name.contains(": ") {
return world_path;
}
// Calculate center coordinates of bbox
let center_lat = (bbox.min().lat() + bbox.max().lat()) / 2.0;
let center_lon = (bbox.min().lng() + bbox.max().lng()) / 2.0;
// Try to fetch the area name
let area_name = match retrieve_data::fetch_area_name(center_lat, center_lon) {
Ok(Some(name)) => name,
_ => return world_path, // Keep original name if no area name found
};
// Create new name with localized area name, ensuring total length doesn't exceed 30 characters
let base_name = current_name.clone();
let max_area_name_len = 30 - base_name.len() - 2; // 2 chars for ": "
let truncated_area_name =
if area_name.chars().count() > max_area_name_len && max_area_name_len > 0 {
// Truncate the area name to fit within the 30 character limit
area_name
.chars()
.take(max_area_name_len)
.collect::<String>()
} else if max_area_name_len == 0 {
// If base name is already too long, don't add area name
return world_path;
} else {
area_name
};
let new_name = format!("{base_name}: {truncated_area_name}");
// Update the level.dat file with the new name
if let Ok(level_data) = std::fs::read(&level_path) {
let mut decoder = GzDecoder::new(level_data.as_slice());
let mut decompressed_data = Vec::new();
if decoder.read_to_end(&mut decompressed_data).is_ok() {
if let Ok(mut nbt_data) = fastnbt::from_bytes::<Value>(&decompressed_data) {
// Update the level name in NBT data
if let Value::Compound(ref mut root) = nbt_data {
if let Some(Value::Compound(ref mut data)) = root.get_mut("Data") {
data.insert("LevelName".to_string(), Value::String(new_name));
// Save the updated NBT data
if let Ok(serialized_data) = fastnbt::to_bytes(&nbt_data) {
let mut encoder = flate2::write::GzEncoder::new(
Vec::new(),
flate2::Compression::default(),
);
if encoder.write_all(&serialized_data).is_ok() {
if let Ok(compressed_data) = encoder.finish() {
if let Err(e) = std::fs::write(&level_path, compressed_data) {
eprintln!("Failed to update level.dat with area name: {e}");
send_log(
LogLevel::Warning,
"Failed to update level.dat with area name",
);
}
}
}
}
}
}
}
}
}
// Return the original path since we didn't change the directory name
world_path
}
// Function to update player position in level.dat based on spawn point coordinates
fn update_player_position(
world_path: &str,
spawn_point: Option<(f64, f64)>,
bbox_text: String,
scale: f64,
) -> Result<(), String> {
use crate::coordinate_system::transformation::CoordTransformer;
let Some((lat, lng)) = spawn_point else {
return Ok(()); // No spawn point selected, exit early
};
// Parse geometrical point and bounding box
let llpoint =
LLPoint::new(lat, lng).map_err(|e| format!("Failed to parse spawn point:\n{e}"))?;
let llbbox = LLBBox::from_str(&bbox_text)
.map_err(|e| format!("Failed to parse bounding box for spawn point:\n{e}"))?;
// Check if spawn point is within the bbox
if !llbbox.contains(&llpoint) {
return Err("Spawn point is outside the selected area".to_string());
}
// Convert lat/lng to Minecraft coordinates
let (transformer, _) = CoordTransformer::llbbox_to_xzbbox(&llbbox, scale)
.map_err(|e| format!("Failed to build transformation on coordinate systems:\n{e}"))?;
let xzpoint = transformer.transform_point(llpoint);
// Default y spawn position since terrain elevation cannot be determined yet
let y = 150.0;
// Read and update the level.dat file
let level_path = PathBuf::from(world_path).join("level.dat");
if !level_path.exists() {
return Err(format!("Level.dat not found at {level_path:?}"));
}
// Read the level.dat file
let level_data = match std::fs::read(&level_path) {
Ok(data) => data,
Err(e) => return Err(format!("Failed to read level.dat: {e}")),
};
// Decompress and parse the NBT data
let mut decoder = GzDecoder::new(level_data.as_slice());
let mut decompressed_data = Vec::new();
if let Err(e) = decoder.read_to_end(&mut decompressed_data) {
return Err(format!("Failed to decompress level.dat: {e}"));
}
let mut nbt_data = match fastnbt::from_bytes::<Value>(&decompressed_data) {
Ok(data) => data,
Err(e) => return Err(format!("Failed to parse level.dat NBT data: {e}")),
};
// Update player position and world spawn point
if let Value::Compound(ref mut root) = nbt_data {
if let Some(Value::Compound(ref mut data)) = root.get_mut("Data") {
// Set world spawn point
data.insert("SpawnX".to_string(), Value::Int(xzpoint.x));
data.insert("SpawnY".to_string(), Value::Int(y as i32));
data.insert("SpawnZ".to_string(), Value::Int(xzpoint.z));
// Update player position
if let Some(Value::Compound(ref mut player)) = data.get_mut("Player") {
if let Some(Value::List(ref mut pos)) = player.get_mut("Pos") {
if let Value::Double(ref mut pos_x) = pos.get_mut(0).unwrap() {
*pos_x = xzpoint.x as f64;
}
if let Value::Double(ref mut pos_y) = pos.get_mut(1).unwrap() {
*pos_y = y;
}
if let Value::Double(ref mut pos_z) = pos.get_mut(2).unwrap() {
*pos_z = xzpoint.z as f64;
}
}
}
}
}
// Serialize and save the updated level.dat
let serialized_data = match fastnbt::to_bytes(&nbt_data) {
Ok(data) => data,
Err(e) => return Err(format!("Failed to serialize updated level.dat: {e}")),
};
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
if let Err(e) = encoder.write_all(&serialized_data) {
return Err(format!("Failed to compress updated level.dat: {e}"));
}
let compressed_data = match encoder.finish() {
Ok(data) => data,
Err(e) => return Err(format!("Failed to finalize compression for level.dat: {e}")),
};
// Write the updated level.dat file
if let Err(e) = std::fs::write(level_path, compressed_data) {
return Err(format!("Failed to write updated level.dat: {e}"));
}
Ok(())
}
// Function to update player spawn Y coordinate based on terrain height after generation
pub fn update_player_spawn_y_after_generation(
world_path: &Path,
spawn_point: Option<(f64, f64)>,
bbox_text: String,
scale: f64,
ground: &Ground,
) -> Result<(), String> {
use crate::coordinate_system::transformation::CoordTransformer;
let Some((_lat, _lng)) = spawn_point else {
return Ok(()); // No spawn point selected, exit early
};
// Read the current level.dat file to get existing spawn coordinates
let level_path = PathBuf::from(world_path).join("level.dat");
if !level_path.exists() {
return Err(format!("Level.dat not found at {level_path:?}"));
}
// Read the level.dat file
let level_data = match std::fs::read(&level_path) {
Ok(data) => data,
Err(e) => return Err(format!("Failed to read level.dat: {e}")),
};
// Decompress and parse the NBT data
let mut decoder = GzDecoder::new(level_data.as_slice());
let mut decompressed_data = Vec::new();
if let Err(e) = decoder.read_to_end(&mut decompressed_data) {
return Err(format!("Failed to decompress level.dat: {e}"));
}
let mut nbt_data = match fastnbt::from_bytes::<Value>(&decompressed_data) {
Ok(data) => data,
Err(e) => return Err(format!("Failed to parse level.dat NBT data: {e}")),
};
// Get existing spawn coordinates and calculate new Y based on terrain
let (existing_spawn_x, existing_spawn_z) = if let Value::Compound(ref root) = nbt_data {
if let Some(Value::Compound(ref data)) = root.get("Data") {
let spawn_x = data.get("SpawnX").and_then(|v| {
if let Value::Int(x) = v {
Some(*x)
} else {
None
}
});
let spawn_z = data.get("SpawnZ").and_then(|v| {
if let Value::Int(z) = v {
Some(*z)
} else {
None
}
});
match (spawn_x, spawn_z) {
(Some(x), Some(z)) => (x, z),
_ => {
return Err("Spawn coordinates not found in level.dat".to_string());
}
}
} else {
return Err("Invalid level.dat structure: no Data compound".to_string());
}
} else {
return Err("Invalid level.dat structure: root is not a compound".to_string());
};
// Calculate terrain-based Y coordinate
let spawn_y = if ground.elevation_enabled {
// Parse coordinates for terrain lookup
let llbbox = LLBBox::from_str(&bbox_text)
.map_err(|e| format!("Failed to parse bounding box for spawn point:\n{e}"))?;
let (_, xzbbox) = CoordTransformer::llbbox_to_xzbbox(&llbbox, scale)
.map_err(|e| format!("Failed to build transformation:\n{e}"))?;
// Calculate relative coordinates for ground system
let relative_x = existing_spawn_x - xzbbox.min_x();
let relative_z = existing_spawn_z - xzbbox.min_z();
let terrain_point = XZPoint::new(relative_x, relative_z);
ground.level(terrain_point) + 2
} else {
-61 // Default Y if no terrain
};
// Update player position and world spawn point
if let Value::Compound(ref mut root) = nbt_data {
if let Some(Value::Compound(ref mut data)) = root.get_mut("Data") {
// Only update the Y coordinate, keep existing X and Z
data.insert("SpawnY".to_string(), Value::Int(spawn_y));
// Update player position - only Y coordinate
if let Some(Value::Compound(ref mut player)) = data.get_mut("Player") {
if let Some(Value::List(ref mut pos)) = player.get_mut("Pos") {
// Keep existing X and Z, only update Y
if let Value::Double(ref mut pos_y) = pos.get_mut(1).unwrap() {
*pos_y = spawn_y as f64;
}
}
}
}
}
// Serialize and save the updated level.dat
let serialized_data = match fastnbt::to_bytes(&nbt_data) {
Ok(data) => data,
Err(e) => return Err(format!("Failed to serialize updated level.dat: {e}")),
};
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
if let Err(e) = encoder.write_all(&serialized_data) {
return Err(format!("Failed to compress updated level.dat: {e}"));
}
let compressed_data = match encoder.finish() {
Ok(data) => data,
Err(e) => return Err(format!("Failed to finalize compression for level.dat: {e}")),
};
// Write the updated level.dat file
if let Err(e) = std::fs::write(level_path, compressed_data) {
return Err(format!("Failed to write updated level.dat: {e}"));
}
Ok(())
}
#[tauri::command]
fn gui_get_version() -> String {
env!("CARGO_PKG_VERSION").to_string()
}
#[tauri::command]
fn gui_check_for_updates() -> Result<bool, String> {
match version_check::check_for_updates() {
Ok(is_newer) => Ok(is_newer),
Err(e) => Err(format!("Error checking for updates: {e}")),
}
}
/// Returns the world map image data as base64 and geo bounds for overlay display.
/// Returns None if the map image or metadata doesn't exist.
#[tauri::command]
fn gui_get_world_map_data(world_path: String) -> Result<Option<WorldMapData>, String> {
let world_dir = PathBuf::from(&world_path);
let map_path = world_dir.join("arnis_world_map.png");
let metadata_path = world_dir.join("metadata.json");
// Check if both files exist
if !map_path.exists() || !metadata_path.exists() {
return Ok(None);
}
// Read and encode the map image as base64
let image_data = fs::read(&map_path).map_err(|e| format!("Failed to read map image: {e}"))?;
let base64_image =
base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &image_data);
// Read metadata
let metadata_content =
fs::read_to_string(&metadata_path).map_err(|e| format!("Failed to read metadata: {e}"))?;
let metadata: serde_json::Value = serde_json::from_str(&metadata_content)
.map_err(|e| format!("Failed to parse metadata: {e}"))?;
// Extract geo bounds (metadata uses camelCase from serde)
let min_lat = metadata["minGeoLat"]
.as_f64()
.ok_or("Missing minGeoLat in metadata")?;
let max_lat = metadata["maxGeoLat"]
.as_f64()
.ok_or("Missing maxGeoLat in metadata")?;
let min_lon = metadata["minGeoLon"]
.as_f64()
.ok_or("Missing minGeoLon in metadata")?;
let max_lon = metadata["maxGeoLon"]
.as_f64()
.ok_or("Missing maxGeoLon in metadata")?;
Ok(Some(WorldMapData {
image_base64: format!("data:image/png;base64,{}", base64_image),
min_lat,
max_lat,
min_lon,
max_lon,
}))
}
/// Data structure for world map overlay
#[derive(serde::Serialize)]
struct WorldMapData {
image_base64: String,
min_lat: f64,
max_lat: f64,
min_lon: f64,
max_lon: f64,
}
#[tauri::command]
#[allow(clippy::too_many_arguments)]
#[allow(unused_variables)]
fn gui_start_generation(
bbox_text: String,
selected_world: String,
world_scale: f64,
ground_level: i32,
floodfill_timeout: u64,
terrain_enabled: bool,
skip_osm_objects: bool,
interior_enabled: bool,
roof_enabled: bool,
fillground_enabled: bool,
is_new_world: bool,
spawn_point: Option<(f64, f64)>,
telemetry_consent: bool,
) -> Result<(), String> {
use progress::emit_gui_error;
use LLBBox;
// Store telemetry consent for crash reporting
telemetry::set_telemetry_consent(telemetry_consent);
// Send generation click telemetry
telemetry::send_generation_click();
// If spawn point was chosen and the world is new, check and set the spawn point
if is_new_world && spawn_point.is_some() {
// Verify the spawn point is within bounds
if let Some(coords) = spawn_point {
let llbbox = match LLBBox::from_str(&bbox_text) {
Ok(bbox) => bbox,
Err(e) => {
let error_msg = format!("Failed to parse bounding box: {e}");
eprintln!("{error_msg}");
emit_gui_error(&error_msg);
return Err(error_msg);
}
};
let llpoint = LLPoint::new(coords.0, coords.1)
.map_err(|e| format!("Failed to parse spawn point: {e}"))?;
if llbbox.contains(&llpoint) {
// Spawn point is valid, update the player position
update_player_position(
&selected_world,
spawn_point,
bbox_text.clone(),
world_scale,
)
.map_err(|e| format!("Failed to set spawn point: {e}"))?;
}
}
}
tauri::async_runtime::spawn(async move {
if let Err(e) = tokio::task::spawn_blocking(move || {
// Acquire session lock for the world directory before starting generation
let world_path = PathBuf::from(&selected_world);
let _session_lock = match SessionLock::acquire(&world_path) {
Ok(lock) => lock,
Err(e) => {
let error_msg = format!("Failed to acquire session lock: {e}");
eprintln!("{error_msg}");
emit_gui_error(&error_msg);
return Err(error_msg);
}
};
// Parse the bounding box from the text with proper error handling
let bbox = match LLBBox::from_str(&bbox_text) {
Ok(bbox) => bbox,
Err(e) => {
let error_msg = format!("Failed to parse bounding box: {e}");
eprintln!("{error_msg}");
emit_gui_error(&error_msg);
return Err(error_msg);
}
};
// Add localized name to the world if user generated a new world
let updated_world_path = if is_new_world {
add_localized_world_name(world_path, &bbox)
} else {
world_path
};
// Create an Args instance with the chosen bounding box and world directory path
let args: Args = Args {
bbox,
file: None,
save_json_file: None,
path: updated_world_path,
downloader: "requests".to_string(),
scale: world_scale,
ground_level,
terrain: terrain_enabled,
interior: interior_enabled,
roof: roof_enabled,
fillground: fillground_enabled,
debug: false,
timeout: Some(std::time::Duration::from_secs(floodfill_timeout)),
generate_map: true,
spawn_point,
};
// If skip_osm_objects is true (terrain-only mode), skip fetching and processing OSM data
if skip_osm_objects {
// Generate ground data (terrain) for terrain-only mode
let ground = ground::generate_ground_data(&args);
// Create empty parsed_elements and xzbbox for terrain-only mode
let parsed_elements = Vec::new();
let (_coord_transformer, xzbbox) =
CoordTransformer::llbbox_to_xzbbox(&args.bbox, args.scale)
.map_err(|e| format!("Failed to create coordinate transformer: {}", e))?;
let _ = data_processing::generate_world(
parsed_elements,
xzbbox,
args.bbox,
ground,
&args,
);
// Session lock will be automatically released when _session_lock goes out of scope
return Ok(());
}
// Run data fetch and world generation (standard mode: objects + terrain, or objects only)
match retrieve_data::fetch_data_from_overpass(args.bbox, args.debug, "requests", None) {
Ok(raw_data) => {
let (mut parsed_elements, mut xzbbox) =
osm_parser::parse_osm_data(raw_data, args.bbox, args.scale, args.debug);
parsed_elements.sort_by(|el1, el2| {
let (el1_priority, el2_priority) =
(osm_parser::get_priority(el1), osm_parser::get_priority(el2));
match (
el1.tags().contains_key("landuse"),
el2.tags().contains_key("landuse"),
) {
(true, false) => std::cmp::Ordering::Greater,
(false, true) => std::cmp::Ordering::Less,
_ => el1_priority.cmp(&el2_priority),
}
});
let mut ground = ground::generate_ground_data(&args);
// Transform map (parsed_elements). Operations are defined in a json file
map_transformation::transform_map(
&mut parsed_elements,
&mut xzbbox,
&mut ground,
);
let _ = data_processing::generate_world(
parsed_elements,
xzbbox,
args.bbox,
ground,
&args,
);
// Session lock will be automatically released when _session_lock goes out of scope
Ok(())
}
Err(e) => {
let error_msg = format!("Failed to fetch data: {e}");
emit_gui_error(&error_msg);
// Session lock will be automatically released when _session_lock goes out of scope
Err(error_msg)
}
}
})
.await
{
let error_msg = format!("Error in blocking task: {e}");
eprintln!("{error_msg}");
emit_gui_error(&error_msg);
// Session lock will be automatically released when the task fails
}
});
Ok(())
}

15
src/gui/arnis.desktop vendored Normal file
View File

@@ -0,0 +1,15 @@
[Desktop Entry]
Type=Application
Name=Arnis
Comment=Generate cities from real life in Minecraft
Comment[lt]=Sugeneruokite tikrovės miestus „Minecraft“ žaidime
Comment[de]=Generiere echte Städte in Minecraft
Comment[fr]=Générez des villes réelles dans Minecraft
Comment[es]=Genera ciudades reales en Minecraft
Comment[pt]=Gere cidades reais no Minecraft
Comment[zh_CN]=在 Minecraft 中生成现实城市
Icon=icon
Exec=arnis
Categories=Game;Education;Geoscience
Keywords=OSM;OpenStreetMap;Minecraft
StartupWMClass=arnis

View File

@@ -344,4 +344,38 @@ body,
filter: blur(1px) sepia(1) invert(1);
transition: all 1s ease;
}
/* World Preview Button in Edit Toolbar */
.leaflet-draw-toolbar .leaflet-draw-edit-preview {
background-position: -31px -2px;
}
.leaflet-draw-toolbar .leaflet-draw-edit-preview.disabled {
opacity: 0.4;
cursor: not-allowed;
pointer-events: none;
}
.leaflet-draw-toolbar .leaflet-draw-edit-preview.active {
background-color: #a0d0ff;
}
.world-preview-slider-container {
padding: 6px 8px !important;
background: white !important;
background-clip: padding-box;
}
.world-preview-slider-container a {
display: none !important;
}
.world-preview-slider {
width: 80px;
height: 8px;
cursor: pointer;
accent-color: #3887BE;
display: block;
margin: 0;
}

View File

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

Before

Width:  |  Height:  |  Size: 418 B

After

Width:  |  Height:  |  Size: 418 B

View File

Before

Width:  |  Height:  |  Size: 312 B

After

Width:  |  Height:  |  Size: 312 B

View File

Before

Width:  |  Height:  |  Size: 205 B

After

Width:  |  Height:  |  Size: 205 B

View File

Before

Width:  |  Height:  |  Size: 262 B

After

Width:  |  Height:  |  Size: 262 B

Some files were not shown because too many files have changed in this diff Show More