Compare commits

..

2 Commits

Author SHA1 Message Date
louis-e
7a42f011de Fix fmt 2025-05-05 00:25:25 +02:00
louis-e
106214c8ea WIP: Add subway 2025-05-05 00:21:58 +02:00
113 changed files with 15321 additions and 8775 deletions

View File

@@ -1,32 +1,43 @@
name: CI Build
# Trigger CI on pull requests when relevant files change, and pushes to main
# Trigger CI on pull requests and pushes to main, when relevant files change
on:
pull_request:
branches:
- main
paths:
- '.github/**'
- 'src/**'
- 'Cargo.toml'
- 'Cargo.lock'
push:
branches:
- main
paths:
- 'src/**'
- 'Cargo.toml'
- 'Cargo.lock'
workflow_dispatch:
jobs:
lint:
runs-on: ubuntu-latest
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v3
- 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
- name: Install Linux dependencies
if: matrix.os == 'ubuntu-latest'
run: |
sudo apt update
sudo apt install -y software-properties-common
@@ -36,7 +47,16 @@ 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: Set up cache for Cargo
uses: actions/cache@v3
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
restore-keys: |
${{ runner.os }}-cargo-
- name: Check formatting
run: cargo fmt -- --check
@@ -44,28 +64,8 @@ jobs:
- name: Check clippy lints
run: cargo clippy --all-targets --all-features -- -D warnings
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- 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: Install Rust dependencies
run: cargo fetch
- name: Build (all targets, all features)
run: cargo build --all-targets --all-features --release

View File

@@ -1,9 +1,5 @@
name: PR Benchmark
permissions:
contents: read
pull-requests: write
on:
pull_request:
types: [opened, reopened]
@@ -20,22 +16,18 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v3
- name: Set up Rust
uses: dtolnay/rust-toolchain@v1
with:
toolchain: stable
- uses: Swatinem/rust-cache@v2
components: clippy
- 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
@@ -43,7 +35,7 @@ jobs:
- name: Run benchmark command with memory tracking
id: benchmark
run: |
/usr/bin/time -v ./target/release/arnis --path="./world" --terrain --bbox="48.101470,11.517792,48.168375,11.626968" 2> benchmark_log.txt
/usr/bin/time -v cargo run --release --no-default-features -- --path="./world" --terrain --bbox="48.117861,11.541996,48.154520,11.604824" 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))
@@ -65,21 +57,21 @@ jobs:
seconds=$((duration % 60))
peak_mem=${{ steps.benchmark.outputs.peak_memory }}
baseline_time=135
baseline_time=130
diff=$((duration - baseline_time))
abs_diff=${diff#-}
if [ "$diff" -lt -5 ]; then
if [ "$diff" -lt -10 ]; then
verdict="✅ This PR **improves generation time**."
elif [ "$abs_diff" -le 4 ]; then
elif [ "$abs_diff" -le 7 ]; then
verdict="🟢 Generation time is unchanged."
elif [ "$diff" -le 15 ]; then
verdict="⚠️ This PR **worsens generation time**."
elif [ "$diff" -le 25 ]; then
verdict="⚠️ This PR **slightly worsens generation time**."
else
verdict="🚨 This PR **drastically worsens generation time**."
fi
baseline_mem=5865
baseline_mem=1960
mem_annotation=""
if [ "$peak_mem" -gt 2000 ]; then
mem_diff=$((peak_mem - baseline_mem))
@@ -108,4 +100,4 @@ jobs:
message: ${{ steps.comment_body.outputs.summary }}
comment-tag: benchmark-report
env:
GITHUB_TOKEN: ${{ secrets.BENCHMARK_TOKEN }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

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

View File

@@ -1,100 +0,0 @@
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

4
.gitignore vendored
View File

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

1535
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.3.0"
version = "2.2.0"
edition = "2021"
description = "Arnis - Generate real life cities in Minecraft"
homepage = "https://github.com/louis-e/arnis"
@@ -10,7 +10,6 @@ readme = "README.md"
[profile.release]
lto = "thin"
overflow-checks = true
[features]
default = ["gui"]
@@ -20,7 +19,7 @@ gui = ["tauri", "tauri-plugin-log", "tauri-plugin-shell", "tokio", "rfd", "dirs"
tauri-build = {version = "2", optional = true}
[dependencies]
clap = { version = "4.5", features = ["derive", "env"] }
clap = { version = "4.1", features = ["derive"] }
colored = "3.0.0"
dirs = {version = "6.0.0", optional = true }
fastanvil = "0.31.0"
@@ -28,26 +27,23 @@ fastnbt = "2.5.0"
flate2 = "1.1"
fnv = "1.0.7"
fs2 = "0.4"
geo = "0.30.0"
image = "0.25"
indicatif = "0.17.11"
geo = "0.29.3"
image = "0.24"
indicatif = "0.17.8"
itertools = "0.14.0"
log = "0.4.27"
once_cell = "1.21.3"
rand = "0.8.5"
rayon = "1.10.0"
reqwest = { version = "0.12.15", features = ["blocking", "json"] }
rfd = { version = "0.15.4", optional = true }
reqwest = { version = "0.12.7", features = ["blocking", "json"] }
rfd = { version = "0.15.1", optional = true }
semver = "1.0.23"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tauri = { version = "2", optional = true }
tauri-plugin-log = { version = "2.6.0", optional = true }
tauri-plugin-log = { version = "2.2.2", optional = true }
tauri-plugin-shell = { version = "2", optional = true }
tokio = { version = "1.47.0", features = ["full"], optional = true }
tokio = { version = "1.44.2", features = ["full"], optional = true }
[target.'cfg(windows)'.dependencies]
windows = { version = "0.61.1", features = ["Win32_System_Console"] }
[dev-dependencies]
tempfile = "3.20.0"

112
README.md
View File

@@ -1,27 +1,95 @@
<img src="https://github.com/louis-e/arnis/blob/main/gitassets/banner.png?raw=true" width="100%" alt="Banner">
<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>
# 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)
# 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 creates complex and accurate Minecraft Java Edition worlds that reflect real-world geography, topography, and architecture.
Arnis creates complex and accurate Minecraft Java Edition worlds that reflect real-world geography and architecture using OpenStreetMap.
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!
###### ⚠️ This Github page is the official project website. Do not download Arnis from any other website.
![Minecraft Preview](https://raw.githubusercontent.com/louis-e/arnis/refs/heads/main/gitassets/preview.jpg)
<i>This Github page is the official project website. Do not download Arnis from any other website.</i>
## :desktop_computer: Example
![Minecraft Preview](https://github.com/louis-e/arnis/blob/main/gitassets/mc.gif?raw=true)
Arnis is designed to handle large-scale data and generate rich, immersive environments that bring real-world cities, landmarks, and natural features into Minecraft. Whether you're looking to replicate your hometown, explore urban environments, or simply build something unique and realistic, Arnis generates your vision.
## :keyboard: Usage
<img width="60%" src="https://github.com/louis-e/arnis/blob/main/gitassets/gui.png?raw=true"><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 using the rectangle tool and select your Minecraft world - then simply click on 'Start Generation'!
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.
> 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.
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 or above.
If you choose to select an own world, be aware that Arnis will overwrite certain areas.
## 📚 Documentation
[[Arch Linux AUR package](https://aur.archlinux.org/packages/arnis)]
<img src="https://github.com/louis-e/arnis/blob/main/gitassets/documentation.png?raw=true" width="100%" alt="Banner">
## :floppy_disk: How it works
![CLI Generation](https://github.com/louis-e/arnis/blob/main/gitassets/cli.gif?raw=true)
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.
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).
If you're on Linux, your system might be missing the webkit2gtk-4.1 library, install the corresponding package using your distro's package manager.
- *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>
**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 and Mac
- [ ] Fix coastal cities generation duration time (water_areas.rs)
- [ ] Rotate maps (https://github.com/louis-e/arnis/issues/97)
- [ ] 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 street names as signs
- [ ] 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
## :trophy: Open Source
#### Key objectives of this project
@@ -34,8 +102,10 @@ Full documentation is available in the [GitHub Wiki](https://github.com/louis-e/
#### 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. Please respect the above mentioned key objectives. Contributions of all levels are appreciated, and your efforts help improve this tool for everyone.
Command line Build: ```cargo run --no-default-features -- --terrain --path="C:/YOUR_PATH/.minecraft/saves/worldname" --bbox="min_lng,min_lat,max_lng,max_lat"```<br>
GUI Build: ```cargo run```<br>
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>
> You can use the parameter --debug to get a more detailed output of the processed values, which can be helpful for debugging and development.
After your pull request was merged, I will take care of regularly creating update releases which will include your changes.
@@ -49,20 +119,6 @@ After your pull request was merged, I will take care of regularly creating updat
</picture>
</a>
## :newspaper: Academic & Press Recognition
<img src="https://github.com/louis-e/arnis/blob/main/gitassets/recognition.png?raw=true" 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)

View File

@@ -1,32 +0,0 @@
[
{
"comment": "this make all elements x+=2000, z+=2000",
"operation": "translate",
"config": {
"type": "vector",
"config": {
"vector": {
"dx": 2000,
"dz": 2000
}
}
}
},
{
"comment": "This drags the map at point 2000,2000 to 100,100",
"operation": "translate",
"config": {
"type": "startend",
"config": {
"start": {
"x": 2000,
"z": 2000
},
"end": {
"x": 0,
"z": 0
}
}
}
}
]

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 163 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 108 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 196 KiB

After

Width:  |  Height:  |  Size: 198 KiB

BIN
gitassets/mc.gif Normal file
View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 MiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 790 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 127 KiB

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

49
gui-src/css/maps/leaflet.draw.ie.css vendored Normal file
View File

@@ -0,0 +1,49 @@
/* 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;
}

51
gui-src/css/maps/leaflet.ie.css vendored Normal file
View File

@@ -0,0 +1,51 @@
.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;
}

757
gui-src/css/maps/mapbox.standalone.css vendored Normal file
View File

@@ -0,0 +1,757 @@
/* 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 */ }

1
gui-src/css/maps/mapbox.v3.2.0.css vendored Normal file
View File

File diff suppressed because one or more lines are too long

View File

@@ -1,97 +0,0 @@
/* City Search Box Styles */
#search-container {
position: absolute;
top: 5px;
right: 5px;
z-index: 1000;
font-family: Arial, sans-serif;
}
#search-box {
display: flex;
align-items: center;
padding: 0;
}
#city-search {
border: 1px solid #ddd;
border-radius: 3px 0 0 3px;
padding: 6px 10px;
font-size: 13px;
width: 200px;
outline: none;
border-right: none;
}
#city-search:focus {
border-color: #007cbb;
box-shadow: 0 0 5px rgba(0, 124, 187, 0.3);
}
#search-btn {
background: #007cbb;
color: white;
border: 1px solid #007cbb;
border-radius: 0 3px 3px 0;
padding: 4.5px 10px;
cursor: pointer;
font-size: 12px;
transition: background-color 0.2s;
}
#search-results {
max-height: 200px;
max-width: 238px;
overflow-y: auto;
border-top: 1px solid #eee;
display: none;
background: white;
border-radius: 0 0 3px 3px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}
.search-result-item {
padding: 10px 12px;
cursor: pointer;
border-bottom: 1px solid #f0f0f0;
font-size: 13px;
color: #333;
word-wrap: break-word;
overflow-wrap: break-word;
}
.search-result-item:hover {
background-color: #f5f5f5;
}
.search-result-item:last-child {
border-bottom: none;
}
.search-result-name {
font-weight: bold;
color: #007cbb;
word-wrap: break-word;
overflow-wrap: break-word;
}
.search-result-details {
color: #666;
font-size: 11px;
margin-top: 2px;
word-wrap: break-word;
overflow-wrap: break-word;
}
.search-loading {
padding: 10px 12px;
text-align: center;
color: #666;
font-style: italic;
}
.search-no-results {
padding: 10px 12px;
text-align: center;
color: #999;
}

164
gui-src/css/styles.css vendored
View File

@@ -10,11 +10,6 @@
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
/* CSS Variables for consistent theming */
--primary-accent: #fecc44;
--primary-accent-dark: #e6b73d;
--primary-accent-light: #fff2cc;
}
p {
@@ -48,13 +43,12 @@ p {
a {
font-weight: 500;
color: var(--primary-accent);
color: #646cff;
text-decoration: inherit;
transition: color 0.3s ease;
}
a:hover {
color: var(--primary-accent-dark);
color: #535bf2;
}
.flex-container {
@@ -265,22 +259,6 @@ button:hover {
margin: 15px 0;
}
#interior-toggle {
accent-color: #fecc44;
}
.interior-toggle-container, .scale-slider-container {
margin: 15px 0;
}
#roof-toggle {
accent-color: #fecc44;
}
.roof-toggle-container, .scale-slider-container {
margin: 15px 0;
}
.scale-slider-container label {
display: block;
margin-bottom: 5px;
@@ -318,132 +296,6 @@ button:hover {
box-shadow: 0 0 5px #fecc44;
}
/* Settings Modal Layout */
.settings-row {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
.settings-row label {
text-align: left;
flex: 1;
}
.settings-control {
flex: 1;
display: flex;
justify-content: flex-end;
align-items: center;
}
.settings-control input[type="range"] {
width: 60%;
}
.settings-control input[type="text"],
.settings-control input[type="number"] {
width: 100%;
max-width: 180px;
padding: 5px;
border-radius: 4px;
border: 1px solid #fecc44;
}
.license-button-row {
justify-content: center;
margin-top: 10px;
}
.license-button {
width: 80% !important;
}
/* Buy Me a Coffee and Discord styling */
.buymeacoffee-row {
justify-content: center;
align-items: center;
gap: 15px;
margin-top: 10px;
margin-bottom: -10px;
}
.buymeacoffee-link,
.discord-link {
display: inline-block;
transition: transform 0.3s ease, opacity 0.3s ease;
}
.buymeacoffee-link:hover,
.discord-link:hover {
transform: scale(1.05);
opacity: 0.8;
}
.buymeacoffee-logo,
.discord-logo {
height: 35px;
width: auto;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
/* Language dropdown styling */
.language-dropdown {
width: 100%;
max-width: 180px;
padding: 5px 8px;
border-radius: 4px;
border: 1px solid #fecc44;
background-color: #ffffff;
color: #0f0f0f;
appearance: menulist;
cursor: pointer;
font-size: 15px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
.language-dropdown option {
padding: 5px;
font-size: 15px;
}
@media (prefers-color-scheme: dark) {
.language-dropdown {
background-color: #0f0f0f98;
color: #ffffff;
border: 1px solid #fecc44;
}
}
/* Theme dropdown styling */
.theme-dropdown {
width: 100%;
max-width: 180px;
padding: 5px 8px;
border-radius: 4px;
border: 1px solid #fecc44;
background-color: #ffffff;
color: #0f0f0f;
appearance: menulist;
cursor: pointer;
font-size: 15px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
.theme-dropdown option {
padding: 5px;
font-size: 15px;
}
@media (prefers-color-scheme: dark) {
.theme-dropdown {
background-color: #0f0f0f98;
color: #ffffff;
border: 1px solid #fecc44;
}
}
.button-container {
display: flex;
@@ -486,22 +338,18 @@ button:hover {
width: 35%;
height: auto;
opacity: 0;
transform: scale(0) rotate(-10deg);
animation: zoomInLogo 1.2s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
transform: scale(0);
animation: zoomInLogo 1s ease-out forwards;
}
/* Keyframe Animation */
@keyframes zoomInLogo {
0% {
transform: scale(0) rotate(-10deg);
transform: scale(0);
opacity: 0;
}
60% {
transform: scale(1.05) rotate(2deg);
opacity: 0.8;
}
100% {
transform: scale(1) rotate(0deg);
transform: scale(1);
opacity: 1;
}
}

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 556 B

119
gui-src/index.html vendored
View File

@@ -8,14 +8,13 @@
<title>Arnis</title>
<script type="module" src="./js/main.js" defer></script>
<script type="module" src="./js/license.js" defer></script>
<script type="module" src="./js/language-selector.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;">
<img src="./images/logo.png" id="arnis-logo" class="logo arnis" alt="Arnis Logo" style="width: 35%; height: auto;" />
</a>
</div>
@@ -88,113 +87,43 @@
<h2 data-localize="customization_settings">Customization Settings</h2>
<!-- Terrain Toggle Button -->
<div class="settings-row">
<label for="terrain-toggle" data-localize="terrain">Terrain</label>
<div class="settings-control">
<input type="checkbox" id="terrain-toggle" name="terrain-toggle" checked>
</div>
<div class="terrain-toggle-container">
<label for="terrain-toggle" data-localize="terrain">Terrain:</label>
<input type="checkbox" id="terrain-toggle" name="terrain-toggle" checked>
</div>
<!-- Interior Toggle Button -->
<div class="settings-row">
<label for="interior-toggle" data-localize="interior">Interior Generation</label>
<div class="settings-control">
<input type="checkbox" id="interior-toggle" name="interior-toggle" checked>
</div>
</div>
<!-- Roof Toggle Button -->
<div class="settings-row">
<label for="roof-toggle" data-localize="roof">Roof Generation</label>
<div class="settings-control">
<input type="checkbox" id="roof-toggle" name="roof-toggle" checked>
</div>
</div>
<!-- Fill ground Toggle Button -->
<div class="settings-row">
<label for="fillground-toggle" data-localize="fillground">Fill Ground</label>
<div class="settings-control">
<input type="checkbox" id="fillground-toggle" name="fillground-toggle">
</div>
<div class="fillground-toggle-container">
<label for="fillground-toggle" data-localize="fillground">Fill Ground:</label>
<input type="checkbox" id="fillground-toggle" name="fillground-toggle">
</div>
<!-- World Scale Slider -->
<div class="settings-row">
<label for="scale-value-slider" data-localize="world_scale">World Scale</label>
<div class="settings-control">
<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>
<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="settings-row">
<label for="bbox-coords" data-localize="custom_bounding_box">Custom Bounding Box</label>
<div class="settings-control">
<input type="text" id="bbox-coords" name="bbox-coords" maxlength="55" placeholder="Format: lat,lng,lat,lng">
</div>
<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="settings-row">
<label for="floodfill-timeout" data-localize="floodfill_timeout">Floodfill Timeout (sec)</label>
<div class="settings-control">
<input type="number" id="floodfill-timeout" name="floodfill-timeout" min="0" step="1" value="20" placeholder="Seconds">
</div>
</div>
<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>
<!-- Map Theme Selector -->
<div class="settings-row">
<label for="tile-theme-select" data-localize="map_theme">Map Theme</label>
<div class="settings-control">
<select id="tile-theme-select" name="tile-theme-select" class="theme-dropdown">
<option value="osm">Standard</option>
<option value="esri-imagery">Satellite</option>
<option value="opentopomap">Topographic</option>
<option value="stadia-bright">Smooth Bright</option>
<option value="stadia-dark">Smooth Dark</option>
</select>
</div>
</div>
<!-- Language Selector -->
<div class="settings-row">
<label for="language-select" data-localize="language">Language</label>
<div class="settings-control">
<select id="language-select" name="language-select" class="language-dropdown">
<option value="en">English</option>
<option value="de">Deutsch</option>
<option value="es">Español</option>
<option value="fr-FR">Français</option>
<option value="ru">Русский</option>
<option value="zh-CN">中文 (简体)</option>
<option value="ko">한국어</option>
<option value="pl">Polski</option>
<option value="sv">Svenska</option>
<option value="ar">العربية</option>
<option value="fi">Suomi</option>
<option value="hu">Magyar</option>
<option value="lt">Lietuvių</option>
<option value="ua">Українська</option>
</select>
</div>
<!-- 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 -->
<div class="settings-row license-button-row">
<button type="button" id="license-button" class="license-button" onclick="openLicense()" data-localize="license_and_credits">License and Credits</button>
</div>
<!-- Buy Me a Coffee and Discord -->
<div class="settings-row buymeacoffee-row">
<a href="https://buymeacoffee.com/louisdev" target="_blank" class="buymeacoffee-link">
<img src="./images/buymeacoffee.png" alt="Buy Me a Coffee" class="buymeacoffee-logo">
</a>
<a href="https://discord.gg/mA2g69Fhxq" target="_blank" class="discord-link">
<img src="./images/discord.png" alt="Discord" class="discord-logo">
</a>
</div>
<button type="button" id="license-button" class="license-button" onclick="openLicense()" data-localize="license_and_credits">License and Credits</button>
</div>
</div>

280
gui-src/js/bbox.js vendored
View File

@@ -322,7 +322,7 @@ function addLayer(layer, name, title, zIndex, on) {
}
link.innerHTML = name;
link.title = title;
link.onclick = function (e) {
link.onclick = function(e) {
e.preventDefault();
e.stopPropagation();
@@ -429,7 +429,7 @@ function formatPoint(point, proj) {
formattedBounds = y + ' ' + x;
}
}
return formattedPoint
return formattedBounds
}
function validateStringAsBounds(bounds) {
@@ -456,122 +456,13 @@ $(document).ready(function () {
** on top of your DOM
**
*/
// init the projection input box as it is used to format the initial values
$('input[type="textarea"]').on('click', function (evt) { this.select() });
// Have to init the projection input box as it is used to format the initial values
$("#projection").val(currentproj);
// Initialize map
map = L.map('map').setView([50.114768, 8.687322], 4);
// Define available tile themes
var tileThemes = {
'osm': {
url: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
options: {
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
maxZoom: 19
}
},
'esri-imagery': {
url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
options: {
attribution: 'Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community',
maxZoom: 18
}
},
'opentopomap': {
url: 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png',
options: {
attribution: 'Map data: &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, <a href="http://viewfinderpanoramas.org">SRTM</a> | Map style: &copy; <a href="https://opentopomap.org">OpenTopoMap</a> (<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)',
maxZoom: 17
}
},
'stadia-bright': {
url: 'https://tiles.stadiamaps.com/tiles/alidade_smooth/{z}/{x}/{y}.{ext}',
options: {
minZoom: 0,
maxZoom: 19,
attribution: '&copy; <a href="https://www.stadiamaps.com/" target="_blank">Stadia Maps</a> &copy; <a href="https://openmaptiles.org/" target="_blank">OpenMapTiles</a> &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
ext: 'png'
}
},
'stadia-dark': {
url: 'https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/{z}/{x}/{y}.{ext}',
options: {
minZoom: 0,
maxZoom: 19,
attribution: '&copy; <a href="https://www.stadiamaps.com/" target="_blank">Stadia Maps</a> &copy; <a href="https://openmaptiles.org/" target="_blank">OpenMapTiles</a> &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
ext: 'png'
}
}
};
// Global variable to store current tile layer
var currentTileLayer = null;
// Function to change tile theme with automatic HTTP fallback
function changeTileTheme(themeKey) {
// Remove current tile layer if it exists
if (currentTileLayer) {
map.removeLayer(currentTileLayer);
}
// Get the theme configuration
var theme = tileThemes[themeKey];
if (theme) {
// Create and add new tile layer
currentTileLayer = L.tileLayer(theme.url, theme.options);
// Add automatic HTTP fallback for HTTPS failures
var failureCount = 0;
currentTileLayer.on('tileerror', function(error) {
failureCount++;
// After a few failures, try HTTP fallback
if (failureCount >= 3 && !this._httpFallbackAttempted && theme.url.startsWith('https://')) {
console.log('HTTPS tile loading failed, attempting HTTP fallback for', themeKey);
this._httpFallbackAttempted = true;
// Create HTTP version of the URL
var httpUrl = theme.url.replace('https://', 'http://');
// Remove the failed HTTPS layer
map.removeLayer(this);
// Create new layer with HTTP URL
var httpLayer = L.tileLayer(httpUrl, theme.options);
httpLayer._httpFallbackAttempted = true;
httpLayer.addTo(map);
currentTileLayer = httpLayer;
}
});
currentTileLayer.addTo(map);
// Save preference to localStorage
localStorage.setItem('selectedTileTheme', themeKey);
}
}
// Load saved theme or default to OSM
var savedTheme = localStorage.getItem('selectedTileTheme') || 'osm';
changeTileTheme(savedTheme);
// Listen for theme changes from parent window (settings modal)
window.addEventListener('message', function(event) {
if (event.data && event.data.type === 'changeTileTheme') {
changeTileTheme(event.data.theme);
}
});
// Set the dropdown value in parent window if it exists
if (window.parent && window.parent.document) {
var dropdown = window.parent.document.getElementById('tile-theme-select');
if (dropdown) {
dropdown.value = savedTheme;
}
}
L.mapbox.accessToken = 'pk.eyJ1IjoiY3Vnb3MiLCJhIjoiY2p4Nm43MzA3MDFmZDQwcGxsMjB4Z3hnNiJ9.SQbnMASwdqZe6G4n6OMvVw';
map = L.mapbox.map('map').setView([50.114768, 8.687322], 4).addLayer(L.mapbox.styleLayer('mapbox://styles/mapbox/streets-v11'));
rsidebar = L.control.sidebar('rsidebar', {
position: 'right',
@@ -605,53 +496,24 @@ $(document).ready(function () {
crosshair = new L.marker(map.getCenter(), { icon: crosshairIcon, clickable: false });
crosshair.addTo(map);
// Override default tooltips
L.drawLocal = L.drawLocal || {};
L.drawLocal.draw = L.drawLocal.draw || {};
L.drawLocal.draw.toolbar = L.drawLocal.draw.toolbar || {};
L.drawLocal.draw.toolbar.buttons = L.drawLocal.draw.toolbar.buttons || {};
L.drawLocal.draw.toolbar.buttons.rectangle = 'Choose area';
L.drawLocal.draw.toolbar.buttons.marker = 'Set spawnpoint';
// Initialize the FeatureGroup to store editable layers
drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
// Custom icon for drawn markers
var customMarkerIcon = L.icon({
iconUrl: 'images/marker-icon.png',
iconSize: [20, 20],
iconAnchor: [10, 10],
popupAnchor: [0, -10]
});
// Initialize the draw control and pass it the FeatureGroup of editable layers
drawControl = new L.Control.Draw({
edit: {
featureGroup: drawnItems
},
draw: {
rectangle: {
shapeOptions: {
color: '#fe57a1',
opacity: 0.6,
weight: 3,
fillColor: '#fe57a1',
fillOpacity: 0.1,
dashArray: '10, 10',
lineCap: 'round',
lineJoin: 'round'
},
repeatMode: false
},
polyline: false,
polygon: false,
circle: false,
marker: {
icon: customMarkerIcon
}
marker: false
}
});
map.addControl(drawControl);
/*
**
** create bounds layer
@@ -661,22 +523,17 @@ $(document).ready(function () {
**
*/
startBounds = new L.LatLngBounds([0.0, 0.0], [0.0, 0.0]);
var bounds = new L.Rectangle(startBounds, {
color: '#3778d4',
opacity: 1.0,
weight: 3,
fill: '#3778d4',
lineCap: 'round',
lineJoin: 'round'
});
bounds.on('bounds-set', function (e) {
// move it to the end of the parent if renderer exists
if (e.target._renderer && e.target._renderer._container) {
var parent = e.target._renderer._container.parentElement;
$(parent).append(e.target._renderer._container);
var bounds = new L.Rectangle(startBounds,
{
fill: false,
opacity: 1.0,
color: '#000'
}
);
bounds.on('bounds-set', function (e) {
// move it to the end of the parent
var parent = e.target._renderer._container.parentElement;
$(parent).append(e.target._renderer._container);
// Set the hash
var southwest = this.getBounds().getSouthWest();
var northeast = this.getBounds().getNorthEast();
@@ -686,55 +543,13 @@ $(document).ready(function () {
var ymax = northeast.lat.toFixed(6);
location.hash = ymin + ',' + xmin + ',' + ymax + ',' + xmax;
});
map.addLayer(bounds);
map.addLayer(bounds)
map.on('draw:created', function (e) {
// If it's a marker, make sure we only have one
if (e.layerType === 'marker') {
// Remove any existing markers
drawnItems.eachLayer(function(layer) {
if (layer instanceof L.Marker) {
drawnItems.removeLayer(layer);
}
});
}
// Check if it's a rectangle and set proper styles before adding it to the layer
if (e.layerType === 'rectangle') {
e.layer.setStyle({
color: '#3778d4',
opacity: 1.0,
weight: 3,
fill: '#3778d4',
lineCap: 'round',
lineJoin: 'round'
});
}
drawnItems.addLayer(e.layer);
// Only update the bounds based on non-marker layers
if (e.layerType !== 'marker') {
// Calculate bounds only from non-marker layers
const nonMarkerBounds = new L.LatLngBounds();
let hasNonMarkerLayers = false;
drawnItems.eachLayer(function(layer) {
if (!(layer instanceof L.Marker)) {
hasNonMarkerLayers = true;
nonMarkerBounds.extend(layer.getBounds());
}
});
// Only update bounds if there are non-marker layers
if (hasNonMarkerLayers) {
bounds.setBounds(nonMarkerBounds);
$('#boxbounds').text(formatBounds(bounds.getBounds(), '4326'));
$('#boxboundsmerc').text(formatBounds(bounds.getBounds(), currentproj));
notifyBboxUpdate();
}
}
bounds.setBounds(drawnItems.getBounds())
$('#boxbounds').text(formatBounds(bounds.getBounds(), '4326'));
$('#boxboundsmerc').text(formatBounds(bounds.getBounds(), currentproj));
notifyBboxUpdate();
if (!e.geojson &&
!((drawnItems.getLayers().length == 1) && (drawnItems.getLayers()[0] instanceof L.Marker))) {
map.fitBounds(bounds.getBounds());
@@ -768,22 +583,7 @@ $(document).ready(function () {
});
map.on('draw:edited', function (e) {
// Calculate bounds only from non-marker layers
const nonMarkerBounds = new L.LatLngBounds();
let hasNonMarkerLayers = false;
drawnItems.eachLayer(function(layer) {
if (!(layer instanceof L.Marker)) {
hasNonMarkerLayers = true;
nonMarkerBounds.extend(layer.getBounds());
}
});
// Only update bounds if there are non-marker layers
if (hasNonMarkerLayers) {
bounds.setBounds(nonMarkerBounds);
}
bounds.setBounds(drawnItems.getBounds())
$('#boxbounds').text(formatBounds(bounds.getBounds(), '4326'));
$('#boxboundsmerc').text(formatBounds(bounds.getBounds(), currentproj));
notifyBboxUpdate();
@@ -829,14 +629,7 @@ $(document).ready(function () {
var splitBounds = initialBBox.split(',');
startBounds = new L.LatLngBounds([splitBounds[0], splitBounds[1]],
[splitBounds[2], splitBounds[3]]);
var lyr = new L.Rectangle(startBounds, {
color: '#3778d4',
opacity: 1.0,
weight: 3,
fill: '#3778d4',
lineCap: 'round',
lineJoin: 'round'
});
var lyr = new L.Rectangle(startBounds);
var evt = {
layer: lyr,
layerType: "polygon",
@@ -862,24 +655,3 @@ function notifyBboxUpdate() {
const bboxText = document.getElementById('boxbounds').textContent;
window.parent.postMessage({ bboxText: bboxText }, '*');
}
// Expose marker coordinates to the parent window
function getSpawnPointCoords() {
// Check if there are any markers in drawn items
const markers = [];
drawnItems.eachLayer(function(layer) {
if (layer instanceof L.Marker) {
const latLng = layer.getLatLng();
markers.push({
lat: latLng.lat,
lng: latLng.lng
});
}
});
// Return the first marker found or null if none exists
return markers.length > 0 ? markers[0] : null;
}
// Expose the function to the parent window
window.getSpawnPointCoords = getSpawnPointCoords;

View File

@@ -1,45 +0,0 @@
// Wait for DOM to be fully loaded
document.addEventListener('DOMContentLoaded', function () {
// Get language selector
const languageSelect = document.getElementById('language-select');
if (languageSelect) {
// Set initial value based on saved preference or browser language
const savedLanguage = localStorage.getItem('arnis-language');
const currentLang = savedLanguage || navigator.language;
const availableOptions = Array.from(languageSelect.options).map(opt => opt.value);
// Try to match the exact language code first
if (availableOptions.includes(currentLang)) {
languageSelect.value = currentLang;
}
// Try to match just the base language code
else if (availableOptions.includes(currentLang.split('-')[0])) {
languageSelect.value = currentLang.split('-')[0];
}
// Handle language change
languageSelect.addEventListener('change', function () {
const selectedLanguage = languageSelect.value;
// Store selection in localStorage
localStorage.setItem('arnis-language', selectedLanguage);
// Reload localization with the new language
if (window.fetchLanguage) {
window.fetchLanguage(selectedLanguage).then(localization => {
if (window.applyLocalization) {
window.applyLocalization(localization);
// Re-initialize the footer to ensure year and version are properly displayed
if (window.initFooter) {
window.initFooter();
}
}
});
} else {
// If the fetchLanguage function isn't exposed to window, just reload the page
window.location.reload();
}
});
}
});

View File

@@ -1,33 +0,0 @@
const DEFAULT_LOCALE_PATH = `./locales/en.json`;
/**
* 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
*/
export function invalidJSON(response) {
return !response.ok || response.headers.get("Content-Type") === "text/html";
}
/**
* Fetches a specific language file
* @param {string} languageCode - The language code to fetch
* @returns {Promise<Object>} The localization JSON object
*/
export async function fetchLanguage(languageCode) {
let response = await fetch(`./locales/${languageCode}.json`);
// Try with only first part of language code if not found
if (invalidJSON(response)) {
response = await fetch(`./locales/${languageCode.split('-')[0]}.json`);
// Fallback to default English localization
if (invalidJSON(response)) {
response = await fetch(DEFAULT_LOCALE_PATH);
}
}
const localization = await response.json();
return localization;
}

33
gui-src/js/license.js vendored
View File

@@ -1,25 +1,18 @@
export const licenseText = `
<b>Made with ♥️ in Munich by Louis Erbkamm</b>
<p><b>Contributors:</b></p>
louis-e (Louis Erbkamm)<br>
scd31<br>
amir16yp<br>
vfosnar<br>
TheComputerGuy96<br>
zer0-dev<br>
RedAuburn<br>
daniil2327<br>
benjamin051000<br>
<p>For a full list of contributors, please refer to the <a href="https://github.com/louis-e/arnis/graphs/contributors" style="color: inherit;" target="_blank">Github contributors page</a>. Logo made by nxfx21.
<p style="color: #ff8686;"><b>Download Arnis only from the official source:</b> <a href="https://github.com/louis-e/arnis" style="color: inherit;" target="_blank">https://github.com/louis-e/arnis/</a>. Every other website providing a download and claiming to be affiliated with the project is unofficial and may be malicious.</p>
<p><b>Third-Party Map Data and Tile Services:</b></p>
<p>This application uses map tiles from multiple providers, each with their own licensing requirements:</p>
<b>OpenStreetMap:</b><br> © <a href="https://www.openstreetmap.org/copyright" style="color: inherit;" target="_blank">OpenStreetMap</a> contributors
<br><br>
<b>Esri:</b><br> Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community
<br><br>
<b>OpenTopoMap:</b><br> Map style: © <a href="https://opentopomap.org" style="color: inherit;" target="_blank">OpenTopoMap</a> (<a href="https://creativecommons.org/licenses/by-sa/3.0/" style="color: inherit;" target="_blank">CC-BY-SA</a>), Map data: © OpenStreetMap contributors, <a href="http://viewfinderpanoramas.org" style="color: inherit;" target="_blank">SRTM</a>
<br><br>
<b>Stadia Maps:</b><br> © <a href="https://www.stadiamaps.com/" style="color: inherit;" target="_blank">Stadia Maps</a> © <a href="https://openmaptiles.org/" style="color: inherit;" target="_blank">OpenMapTiles</a> © OpenStreetMap contributors
<p>Users of this software must comply with the respective licensing terms of these map data providers when using the application.</p>
<p>For a full list of contributors, please refer to the <a href="https://github.com/louis-e/arnis" style="color: inherit;" target="_blank">Github page</a>. Logo made by nxfx21.</p>
<p style="color: #ff7070;"><b>Download Arnis only from the official source:</b> <a href="https://github.com/louis-e/arnis" style="color: inherit;" target="_blank">https://github.com/louis-e/arnis/</a>. Every other website providing a download and claiming to be affiliated with the project is unofficial and may be malicious.</p>
<p><b>License:</b></p>
<pre style="white-space: pre-wrap; font-family: inherit;">
@@ -33,7 +26,7 @@ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
"License" shall mean the terms and conditions for use, reproduction,and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Licensor" shall mean the copyright owner or entity authorized bythe copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and allother entities that control, are controlled by, or are under commoncontrol with that entity. For the purposes of this definition,"control" means (i) the power, direct or indirect, to cause thedirection or management of such entity, whether by contract orotherwise, or (ii) ownership of fifty percent (50%) or more of theoutstanding shares, or (iii) beneficial ownership of such entity.

298
gui-src/js/main.js vendored
View File

@@ -1,11 +1,10 @@
import { licenseText } from './license.js';
import { fetchLanguage, invalidJSON } from './language.js';
let invoke;
if (window.__TAURI__) {
invoke = window.__TAURI__.core.invoke;
} else {
function dummyFunc() { }
function dummyFunc() {}
window.__TAURI__ = { event: { listen: dummyFunc } };
invoke = dummyFunc;
}
@@ -27,10 +26,15 @@ window.addEventListener("DOMContentLoaded", async () => {
await checkForUpdates();
});
// Expose language functions to window for use by language-selector.js
window.fetchLanguage = fetchLanguage;
window.applyLocalization = applyLocalization;
window.initFooter = initFooter;
/**
* 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
@@ -38,17 +42,21 @@ window.initFooter = initFooter;
* @returns {Promise<Object>} The localization JSON object
*/
async function getLocalization() {
// Check if user has a saved language preference
const savedLanguage = localStorage.getItem('arnis-language');
const lang = navigator.language;
let response = await fetch(`./locales/${lang}.json`);
// If there's a saved preference, use it
if (savedLanguage) {
return await fetchLanguage(savedLanguage);
// 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);
}
}
// Otherwise use the browser's language
const lang = navigator.language;
return await fetchLanguage(lang);
const localization = await response.json();
return localization;
}
/**
@@ -60,7 +68,7 @@ async function getLocalization() {
async function localizeElement(json, elementObject, localizedStringKey) {
const element =
(!elementObject.element || elementObject.element === "")
? document.querySelector(elementObject.selector) : elementObject.element;
? document.querySelector(elementObject.selector) : elementObject.element;
const attribute = localizedStringKey.startsWith("placeholder_") ? "placeholder" : "textContent";
if (element) {
@@ -68,7 +76,8 @@ async function localizeElement(json, elementObject, localizedStringKey) {
element[attribute] = json[localizedStringKey];
} else {
// Fallback to default (English) string
const defaultJson = await fetchLanguage('en');
const response = await fetch(DEFAULT_LOCALE_PATH);
const defaultJson = await response.json();
element[attribute] = defaultJson[localizedStringKey];
}
}
@@ -90,14 +99,7 @@ async function applyLocalization(localization) {
"label[data-localize='world_scale']": "world_scale",
"label[data-localize='custom_bounding_box']": "custom_bounding_box",
"label[data-localize='floodfill_timeout']": "floodfill_timeout",
// DEPRECATED: Ground level localization removed
// "label[data-localize='ground_level']": "ground_level",
"label[data-localize='language']": "language",
"label[data-localize='terrain']": "terrain",
"label[data-localize='interior']": "interior",
"label[data-localize='roof']": "roof",
"label[data-localize='fillground']": "fillground",
"label[data-localize='map_theme']": "map_theme",
"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",
@@ -105,8 +107,7 @@ async function applyLocalization(localization) {
// Placeholder strings
"input[id='bbox-coords']": "placeholder_bbox",
"input[id='floodfill-timeout']": "placeholder_floodfill",
// DEPRECATED: Ground level placeholder removed
// "input[id='ground-level']": "placeholder_ground"
"input[id='ground-level']": "placeholder_ground"
};
for (const selector in localizationElements) {
@@ -130,18 +131,10 @@ async function initFooter() {
const footerElement = document.querySelector(".footer-link");
if (footerElement) {
// Get the original text from localization if available, or use the current text
let footerText = footerElement.textContent;
// Check if the text is from localization and contains placeholders
if (window.localization && window.localization.footer_text) {
footerText = window.localization.footer_text;
}
// Replace placeholders with actual values
footerElement.textContent = footerText
.replace("{year}", currentYear)
.replace("{version}", version);
footerElement.textContent =
footerElement.textContent
.replace("{year}", currentYear)
.replace("{version}", version);
}
}
@@ -216,7 +209,7 @@ function initSettings() {
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";
@@ -228,7 +221,7 @@ function initSettings() {
function closeSettings() {
settingsModal.style.display = "none";
}
window.openSettings = openSettings;
window.closeSettings = closeSettings;
@@ -237,70 +230,6 @@ function initSettings() {
sliderValue.textContent = parseFloat(slider.value).toFixed(2);
});
// Language selector
const languageSelect = document.getElementById("language-select");
const availableOptions = Array.from(languageSelect.options).map(opt => opt.value);
// Check for saved language preference first
const savedLanguage = localStorage.getItem('arnis-language');
let languageToSet = 'en'; // Default to English
if (savedLanguage && availableOptions.includes(savedLanguage)) {
// Use saved language if it exists and is available
languageToSet = savedLanguage;
} else {
// Otherwise use browser language
const currentLang = navigator.language;
// Try to match the exact language code first
if (availableOptions.includes(currentLang)) {
languageToSet = currentLang;
}
// Try to match just the base language code
else if (availableOptions.includes(currentLang.split('-')[0])) {
languageToSet = currentLang.split('-')[0];
}
// languageToSet remains 'en' as default
}
languageSelect.value = languageToSet;
// Handle language change
languageSelect.addEventListener("change", async () => {
const selectedLanguage = languageSelect.value;
// Store the selected language in localStorage for persistence
localStorage.setItem('arnis-language', selectedLanguage);
// Reload localization with the new language
const localization = await fetchLanguage(selectedLanguage);
await applyLocalization(localization);
});
// Tile theme selector
const tileThemeSelect = document.getElementById("tile-theme-select");
// Load saved tile theme preference
const savedTileTheme = localStorage.getItem('selectedTileTheme') || 'osm';
tileThemeSelect.value = savedTileTheme;
// Handle tile theme change
tileThemeSelect.addEventListener("change", () => {
const selectedTheme = tileThemeSelect.value;
// Store the selected theme in localStorage for persistence
localStorage.setItem('selectedTileTheme', selectedTheme);
// Send message to map iframe to change tile theme
const mapIframe = document.querySelector('iframe[src="maps.html"]');
if (mapIframe && mapIframe.contentWindow) {
mapIframe.contentWindow.postMessage({
type: 'changeTileTheme',
theme: selectedTheme
}, '*');
}
});
/// License and Credits
function openLicense() {
@@ -328,7 +257,7 @@ function initSettings() {
function initWorldPicker() {
// World Picker
const worldPickerModal = document.getElementById("world-modal");
// Open world picker modal
function openWorldPicker() {
worldPickerModal.style.display = "flex";
@@ -340,7 +269,7 @@ function initWorldPicker() {
function closeWorldPicker() {
worldPickerModal.style.display = "none";
}
window.openWorldPicker = openWorldPicker;
window.closeWorldPicker = closeWorldPicker;
}
@@ -355,81 +284,58 @@ function handleBboxInput() {
const bboxInfo = document.getElementById("bbox-info");
inputBox.addEventListener("input", function () {
const input = inputBox.value.trim();
const input = inputBox.value.trim();
if (input === "") {
// Empty input - revert to map selection if available
customBBoxValid = false;
selectedBBox = mapSelectedBBox;
// Clear the info text only if no map selection exists
if (!mapSelectedBBox) {
bboxInfo.textContent = "";
bboxInfo.style.color = "";
} else {
// Restore map selection display
displayBboxInfoText(mapSelectedBBox);
}
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 with consistent comma-separated format
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 and mark custom input as valid
customBBoxValid = true;
selectedBBox = bboxText.replace(/,/g, ' '); // Convert to space format for consistency
localizeElement(window.localization, { element: bboxInfo }, "custom_selection_confirmed");
bboxInfo.style.color = "#7bd864";
} else {
// Valid numbers but invalid order or range
customBBoxValid = false;
// Don't clear selectedBBox - keep map selection if available
if (!mapSelectedBBox) {
if (input === "") {
bboxInfo.textContent = "";
bboxInfo.style.color = "";
selectedBBox = "";
} else {
selectedBBox = mapSelectedBBox;
}
localizeElement(window.localization, { element: bboxInfo }, "error_coordinates_out_of_range");
bboxInfo.style.color = "#fecc44";
return;
}
} else {
// Input doesn't match the required format
customBBoxValid = false;
// Don't clear selectedBBox - keep map selection if available
if (!mapSelectedBBox) {
selectedBBox = "";
// 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 with consistent comma-separated format
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 {
selectedBBox = mapSelectedBBox;
// Input doesn't match the required format
localizeElement(window.localization, { element: bboxInfo }, "invalid_format");
bboxInfo.style.color = "#fecc44";
selectedBBox = "";
}
localizeElement(window.localization, { element: bboxInfo }, "invalid_format");
bboxInfo.style.color = "#fecc44";
}
});
}
@@ -474,8 +380,6 @@ function normalizeLongitude(lon) {
const threshold1 = 30000000.00;
const threshold2 = 45000000.00;
let selectedBBox = "";
let mapSelectedBBox = ""; // Tracks bbox from map selection
let customBBoxValid = false; // Tracks if custom input is valid
// Function to handle incoming bbox data
function displayBboxInfoText(bboxText) {
@@ -484,21 +388,14 @@ function displayBboxInfoText(bboxText) {
// Normalize longitudes
lat1 = parseFloat(normalizeLongitude(lat1).toFixed(6));
lat2 = parseFloat(normalizeLongitude(lat2).toFixed(6));
mapSelectedBBox = `${lng1} ${lat1} ${lng2} ${lat2}`;
// Map selection always takes priority - clear custom input and update selectedBBox
selectedBBox = mapSelectedBBox;
customBBoxValid = false;
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 = "";
mapSelectedBBox = "";
if (!customBBoxValid) {
selectedBBox = "";
}
selectedBBox = "";
return;
}
@@ -522,7 +419,7 @@ let isNewWorld = false;
async function selectWorld(generate_new_world) {
try {
const worldName = await invoke('gui_select_world', { generateNew: generate_new_world });
const worldName = await invoke('gui_select_world', { generateNew: generate_new_world } );
if (worldName) {
worldPath = worldName;
isNewWorld = generate_new_world;
@@ -583,33 +480,17 @@ async function startGeneration() {
return;
}
// Get the map iframe reference
const mapFrame = document.querySelector('.map-container');
// Get spawn point coordinates if marker exists
let spawnPoint = null;
if (mapFrame && mapFrame.contentWindow && mapFrame.contentWindow.getSpawnPointCoords) {
const coords = mapFrame.contentWindow.getSpawnPointCoords();
// Convert object format to tuple format if coordinates exist
if (coords) {
spawnPoint = [coords.lat, coords.lng];
}
}
var terrain = document.getElementById("terrain-toggle").checked;
var interior = document.getElementById("interior-toggle").checked;
var roof = document.getElementById("roof-toggle").checked;
var fill_ground = document.getElementById("fillground-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);
// DEPRECATED: Ground level input removed from UI
var ground_level = -62;
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 selected options to the Rust backend
// Pass the bounding box and selected world to the Rust backend
await invoke("gui_start_generation", {
bboxText: selectedBBox,
selectedWorld: worldPath,
@@ -617,11 +498,8 @@ async function startGeneration() {
groundLevel: ground_level,
floodfillTimeout: floodfill_timeout,
terrainEnabled: terrain,
interiorEnabled: interior,
roofEnabled: roof,
fillgroundEnabled: fill_ground,
isNewWorld: isNewWorld,
spawnPoint: spawnPoint
isNewWorld: isNewWorld
});
console.log("Generation process started.");

9180
gui-src/js/maps/leaflet-src.js vendored Normal file
View File

File diff suppressed because it is too large Load Diff

2766
gui-src/js/maps/leaflet.draw-src.js vendored Normal file
View File

File diff suppressed because it is too large Load Diff

3
gui-src/js/maps/mapbox.standalone.js vendored Normal file
View File

File diff suppressed because one or more lines are too long

66
gui-src/js/maps/mapbox.v3.2.0.js vendored Normal file
View File

File diff suppressed because one or more lines are too long

3
gui-src/js/maps/proj4.js vendored Normal file
View File

File diff suppressed because one or more lines are too long

158
gui-src/js/maps/test.runner.js vendored Normal file
View File

@@ -0,0 +1,158 @@
(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
});

184
gui-src/js/search.js vendored
View File

@@ -1,184 +0,0 @@
// City Search Functionality
var citySearch = {
searchTimeout: null,
init: function() {
this.bindEvents();
},
bindEvents: function() {
var self = this;
// Search on button click
$('#search-btn').on('click', function() {
self.performSearch();
});
// Search on Enter key
$('#city-search').on('keypress', function(e) {
if (e.which === 13) { // Enter key
self.performSearch();
}
});
// Search as user types (debounced)
$('#city-search').on('input', function() {
clearTimeout(self.searchTimeout);
var query = $(this).val().trim();
if (query.length >= 3) {
self.searchTimeout = setTimeout(function() {
self.performSearch(query);
}, 500);
} else {
self.hideResults();
}
});
// Hide results when clicking outside
$(document).on('click', function(e) {
if (!$(e.target).closest('#search-container').length) {
self.hideResults();
}
});
},
performSearch: function(query) {
var self = this;
query = query || $('#city-search').val().trim();
if (query.length < 2) {
return;
}
this.showLoading();
// Use Nominatim geocoding service
var url = 'https://nominatim.openstreetmap.org/search';
var params = {
q: query,
format: 'json',
limit: 5,
addressdetails: 1,
extratags: 1,
'accept-language': 'en'
};
$.ajax({
url: url,
data: params,
method: 'GET',
timeout: 10000,
success: function(data) {
self.displayResults(data);
},
error: function() {
self.showError('Search failed. Please try again.');
}
});
},
showLoading: function() {
$('#search-results').html('<div class="search-loading">Searching...</div>').show();
},
showError: function(message) {
$('#search-results').html('<div class="search-no-results">' + message + '</div>').show();
},
hideResults: function() {
$('#search-results').hide();
},
displayResults: function(results) {
var self = this;
var $results = $('#search-results');
if (results.length === 0) {
$results.html('<div class="search-no-results">No cities found</div>').show();
return;
}
var html = '';
results.forEach(function(result) {
var displayName = result.display_name;
var nameParts = displayName.split(',');
var mainName = nameParts[0];
var details = nameParts.slice(1, 3).join(',');
html += '<div class="search-result-item" data-lat="' + result.lat + '" data-lon="' + result.lon + '">';
html += '<div class="search-result-name">' + self.escapeHtml(mainName) + '</div>';
html += '<div class="search-result-details">' + self.escapeHtml(details) + '</div>';
html += '</div>';
});
$results.html(html).show();
// Bind click events to results
$('.search-result-item').on('click', function() {
var lat = parseFloat($(this).data('lat'));
var lon = parseFloat($(this).data('lon'));
var name = $(this).find('.search-result-name').text();
self.goToLocation(lat, lon, name);
self.hideResults();
});
},
goToLocation: function(lat, lon, name) {
if (typeof map !== 'undefined' && map) {
// Clear existing bbox selection and spawn points
if (typeof drawnItems !== 'undefined' && drawnItems) {
drawnItems.clearLayers();
}
// Try to access bounds through the map layers or find the bounds rectangle
var boundsLayer = null;
map.eachLayer(function(layer) {
if (layer instanceof L.Rectangle && layer.options.color === '#3778d4') {
boundsLayer = layer;
}
});
if (boundsLayer) {
boundsLayer.setBounds(new L.LatLngBounds([0.0, 0.0], [0.0, 0.0]));
// Update the bbox display
if (typeof formatBounds === 'function') {
$('#boxbounds').text(formatBounds(boundsLayer.getBounds(), '4326'));
if (typeof currentproj !== 'undefined') {
$('#boxboundsmerc').text(formatBounds(boundsLayer.getBounds(), currentproj));
}
}
// Notify parent window of bbox update
if (typeof notifyBboxUpdate === 'function') {
notifyBboxUpdate();
}
}
// Simply zoom to location without adding markers or popups
map.setView([lat, lon], 12);
// Clear search box
$('#city-search').val('');
}
},
escapeHtml: function(text) {
var div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
};
// Initialize search when document is ready
$(document).ready(function() {
// Wait a bit for the map to be initialized
setTimeout(function() {
if (typeof map !== 'undefined') {
citySearch.init();
}
}, 1000);
});

View File

@@ -10,11 +10,11 @@
"error_coordinates_out_of_range": "خطأ: الإحداثيات خارج النطاق أو مرتبة بشكل غير صحيح (مطلوب خط العرض قبل خط الطول).",
"invalid_format": "تنسيق غير صالح. استخدم 'lat,lng,lat,lng' أو 'lat lng lat lng'.",
"generation_process_started": "بدأت عملية البناء.",
"winter_mode": "وضع الشتاء",
"world_scale": "مقياس العالم",
"custom_bounding_box": "مربع الحدود المخصص",
"floodfill_timeout": "مهلة ملء الفيضان (ثواني)",
"ground_level": "مستوى الأرض",
"winter_mode": "وضع الشتاء:",
"world_scale": "مقياس العالم:",
"custom_bounding_box": "مربع الحدود المخصص:",
"floodfill_timeout": "مهلة ملء الفيضان (ثواني):",
"ground_level": "مستوى الأرض:",
"choose_world_modal_title": "اختيار عالم",
"select_existing_world": "اختيار عالم موجود مسبقًا",
"generate_new_world": "إنشاء عالم جديد",
@@ -34,11 +34,5 @@
"license_and_credits": "الرخصة والمساهمون",
"placeholder_bbox": "الصيغة: lat,lng,lat,lng",
"placeholder_floodfill": "ثوانٍ",
"placeholder_ground": "مستوى الأرض",
"language": "اللغة",
"map_theme": "موضوع الخريطة",
"terrain": "التضاريس",
"interior": "توليد الداخلية",
"roof": "توليد السقف",
"fillground": "ملء الأرض"
"placeholder_ground": "مستوى الأرض"
}

View File

@@ -10,15 +10,15 @@
"error_coordinates_out_of_range": "Fehler: Koordinaten sind außerhalb des Bereichs oder falsch geordnet (Lat vor Lng erforderlich).",
"invalid_format": "Ungültiges Format. Bitte verwende 'lat,lng,lat,lng' oder 'lat lng lat lng'.",
"generation_process_started": "Generierungsprozess gestartet.",
"winter_mode": "Wintermodus",
"world_scale": "Weltmaßstab",
"custom_bounding_box": "Benutzerdefinierte BBOX",
"floodfill_timeout": "Floodfill-Timeout (Sek)",
"ground_level": "Bodenhöhe",
"winter_mode": "Wintermodus:",
"world_scale": "Weltmaßstab:",
"custom_bounding_box": "Benutzerdefinierte BBOX:",
"floodfill_timeout": "Floodfill-Timeout (Sek):",
"ground_level": "Bodenhöhe:",
"choose_world_modal_title": "Welt wählen",
"select_existing_world": "Vorhandene Welt auswählen",
"generate_new_world": "Neue Welt generieren",
"customization_settings": "Einstellungen",
"customization_settings": "Anpassungseinstellungen",
"footer_text": "© {year} Arnis v{version} von louis-e",
"new_version_available": "Eine neue Version ist verfügbar! Klicke hier, um sie herunterzuladen.",
"minecraft_directory_not_found": "Minecraft Verzeichnis nicht gefunden",
@@ -30,15 +30,9 @@
"area_too_large": "Dieses Gebiet ist sehr groß und könnte das Berechnungslimit überschreiten.",
"area_extensive": "Diese Gebietsgröße könnte längere Zeit für die Generierung benötigen.",
"selection_confirmed": "Auswahl bestätigt!",
"unknown_error": "Unbekannter Fehler",
"license_and_credits": "Lizenz und Credits",
"unknown_error": "Unknown error",
"license_and_credits": "License and Credits",
"placeholder_bbox": "Format: lat,lng,lat,lng",
"placeholder_floodfill": "Sekunden",
"placeholder_ground": "Bodenhöhe",
"language": "Sprache",
"map_theme": "Kartenstil",
"terrain": "Terrain",
"interior": "Innenraum Generierung",
"roof": "Dach Generierung",
"fillground": "Boden füllen"
"placeholder_ground": "Bodenhöhe"
}

View File

@@ -10,11 +10,11 @@
"error_coordinates_out_of_range": "Error: Coordinates are out of range or incorrectly ordered (Lat before Lng required).",
"invalid_format": "Invalid format. Please use 'lat,lng,lat,lng' or 'lat lng lat lng'.",
"generation_process_started": "Generation process started.",
"winter_mode": "Winter Mode",
"world_scale": "World Scale",
"custom_bounding_box": "Custom Bounding Box",
"floodfill_timeout": "Floodfill Timeout (sec)",
"ground_level": "Ground Level",
"winter_mode": "Winter Mode:",
"world_scale": "World Scale:",
"custom_bounding_box": "Custom Bounding Box:",
"floodfill_timeout": "Floodfill Timeout (sec):",
"ground_level": "Ground Level:",
"choose_world_modal_title": "Choose World",
"select_existing_world": "Select existing world",
"generate_new_world": "Generate new world",
@@ -34,11 +34,5 @@
"license_and_credits": "License and Credits",
"placeholder_bbox": "Format: lat,lng,lat,lng",
"placeholder_floodfill": "Seconds",
"placeholder_ground": "Ground Level",
"language": "Language",
"map_theme": "Map Theme",
"terrain": "Terrain",
"interior": "Interior Generation",
"roof": "Roof Generation",
"fillground": "Fill Ground"
"placeholder_ground": "Ground Level"
}

View File

@@ -10,11 +10,11 @@
"error_coordinates_out_of_range": "Error: Las coordenadas están fuera de rango o están ordenadas incorrectamente (Lat antes de Lng requerido).",
"invalid_format": "Formato inválido. Por favor, use 'lat,lng,lat,lng' o 'lat lng lat lng'.",
"generation_process_started": "Proceso de generación iniciado.",
"winter_mode": "Modo invierno",
"world_scale": "Escala del mundo",
"custom_bounding_box": "Caja delimitadora personalizada",
"floodfill_timeout": "Tiempo de espera de relleno (seg)",
"ground_level": "Nivel del suelo",
"winter_mode": "Modo invierno:",
"world_scale": "Escala del mundo:",
"custom_bounding_box": "Caja delimitadora personalizada:",
"floodfill_timeout": "Tiempo de espera de relleno (seg):",
"ground_level": "Nivel del suelo:",
"choose_world_modal_title": "Elegir mundo",
"select_existing_world": "Seleccionar mundo existente",
"generate_new_world": "Generar nuevo mundo",
@@ -34,11 +34,5 @@
"license_and_credits": "License and Credits",
"placeholder_bbox": "Format: lat,lng,lat,lng",
"placeholder_floodfill": "Seconds",
"placeholder_ground": "Ground Level",
"language": "Idioma",
"map_theme": "Tema del mapa",
"terrain": "Terreno",
"interior": "Generación de interiores",
"roof": "Generación de techos",
"fillground": "Rellenar suelo"
"placeholder_ground": "Ground Level"
}

View File

@@ -10,11 +10,11 @@
"error_coordinates_out_of_range": "Virhe: Koordinaatit ovat kantaman ulkopuolella tai vääriin aseteltu (Lat ennen Lng vaadittu).",
"invalid_format": "Väärä formaatti. Käytä 'lat,lng,lat,lng' tai 'lat lng lat lng'.",
"generation_process_started": "Luontiprosessi aloitettu.",
"winter_mode": "Talvitila",
"world_scale": "Maailmanskaalaus",
"custom_bounding_box": "Mukautettu rajoituslaatikko",
"floodfill_timeout": "Täytön aikakatkaisu (sec)",
"ground_level": "Maataso",
"winter_mode": "Talvitila:",
"world_scale": "Maailmanskaalaus:",
"custom_bounding_box": "Mukautettu rajoituslaatikko:",
"floodfill_timeout": "Täytön aikakatkaisu (sec):",
"ground_level": "Maataso:",
"choose_world_modal_title": "Valitse maailma",
"select_existing_world": "Valitse olemassa oleva maailma",
"generate_new_world": "Luo uusi maailma",
@@ -34,11 +34,5 @@
"license_and_credits": "Lisenssi ja krediitit",
"placeholder_bbox": "Formaatti: lat,lng,lat,lng",
"placeholder_floodfill": "Sekuntia",
"placeholder_ground": "Maataso",
"language": "Kieli",
"map_theme": "Karttateema",
"terrain": "Maasto",
"interior": "Sisätilan luonti",
"roof": "Katon luonti",
"fillground": "Täytä maa"
"placeholder_ground": "Maataso"
}

View File

@@ -1,6 +1,6 @@
{
"select_location": "Sélectionner une localisation",
"zoom_in_and_choose": "Zoomez et choisissez votre zone avec l'outil rectangle",
"zoom_in_and_choose": "Zoomez et choisissez une zone avec l'outil de sélection rectangulaire",
"select_world": "Sélectionner un monde",
"choose_world": "Choisir un monde",
"no_world_selected": "Aucun monde sélectionné",
@@ -10,11 +10,11 @@
"error_coordinates_out_of_range": "Erreur: Coordonnées hors de portée ou dans un ordre incorrect (besoin de la latitude avant la longitude).",
"invalid_format": "Format invalide. Utilisez 'lat,lng,lat,lng' ou 'lat lng lat lng'.",
"generation_process_started": "Processus de génération commencé.",
"winter_mode": "Mode hiver",
"world_scale": "Échelle du monde",
"custom_bounding_box": "Cadre de délimitation personnalisé",
"floodfill_timeout": "Expiration du délai de remplissage (en secondes)",
"ground_level": "Niveau du sol",
"winter_mode": "Mode hiver:",
"world_scale": "Échelle du monde:",
"custom_bounding_box": "Cadre de délimitation personnalisé:",
"floodfill_timeout": "Expiration du délai de remplissage (en secondes):",
"ground_level": "Niveau du sol:",
"choose_world_modal_title": "Choisir un monde",
"select_existing_world": "Sélectionner un monde existant",
"generate_new_world": "Générer un nouveau monde",
@@ -34,11 +34,5 @@
"license_and_credits": "Licence et crédits",
"placeholder_bbox": "Format: lat,lng,lat,lng",
"placeholder_floodfill": "Secondes",
"placeholder_ground": "Niveau du sol",
"language": "Langue",
"map_theme": "Thème de carte",
"terrain": "Terrain",
"interior": "Génération d'intérieur",
"roof": "Génération de toit",
"fillground": "Remplir le sol"
"placeholder_ground": "Niveau du sol"
}

View File

@@ -1,6 +1,6 @@
{
"select_location": "Hely kiválasztása",
"zoom_in_and_choose": "Nagyíts és jelöld ki a területet a kijelölő eszközzel",
"zoom_in_and_choose": "Közelíts és válaszd ki a területet a téglalap eszköz segítségével",
"select_world": "Világ kijelölése",
"choose_world": "Világ kiválasztása",
"no_world_selected": "Nincs világ kiválasztva",
@@ -13,7 +13,7 @@
"winter_mode": "Téli mód",
"world_scale": "Világ nagysága",
"custom_bounding_box": "Egyéni határoló keret",
"floodfill_timeout": "Floodfill Timeout (sec)",
"floodfill_timeout": "Floodfill Timeout (sec):",
"ground_level": "Földszint",
"choose_world_modal_title": "Világ kiválasztása",
"select_existing_world": "Már létező világ kiválasztása",
@@ -34,11 +34,5 @@
"license_and_credits": "Licenc és elismerés.",
"placeholder_bbox": "Formátum: lat,lng,lat,lng",
"placeholder_floodfill": "Másodpercek",
"placeholder_ground": "Földszint",
"language": "Nyelv",
"map_theme": "Térkép téma",
"terrain": "Terep",
"interior": "Belső generálás",
"roof": "Tető generálás",
"fillground": "Talaj feltöltése"
"placeholder_ground": "Földszint"
}

View File

@@ -10,11 +10,11 @@
"error_coordinates_out_of_range": "오류: 좌표가 범위를 벗어나거나 잘못된 순서입니다 (Lat이 Lng보다 먼저 필요합니다).",
"invalid_format": "잘못된 형식입니다. 'lat,lng,lat,lng' 또는 'lat lng lat lng' 형식을 사용하세요.",
"generation_process_started": "생성 프로세스가 시작되었습니다.",
"winter_mode": "겨울 모드",
"world_scale": "세계 규모",
"custom_bounding_box": "사용자 지정 경계 상자",
"floodfill_timeout": "채우기 시간 초과 (초)",
"ground_level": "지면 레벨",
"winter_mode": "겨울 모드:",
"world_scale": "세계 규모:",
"custom_bounding_box": "사용자 지정 경계 상자:",
"floodfill_timeout": "채우기 시간 초과 (초):",
"ground_level": "지면 레벨:",
"choose_world_modal_title": "세계 선택",
"select_existing_world": "이미 존재하는 세계 선택",
"generate_new_world": "새 세계 생성",
@@ -34,11 +34,5 @@
"license_and_credits": "License and Credits",
"placeholder_bbox": "Format: lat,lng,lat,lng",
"placeholder_floodfill": "Seconds",
"placeholder_ground": "Ground Level",
"language": "언어",
"map_theme": "지도 테마",
"terrain": "지형",
"interior": "내부 생성",
"roof": "지붕 생성",
"fillground": "지면 채우기"
"placeholder_ground": "Ground Level"
}

View File

@@ -10,11 +10,12 @@
"error_coordinates_out_of_range": "Klaida: Koordinatės yra už ribų arba neteisingai išdėstytos (plat turi būti prieš ilg).",
"invalid_format": "Neteisingas formatas. Prašome naudoti 'plat,ilg,plat,ilg' arba 'plat ilg plat ilg'.",
"generation_process_started": "Generacijos procesas pradėtas.",
"winter_mode": "Žiemos režimas",
"world_scale": "Pasaulio mastelis",
"custom_bounding_box": "Pasirinktinis ribos rėmas",
"floodfill_timeout": "Užpildymo laiko limitas (sek.)",
"ground_level": "Žemės lygis",
"terrain": "Reljefas:",
"winter_mode": "Žiemos režimas:",
"world_scale": "Pasaulio mastelis:",
"custom_bounding_box": "Pasirinktinis ribos rėmas:",
"floodfill_timeout": "Užpildymo laiko limitas (sek.):",
"ground_level": "Žemės lygis:",
"choose_world_modal_title": "Pasaulio pasirinkimas",
"select_existing_world": "Pasirinkti esamą pasaulį",
"generate_new_world": "Sugeneruoti naują pasaulį",
@@ -34,11 +35,5 @@
"license_and_credits": "Licencija ir padėkos",
"placeholder_bbox": "Formatas: plat,lyg,plat,lyg",
"placeholder_floodfill": "Sekundės",
"placeholder_ground": "Žemės lygis",
"language": "Kalba",
"map_theme": "Žemėlapio tema",
"terrain": "Reljefas",
"interior": "Vidaus generavimas",
"roof": "Stogo generavimas",
"fillground": "Užpildyti pagrindą"
"placeholder_ground": "Žemės lygis"
}

View File

@@ -10,11 +10,12 @@
"error_coordinates_out_of_range": "Błąd: Współrzędne są poza zakresem lub w złej kolejności (wymagana szerokość przed długością).",
"invalid_format": "Nieprawidłowy format. Użyj 'szer.,dł.,szer.,dł.' lub 'szer. dł. szer. dł.'.",
"generation_process_started": "Proces generowania rozpoczęty.",
"winter_mode": "Tryb Zimowy",
"world_scale": "Skala świata",
"custom_bounding_box": "Niestandardowy obszar",
"floodfill_timeout": "Limit czasu wypełniania (sek)",
"ground_level": "Wysokość obszaru",
"terrain": "Teren:",
"winter_mode": "Tryb Zimowy:",
"world_scale": "Skala świata:",
"custom_bounding_box": "Niestandardowy obszar:",
"floodfill_timeout": "Limit czasu wypełniania (sek):",
"ground_level": "Wysokość obszaru:",
"choose_world_modal_title": "Wybierz świat",
"select_existing_world": "Wybierz istniejący świat",
"generate_new_world": "Generuj nowy świat",
@@ -34,11 +35,5 @@
"license_and_credits": "Licencja i autorzy",
"placeholder_bbox": "Format: szer,dł,szer,dł",
"placeholder_floodfill": "Sekundy",
"placeholder_ground": "Wysokość",
"language": "Język",
"map_theme": "Motyw mapy",
"terrain": "Teren",
"interior": "Generowanie wnętrz",
"roof": "Generowanie dachów",
"fillground": "Wypełnij podłoże"
"placeholder_ground": "Wysokość"
}

View File

@@ -10,11 +10,12 @@
"error_coordinates_out_of_range": "Ошибка: Координаты находятся вне зоны действия или указаны в неправильном порядке (сначала широта, затем долгота)",
"invalid_format": "Неверный формат. Используйте 'широта,долгота,широта,долгота' или 'широта долгота широта долгота'",
"generation_process_started": "Процесс генерации начат",
"winter_mode": "Зимний режим",
"world_scale": "Масштаб мира",
"custom_bounding_box": "Пользовательская ограничивающая рамка",
"floodfill_timeout": "Тайм-аут заливки (сек)",
"ground_level": "Уровень земли",
"terrain": "Рельеф",
"winter_mode": "Зимний режим:",
"world_scale": "Масштаб мира:",
"custom_bounding_box": "Пользовательская ограничивающая рамка:",
"floodfill_timeout": "Тайм-аут заливки (сек):",
"ground_level": "Уровень земли:",
"choose_world_modal_title": "Выбрать мир",
"select_existing_world": "Выбрать существующий мир",
"generate_new_world": "Создать новый мир",
@@ -34,11 +35,5 @@
"license_and_credits": "Лицензия и авторы",
"placeholder_bbox": "Формат: широта,долгота,широта,долгота",
"placeholder_floodfill": "Секунды",
"placeholder_ground": "Уровень земли",
"language": "Язык",
"map_theme": "Тема карты",
"terrain": "Рельеф",
"interior": "Генерация интерьера",
"roof": "Генерация крыш",
"fillground": "Заполнить землю"
"placeholder_ground": "Уровень земли"
}

View File

@@ -10,11 +10,11 @@
"error_coordinates_out_of_range": "Fel: Koordinater är utanför området eller felaktigt ordnade (Lat före Lng krävs).",
"invalid_format": "Ogiltigt format. Använd 'lat,lng,lat,lng' eller 'lat lng lat lng'.",
"generation_process_started": "Genereringsprocessen startad.",
"winter_mode": "Vinterläge",
"world_scale": "Världsskala",
"custom_bounding_box": "Anpassad begränsningsram",
"floodfill_timeout": "Floodfill-tidsgräns (sek)",
"ground_level": "Marknivå",
"winter_mode": "Vinterläge:",
"world_scale": "Världsskala:",
"custom_bounding_box": "Anpassad begränsningsram:",
"floodfill_timeout": "Floodfill-tidsgräns (sek):",
"ground_level": "Marknivå:",
"choose_world_modal_title": "Välj värld",
"select_existing_world": "Välj existerande värld",
"generate_new_world": "Generera ny värld",
@@ -34,11 +34,5 @@
"license_and_credits": "License and Credits",
"placeholder_bbox": "Format: lat,lng,lat,lng",
"placeholder_floodfill": "Seconds",
"placeholder_ground": "Ground Level",
"language": "Språk",
"map_theme": "Karttema",
"terrain": "Terräng",
"interior": "Interiörgenerering",
"roof": "Takgenerering",
"fillground": "Fyll mark"
"placeholder_ground": "Ground Level"
}

View File

@@ -1,6 +1,6 @@
{
"select_location": "Обрати локацію",
"zoom_in_and_choose": "Збільште і оберіть область за допомогою прямокутника",
"zoom_in_and_choose": "Збільште масштаб і оберіть область за допомогою прямокутника",
"select_world": "Обрати світ",
"choose_world": "Обрати світ",
"no_world_selected": "Світ не обрано",
@@ -10,11 +10,11 @@
"error_coordinates_out_of_range": "Помилка: Координати поза діапазоном або неправильно впорядковані (потрібно широта перед довгота)",
"invalid_format": "Неправильний формат. Будь ласка, використовуйте 'широта,довгота,широта,довгота' або 'широта довгота широта довгота'",
"generation_process_started": "Процес генерації розпочато",
"winter_mode": "Зимовий режим",
"world_scale": "Масштаб світу",
"custom_bounding_box": "Користувацька обмежувальна рамка",
"floodfill_timeout": "Тайм-аут заливки (сек)",
"ground_level": "Рівень землі",
"winter_mode": "Зимовий режим:",
"world_scale": "Масштаб світу:",
"custom_bounding_box": "Користувацька обмежувальна рамка:",
"floodfill_timeout": "Тайм-аут заливки (сек):",
"ground_level": "Рівень землі:",
"choose_world_modal_title": "Обрати світ",
"select_existing_world": "Обрати наявний світ",
"generate_new_world": "Створити новий світ",
@@ -34,11 +34,5 @@
"license_and_credits": "License and Credits",
"placeholder_bbox": "Format: lat,lng,lat,lng",
"placeholder_floodfill": "Seconds",
"placeholder_ground": "Ground Level",
"language": "Мова",
"map_theme": "Тема карти",
"terrain": "Рельєф",
"interior": "Генерація інтер'єру",
"roof": "Генерація даху",
"fillground": "Заповнити землю"
"placeholder_ground": "Ground Level"
}

View File

@@ -10,11 +10,11 @@
"error_coordinates_out_of_range": "错误:坐标超出范围或顺序不正确(需要先纬度后经度)。",
"invalid_format": "格式无效。请使用 'lat,lng,lat,lng' 或 'lat lng lat lng'。",
"generation_process_started": "生成过程已开始。",
"winter_mode": "冬季模式",
"world_scale": "世界比例",
"custom_bounding_box": "自定义边界框",
"floodfill_timeout": "填充超时(秒)",
"ground_level": "地面高度",
"winter_mode": "冬季模式",
"world_scale": "世界比例",
"custom_bounding_box": "自定义边界框",
"floodfill_timeout": "填充超时(秒)",
"ground_level": "地面高度",
"choose_world_modal_title": "选择世界",
"select_existing_world": "选择现有世界",
"generate_new_world": "生成新世界",
@@ -34,11 +34,5 @@
"license_and_credits": "许可证和致谢",
"placeholder_bbox": "格式: lat,lng,lat,lng",
"placeholder_floodfill": "秒",
"placeholder_ground": "地面高度",
"language": "语言",
"map_theme": "地图主题",
"terrain": "地形",
"interior": "内部生成",
"roof": "屋顶生成",
"fillground": "填充地面"
"placeholder_ground": "地面高度"
}

14
gui-src/maps.html vendored
View File

@@ -3,34 +3,26 @@
<title>Map View</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="css/maps/leaflet.css" />
<link rel="stylesheet" href="css/maps/leaflet.draw.css" />
<link rel="stylesheet" href="css/maps/leaflet.sidebar.css" />
<link rel="stylesheet" href="css/maps/mapbox.v3.2.0.css" />
<link rel="stylesheet" href="css/bbox.css" />
<link rel="stylesheet" href="css/search.css" />
<script src="js/libs/jquery-1.9.1.min.js"></script>
<script src="js/libs/jquery-ui-1.10.3.custom.js"></script>
<script src="js/maps/leaflet.js"></script>
<script src="js/maps/mapbox.v3.2.0.js"></script>
<script src="js/maps/leaflet.draw.js"></script>
<script src="js/maps/leaflet.sidebar.js"></script>
<script src="js/maps/wkt.parser.js"></script>
<script src="js/maps/proj4-src.js"></script>
<script src="js/maps/proj4leaflet.js"></script>
<script src="js/search.js"></script>
<script src="js/bbox.js"></script>
</head>
<body>
<!-- City Search Box -->
<div id="search-container">
<div id="search-box">
<input type="text" id="city-search" placeholder="Search for a city..." autocomplete="off" />
<button id="search-btn">🔍</button>
</div>
<div id="search-results"></div>
</div>
<div id="map"></div>
<div id="rsidebar" >
<button id="add">Add</button>

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 31 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

After

Width:  |  Height:  |  Size: 89 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

After

Width:  |  Height:  |  Size: 2.9 KiB

View File

Binary file not shown.

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

After

Width:  |  Height:  |  Size: 221 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 258 KiB

After

Width:  |  Height:  |  Size: 232 KiB

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@@ -1,26 +1,24 @@
use crate::coordinate_system::geographic::LLBBox;
use crate::bbox::BBox;
use clap::Parser;
use colored::Colorize;
use std::path::Path;
use std::process::exit;
use std::time::Duration;
/// Command-line arguments parser
#[derive(Parser, Debug)]
#[command(author, version, about)]
pub struct Args {
/// 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,
/// Bounding box of the area (min_lng,min_lat,max_lng,max_lat) (required)
#[arg(long, allow_hyphen_values = true, value_parser = BBox::from_str)]
pub bbox: BBox,
/// JSON file containing OSM data (optional)
#[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, value_parser = validate_minecraft_world_path)]
#[arg(long)]
pub path: String,
/// Downloader method (requests/curl/wget) (optional)
@@ -38,19 +36,9 @@ pub struct Args {
/// Enable terrain (optional)
#[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)]
pub debug: bool,
@@ -58,25 +46,22 @@ pub struct Args {
/// Set floodfill timeout (seconds) (optional)
#[arg(long, value_parser = parse_duration)]
pub timeout: Option<Duration>,
/// Spawn point coordinates (lat, lng)
#[arg(skip)]
pub spawn_point: Option<(f64, f64)>,
}
fn validate_minecraft_world_path(path: &str) -> Result<String, String> {
let mc_world_path = Path::new(path);
if !mc_world_path.exists() {
return Err(format!("Path does not exist: {path}"));
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);
}
}
if !mc_world_path.is_dir() {
return Err(format!("Path is not a directory: {path}"));
}
let region = mc_world_path.join("region");
if !region.is_dir() {
return Err(format!("No Minecraft world found at {region:?}"));
}
Ok(path.to_string())
}
fn parse_duration(arg: &str) -> Result<std::time::Duration, std::num::ParseIntError> {
@@ -88,23 +73,13 @@ fn parse_duration(arg: &str) -> Result<std::time::Duration, std::num::ParseIntEr
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",
@@ -114,7 +89,7 @@ mod tests {
assert!(args.debug);
assert!(args.terrain);
let cmd = ["arnis", "--path", tmp_path, "--bbox", "1,2,3,4"];
let cmd = ["arnis", "--path", "", "--bbox", "1,2,3,4"];
let args = Args::parse_from(cmd.iter());
assert!(!args.debug);
assert!(!args.terrain);
@@ -122,16 +97,13 @@ mod tests {
#[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"];
let cmd = ["arnis", "--path", "", "--bbox", "1,2,3,4"];
assert!(Args::try_parse_from(cmd.iter()).is_ok());
let cmd = ["arnis", "--path", tmp_path, "--file", ""];
let cmd = ["arnis", "--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.

101
src/bbox.rs Normal file
View File

@@ -0,0 +1,101 @@
use crate::geo_coord::GeoCoord;
/// A checked Bounding Box.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct BBox {
/// The "bottom-left" vertex of the rectangle
min: GeoCoord,
/// The "top-right" vertex of the rectangle
max: GeoCoord,
}
impl BBox {
pub fn new(min_lat: f64, min_lng: f64, max_lat: f64, max_lng: f64) -> Result<Self, String> {
let vals_in_order = min_lng < max_lng && min_lat < max_lat;
if !vals_in_order {
return Err("Invalid BBox".to_string());
}
let min = GeoCoord::new(min_lat, min_lng)?;
let max = GeoCoord::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) -> GeoCoord {
self.min
}
pub fn max(&self) -> GeoCoord {
self.max
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_valid_input() {
assert!(BBox::new(0., 0., 1., 1.).is_ok());
assert!(BBox::new(1., 2., 3., 4.).is_ok());
// Arnis, Germany
assert!(BBox::new(9.927928, 54.627053, 9.937563, 54.634902).is_ok());
}
#[test]
fn test_from_str_commas() {
const ARNIS_STR: &str = "9.927928,54.627053,9.937563,54.634902";
let bbox_result = BBox::from_str(ARNIS_STR);
assert!(bbox_result.is_ok());
let arnis_correct: BBox = BBox {
min: GeoCoord::new(9.927928, 54.627053).unwrap(),
max: GeoCoord::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 = BBox::from_str(ARNIS_SPACE_STR);
assert!(bbox_result.is_ok());
let arnis_correct: BBox = BBox {
min: GeoCoord::new(9.927928, 54.627053).unwrap(),
max: GeoCoord::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!(BBox::new(0., 0., 0., 0.).is_err());
assert!(BBox::new(1., 0., 0., 1.).is_err());
assert!(BBox::new(0., 1., 1., 0.).is_err());
}
}

View File

@@ -7,91 +7,20 @@ 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 {
"minecraft"
}
@@ -112,7 +41,7 @@ impl Block {
11 => "chiseled_stone_bricks",
12 => "cobblestone_wall",
13 => "cobblestone",
14 => "polished_blackstone_bricks",
14 => "cracked_polished_blackstone_bricks",
15 => "cracked_stone_bricks",
16 => "crimson_planks",
17 => "cut_sandstone",
@@ -123,7 +52,7 @@ impl Block {
22 => "dirt",
23 => "end_stone_bricks",
24 => "farmland",
25 => "glass",
25 => "glass_pane",
26 => "glowstone",
27 => "granite",
28 => "grass_block",
@@ -145,7 +74,7 @@ impl Block {
44 => "mossy_cobblestone",
45 => "mud_bricks",
46 => "nether_bricks",
47 => "netherite_block",
47 => "nether_bricks",
48 => "oak_fence",
49 => "oak_leaves",
50 => "oak_log",
@@ -155,7 +84,7 @@ impl Block {
54 => "podzol",
55 => "polished_andesite",
56 => "polished_basalt",
57 => "quartz_block",
57 => "polished_blackstone_bricks",
58 => "polished_blackstone",
59 => "polished_deepslate",
60 => "polished_diorite",
@@ -227,45 +156,6 @@ impl Block {
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 => "jukebox",
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"),
}
}
@@ -408,116 +298,11 @@ impl Block {
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);
@@ -533,7 +318,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 POLISHED_BLACKSTONE_BRICKS: Block = Block::new(14);
pub const CRACKED_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);
@@ -566,7 +351,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 NETHERITE_BLOCK: Block = Block::new(47);
pub const NETHER_BRICKS: 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);
@@ -576,7 +361,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 QUARTZ_BLOCK: Block = Block::new(57);
pub const POLISHED_BLACKSTONE_BRICKS: 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);
@@ -587,7 +372,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_BRICK: Block = Block::new(68);
pub const RED_NETHER_BRICKS: 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);
@@ -629,12 +414,15 @@ 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);
@@ -645,6 +433,7 @@ 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);
@@ -658,350 +447,91 @@ 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 JUKEBOX: 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);
/// 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,
// Variations for building corners
pub static BUILDING_CORNER_VARIATIONS: [Block; 20] = [
STONE_BRICKS,
COBBLESTONE,
BRICK,
MOSSY_COBBLESTONE,
SANDSTONE,
RED_NETHER_BRICKS,
BLACKSTONE,
SMOOTH_QUARTZ,
CHISELED_STONE_BRICKS,
POLISHED_BASALT,
CUT_SANDSTONE,
POLISHED_BLACKSTONE_BRICKS,
ANDESITE,
GRANITE,
DIORITE,
CRACKED_STONE_BRICKS,
PRISMARINE,
BLUE_TERRACOTTA,
NETHER_BRICK,
QUARTZ_BRICKS,
];
// 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())],
}
// Variations for building walls
pub fn building_wall_variations() -> Vec<Block> {
BUILDING_WALL_COLOR_MAP
.into_iter()
.map(|(_, block)| block)
.collect()
}
// 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,
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]),
// https://wiki.openstreetmap.org/wiki/Key:building:colour
pub static BUILDING_WALL_COLOR_MAP: [(RGBTuple, Block); 21] = [
((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),
];
// 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()
}
// Variations for building floors
pub fn building_floor_variations() -> Vec<Block> {
BUILDING_WALL_COLOR_MAP
.into_iter()
.map(|(_, block)| block)
.collect()
}
// 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,
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())]
}
// Function to get a random castle wall block
pub fn get_castle_wall_block() -> Block {
use rand::Rng;
let mut rng = rand::thread_rng();
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())]
}
pub static BUILDING_FLOOR_COLOR_MAP: [(RGBTuple, Block); 20] = [
((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),
];

12
src/cartesian.rs Normal file
View File

@@ -0,0 +1,12 @@
#[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 }
}
}

View File

@@ -32,7 +32,7 @@ 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;
}

View File

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

View File

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

View File

@@ -1,112 +0,0 @@
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

@@ -1,202 +0,0 @@
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

@@ -1,70 +0,0 @@
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

@@ -1,56 +0,0 @@
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

@@ -1,125 +0,0 @@
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

@@ -1,60 +0,0 @@
/// 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

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

View File

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

View File

@@ -1,185 +0,0 @@
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,6 +1,5 @@
use crate::args::Args;
use crate::block_definitions::{BEDROCK, DIRT, GRASS_BLOCK, STONE};
use crate::coordinate_system::cartesian::XZBBox;
use crate::element_processing::*;
use crate::ground::Ground;
use crate::osm_parser::ProcessedElement;
@@ -13,20 +12,23 @@ pub const MIN_Y: i32 = -64;
pub fn generate_world(
elements: Vec<ProcessedElement>,
xzbbox: XZBBox,
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, &xzbbox);
let mut editor: WorldEditor = WorldEditor::new(&region_dir, scale_factor_x, scale_factor_z);
println!("{} Processing data...", "[4/7]".bold());
println!("{} Processing data...", "[3/5]".bold());
if args.terrain {
emit_gui_progress_update(10.0, "Fetching elevation...");
}
let ground: Ground = Ground::new(args);
// 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...");
emit_gui_progress_update(11.0, "Processing terrain...");
// Process data
let elements_count: usize = elements.len();
@@ -36,8 +38,8 @@ pub fn generate_world(
.unwrap()
.progress_chars("█▓░"));
let progress_increment_prcs: f64 = 45.0 / elements_count as f64;
let mut current_progress_prcs: f64 = 25.0;
let progress_increment_prcs: f64 = 49.0 / elements_count as f64;
let mut current_progress_prcs: f64 = 11.0;
let mut last_emitted_progress: f64 = current_progress_prcs;
for element in &elements {
@@ -78,15 +80,13 @@ pub fn generate_world(
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") {
} else if way.tags.contains_key("railway") || way.tags.contains_key("subway") {
railways::generate_railways(&mut editor, way);
} else if way.tags.contains_key("aeroway") || way.tags.contains_key("area:aeroway")
{
highways::generate_aeroway(&mut editor, way, args);
highways::generate_aeroway(&mut editor, way);
} else if way.tags.get("service") == Some(&"siding".to_string()) {
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) => {
@@ -99,34 +99,20 @@ pub fn generate_world(
} else if node.tags.contains_key("amenity") {
amenities::generate_amenities(&mut editor, element, args);
} else if node.tags.contains_key("barrier") {
barriers::generate_barrier_nodes(&mut editor, node);
barriers::generate_barriers(&mut editor, element);
} else if node.tags.contains_key("highway") {
highways::generate_highways(&mut editor, element, args);
} else if node.tags.contains_key("tourism") {
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, args);
} else if rel.tags.contains_key("water")
|| rel.tags.get("natural") == Some(&"water".to_string())
{
} else if rel.tags.contains_key("water") {
water_areas::generate_water_areas(&mut editor, rel);
} 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, args);
} else if rel.tags.contains_key("man_made") {
man_made::generate_man_made(
&mut editor,
&ProcessedElement::Relation(rel.clone()),
args,
);
}
}
}
@@ -135,14 +121,14 @@ pub fn generate_world(
process_pb.finish();
// Generate ground layer
let total_blocks: u64 = xzbbox.bounding_rect().total_blocks();
let total_blocks: u64 = (scale_factor_x as i32 + 1) as u64 * (scale_factor_z as i32 + 1) as u64;
let desired_updates: u64 = 1500;
let batch_size: u64 = (total_blocks / desired_updates).max(1);
let mut block_counter: u64 = 0;
println!("{} Generating ground...", "[6/7]".bold());
emit_gui_progress_update(70.0, "Generating ground...");
println!("{} Generating ground...", "[4/5]".bold());
emit_gui_progress_update(60.0, "Generating ground...");
let ground_pb: ProgressBar = ProgressBar::new(total_blocks);
ground_pb.set_style(
@@ -152,15 +138,15 @@ pub fn generate_world(
.progress_chars("█▓░"),
);
let mut gui_progress_grnd: f64 = 70.0;
let mut gui_progress_grnd: f64 = 60.0;
let mut last_emitted_progress: f64 = gui_progress_grnd;
let total_iterations_grnd: f64 = total_blocks as f64;
let progress_increment_grnd: f64 = 20.0 / total_iterations_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 groundlayer_block = GRASS_BLOCK;
for x in xzbbox.min_x()..=xzbbox.max_x() {
for z in xzbbox.min_z()..=xzbbox.max_z() {
for x in 0..=(scale_factor_x as i32) {
for z in 0..=(scale_factor_z as i32) {
// 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);
@@ -217,29 +203,6 @@ 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,
) {
eprintln!("Warning: Failed to update spawn point Y coordinate: {e}");
}
}
emit_gui_progress_update(100.0, "Done! World generation completed.");
println!("{}", "Done! World generation completed.".green().bold());
Ok(())

View File

@@ -1,7 +1,7 @@
use crate::args::Args;
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::coordinate_system::cartesian::XZPoint;
use crate::cartesian::XZPoint;
use crate::floodfill::flood_fill_area;
use crate::osm_parser::ProcessedElement;
use crate::world_editor::WorldEditor;
@@ -80,16 +80,9 @@ pub fn generate_amenities(editor: &mut WorldEditor, element: &ProcessedElement,
"bench" => {
// Place a bench
if let Some(pt) = first_node {
// 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);
}
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);
}
}
"vending" => {
@@ -190,75 +183,16 @@ pub fn generate_amenities(editor: &mut WorldEditor, element: &ProcessedElement,
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);
}
// Add parking spot markings
if amenity_type == "parking" && (x + z) % 8 == 0 && (x * z) % 32 != 0 {
editor.set_block(
LIGHT_GRAY_CONCRETE,
x,
0,
z,
Some(&[BLACK_CONCRETE, GRAY_CONCRETE]),
None,
);
}
}
}

View File

@@ -1,6 +1,6 @@
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::osm_parser::{ProcessedElement, ProcessedNode};
use crate::osm_parser::ProcessedElement;
use crate::world_editor::WorldEditor;
pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement) {
@@ -10,8 +10,11 @@ pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement) {
match element.tags().get("barrier").map(|s| s.as_str()) {
Some("bollard") => {
barrier_material = COBBLESTONE_WALL;
barrier_height = 1;
if let ProcessedElement::Node(node) = element {
// Place bollard one above ground
editor.set_block(COBBLESTONE_WALL, node.x, 1, node.z, None, None);
}
return;
}
Some("kerb") => {
// Ignore kerbs
@@ -28,11 +31,8 @@ pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement) {
barrier_material = STONE_BRICK_WALL;
barrier_height = 1;
}
Some(
"chain_link" | "metal" | "wire" | "barbed_wire" | "corrugated_metal"
| "electric" | "metal_bars",
) => {
barrier_material = STONE_BRICK_WALL; // IRON_BARS
Some("chain_link" | "metal" | "wire" | "barbed_wire" | "corrugated_metal") => {
barrier_material = STONE_BRICK_WALL;
barrier_height = 2;
}
Some("slatted" | "paling") => {
@@ -43,8 +43,8 @@ pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement) {
barrier_material = OAK_FENCE;
barrier_height = 2;
}
Some("concrete" | "stone") => {
barrier_material = STONE_BRICK_WALL;
Some("concrete") => {
barrier_material = ANDESITE_WALL;
barrier_height = 2;
}
Some("glass") => {
@@ -54,10 +54,6 @@ pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement) {
_ => {}
}
}
Some("wall") => {
barrier_material = STONE_BRICK_WALL;
barrier_height = 3;
}
_ => {}
}
// Tagged material takes priority over inferred
@@ -65,12 +61,6 @@ pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement) {
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 {
@@ -79,7 +69,7 @@ pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement) {
.tags()
.get("height")
.and_then(|height: &String| height.parse::<f32>().ok())
.map(|height: f32| height.round() as i32)
.map(|height: f32| f32::min(3.0, height).round() as i32)
.unwrap_or(barrier_height);
// Process nodes to create the barrier wall
@@ -109,63 +99,3 @@ pub fn generate_barriers(editor: &mut WorldEditor, element: &ProcessedElement) {
}
}
}
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

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
use crate::args::Args;
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::coordinate_system::cartesian::XZPoint;
use crate::cartesian::XZPoint;
use crate::floodfill::flood_fill_area;
use crate::osm_parser::{ProcessedElement, ProcessedWay};
use crate::world_editor::WorldEditor;
@@ -13,8 +13,7 @@ pub fn generate_highways(editor: &mut WorldEditor, element: &ProcessedElement, a
if let ProcessedElement::Node(first_node) = element {
let x: i32 = first_node.x;
let z: i32 = first_node.z;
editor.set_block(COBBLESTONE_WALL, x, 1, z, None, None);
for dy in 2..=4 {
for dy in 1..=4 {
editor.set_block(OAK_FENCE, x, dy, z, None, None);
}
editor.set_block(GLOWSTONE, x, 5, z, None, None);
@@ -94,8 +93,6 @@ pub fn generate_highways(editor: &mut WorldEditor, element: &ProcessedElement, a
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") {
@@ -155,11 +152,9 @@ pub fn generate_highways(editor: &mut WorldEditor, element: &ProcessedElement, a
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;
}
}
}
@@ -169,10 +164,6 @@ pub fn generate_highways(editor: &mut WorldEditor, element: &ProcessedElement, a
return;
};
if scale_factor < 1.0 {
block_range = ((block_range as f64) * scale_factor).floor() as i32;
}
// Iterate over nodes to create the highway
for node in &way.nodes {
if let Some(prev) = previous_node {
@@ -188,8 +179,8 @@ pub fn generate_highways(editor: &mut WorldEditor, element: &ProcessedElement, a
// Variables to manage dashed line pattern
let mut stripe_length: i32 = 0;
let dash_length: i32 = (5.0 * scale_factor).ceil() as i32; // Length of the solid part of the stripe
let gap_length: i32 = (5.0 * scale_factor).ceil() as i32; // Length of the gap part of the stripe
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
for (x, _, z) in bresenham_points {
// Draw the road surface for the entire width
@@ -256,36 +247,6 @@ pub fn generate_highways(editor: &mut WorldEditor, element: &ProcessedElement, a
}
}
// 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,
0,
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,
0,
outline_z,
None,
None,
);
}
}
// Add a dashed white line in the middle for larger roads
if add_stripe {
if stripe_length < dash_length {
@@ -346,7 +307,7 @@ pub fn generate_siding(editor: &mut WorldEditor, element: &ProcessedWay) {
}
/// Generates an aeroway
pub fn generate_aeroway(editor: &mut WorldEditor, way: &ProcessedWay, args: &Args) {
pub fn generate_aeroway(editor: &mut WorldEditor, way: &ProcessedWay) {
let mut previous_node: Option<(i32, i32)> = None;
let surface_block = LIGHT_GRAY_CONCRETE;
@@ -356,11 +317,10 @@ pub fn generate_aeroway(editor: &mut WorldEditor, way: &ProcessedWay, args: &Arg
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 -way_width..=way_width {
for dz in -way_width..=way_width {
for dx in -12..=12 {
for dz in -12..=12 {
let set_x = x + dx;
let set_z = z + dz;
editor.set_block(surface_block, set_x, 0, set_z, None, None);

View File

@@ -2,7 +2,7 @@ use crate::args::Args;
use crate::block_definitions::*;
use crate::element_processing::tree::Tree;
use crate::floodfill::flood_fill_area;
use crate::osm_parser::{ProcessedMemberRole, ProcessedRelation, ProcessedWay};
use crate::osm_parser::ProcessedWay;
use crate::world_editor::WorldEditor;
use rand::Rng;
@@ -26,8 +26,7 @@ pub fn generate_landuse(editor: &mut WorldEditor, element: &ProcessedWay, args:
}
}
"commercial" => SMOOTH_STONE,
"education" => POLISHED_ANDESITE,
"religious" => POLISHED_ANDESITE,
"education" => LIGHT_GRAY_CONCRETE,
"industrial" => COBBLESTONE,
"military" => GRAY_CONCRETE,
"railway" => GRAVEL,
@@ -85,8 +84,6 @@ pub fn generate_landuse(editor: &mut WorldEditor, element: &ProcessedWay, args:
}
} else if random_choice < 33 {
Tree::create(editor, (x, 1, z));
} else if random_choice < 35 {
editor.set_block(OAK_LEAVES, x, 1, z, None, None);
}
}
}
@@ -96,11 +93,10 @@ pub fn generate_landuse(editor: &mut WorldEditor, element: &ProcessedWay, args:
if random_choice == 20 {
Tree::create(editor, (x, 1, z));
} else if random_choice == 2 {
let flower_block: Block = match rng.gen_range(1..=5) {
1 => OAK_LEAVES,
2 => RED_FLOWER,
3 => BLUE_FLOWER,
4 => YELLOW_FLOWER,
let flower_block: 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);
@@ -133,7 +129,7 @@ pub fn generate_landuse(editor: &mut WorldEditor, element: &ProcessedWay, args:
}
"construction" => {
let random_choice: i32 = rng.gen_range(0..1501);
if random_choice < 15 {
if random_choice < 6 {
editor.set_block(SCAFFOLDING, x, 1, z, None, None);
if random_choice < 2 {
editor.set_block(SCAFFOLDING, x, 2, z, None, None);
@@ -151,8 +147,8 @@ pub fn generate_landuse(editor: &mut WorldEditor, element: &ProcessedWay, args:
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 < 55 {
let construction_items: [Block; 13] = [
} else if random_choice < 30 {
let construction_items: [Block; 11] = [
OAK_LOG,
COBBLESTONE,
GRAVEL,
@@ -164,8 +160,6 @@ pub fn generate_landuse(editor: &mut WorldEditor, element: &ProcessedWay, args:
OAK_PLANKS,
DIRT,
BRICK,
CRAFTING_TABLE,
FURNACE,
];
editor.set_block(
construction_items[rng.gen_range(0..construction_items.len())],
@@ -175,8 +169,8 @@ pub fn generate_landuse(editor: &mut WorldEditor, element: &ProcessedWay, args:
None,
None,
);
} else if random_choice < 65 {
if random_choice < 60 {
} else if random_choice < 35 {
if random_choice < 30 {
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);
@@ -187,38 +181,13 @@ pub fn generate_landuse(editor: &mut WorldEditor, element: &ProcessedWay, args:
editor.set_block(DIRT, x - 1, 1, z, None, None);
editor.set_block(DIRT, x, 1, z - 1, None, None);
}
} 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]));
} else if random_choice < 150 {
editor.set_block(AIR, x, 0, z, None, Some(&[SPONGE]));
}
}
"grass" => {
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),
_ => {}
}
if rng.gen_bool(0.85) && editor.check_for_block(x, 0, z, Some(&[GRASS_BLOCK])) {
editor.set_block(GRASS, x, 1, z, None, None);
}
}
"meadow" => {
@@ -226,10 +195,6 @@ pub fn generate_landuse(editor: &mut WorldEditor, element: &ProcessedWay, args:
let random_choice: i32 = rng.gen_range(0..1001);
if random_choice < 5 {
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, 1, z, None, None);
}
@@ -238,12 +203,6 @@ pub fn generate_landuse(editor: &mut WorldEditor, element: &ProcessedWay, args:
"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" => {
@@ -270,39 +229,3 @@ pub fn generate_landuse(editor: &mut WorldEditor, element: &ProcessedWay, args:
}
}
}
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

@@ -94,7 +94,7 @@ pub fn generate_leisure(editor: &mut WorldEditor, element: &ProcessedWay, args:
let random_choice: i32 = rng.gen_range(0..1000);
match random_choice {
0..30 => {
0..40 => {
// Flowers
let flower_choice = match random_choice {
0..10 => RED_FLOWER,
@@ -104,15 +104,11 @@ pub fn generate_leisure(editor: &mut WorldEditor, element: &ProcessedWay, args:
};
editor.set_block(flower_choice, x, 1, z, None, None);
}
30..90 => {
40..80 => {
// Grass
editor.set_block(GRASS, x, 1, z, None, None);
}
90..105 => {
// Oak leaves
editor.set_block(OAK_LEAVES, x, 1, z, None, None);
}
105..120 => {
80..90 => {
// Tree
Tree::create(editor, (x, 1, z));
}
@@ -128,13 +124,11 @@ pub fn generate_leisure(editor: &mut WorldEditor, element: &ProcessedWay, args:
match random_choice {
0..10 => {
// Swing set
for y in 1..=3 {
for y in 1..=4 {
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_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(OAK_FENCE, x, 4, z, None, None);
editor.set_block(STONE_BLOCK_SLAB, x, 2, z, None, None);
}
10..20 => {

View File

@@ -1,255 +0,0 @@
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),
_ => {} // 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("transmission") => 25,
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),
_ => {} // Unknown man_made type, ignore
}
}
}

View File

@@ -6,10 +6,8 @@ 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

@@ -3,7 +3,7 @@ use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::element_processing::tree::Tree;
use crate::floodfill::flood_fill_area;
use crate::osm_parser::{ProcessedElement, ProcessedMemberRole, ProcessedRelation, ProcessedWay};
use crate::osm_parser::ProcessedElement;
use crate::world_editor::WorldEditor;
use rand::Rng;
@@ -38,10 +38,6 @@ pub fn generate_natural(editor: &mut WorldEditor, element: &ProcessedElement, ar
"blockfield" => COBBLESTONE,
"glacier" => PACKED_ICE,
"mud" | "wetland" => MUD,
"mountain_range" => COBBLESTONE,
"saddle" | "ridge" => STONE,
"shrubbery" | "tundra" | "hill" => GRASS_BLOCK,
"cliff" => STONE,
_ => GRASS_BLOCK,
};
@@ -86,14 +82,16 @@ pub fn generate_natural(editor: &mut WorldEditor, element: &ProcessedElement, ar
// 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);
editor.set_block(SAND, x, -1, z, None, None);
editor.set_block(STONE, x, -2, z, None, None);
}
"glacier" => {
editor.set_block(PACKED_ICE, x, 0, z, None, None);
editor.set_block(STONE, x, -1, z, None, None);
editor.set_block(PACKED_ICE, x, -1, z, None, None);
editor.set_block(STONE, x, -2, z, None, None);
}
"bare_rock" => {
editor.set_block(STONE, x, 0, z, None, None);
editor.set_block(STONE, x, -1, z, None, None);
editor.set_block(STONE, x, -2, z, None, None);
}
_ => {}
}
@@ -116,10 +114,8 @@ pub fn generate_natural(editor: &mut WorldEditor, element: &ProcessedElement, ar
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 {
if random_choice < 30 {
if random_choice < 3 {
editor.set_block(OAK_LEAVES, x, 1, z, None, None);
} else {
editor.set_block(GRASS, x, 1, z, None, None);
@@ -256,186 +252,6 @@ pub fn generate_natural(editor: &mut WorldEditor, element: &ProcessedElement, ar
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
}
_ => {}
}
}
@@ -443,39 +259,3 @@ pub fn generate_natural(editor: &mut WorldEditor, element: &ProcessedElement, ar
}
}
}
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

@@ -5,10 +5,26 @@ use crate::world_editor::WorldEditor;
pub fn generate_railways(editor: &mut WorldEditor, element: &ProcessedWay) {
if let Some(railway_type) = element.tags.get("railway") {
// Check for underground railways (negative level or layer)
let is_underground = element
.tags
.get("level")
.map_or(false, |level| level.parse::<i32>().map_or(false, |l| l < 0))
|| element
.tags
.get("layer")
.map_or(false, |layer| layer.parse::<i32>().map_or(false, |l| l < 0));
// Also check for tunnel=yes tag
let is_tunnel = element
.tags
.get("tunnel")
.map_or(false, |tunnel| tunnel == "yes");
// Skip certain railway types
if [
"proposed",
"abandoned",
"subway",
"construction",
"razed",
"turntable",
@@ -18,18 +34,13 @@ pub fn generate_railways(editor: &mut WorldEditor, element: &ProcessedWay) {
return;
}
if let Some(subway) = element.tags.get("subway") {
if subway == "yes" {
return;
}
}
if let Some(tunnel) = element.tags.get("tunnel") {
if tunnel == "yes" {
return;
}
// Process as subway if it's a subway, underground by level/layer tag, or a tunnel
if element.tags.get("subway").map_or(false, |v| v == "yes") || is_underground || is_tunnel {
generate_subway(editor, element);
return;
}
// Regular surface railways
for i in 1..element.nodes.len() {
let prev_node = element.nodes[i - 1].xz();
let cur_node = element.nodes[i].xz();
@@ -69,6 +80,115 @@ pub fn generate_railways(editor: &mut WorldEditor, element: &ProcessedWay) {
}
}
fn generate_subway(editor: &mut WorldEditor, element: &ProcessedWay) {
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];
// Create a 4-block wide floor
for dx in -2..=1 {
for dz in -2..=1 {
editor.set_block(SMOOTH_STONE, bx + dx, -9, bz + dz, None, None);
}
}
// Create a 4-block wide ceiling 3 blocks above the floor
for dx in -2..=1 {
for dz in -2..=1 {
// Add occasional glowstone for lighting
if dx == 0 && dz == 0 && j % 4 == 0 {
editor.set_block(GLOWSTONE, bx, -4, bz, None, None);
} else {
editor.set_block(
SMOOTH_STONE,
bx + dx,
-4,
bz + dz,
None,
Some(&[GLOWSTONE]),
);
}
}
}
// Get previous and next points for direction
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 the rail on top of the floor
editor.set_block(rail_block, bx, -8, bz, None, None);
// Helper function to place wall only if block below is not SMOOTH_STONE
let mut place_wall = |x: i32, y: i32, z: i32| {
if !editor.check_for_block(x, y - 1, z, Some(&[SMOOTH_STONE])) {
editor.set_block(POLISHED_ANDESITE, x, y, z, None, None);
editor.set_block(POLISHED_ANDESITE, x, y + 1, z, None, None);
editor.set_block(POLISHED_ANDESITE, x, y + 2, z, None, None);
editor.set_block(POLISHED_ANDESITE, x, y + 3, z, None, None);
editor.set_block(POLISHED_ANDESITE, x, y + 4, z, None, None);
}
};
// Place dirt blocks two blocks away from the rail
// Determine orientation based on rail block
match rail_block {
RAIL_NORTH_SOUTH => {
// For north-south rails, place dirt two blocks east and west
place_wall(bx + 3, -8, bz);
place_wall(bx - 3, -8, bz);
}
RAIL_EAST_WEST => {
// For east-west rails, place dirt two blocks north and south
place_wall(bx, -8, bz + 3);
place_wall(bx, -8, bz - 3);
}
RAIL_NORTH_EAST => {
// For curves, place dirt two blocks away at appropriate positions
place_wall(bx - 3, -8, bz);
place_wall(bx, -8, bz + 3);
}
RAIL_NORTH_WEST => {
place_wall(bx + 3, -8, bz);
place_wall(bx, -8, bz + 3);
}
RAIL_SOUTH_EAST => {
place_wall(bx - 3, -8, bz);
place_wall(bx, -8, bz - 3);
}
RAIL_SOUTH_WEST => {
place_wall(bx + 3, -8, bz);
place_wall(bx, -8, bz - 3);
}
_ => {
// Default for any other rail blocks
place_wall(bx + 3, -8, bz);
place_wall(bx - 3, -8, bz);
}
}
}
}
}
fn smooth_diagonal_rails(points: &[(i32, i32, i32)]) -> Vec<(i32, i32, i32)> {
let mut smoothed = Vec::new();

View File

@@ -1,303 +0,0 @@
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(JUKEBOX), // Jukebox
'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

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

View File

@@ -64,13 +64,12 @@ const OAK_LEAVES_FILL: [(Coord, Coord); 5] = [
((0, 9, 0), (0, 10, 0)),
];
const SPRUCE_LEAVES_FILL: [(Coord, Coord); 6] = [
const SPRUCE_LEAVES_FILL: [(Coord, Coord); 5] = [
((-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] = [
@@ -109,10 +108,9 @@ pub struct Tree<'a> {
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.extend(BUILDING_CORNER_VARIATIONS);
blacklist.extend(building_wall_variations());
blacklist.extend(building_floor_variations());
blacklist.push(WATER);
let mut rng = rand::thread_rng();
@@ -195,148 +193,4 @@ impl Tree<'_> {
},
} // 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,
JUKEBOX,
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

@@ -3,7 +3,7 @@ use std::time::Instant;
use crate::{
block_definitions::WATER,
coordinate_system::cartesian::XZPoint,
cartesian::XZPoint,
osm_parser::{ProcessedMemberRole, ProcessedNode, ProcessedRelation},
world_editor::WorldEditor,
};
@@ -11,11 +11,7 @@ use crate::{
pub fn generate_water_areas(editor: &mut WorldEditor, element: &ProcessedRelation) {
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") == Some(&"water".to_string());
if !is_water {
if !element.tags.contains_key("water") {
return;
}
@@ -36,70 +32,27 @@ pub fn generate_water_areas(editor: &mut WorldEditor, element: &ProcessedRelatio
}
}
// Process each outer polygon individually
for (i, outer_nodes) in outers.iter().enumerate() {
let mut individual_outers = vec![outer_nodes.clone()];
merge_loopy_loops(&mut individual_outers);
if !verify_loopy_loops(&individual_outers) {
println!(
"Skipping invalid outer polygon {} for relation {}",
i + 1,
element.id
);
continue; // Skip this outer if it's not valid
}
merge_loopy_loops(&mut inners);
if !verify_loopy_loops(&inners) {
// If inners are invalid, process outer without inners
let empty_inners: Vec<Vec<ProcessedNode>> = vec![];
let mut temp_inners = empty_inners;
merge_loopy_loops(&mut temp_inners);
let (min_x, min_z) = editor.get_min_coords();
let (max_x, max_z) = editor.get_max_coords();
let individual_outers_xz: Vec<Vec<XZPoint>> = individual_outers
.iter()
.map(|x| x.iter().map(|y| y.xz()).collect::<Vec<_>>())
.collect();
let empty_inners_xz: Vec<Vec<XZPoint>> = vec![];
inverse_floodfill(
min_x,
min_z,
max_x,
max_z,
individual_outers_xz,
empty_inners_xz,
editor,
start_time,
);
continue;
}
let (min_x, min_z) = editor.get_min_coords();
let (max_x, max_z) = editor.get_max_coords();
let individual_outers_xz: Vec<Vec<XZPoint>> = individual_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,
individual_outers_xz,
inners_xz,
editor,
start_time,
);
merge_loopy_loops(&mut outers);
if !verify_loopy_loops(&outers) {
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, start_time);
}
// Merges ways that share nodes into full loops
@@ -154,14 +107,6 @@ fn merge_loopy_loops(loops: &mut Vec<Vec<ProcessedNode>>) {
y.extend(x.iter().skip(1).cloned());
merged.push(y);
} else if x.last().unwrap().id == y[0].id {
removed.push(i);
removed.push(j);
let mut x: Vec<ProcessedNode> = x.clone();
x.extend(y.iter().skip(1).cloned());
merged.push(x);
}
}
}
@@ -197,10 +142,7 @@ 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>>,
@@ -208,6 +150,9 @@ fn inverse_floodfill(
editor: &mut WorldEditor,
start_time: Instant,
) {
let min_x: i32 = 0;
let min_z: i32 = 0;
let inners: Vec<_> = inners
.into_iter()
.map(|x| {
@@ -259,15 +204,13 @@ fn inverse_floodfill_recursive(
println!("Water area generation exceeded 25 seconds, continuing anyway");
}
const ITERATIVE_THRES: i64 = 10_000;
const ITERATIVE_THRES: i32 = 10_000;
if min.0 > max.0 || min.1 > max.1 {
return;
}
// 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 {
if (max.0 - min.0) * (max.1 - min.1) < ITERATIVE_THRES {
inverse_floodfill_iterative(min, max, 0, outers, inners, editor);
return;
}

View File

@@ -1,11 +1,13 @@
use crate::block_definitions::*;
use crate::bresenham::bresenham_line;
use crate::cartesian::XZPoint;
use crate::osm_parser::ProcessedWay;
use crate::world_editor::WorldEditor;
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);
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
// Check for custom width in tags
if let Some(width_str) = element.tags.get("width") {
@@ -17,99 +19,40 @@ pub fn generate_waterways(editor: &mut WorldEditor, element: &ProcessedWay) {
});
}
// Skip layers below the ground level
if matches!(
element.tags.get("layer").map(|s| s.as_str()),
Some("-1") | Some("-2") | Some("-3")
) {
return;
}
// Process nodes to create waterways
for node in &element.nodes {
let current_node = node.xz();
// 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();
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);
// 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 (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);
for (bx, _, bz) in bresenham_points {
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, 0, z, None, None);
// Clear vegetation above the water
editor.set_block(
AIR,
x,
1,
z,
Some(&[GRASS, WHEAT, CARROTS, POTATOES]),
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);
}
}
}

View File

@@ -1,528 +0,0 @@
use crate::coordinate_system::{geographic::LLBBox, transformation::geo_distance};
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)
}
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() {
println!(
"Loading cached tile x={tile_x},y={tile_y},z={zoom} from {}",
tile_path.display()
);
let img: image::DynamicImage = image::open(&tile_path)?;
img.to_rgb8()
} else {
// AWS Terrain Tiles don't require an API key
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)?;
img.to_rgb8()
};
// 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};
/// Main flood fill function with automatic algorithm selection
/// Chooses the best algorithm based on polygon size and complexity
/// Perform a flood-fill to find the area inside a polygon.
/// Returns a vector of (x, z) coordinates representing the filled area.
pub fn flood_fill_area(
polygon_coords: &[(i32, i32)],
timeout: Option<&Duration>,
@@ -13,6 +13,8 @@ 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()
@@ -27,185 +29,73 @@ pub fn flood_fill_area(
.into_option()
.unwrap();
let area = (max_x - min_x + 1) as i64 * (max_z - min_z + 1) as i64;
// 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();
let exterior = LineString::from(exterior_coords);
let polygon = Polygon::new(exterior, vec![]);
// 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);
// Pre-allocate queue with reasonable capacity to avoid reallocations
let mut queue = VecDeque::with_capacity(1024);
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 {
return filled_area;
}
}
}
// 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;
}
// 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();
let mut 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![]);
let exterior: LineString = LineString::from(exterior_coords); // Create LineString from coordinates
let polygon: Polygon<f64> = Polygon::new(exterior, vec![]); // Create Polygon using LineString
// 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);
// 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
// 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
// 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));
}
}
// 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
if global_visited.len() % 200 == 0 {
// 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() {
if let Some(timeout) = timeout {
if &start_time.elapsed() > timeout {
return filled_area;
eprintln!("Floodfill timeout");
break;
}
}
}
// 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;
}
if polygon.contains(&Point::new(x as f64, z as f64)) {
filled_area.push((x, z));
// 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() {
// 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
&& !global_visited.contains(&(*nx, *nz))
&& !visited.contains(&(*nx, *nz))
{
global_visited.insert((*nx, *nz));
visited.insert((*nx, *nz));
queue.push_back((*nx, *nz));
}
}
}
}
if !filled_area.is_empty() {
break; // Exit if a valid area has been flood-filled
}
}
}

60
src/geo_coord.rs Normal file
View File

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

View File

@@ -1,10 +1,19 @@
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 crate::{bbox::BBox, cartesian::XZPoint};
use image::{Rgb, RgbImage};
/// 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.72;
/// 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 {
@@ -13,22 +22,42 @@ pub struct Ground {
elevation_data: Option<ElevationData>,
}
impl Ground {
pub fn new_flat(ground_level: i32) -> Self {
Self {
elevation_enabled: false,
ground_level,
elevation_data: None,
}
}
/// 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 {
match Self::fetch_elevation_data(args) {
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
}
}
} else {
None
};
pub fn new_enabled(bbox: &LLBBox, scale: f64, ground_level: i32) -> Self {
let elevation_data = fetch_elevation_data(bbox, scale, ground_level)
.expect("Failed to fetch elevation data");
Self {
elevation_enabled: true,
ground_level,
elevation_data: Some(elevation_data),
elevation_enabled,
ground_level: args.ground_level,
elevation_data,
}
}
@@ -78,12 +107,267 @@ impl Ground {
data.heights[z][x]
}
fn save_debug_image(&self, filename: &str) {
let heights = &self
.elevation_data
.as_ref()
.expect("Elevation data not available")
.heights;
/// Calculates appropriate zoom level for the given bounding box
fn calculate_zoom_level(bbox: BBox) -> 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)
}
fn fetch_elevation_data(
args: &crate::args::Args,
) -> Result<ElevationData, Box<dyn std::error::Error>> {
// Use OSM parser's scale calculation and apply user scale factor
let (scale_factor_z, scale_factor_x) =
crate::osm_parser::geo_distance(args.bbox.min(), args.bbox.max());
let scale_factor_x: f64 = scale_factor_x * args.scale;
let scale_factor_z: f64 = scale_factor_z * args.scale;
// Calculate zoom and tiles
let zoom: u8 = Self::calculate_zoom_level(args.bbox);
let tiles: Vec<(u32, u32)> = Self::get_tile_coordinates(args.bbox, 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 * args.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;
// With terrain enabled, ground_level is used as the MIN_Y for terrain
((args.ground_level as f64 + scaled_height).round() as i32)
.clamp(args.ground_level, MAX_Y)
})
.collect();
mc_heights.push(mc_row);
}
Ok(ElevationData {
heights: mc_heights,
width: grid_width,
height: grid_height,
})
}
fn get_tile_coordinates(bbox: BBox, zoom: u8) -> Vec<(u32, u32)> {
// Convert lat/lng to tile coordinates
let (x1, y1) = Self::lat_lng_to_tile(bbox.min().lat(), bbox.min().lng(), zoom);
let (x2, y2) = Self::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> = 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) {
if heights.is_empty() || heights[0].is_empty() {
return;
}
@@ -117,26 +401,13 @@ impl Ground {
// Ensure filename has .png extension
let filename: String = if !filename.ends_with(".png") {
format!("{filename}.png")
format!("{}.png", filename)
} 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)
}

View File

@@ -1,16 +1,12 @@
use crate::args::Args;
use crate::coordinate_system::cartesian::XZPoint;
use crate::coordinate_system::geographic::{LLBBox, LLPoint};
use crate::bbox;
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::version_check;
use fastnbt::Value;
use flate2::read::GzDecoder;
use fs2::FileExt;
use log::{error, LevelFilter};
use rfd::FileDialog;
use std::io::Read;
@@ -18,71 +14,22 @@ use std::path::{Path, PathBuf};
use std::{env, fs, io::Write, panic};
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...");
// Set a custom panic hook to log panic information
panic::set_hook(Box::new(|panic_info| {
let message = format!("Application panicked: {panic_info:?}");
error!("{message}");
let message = format!("Application panicked: {:?}", panic_info);
error!("{}", message);
std::process::exit(1);
}));
// Workaround WebKit2GTK issue with NVIDIA drivers and graphics issues
// Source: https://github.com/tauri-apps/tauri/issues/10702
// Workaround WebKit2GTK issue with NVIDIA drivers (likely explicit sync related?)
// Source: https://github.com/tauri-apps/tauri/issues/10702 (TODO: Remove this later)
#[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()
@@ -196,14 +143,14 @@ fn create_new_world(base_path: &Path) -> Result<String, String> {
// 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_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_pattern = format!("Arnis World {}: ", counter);
let location_match_exists = fs::read_dir(base_path)
.map(|entries| {
entries
@@ -223,13 +170,13 @@ fn create_new_world(base_path: &Path) -> Result<String, String> {
// 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}"))?;
.map_err(|e| format!("Failed to create world directory: {}", e))?;
// Copy the region template file
const REGION_TEMPLATE: &[u8] = include_bytes!("../mcassets/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}"))?;
.map_err(|e| format!("Failed to create region file: {}", e))?;
// Add the level.dat file
const LEVEL_TEMPLATE: &[u8] = include_bytes!("../mcassets/level.dat");
@@ -239,11 +186,11 @@ fn create_new_world(base_path: &Path) -> Result<String, String> {
let mut decompressed_data = Vec::new();
decoder
.read_to_end(&mut decompressed_data)
.map_err(|e| format!("Failed to decompress level.template: {e}"))?;
.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}"))?;
.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 {
@@ -254,7 +201,7 @@ fn create_new_world(base_path: &Path) -> Result<String, String> {
// 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}"))?;
.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));
@@ -283,31 +230,31 @@ fn create_new_world(base_path: &Path) -> Result<String, String> {
// 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}"))?;
.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}"))?;
.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}"))?;
.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}"))?;
.map_err(|e| format!("Failed to create level.dat file: {}", e))?;
// Add the icon.png file
const ICON_TEMPLATE: &[u8] = include_bytes!("../mcassets/icon.png");
fs::write(new_world_path.join("icon.png"), ICON_TEMPLATE)
.map_err(|e| format!("Failed to create icon.png file: {e}"))?;
.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_str: &str, bbox: &LLBBox) -> String {
fn add_localized_world_name(world_path_str: &str, bbox: &bbox::BBox) -> String {
let world_path = PathBuf::from(world_path_str);
// Only proceed if the path exists
@@ -383,7 +330,7 @@ fn add_localized_world_name(world_path_str: &str, bbox: &LLBBox) -> String {
area_name
};
let new_name = format!("{base_name}: {truncated_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) {
@@ -405,7 +352,10 @@ fn add_localized_world_name(world_path_str: &str, bbox: &LLBBox) -> String {
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}");
eprintln!(
"Failed to update level.dat with area name: {}",
e
);
}
}
}
@@ -419,242 +369,6 @@ fn add_localized_world_name(world_path_str: &str, bbox: &LLBBox) -> String {
// Return the original path since we didn't change the directory name
world_path_str.to_string()
}
// 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: &str,
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()
@@ -664,13 +378,12 @@ fn gui_get_version() -> String {
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}")),
Err(e) => Err(format!("Error checking for updates: {}", e)),
}
}
#[tauri::command]
#[allow(clippy::too_many_arguments)]
#[allow(unused_variables)]
fn gui_start_generation(
bbox_text: String,
selected_world: String,
@@ -678,65 +391,20 @@ fn gui_start_generation(
ground_level: i32,
floodfill_timeout: u64,
terrain_enabled: bool,
interior_enabled: bool,
roof_enabled: bool,
fillground_enabled: bool,
is_new_world: bool,
spawn_point: Option<(f64, f64)>,
) -> Result<(), String> {
use bbox::BBox;
use progress::emit_gui_error;
use LLBBox;
// 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) {
let bbox = match BBox::from_str(&bbox_text) {
Ok(bbox) => bbox,
Err(e) => {
let error_msg = format!("Failed to parse bounding box: {e}");
eprintln!("{error_msg}");
let error_msg = format!("Failed to parse bounding box: {}", e);
eprintln!("{}", error_msg);
emit_gui_error(&error_msg);
return Err(error_msg);
}
@@ -746,32 +414,28 @@ fn gui_start_generation(
let updated_world_path = if is_new_world {
add_localized_world_name(&selected_world, &bbox)
} else {
selected_world.clone()
selected_world
};
// 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)),
spawn_point,
};
// Run data fetch and world generation
match retrieve_data::fetch_data_from_overpass(args.bbox, args.debug, "requests", None) {
match retrieve_data::fetch_data(args.bbox, None, args.debug, "requests") {
Ok(raw_data) => {
let (mut parsed_elements, mut xzbbox) =
osm_parser::parse_osm_data(raw_data, args.bbox, args.scale, args.debug);
let (mut parsed_elements, scale_factor_x, scale_factor_z) =
osm_parser::parse_osm_data(&raw_data, args.bbox, &args);
parsed_elements.sort_by(|el1, el2| {
let (el1_priority, el2_priority) =
(osm_parser::get_priority(el1), osm_parser::get_priority(el2));
@@ -785,33 +449,26 @@ fn gui_start_generation(
}
});
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,
&args,
scale_factor_x,
scale_factor_z,
);
let _ = data_processing::generate_world(parsed_elements, xzbbox, 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}");
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}");
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
}
});

View File

@@ -1,21 +1,20 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod args;
mod bbox;
mod block_definitions;
mod bresenham;
mod cartesian;
mod colors;
mod coordinate_system;
mod data_processing;
mod element_processing;
mod floodfill;
mod geo_coord;
mod ground;
mod map_transformation;
mod osm_parser;
#[cfg(feature = "gui")]
mod progress;
mod retrieve_data;
#[cfg(test)]
mod test_utilities;
mod version_check;
mod world_editor;
@@ -24,7 +23,6 @@ use clap::Parser;
use colored::*;
use std::{env, fs, io::Write};
mod elevation_data;
#[cfg(feature = "gui")]
mod gui;
@@ -37,6 +35,7 @@ mod progress {
false
}
}
#[cfg(target_os = "windows")]
use windows::Win32::System::Console::{AttachConsole, FreeConsole, ATTACH_PARENT_PROCESS};
@@ -73,35 +72,26 @@ fn run_cli() {
// Parse input arguments
let args: Args = Args::parse();
args.run();
// Fetch data
let raw_data = match &args.file {
Some(file) => retrieve_data::fetch_data_from_file(file),
None => retrieve_data::fetch_data_from_overpass(
args.bbox,
args.debug,
args.downloader.as_str(),
args.save_json_file.as_deref(),
),
}
.expect("Failed to fetch data");
let mut ground = ground::generate_ground_data(&args);
let raw_data: serde_json::Value =
retrieve_data::fetch_data(args.bbox, args.file.as_deref(), args.debug, "requests")
.expect("Failed to fetch data");
// Parse raw data
let (mut parsed_elements, mut xzbbox) =
osm_parser::parse_osm_data(raw_data, args.bbox, args.scale, args.debug);
let (mut parsed_elements, scale_factor_x, scale_factor_z) =
osm_parser::parse_osm_data(&raw_data, args.bbox, &args);
parsed_elements
.sort_by_key(|element: &osm_parser::ProcessedElement| osm_parser::get_priority(element));
// Write the parsed OSM data to a file for inspection
if args.debug {
let mut buf = std::io::BufWriter::new(
fs::File::create("parsed_osm_data.txt").expect("Failed to create output file"),
);
let mut output_file: fs::File =
fs::File::create("parsed_osm_data.txt").expect("Failed to create output file");
for element in &parsed_elements {
writeln!(
buf,
output_file,
"Element ID: {}, Type: {}, Tags: {:?}",
element.id(),
element.kind(),
@@ -111,11 +101,8 @@ fn run_cli() {
}
}
// Transform map (parsed_elements). Operations are defined in a json file
map_transformation::transform_map(&mut parsed_elements, &mut xzbbox, &mut ground);
// Generate world
let _ = data_processing::generate_world(parsed_elements, xzbbox, ground, &args);
let _ = data_processing::generate_world(parsed_elements, &args, scale_factor_x, scale_factor_z);
}
fn main() {

View File

@@ -1,8 +0,0 @@
mod operator;
mod transform_map;
// interface for world generation pipeline
pub use transform_map::transform_map;
// interface for custom specific operator generation
pub mod translate;

View File

@@ -1,105 +0,0 @@
use super::translate::translator_from_json;
use crate::coordinate_system::cartesian::XZBBox;
use crate::ground::Ground;
use crate::osm_parser::ProcessedElement;
/// An Operator does transformation on the map, modifying Vec<ProcessedElement> and XZBBox
pub trait Operator {
/// Apply the operation
fn operate(
&self,
elements: &mut Vec<ProcessedElement>,
xzbbox: &mut XZBBox,
ground: &mut Ground,
);
#[allow(dead_code)]
/// Return a string describing the current specific operator
fn repr(&self) -> String;
}
pub fn operator_from_json(config: &serde_json::Value) -> Result<Box<dyn Operator>, String> {
let operation_str = config
.get("operation")
.and_then(serde_json::Value::as_str)
.ok_or("Expected a string field 'operator' in an operator dict")?;
let operator_config = config
.get("config")
.ok_or("Expected a dict field 'config' in an operator dict")?;
let operator_result: Result<Box<dyn Operator>, String> = match operation_str {
"translate" => translator_from_json(operator_config),
_ => Err(format!("Unrecognized operation type '{operation_str}'")),
};
operator_result.map_err(|e| format!("Operator config format error:\n{e}"))
}
pub fn operator_vec_from_json(list: &serde_json::Value) -> Result<Vec<Box<dyn Operator>>, String> {
let oplist = list
.as_array()
.ok_or("Expected a list of operator dict".to_string())?;
oplist
.iter()
.enumerate()
.map(|(i, v)| {
operator_from_json(v)
.map_err(|e| format!("Operator dict at index {i} format error:\n{e}"))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::coordinate_system::cartesian::{XZPoint, XZVector};
use crate::map_transformation::translate;
use std::fs;
// this ensures json can be correctly read into the specific operator struct
#[test]
fn test_read_valid_formats() {
let opjson = serde_json::from_str(
&fs::read_to_string("tests/map_transformation/all_valid_examples.json").unwrap(),
)
.unwrap();
let ops = operator_vec_from_json(&opjson);
assert!(ops.is_ok());
let ops = ops.unwrap();
// total number of operations
assert_eq!(ops.len(), 2);
// below tests the operators one by one by comparing repr description
let testop = translate::VectorTranslator {
vector: XZVector { dx: 2000, dz: 1000 },
};
assert_eq!(ops[0].repr(), testop.repr());
let testop = translate::StartEndTranslator {
start: XZPoint { x: 0, z: 0 },
end: XZPoint { x: -1000, z: -2000 },
};
assert_eq!(ops[1].repr(), testop.repr());
}
// this ensures json format error can be handled as Err
#[test]
fn test_read_invalid_formats() {
let opjson = serde_json::from_str(
&fs::read_to_string("tests/map_transformation/invalid_example_missing_field.json")
.unwrap(),
)
.unwrap();
let ops = operator_vec_from_json(&opjson);
assert!(ops.is_err());
}
}

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