Compare commits
9
Commits
main
..
f75c8b9d3c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f75c8b9d3c | ||
|
|
70ff6f7c51 | ||
|
|
a359518dd8 | ||
|
|
b2323d492c | ||
|
|
63b03d7131 | ||
|
|
461fa28d94 | ||
|
|
0c97023f59 | ||
|
|
72c6ab6cbc | ||
|
|
3e5a806657 |
@@ -0,0 +1 @@
|
||||
packs/** binary
|
||||
@@ -1,8 +0,0 @@
|
||||
#Plans and tests
|
||||
/plan/
|
||||
/tests/
|
||||
|
||||
# Added by cargo
|
||||
|
||||
/target/
|
||||
/binaries/
|
||||
Generated
-4491
File diff suppressed because it is too large
Load Diff
-18
@@ -1,18 +0,0 @@
|
||||
[package]
|
||||
name = "advanced_erosion_terrain_heightmap_generation"
|
||||
version = "0.2.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
arboard = "3.6"
|
||||
eframe = "0.33"
|
||||
egui = "0.33"
|
||||
image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp"] }
|
||||
rand = "0.9"
|
||||
rayon = "1.10"
|
||||
rfd = "0.17.2"
|
||||
|
||||
[profile.release]
|
||||
opt-level = "z"
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
@@ -1,373 +1,18 @@
|
||||
Mozilla Public License Version 2.0
|
||||
==================================
|
||||
MIT License
|
||||
|
||||
1. Definitions
|
||||
--------------
|
||||
Copyright (c) 2026 Grimsace
|
||||
|
||||
1.1. "Contributor"
|
||||
means each individual or legal entity that creates, contributes to
|
||||
the creation of, or owns Covered Software.
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
||||
associated documentation files (the "Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
|
||||
following conditions:
|
||||
|
||||
1.2. "Contributor Version"
|
||||
means the combination of the Contributions of others (if any) used
|
||||
by a Contributor and that particular Contributor's Contribution.
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial
|
||||
portions of the Software.
|
||||
|
||||
1.3. "Contribution"
|
||||
means Covered Software of a particular Contributor.
|
||||
|
||||
1.4. "Covered Software"
|
||||
means Source Code Form to which the initial Contributor has attached
|
||||
the notice in Exhibit A, the Executable Form of such Source Code
|
||||
Form, and Modifications of such Source Code Form, in each case
|
||||
including portions thereof.
|
||||
|
||||
1.5. "Incompatible With Secondary Licenses"
|
||||
means
|
||||
|
||||
(a) that the initial Contributor has attached the notice described
|
||||
in Exhibit B to the Covered Software; or
|
||||
|
||||
(b) that the Covered Software was made available under the terms of
|
||||
version 1.1 or earlier of the License, but not also under the
|
||||
terms of a Secondary License.
|
||||
|
||||
1.6. "Executable Form"
|
||||
means any form of the work other than Source Code Form.
|
||||
|
||||
1.7. "Larger Work"
|
||||
means a work that combines Covered Software with other material, in
|
||||
a separate file or files, that is not Covered Software.
|
||||
|
||||
1.8. "License"
|
||||
means this document.
|
||||
|
||||
1.9. "Licensable"
|
||||
means having the right to grant, to the maximum extent possible,
|
||||
whether at the time of the initial grant or subsequently, any and
|
||||
all of the rights conveyed by this License.
|
||||
|
||||
1.10. "Modifications"
|
||||
means any of the following:
|
||||
|
||||
(a) any file in Source Code Form that results from an addition to,
|
||||
deletion from, or modification of the contents of Covered
|
||||
Software; or
|
||||
|
||||
(b) any new file in Source Code Form that contains any Covered
|
||||
Software.
|
||||
|
||||
1.11. "Patent Claims" of a Contributor
|
||||
means any patent claim(s), including without limitation, method,
|
||||
process, and apparatus claims, in any patent Licensable by such
|
||||
Contributor that would be infringed, but for the grant of the
|
||||
License, by the making, using, selling, offering for sale, having
|
||||
made, import, or transfer of either its Contributions or its
|
||||
Contributor Version.
|
||||
|
||||
1.12. "Secondary License"
|
||||
means either the GNU General Public License, Version 2.0, the GNU
|
||||
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||
Public License, Version 3.0, or any later versions of those
|
||||
licenses.
|
||||
|
||||
1.13. "Source Code Form"
|
||||
means the form of the work preferred for making modifications.
|
||||
|
||||
1.14. "You" (or "Your")
|
||||
means an individual or a legal entity exercising rights under this
|
||||
License. For legal entities, "You" includes any entity that
|
||||
controls, is controlled by, or is under common control with You. For
|
||||
purposes of this definition, "control" means (a) the power, direct
|
||||
or indirect, to cause the direction or management of such entity,
|
||||
whether by contract or otherwise, or (b) ownership of more than
|
||||
fifty percent (50%) of the outstanding shares or beneficial
|
||||
ownership of such entity.
|
||||
|
||||
2. License Grants and Conditions
|
||||
--------------------------------
|
||||
|
||||
2.1. Grants
|
||||
|
||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
|
||||
(a) under intellectual property rights (other than patent or trademark)
|
||||
Licensable by such Contributor to use, reproduce, make available,
|
||||
modify, display, perform, distribute, and otherwise exploit its
|
||||
Contributions, either on an unmodified basis, with Modifications, or
|
||||
as part of a Larger Work; and
|
||||
|
||||
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||
for sale, have made, import, and otherwise transfer either its
|
||||
Contributions or its Contributor Version.
|
||||
|
||||
2.2. Effective Date
|
||||
|
||||
The licenses granted in Section 2.1 with respect to any Contribution
|
||||
become effective for each Contribution on the date the Contributor first
|
||||
distributes such Contribution.
|
||||
|
||||
2.3. Limitations on Grant Scope
|
||||
|
||||
The licenses granted in this Section 2 are the only rights granted under
|
||||
this License. No additional rights or licenses will be implied from the
|
||||
distribution or licensing of Covered Software under this License.
|
||||
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||
Contributor:
|
||||
|
||||
(a) for any code that a Contributor has removed from Covered Software;
|
||||
or
|
||||
|
||||
(b) for infringements caused by: (i) Your and any other third party's
|
||||
modifications of Covered Software, or (ii) the combination of its
|
||||
Contributions with other software (except as part of its Contributor
|
||||
Version); or
|
||||
|
||||
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||
its Contributions.
|
||||
|
||||
This License does not grant any rights in the trademarks, service marks,
|
||||
or logos of any Contributor (except as may be necessary to comply with
|
||||
the notice requirements in Section 3.4).
|
||||
|
||||
2.4. Subsequent Licenses
|
||||
|
||||
No Contributor makes additional grants as a result of Your choice to
|
||||
distribute the Covered Software under a subsequent version of this
|
||||
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||
permitted under the terms of Section 3.3).
|
||||
|
||||
2.5. Representation
|
||||
|
||||
Each Contributor represents that the Contributor believes its
|
||||
Contributions are its original creation(s) or it has sufficient rights
|
||||
to grant the rights to its Contributions conveyed by this License.
|
||||
|
||||
2.6. Fair Use
|
||||
|
||||
This License is not intended to limit any rights You have under
|
||||
applicable copyright doctrines of fair use, fair dealing, or other
|
||||
equivalents.
|
||||
|
||||
2.7. Conditions
|
||||
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||
in Section 2.1.
|
||||
|
||||
3. Responsibilities
|
||||
-------------------
|
||||
|
||||
3.1. Distribution of Source Form
|
||||
|
||||
All distribution of Covered Software in Source Code Form, including any
|
||||
Modifications that You create or to which You contribute, must be under
|
||||
the terms of this License. You must inform recipients that the Source
|
||||
Code Form of the Covered Software is governed by the terms of this
|
||||
License, and how they can obtain a copy of this License. You may not
|
||||
attempt to alter or restrict the recipients' rights in the Source Code
|
||||
Form.
|
||||
|
||||
3.2. Distribution of Executable Form
|
||||
|
||||
If You distribute Covered Software in Executable Form then:
|
||||
|
||||
(a) such Covered Software must also be made available in Source Code
|
||||
Form, as described in Section 3.1, and You must inform recipients of
|
||||
the Executable Form how they can obtain a copy of such Source Code
|
||||
Form by reasonable means in a timely manner, at a charge no more
|
||||
than the cost of distribution to the recipient; and
|
||||
|
||||
(b) You may distribute such Executable Form under the terms of this
|
||||
License, or sublicense it under different terms, provided that the
|
||||
license for the Executable Form does not attempt to limit or alter
|
||||
the recipients' rights in the Source Code Form under this License.
|
||||
|
||||
3.3. Distribution of a Larger Work
|
||||
|
||||
You may create and distribute a Larger Work under terms of Your choice,
|
||||
provided that You also comply with the requirements of this License for
|
||||
the Covered Software. If the Larger Work is a combination of Covered
|
||||
Software with a work governed by one or more Secondary Licenses, and the
|
||||
Covered Software is not Incompatible With Secondary Licenses, this
|
||||
License permits You to additionally distribute such Covered Software
|
||||
under the terms of such Secondary License(s), so that the recipient of
|
||||
the Larger Work may, at their option, further distribute the Covered
|
||||
Software under the terms of either this License or such Secondary
|
||||
License(s).
|
||||
|
||||
3.4. Notices
|
||||
|
||||
You may not remove or alter the substance of any license notices
|
||||
(including copyright notices, patent notices, disclaimers of warranty,
|
||||
or limitations of liability) contained within the Source Code Form of
|
||||
the Covered Software, except that You may alter any license notices to
|
||||
the extent required to remedy known factual inaccuracies.
|
||||
|
||||
3.5. Application of Additional Terms
|
||||
|
||||
You may choose to offer, and to charge a fee for, warranty, support,
|
||||
indemnity or liability obligations to one or more recipients of Covered
|
||||
Software. However, You may do so only on Your own behalf, and not on
|
||||
behalf of any Contributor. You must make it absolutely clear that any
|
||||
such warranty, support, indemnity, or liability obligation is offered by
|
||||
You alone, and You hereby agree to indemnify every Contributor for any
|
||||
liability incurred by such Contributor as a result of warranty, support,
|
||||
indemnity or liability terms You offer. You may include additional
|
||||
disclaimers of warranty and limitations of liability specific to any
|
||||
jurisdiction.
|
||||
|
||||
4. Inability to Comply Due to Statute or Regulation
|
||||
---------------------------------------------------
|
||||
|
||||
If it is impossible for You to comply with any of the terms of this
|
||||
License with respect to some or all of the Covered Software due to
|
||||
statute, judicial order, or regulation then You must: (a) comply with
|
||||
the terms of this License to the maximum extent possible; and (b)
|
||||
describe the limitations and the code they affect. Such description must
|
||||
be placed in a text file included with all distributions of the Covered
|
||||
Software under this License. Except to the extent prohibited by statute
|
||||
or regulation, such description must be sufficiently detailed for a
|
||||
recipient of ordinary skill to be able to understand it.
|
||||
|
||||
5. Termination
|
||||
--------------
|
||||
|
||||
5.1. The rights granted under this License will terminate automatically
|
||||
if You fail to comply with any of its terms. However, if You become
|
||||
compliant, then the rights granted under this License from a particular
|
||||
Contributor are reinstated (a) provisionally, unless and until such
|
||||
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||
ongoing basis, if such Contributor fails to notify You of the
|
||||
non-compliance by some reasonable means prior to 60 days after You have
|
||||
come back into compliance. Moreover, Your grants from a particular
|
||||
Contributor are reinstated on an ongoing basis if such Contributor
|
||||
notifies You of the non-compliance by some reasonable means, this is the
|
||||
first time You have received notice of non-compliance with this License
|
||||
from such Contributor, and You become compliant prior to 30 days after
|
||||
Your receipt of the notice.
|
||||
|
||||
5.2. If You initiate litigation against any entity by asserting a patent
|
||||
infringement claim (excluding declaratory judgment actions,
|
||||
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||
directly or indirectly infringes any patent, then the rights granted to
|
||||
You by any and all Contributors for the Covered Software under Section
|
||||
2.1 of this License shall terminate.
|
||||
|
||||
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||
end user license agreements (excluding distributors and resellers) which
|
||||
have been validly granted by You or Your distributors under this License
|
||||
prior to termination shall survive termination.
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 6. Disclaimer of Warranty *
|
||||
* ------------------------- *
|
||||
* *
|
||||
* Covered Software is provided under this License on an "as is" *
|
||||
* basis, without warranty of any kind, either expressed, implied, or *
|
||||
* statutory, including, without limitation, warranties that the *
|
||||
* Covered Software is free of defects, merchantable, fit for a *
|
||||
* particular purpose or non-infringing. The entire risk as to the *
|
||||
* quality and performance of the Covered Software is with You. *
|
||||
* Should any Covered Software prove defective in any respect, You *
|
||||
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||
* essential part of this License. No use of any Covered Software is *
|
||||
* authorized under this License except under this disclaimer. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 7. Limitation of Liability *
|
||||
* -------------------------- *
|
||||
* *
|
||||
* Under no circumstances and under no legal theory, whether tort *
|
||||
* (including negligence), contract, or otherwise, shall any *
|
||||
* Contributor, or anyone who distributes Covered Software as *
|
||||
* permitted above, be liable to You for any direct, indirect, *
|
||||
* special, incidental, or consequential damages of any character *
|
||||
* including, without limitation, damages for lost profits, loss of *
|
||||
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||
* and all other commercial damages or losses, even if such party *
|
||||
* shall have been informed of the possibility of such damages. This *
|
||||
* limitation of liability shall not apply to liability for death or *
|
||||
* personal injury resulting from such party's negligence to the *
|
||||
* extent applicable law prohibits such limitation. Some *
|
||||
* jurisdictions do not allow the exclusion or limitation of *
|
||||
* incidental or consequential damages, so this exclusion and *
|
||||
* limitation may not apply to You. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
8. Litigation
|
||||
-------------
|
||||
|
||||
Any litigation relating to this License may be brought only in the
|
||||
courts of a jurisdiction where the defendant maintains its principal
|
||||
place of business and such litigation shall be governed by laws of that
|
||||
jurisdiction, without reference to its conflict-of-law provisions.
|
||||
Nothing in this Section shall prevent a party's ability to bring
|
||||
cross-claims or counter-claims.
|
||||
|
||||
9. Miscellaneous
|
||||
----------------
|
||||
|
||||
This License represents the complete agreement concerning the subject
|
||||
matter hereof. If any provision of this License is held to be
|
||||
unenforceable, such provision shall be reformed only to the extent
|
||||
necessary to make it enforceable. Any law or regulation which provides
|
||||
that the language of a contract shall be construed against the drafter
|
||||
shall not be used to construe this License against a Contributor.
|
||||
|
||||
10. Versions of the License
|
||||
---------------------------
|
||||
|
||||
10.1. New Versions
|
||||
|
||||
Mozilla Foundation is the license steward. Except as provided in Section
|
||||
10.3, no one other than the license steward has the right to modify or
|
||||
publish new versions of this License. Each version will be given a
|
||||
distinguishing version number.
|
||||
|
||||
10.2. Effect of New Versions
|
||||
|
||||
You may distribute the Covered Software under the terms of the version
|
||||
of the License under which You originally received the Covered Software,
|
||||
or under the terms of any subsequent version published by the license
|
||||
steward.
|
||||
|
||||
10.3. Modified Versions
|
||||
|
||||
If you create software not governed by this License, and you want to
|
||||
create a new license for such software, you may create and use a
|
||||
modified version of this License if you rename the license and remove
|
||||
any references to the name of the license steward (except to note that
|
||||
such modified license differs from this License).
|
||||
|
||||
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||
Licenses
|
||||
|
||||
If You choose to distribute Source Code Form that is Incompatible With
|
||||
Secondary Licenses under the terms of this version of the License, the
|
||||
notice described in Exhibit B of this License must be attached.
|
||||
|
||||
Exhibit A - Source Code Form License Notice
|
||||
-------------------------------------------
|
||||
|
||||
This Source Code Form is subject to the terms of the Mozilla Public
|
||||
License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
If it is not possible or desirable to put the notice in a particular
|
||||
file, then You may include the notice in a location (such as a LICENSE
|
||||
file in a relevant directory) where a recipient would be likely to look
|
||||
for such a notice.
|
||||
|
||||
You may add additional accurate notices of copyright ownership.
|
||||
|
||||
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||
---------------------------------------------------------
|
||||
|
||||
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||
defined by the Mozilla Public License, v. 2.0.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
|
||||
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
|
||||
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
||||
USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
@@ -1,30 +1,3 @@
|
||||
# Grim Rune Terrain Generator
|
||||
# Basic Aura Highlighting
|
||||
|
||||
A standalone Rust terrain generator using `egui`, using a terrain generation method by Runevision (Skovbo Johansen).
|
||||
|
||||
See here:
|
||||
|
||||
https://www.shadertoy.com/view/wXcfWn
|
||||
https://www.shadertoy.com/view/sf23W1
|
||||
https://blog.runevision.com/2026/03/fast-and-gorgeous-erosion-filter.html
|
||||
https://www.youtube.com/watch?v=r4V21_uUK8Y
|
||||
|
||||
## Building:
|
||||
|
||||
```bash
|
||||
git clone https://codeberg.org/Grimsace/advanced_erosion_terrain_heightmap_generation.git
|
||||
cargo build --release
|
||||
```
|
||||
|
||||
## Easy Way:
|
||||
|
||||
Download the latest release!
|
||||
|
||||
## Current UI
|
||||
|
||||
The app uses an `egui` desktop interface with:
|
||||
|
||||
- A left control panel with `Generation` and `Advanced` tabs
|
||||
- Generation controls for image width, image height, generation scale, erosion scale, and random seed
|
||||
- Advanced controls for strength, gully weight, detail, and octaves
|
||||
- A right preview area showing both the normalized heightmap and the shaded bumpmap
|
||||
A small, FoundryVTT Pathfinder 2e/Starfinder 2e module that places a highlight around tokens in another token's aura.
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"BASIC_AURA_HIGHLIGHTING": {
|
||||
"tabs": {
|
||||
"auras": "Auras",
|
||||
"add": "Add aura",
|
||||
"delete": "Delete aura",
|
||||
"empty": "No auras configured."
|
||||
},
|
||||
"settings": {
|
||||
"refreshDuringMove": {
|
||||
"name": "Refresh During Movement",
|
||||
"hint": "If disabled, aura highlights will only refresh when a token stops moving or its settings are updated. This can improve performance."
|
||||
},
|
||||
"name": {
|
||||
"name": "Aura Name"
|
||||
},
|
||||
"radius": {
|
||||
"name": "Aura Radius",
|
||||
"hint": "The radius of the aura in scene distance units."
|
||||
},
|
||||
"color": {
|
||||
"name": "Highlight Color"
|
||||
},
|
||||
"measurement": {
|
||||
"from": "From",
|
||||
"to": "To",
|
||||
"edge": "Edge",
|
||||
"center": "Center"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"id": "basic_aura_highlighting",
|
||||
"title": "Basic Aura Highlighting",
|
||||
"version": "0.1.0",
|
||||
"compatibility": {
|
||||
"minimum": "13",
|
||||
"verified": "13",
|
||||
"maximum": "14"
|
||||
},
|
||||
"description": "<p>A module specifically for Pathfinder 2e that places a highlight around tokens in another token's aura. This aura can be measured from the center of the tokens or edge to edge. See the token or prototype token menus for configuration.</p>",
|
||||
"relationships": {
|
||||
"systems": [
|
||||
{
|
||||
"id": "pf2e",
|
||||
"manifest": "https://github.com/foundryvtt/pf2e/releases/latest/download/system.json",
|
||||
"compatibility": {
|
||||
"minimum": "6.0.0"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"flags": {
|
||||
"canUpload": true
|
||||
},
|
||||
"url": "https://codeberg.org/Grimsace/basic_aura_highlighting",
|
||||
"esmodules": ["scripts/module.js"],
|
||||
"styles": ["styles/module.css"],
|
||||
"languages": [
|
||||
{
|
||||
"lang": "en",
|
||||
"name": "English",
|
||||
"path": "languages/en.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,930 @@
|
||||
const MODULE_ID = "basic_aura_highlighting";
|
||||
const AURAS_TAB = "basic-aura-highlighting-auras";
|
||||
const AURAS_FLAG_PATH = `flags.${MODULE_ID}.auras`;
|
||||
const HIGHLIGHT_CONTAINER_NAME = `${MODULE_ID}.highlights`;
|
||||
const HIGHLIGHT_LINE_WIDTH = 4;
|
||||
const HIGHLIGHT_RING_SPACING = 5;
|
||||
const HIGHLIGHT_ALPHA_THRESHOLD = 0.2;
|
||||
const ALPHA_SAMPLE_SIZE = 48;
|
||||
const HIGHLIGHT_FILTER_MARKER = Symbol(MODULE_ID);
|
||||
const ALPHA_OUTLINE_FRAGMENT_SHADER = `
|
||||
varying vec2 vTextureCoord;
|
||||
uniform sampler2D uSampler;
|
||||
uniform vec4 inputSize;
|
||||
uniform vec4 outlineColor;
|
||||
uniform float thickness;
|
||||
uniform float alphaThreshold;
|
||||
|
||||
void main() {
|
||||
vec4 currentColor = texture2D(uSampler, vTextureCoord);
|
||||
if (currentColor.a > alphaThreshold) {
|
||||
gl_FragColor = currentColor;
|
||||
return;
|
||||
}
|
||||
|
||||
vec2 pixel = vec2(1.0 / inputSize.x, 1.0 / inputSize.y) * thickness;
|
||||
float alpha = 0.0;
|
||||
alpha = max(alpha, texture2D(uSampler, vTextureCoord + vec2(pixel.x, 0.0)).a);
|
||||
alpha = max(alpha, texture2D(uSampler, vTextureCoord + vec2(-pixel.x, 0.0)).a);
|
||||
alpha = max(alpha, texture2D(uSampler, vTextureCoord + vec2(0.0, pixel.y)).a);
|
||||
alpha = max(alpha, texture2D(uSampler, vTextureCoord + vec2(0.0, -pixel.y)).a);
|
||||
alpha = max(alpha, texture2D(uSampler, vTextureCoord + vec2(pixel.x, pixel.y)).a);
|
||||
alpha = max(alpha, texture2D(uSampler, vTextureCoord + vec2(-pixel.x, pixel.y)).a);
|
||||
alpha = max(alpha, texture2D(uSampler, vTextureCoord + vec2(pixel.x, -pixel.y)).a);
|
||||
alpha = max(alpha, texture2D(uSampler, vTextureCoord + vec2(-pixel.x, -pixel.y)).a);
|
||||
|
||||
if (alpha > alphaThreshold) {
|
||||
gl_FragColor = outlineColor;
|
||||
return;
|
||||
}
|
||||
|
||||
gl_FragColor = currentColor;
|
||||
}
|
||||
`;
|
||||
|
||||
let highlightedFilterTargets = new Set();
|
||||
let pendingHighlightRefresh = null;
|
||||
const alphaShapeCache = new Map();
|
||||
|
||||
const REFRESH_DURING_MOVE_SETTING = "refreshDuringMove";
|
||||
|
||||
Hooks.once("init", () => {
|
||||
game.settings.register(MODULE_ID, REFRESH_DURING_MOVE_SETTING, {
|
||||
name: localize("settings.refreshDuringMove.name"),
|
||||
hint: localize("settings.refreshDuringMove.hint"),
|
||||
scope: "client",
|
||||
config: true,
|
||||
type: Boolean,
|
||||
default: true,
|
||||
onChange: scheduleAuraHighlightRefresh,
|
||||
});
|
||||
});
|
||||
|
||||
Hooks.on("renderTokenConfig", injectAurasTab);
|
||||
Hooks.on("renderPrototypeTokenConfig", injectAurasTab);
|
||||
Hooks.on("preUpdateToken", (_token, changes) =>
|
||||
parseAurasInChanges(changes, AURAS_FLAG_PATH),
|
||||
);
|
||||
Hooks.on("preUpdateActor", (_actor, changes) =>
|
||||
parseAurasInChanges(changes, `prototypeToken.${AURAS_FLAG_PATH}`),
|
||||
);
|
||||
Hooks.on("canvasReady", scheduleAuraHighlightRefresh);
|
||||
Hooks.on("canvasTearDown", clearAuraHighlights);
|
||||
Hooks.on("controlToken", scheduleAuraHighlightRefresh);
|
||||
Hooks.on("updateToken", scheduleAuraHighlightRefresh);
|
||||
Hooks.on("moveToken", () => {
|
||||
if (game.settings.get(MODULE_ID, REFRESH_DURING_MOVE_SETTING))
|
||||
scheduleAuraHighlightRefresh();
|
||||
});
|
||||
Hooks.on("stopToken", scheduleAuraHighlightRefresh);
|
||||
Hooks.on("refreshToken", (token) => {
|
||||
const isAnimating = !!(token.animationContexts?.size || token._animation);
|
||||
if (
|
||||
game.settings.get(MODULE_ID, REFRESH_DURING_MOVE_SETTING) ||
|
||||
!isAnimating
|
||||
) {
|
||||
scheduleAuraHighlightRefresh();
|
||||
}
|
||||
});
|
||||
Hooks.on("createToken", scheduleAuraHighlightRefresh);
|
||||
Hooks.on("deleteToken", scheduleAuraHighlightRefresh);
|
||||
|
||||
function injectAurasTab(app, element) {
|
||||
const root = getRootElement(element);
|
||||
if (!root || root.querySelector(`[data-tab="${AURAS_TAB}"]`)) return;
|
||||
|
||||
const tabsNav = findTabsNav(root);
|
||||
const existingTab = findExistingTab(root, tabsNav);
|
||||
if (!tabsNav || !existingTab) {
|
||||
console.warn(
|
||||
`${MODULE_ID} | Could not find token config tabs to add Auras tab.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const group = tabsNav.dataset.group || existingTab.dataset.group || "sheet";
|
||||
const aurasTabButton = createAurasTabButton(group);
|
||||
const aurasPanel = createAurasTabPanel(group, getSavedAuras(app));
|
||||
|
||||
tabsNav.append(aurasTabButton);
|
||||
existingTab.after(aurasPanel);
|
||||
activateAurasControls(root, group, aurasPanel);
|
||||
}
|
||||
|
||||
function getRootElement(element) {
|
||||
if (element instanceof HTMLElement) return element;
|
||||
if (element?.[0] instanceof HTMLElement) return element[0];
|
||||
return null;
|
||||
}
|
||||
|
||||
function findTabsNav(root) {
|
||||
return root.querySelector(
|
||||
`nav.tabs[data-group], .tabs[data-group], nav.tabs, .tabs`,
|
||||
);
|
||||
}
|
||||
|
||||
function findExistingTab(root, tabsNav) {
|
||||
const group = tabsNav?.dataset.group;
|
||||
const selector = group
|
||||
? `.tab[data-group="${group}"][data-tab]`
|
||||
: `.tab[data-tab]`;
|
||||
return root.querySelector(selector) || root.querySelector(`.tab[data-tab]`);
|
||||
}
|
||||
|
||||
function getSavedAuras(app) {
|
||||
const document =
|
||||
app.document ?? app.object ?? app.token ?? app.actor?.prototypeToken;
|
||||
return normalizeAuras(parseAuras(document?.getFlag?.(MODULE_ID, "auras")));
|
||||
}
|
||||
|
||||
function createAurasTabButton(group) {
|
||||
const button = document.createElement("a");
|
||||
button.classList.add("item");
|
||||
button.dataset.tab = AURAS_TAB;
|
||||
button.dataset.group = group;
|
||||
button.dataset.action = "tab";
|
||||
button.innerHTML = `<i class="fa-solid fa-bullseye"></i> ${localize("tabs.auras")}`;
|
||||
return button;
|
||||
}
|
||||
|
||||
function createAurasTabPanel(group, auras) {
|
||||
const panel = document.createElement("section");
|
||||
panel.classList.add("tab", "basic-aura-highlighting");
|
||||
panel.dataset.tab = AURAS_TAB;
|
||||
panel.dataset.group = group;
|
||||
panel.innerHTML = `
|
||||
<input type="hidden" name="${AURAS_FLAG_PATH}" data-dtype="JSON">
|
||||
<div class="basic-aura-highlighting__header">
|
||||
<button type="button" class="basic-aura-highlighting__add" data-action="add-aura" title="${localize("tabs.add")}">
|
||||
<i class="fa-solid fa-plus"></i>
|
||||
</button>
|
||||
</div>
|
||||
<div class="basic-aura-highlighting__list" data-auras-list></div>
|
||||
<p class="hint basic-aura-highlighting__empty" data-empty>${localize("tabs.empty")}</p>
|
||||
`;
|
||||
|
||||
renderAuras(panel, auras);
|
||||
return panel;
|
||||
}
|
||||
|
||||
function activateAurasControls(root, group, panel) {
|
||||
const form = root.querySelector("form");
|
||||
const aurasTabButton = root.querySelector(
|
||||
`[data-tab="${AURAS_TAB}"][data-group="${group}"]`,
|
||||
);
|
||||
|
||||
aurasTabButton?.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
activateAurasTab(root, group);
|
||||
});
|
||||
|
||||
panel
|
||||
.querySelector("[data-action='add-aura']")
|
||||
?.addEventListener("click", () => {
|
||||
const auras = readAuras(panel);
|
||||
auras.push(createDefaultAura(auras.length));
|
||||
renderAuras(panel, auras);
|
||||
});
|
||||
|
||||
panel.addEventListener("input", () => syncAurasField(panel));
|
||||
panel.addEventListener("change", () => syncAurasField(panel));
|
||||
panel.addEventListener("click", (event) => {
|
||||
if (!(event.target instanceof Element)) return;
|
||||
|
||||
const deleteButton = event.target.closest("[data-action='delete-aura']");
|
||||
if (!deleteButton) return;
|
||||
|
||||
const auraItem = deleteButton.closest("[data-aura-id]");
|
||||
const id = auraItem?.dataset.auraId;
|
||||
renderAuras(
|
||||
panel,
|
||||
readAuras(panel).filter((aura) => aura.id !== id),
|
||||
);
|
||||
});
|
||||
|
||||
form?.addEventListener("submit", () => syncAurasField(panel), {
|
||||
capture: true,
|
||||
});
|
||||
}
|
||||
|
||||
function renderAuras(panel, auras) {
|
||||
const normalizedAuras = normalizeAuras(auras);
|
||||
const list = panel.querySelector("[data-auras-list]");
|
||||
const empty = panel.querySelector("[data-empty]");
|
||||
if (!list || !empty) return;
|
||||
|
||||
list.innerHTML = normalizedAuras
|
||||
.map((aura, index) => renderAura(aura, index))
|
||||
.join("");
|
||||
empty.hidden = normalizedAuras.length > 0;
|
||||
syncAurasField(panel);
|
||||
}
|
||||
|
||||
function renderAura(aura, index) {
|
||||
const id = escapeHtml(aura.id);
|
||||
const nameLabel = localize("settings.name.name");
|
||||
const rangeLabel = localize("settings.radius.name");
|
||||
const colorLabel = localize("settings.color.name");
|
||||
const fromLabel = localize("settings.measurement.from");
|
||||
const toLabel = localize("settings.measurement.to");
|
||||
|
||||
return `
|
||||
<fieldset class="basic-aura-highlighting__aura" data-aura-id="${id}">
|
||||
<legend>${escapeHtml(aura.name || defaultAuraName(index))}</legend>
|
||||
<div class="form-group">
|
||||
<label for="${id}-name">${nameLabel}</label>
|
||||
<div class="form-fields">
|
||||
<input id="${id}-name" type="text" value="${escapeHtml(aura.name)}" data-aura-field="name">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="${id}-range">${rangeLabel}</label>
|
||||
<div class="form-fields">
|
||||
<input id="${id}-range" type="number" min="0" step="0.5" value="${aura.range}" data-aura-field="range">
|
||||
</div>
|
||||
<p class="hint">${localize("settings.radius.hint")}</p>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="${id}-color">${colorLabel}</label>
|
||||
<div class="form-fields">
|
||||
<input id="${id}-color" type="color" value="${escapeHtml(aura.color)}" data-aura-field="color">
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="${id}-from">${fromLabel}</label>
|
||||
<div class="form-fields">
|
||||
<select id="${id}-from" data-aura-field="from">
|
||||
<option value="edge" ${aura.from === "edge" ? "selected" : ""}>${localize("settings.measurement.edge")}</option>
|
||||
<option value="center" ${aura.from === "center" ? "selected" : ""}>${localize("settings.measurement.center")}</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="${id}-to">${toLabel}</label>
|
||||
<div class="form-fields">
|
||||
<select id="${id}-to" data-aura-field="to">
|
||||
<option value="edge" ${aura.to === "edge" ? "selected" : ""}>${localize("settings.measurement.edge")}</option>
|
||||
<option value="center" ${aura.to === "center" ? "selected" : ""}>${localize("settings.measurement.center")}</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<button type="button" class="basic-aura-highlighting__delete" data-action="delete-aura">
|
||||
<i class="fa-solid fa-trash"></i> ${localize("tabs.delete")}
|
||||
</button>
|
||||
</div>
|
||||
</fieldset>
|
||||
`;
|
||||
}
|
||||
|
||||
function readAuras(panel) {
|
||||
return Array.from(panel.querySelectorAll("[data-aura-id]")).map((item) => ({
|
||||
id: item.dataset.auraId,
|
||||
name: item.querySelector("[data-aura-field='name']")?.value?.trim() || "",
|
||||
range: Number(item.querySelector("[data-aura-field='range']")?.value) || 0,
|
||||
color: item.querySelector("[data-aura-field='color']")?.value || "#ff0000",
|
||||
from: normalizeMeasurementMode(
|
||||
item.querySelector("[data-aura-field='from']")?.value,
|
||||
),
|
||||
to: normalizeMeasurementMode(
|
||||
item.querySelector("[data-aura-field='to']")?.value,
|
||||
),
|
||||
}));
|
||||
}
|
||||
|
||||
function syncAurasField(panel) {
|
||||
const hidden = panel.querySelector(`input[name="${AURAS_FLAG_PATH}"]`);
|
||||
if (hidden) hidden.value = JSON.stringify(readAuras(panel));
|
||||
}
|
||||
|
||||
function normalizeAura(aura = {}) {
|
||||
const legacyMeasurement = normalizeMeasurementMode(aura.measurement);
|
||||
return {
|
||||
id: typeof aura.id === "string" ? aura.id : randomId(),
|
||||
name: typeof aura.name === "string" ? aura.name : "",
|
||||
range: Number.isFinite(Number(aura.range)) ? Number(aura.range) : 10,
|
||||
color: typeof aura.color === "string" ? aura.color : "#ff0000",
|
||||
from: normalizeMeasurementMode(aura.from ?? legacyMeasurement),
|
||||
to: normalizeMeasurementMode(aura.to ?? legacyMeasurement),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeAuras(auras) {
|
||||
return auras.map((aura, index) => {
|
||||
const normalizedAura = normalizeAura(aura);
|
||||
if (!normalizedAura.name) normalizedAura.name = defaultAuraName(index);
|
||||
return normalizedAura;
|
||||
});
|
||||
}
|
||||
|
||||
function createDefaultAura(index) {
|
||||
return {
|
||||
...normalizeAura(),
|
||||
name: defaultAuraName(index),
|
||||
};
|
||||
}
|
||||
|
||||
function defaultAuraName(index) {
|
||||
return `${localize("tabs.auras")} ${index + 1}`;
|
||||
}
|
||||
|
||||
function normalizeMeasurementMode(value) {
|
||||
return value === "center" ? "center" : "edge";
|
||||
}
|
||||
|
||||
function parseAurasInChanges(changes, path) {
|
||||
const value = foundry.utils.getProperty(changes, path);
|
||||
if (typeof value !== "string") return;
|
||||
foundry.utils.setProperty(changes, path, normalizeAuras(parseAuras(value)));
|
||||
}
|
||||
|
||||
function parseAuras(value) {
|
||||
if (Array.isArray(value)) return value;
|
||||
if (typeof value !== "string") return [];
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(value);
|
||||
return Array.isArray(parsed) ? parsed : [];
|
||||
} catch (_error) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleAuraHighlightRefresh() {
|
||||
if (pendingHighlightRefresh !== null) return;
|
||||
|
||||
pendingHighlightRefresh = requestAnimationFrame(() => {
|
||||
pendingHighlightRefresh = null;
|
||||
refreshAuraHighlights();
|
||||
});
|
||||
}
|
||||
|
||||
function refreshAuraHighlights() {
|
||||
const activeCanvas = globalThis.canvas;
|
||||
if (!activeCanvas?.ready || !activeCanvas.tokens) return;
|
||||
|
||||
clearAuraHighlights();
|
||||
|
||||
const sourceTokens = activeCanvas.tokens.controlled.filter(
|
||||
(token) => getTokenAuras(token).length > 0,
|
||||
);
|
||||
if (sourceTokens.length === 0) return;
|
||||
|
||||
const highlights = collectAuraHighlights(sourceTokens);
|
||||
for (const [targetId, targetHighlights] of highlights) {
|
||||
const target = activeCanvas.tokens.placeables.find(
|
||||
(token) => token.id === targetId,
|
||||
);
|
||||
if (!target) continue;
|
||||
highlightToken(target, targetHighlights);
|
||||
}
|
||||
}
|
||||
|
||||
function clearAuraHighlights() {
|
||||
if (pendingHighlightRefresh !== null) {
|
||||
cancelAnimationFrame(pendingHighlightRefresh);
|
||||
pendingHighlightRefresh = null;
|
||||
}
|
||||
|
||||
for (const target of highlightedFilterTargets) {
|
||||
removeHighlightFilters(target);
|
||||
}
|
||||
highlightedFilterTargets = new Set();
|
||||
|
||||
const activeCanvas = globalThis.canvas;
|
||||
const parent = activeCanvas?.interface ?? activeCanvas?.tokens;
|
||||
const container =
|
||||
parent?.getChildByName?.(HIGHLIGHT_CONTAINER_NAME) ??
|
||||
parent?.children?.find((child) => child.name === HIGHLIGHT_CONTAINER_NAME);
|
||||
if (container) clearHighlightContainer(container);
|
||||
}
|
||||
|
||||
function getHighlightContainer() {
|
||||
const activeCanvas = globalThis.canvas;
|
||||
const parent = activeCanvas.interface ?? activeCanvas.tokens;
|
||||
let container =
|
||||
parent.getChildByName?.(HIGHLIGHT_CONTAINER_NAME) ??
|
||||
parent.children?.find((child) => child.name === HIGHLIGHT_CONTAINER_NAME);
|
||||
if (container) return container;
|
||||
|
||||
container = new PIXI.Container();
|
||||
container.name = HIGHLIGHT_CONTAINER_NAME;
|
||||
container.eventMode = "none";
|
||||
container.interactiveChildren = false;
|
||||
parent.addChild(container);
|
||||
return container;
|
||||
}
|
||||
|
||||
function clearHighlightContainer(container) {
|
||||
for (const child of container.removeChildren()) {
|
||||
child.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
function collectAuraHighlights(sourceTokens) {
|
||||
const highlights = new Map();
|
||||
|
||||
for (const source of sourceTokens) {
|
||||
const auras = getTokenAuras(source);
|
||||
for (const target of globalThis.canvas.tokens.placeables) {
|
||||
if (target === source || target.document.hidden) continue;
|
||||
|
||||
for (const aura of auras) {
|
||||
if (!isTokenInAura(source, target, aura)) continue;
|
||||
|
||||
const targetHighlights = highlights.get(target.id) ?? [];
|
||||
targetHighlights.push(aura);
|
||||
highlights.set(target.id, targetHighlights);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return highlights;
|
||||
}
|
||||
|
||||
function getTokenAuras(token) {
|
||||
return normalizeAuras(
|
||||
parseAuras(token.document?.getFlag?.(MODULE_ID, "auras")),
|
||||
);
|
||||
}
|
||||
|
||||
function isTokenInAura(source, target, aura) {
|
||||
const rangePixels = aura.range * getPixelsPerSceneUnit();
|
||||
return measureAuraDistance(source, target, aura) <= rangePixels;
|
||||
}
|
||||
|
||||
function measureCenterDistance(source, target) {
|
||||
const dx = source.center.x - target.center.x;
|
||||
const dy = source.center.y - target.center.y;
|
||||
const dz = getElevationOffset(source, target);
|
||||
return Math.sqrt(dx * dx + dy * dy + dz * dz);
|
||||
}
|
||||
|
||||
function measureAuraDistance(source, target, aura) {
|
||||
const sourcePoints = getMeasurementPoints(source, aura.from);
|
||||
const targetPoints = getMeasurementPoints(target, aura.to);
|
||||
if (sourcePoints.length === 0 || targetPoints.length === 0)
|
||||
return measureBoundsDistance(source, target, aura);
|
||||
|
||||
return measurePointSetDistance(sourcePoints, targetPoints, source, target);
|
||||
}
|
||||
|
||||
function measureBoundsDistance(source, target, aura) {
|
||||
const dz = getElevationOffset(source, target);
|
||||
let d2d = 0;
|
||||
if (aura.from === "center" && aura.to === "center")
|
||||
return measureCenterDistance(source, target);
|
||||
if (aura.from === "center")
|
||||
d2d = measurePointToBoundsDistance(source.center, target.bounds);
|
||||
else if (aura.to === "center")
|
||||
d2d = measurePointToBoundsDistance(target.center, source.bounds);
|
||||
else d2d = measureBoundsEdgeDistance(source, target);
|
||||
|
||||
return Math.sqrt(d2d * d2d + dz * dz);
|
||||
}
|
||||
|
||||
function measureBoundsEdgeDistance(source, target) {
|
||||
const alphaDistance = measureAlphaEdgeDistance(source, target);
|
||||
if (Number.isFinite(alphaDistance)) return alphaDistance;
|
||||
|
||||
const sourceBounds = source.bounds;
|
||||
const targetBounds = target.bounds;
|
||||
const dx = Math.max(
|
||||
sourceBounds.x - targetBounds.right,
|
||||
targetBounds.x - sourceBounds.right,
|
||||
0,
|
||||
);
|
||||
const dy = Math.max(
|
||||
sourceBounds.y - targetBounds.bottom,
|
||||
targetBounds.y - sourceBounds.bottom,
|
||||
0,
|
||||
);
|
||||
return Math.hypot(dx, dy);
|
||||
}
|
||||
|
||||
function measurePointToBoundsDistance(point, bounds) {
|
||||
const dx = Math.max(bounds.x - point.x, point.x - bounds.right, 0);
|
||||
const dy = Math.max(bounds.y - point.y, point.y - bounds.bottom, 0);
|
||||
return Math.hypot(dx, dy);
|
||||
}
|
||||
|
||||
function measureAlphaEdgeDistance(source, target) {
|
||||
const sourcePoints = getTokenAlphaEdgePoints(source);
|
||||
const targetPoints = getTokenAlphaEdgePoints(target);
|
||||
if (sourcePoints.length === 0 || targetPoints.length === 0) return Number.NaN;
|
||||
|
||||
return measurePointSetDistance(sourcePoints, targetPoints, source, target);
|
||||
}
|
||||
|
||||
function getMeasurementPoints(token, mode) {
|
||||
if (mode === "center") return [token.center];
|
||||
|
||||
const alphaPoints = getTokenAlphaEdgePoints(token);
|
||||
if (alphaPoints.length > 0) return alphaPoints;
|
||||
return [];
|
||||
}
|
||||
|
||||
function measurePointSetDistance(sourcePoints, targetPoints, source, target) {
|
||||
let minDistanceSquared = Infinity;
|
||||
for (const sourcePoint of sourcePoints) {
|
||||
for (const targetPoint of targetPoints) {
|
||||
const dx = sourcePoint.x - targetPoint.x;
|
||||
const dy = sourcePoint.y - targetPoint.y;
|
||||
const distanceSquared = dx * dx + dy * dy;
|
||||
if (distanceSquared < minDistanceSquared)
|
||||
minDistanceSquared = distanceSquared;
|
||||
}
|
||||
}
|
||||
|
||||
const dz = getElevationOffset(source, target);
|
||||
return Math.sqrt(minDistanceSquared + dz * dz);
|
||||
}
|
||||
|
||||
function getElevationOffset(source, target) {
|
||||
const e1 = source.document?.elevation ?? 0;
|
||||
const e2 = target.document?.elevation ?? 0;
|
||||
return Math.abs(e1 - e2) * getPixelsPerSceneUnit();
|
||||
}
|
||||
|
||||
function getTokenAlphaEdgePoints(token) {
|
||||
const displayObject = getTokenFilterTarget(token);
|
||||
const normalizedPoints = getTextureAlphaEdgePoints(displayObject);
|
||||
if (normalizedPoints.length === 0) return [];
|
||||
|
||||
const mapper = getAlphaPointMapper(displayObject, token);
|
||||
return normalizedPoints.map(mapper);
|
||||
}
|
||||
|
||||
function getAlphaPointMapper(displayObject, token) {
|
||||
const localBounds = displayObject?.getLocalBounds?.();
|
||||
const transform = displayObject?.worldTransform;
|
||||
const stageTransform = globalThis.canvas?.stage?.worldTransform;
|
||||
|
||||
if (localBounds && transform?.apply && stageTransform?.applyInverse) {
|
||||
return (point) => {
|
||||
const localPoint = {
|
||||
x: localBounds.x + point.x * localBounds.width,
|
||||
y: localBounds.y + point.y * localBounds.height,
|
||||
};
|
||||
const worldPoint = transform.apply(localPoint);
|
||||
return stageTransform.applyInverse(worldPoint);
|
||||
};
|
||||
}
|
||||
|
||||
const bounds = token.bounds;
|
||||
return (point) => ({
|
||||
x: bounds.x + point.x * bounds.width,
|
||||
y: bounds.y + point.y * bounds.height,
|
||||
});
|
||||
}
|
||||
|
||||
function getTextureAlphaEdgePoints(displayObject) {
|
||||
const texture = displayObject?.texture;
|
||||
const source = getTextureSource(texture);
|
||||
if (!texture || !source) return [];
|
||||
|
||||
const frame = getTextureFrame(texture, source);
|
||||
const cacheKey = getAlphaShapeCacheKey(texture, frame);
|
||||
if (alphaShapeCache.has(cacheKey)) return alphaShapeCache.get(cacheKey);
|
||||
|
||||
const points = sampleTextureAlphaEdges(source, frame);
|
||||
alphaShapeCache.set(cacheKey, points);
|
||||
return points;
|
||||
}
|
||||
|
||||
function getTextureSource(texture) {
|
||||
const source =
|
||||
texture?.source?.resource?.source ??
|
||||
texture?.source?.resource ??
|
||||
texture?.baseTexture?.resource?.source ??
|
||||
texture?.baseTexture?.resource ??
|
||||
null;
|
||||
|
||||
return isCanvasImageSource(source) ? source : null;
|
||||
}
|
||||
|
||||
function isCanvasImageSource(source) {
|
||||
const constructors = [
|
||||
globalThis.HTMLImageElement,
|
||||
globalThis.HTMLCanvasElement,
|
||||
globalThis.HTMLVideoElement,
|
||||
globalThis.ImageBitmap,
|
||||
globalThis.OffscreenCanvas,
|
||||
].filter(Boolean);
|
||||
|
||||
return constructors.some((constructor) => source instanceof constructor);
|
||||
}
|
||||
|
||||
function getTextureFrame(texture, source) {
|
||||
const frame = texture.frame ?? texture._frame;
|
||||
const width =
|
||||
frame?.width ??
|
||||
texture.width ??
|
||||
source.videoWidth ??
|
||||
source.naturalWidth ??
|
||||
source.width;
|
||||
const height =
|
||||
frame?.height ??
|
||||
texture.height ??
|
||||
source.videoHeight ??
|
||||
source.naturalHeight ??
|
||||
source.height;
|
||||
return {
|
||||
x: frame?.x ?? 0,
|
||||
y: frame?.y ?? 0,
|
||||
width,
|
||||
height,
|
||||
};
|
||||
}
|
||||
|
||||
function getAlphaShapeCacheKey(texture, frame) {
|
||||
const textureId =
|
||||
texture.cacheId ??
|
||||
texture.source?.uid ??
|
||||
texture.baseTexture?.uid ??
|
||||
texture.baseTexture?.cacheId ??
|
||||
texture.uid ??
|
||||
"texture";
|
||||
return `${textureId}:${frame.x}:${frame.y}:${frame.width}:${frame.height}:${ALPHA_SAMPLE_SIZE}:${HIGHLIGHT_ALPHA_THRESHOLD}`;
|
||||
}
|
||||
|
||||
function sampleTextureAlphaEdges(source, frame) {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = ALPHA_SAMPLE_SIZE;
|
||||
canvas.height = ALPHA_SAMPLE_SIZE;
|
||||
|
||||
const context = canvas.getContext("2d", { willReadFrequently: true });
|
||||
if (!context || !frame.width || !frame.height) return [];
|
||||
|
||||
try {
|
||||
context.clearRect(0, 0, canvas.width, canvas.height);
|
||||
context.drawImage(
|
||||
source,
|
||||
frame.x,
|
||||
frame.y,
|
||||
frame.width,
|
||||
frame.height,
|
||||
0,
|
||||
0,
|
||||
canvas.width,
|
||||
canvas.height,
|
||||
);
|
||||
return getAlphaEdgeSamplePoints(
|
||||
context.getImageData(0, 0, canvas.width, canvas.height),
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
`${MODULE_ID} | Could not sample token texture alpha for aura distance. Falling back to token bounds.`,
|
||||
error,
|
||||
);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function getAlphaEdgeSamplePoints(imageData) {
|
||||
const alphaThreshold = HIGHLIGHT_ALPHA_THRESHOLD * 255;
|
||||
const { data, width, height } = imageData;
|
||||
const opaquePixels = new Uint8Array(width * height);
|
||||
const points = [];
|
||||
|
||||
for (let y = 0; y < height; y += 1) {
|
||||
for (let x = 0; x < width; x += 1) {
|
||||
const index = y * width + x;
|
||||
opaquePixels[index] = data[index * 4 + 3] >= alphaThreshold ? 1 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
for (let y = 0; y < height; y += 1) {
|
||||
for (let x = 0; x < width; x += 1) {
|
||||
const index = y * width + x;
|
||||
if (
|
||||
!opaquePixels[index] ||
|
||||
!isAlphaEdgePixel(opaquePixels, width, height, x, y)
|
||||
)
|
||||
continue;
|
||||
|
||||
points.push({
|
||||
x: (x + 0.5) / width,
|
||||
y: (y + 0.5) / height,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return points;
|
||||
}
|
||||
|
||||
function isAlphaEdgePixel(opaquePixels, width, height, x, y) {
|
||||
for (let dy = -1; dy <= 1; dy += 1) {
|
||||
for (let dx = -1; dx <= 1; dx += 1) {
|
||||
if (dx === 0 && dy === 0) continue;
|
||||
|
||||
const neighborX = x + dx;
|
||||
const neighborY = y + dy;
|
||||
if (
|
||||
neighborX < 0 ||
|
||||
neighborY < 0 ||
|
||||
neighborX >= width ||
|
||||
neighborY >= height
|
||||
)
|
||||
return true;
|
||||
if (!opaquePixels[neighborY * width + neighborX]) return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function highlightToken(token, highlights) {
|
||||
const target = getTokenFilterTarget(token);
|
||||
const filters = highlights
|
||||
.map((aura) => createOutlineFilter(aura.color))
|
||||
.filter(Boolean);
|
||||
|
||||
if (target && filters.length > 0) {
|
||||
applyHighlightFilters(target, filters);
|
||||
return;
|
||||
}
|
||||
|
||||
drawFallbackTokenHighlights(getHighlightContainer(), token, highlights);
|
||||
}
|
||||
|
||||
function getTokenFilterTarget(token) {
|
||||
return (
|
||||
token.mesh ??
|
||||
token.icon ??
|
||||
token.children?.find((child) => child.texture) ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
function applyHighlightFilters(target, filters) {
|
||||
removeHighlightFilters(target);
|
||||
|
||||
for (const filter of filters) {
|
||||
filter[HIGHLIGHT_FILTER_MARKER] = true;
|
||||
}
|
||||
|
||||
target.filters = [...(target.filters ?? []), ...filters];
|
||||
highlightedFilterTargets.add(target);
|
||||
}
|
||||
|
||||
function removeHighlightFilters(target) {
|
||||
const filters = target.filters ?? [];
|
||||
const remainingFilters = filters.filter(
|
||||
(filter) => !filter?.[HIGHLIGHT_FILTER_MARKER],
|
||||
);
|
||||
target.filters = remainingFilters.length > 0 ? remainingFilters : null;
|
||||
}
|
||||
|
||||
function createOutlineFilter(color) {
|
||||
const colorNumber = colorToNumber(color);
|
||||
const pixiOutlineFilter = globalThis.PIXI?.filters?.OutlineFilter;
|
||||
if (pixiOutlineFilter)
|
||||
return new pixiOutlineFilter(HIGHLIGHT_LINE_WIDTH, colorNumber, 0.2);
|
||||
|
||||
const outlineOverlayFilter =
|
||||
globalThis.OutlineOverlayFilter ??
|
||||
globalThis.foundry?.canvas?.rendering?.filters?.OutlineOverlayFilter;
|
||||
if (outlineOverlayFilter?.create) {
|
||||
const filter = outlineOverlayFilter.create({
|
||||
outlineColor: colorToRgbArray(colorNumber),
|
||||
thickness: [HIGHLIGHT_LINE_WIDTH, HIGHLIGHT_LINE_WIDTH],
|
||||
alphaThreshold: HIGHLIGHT_ALPHA_THRESHOLD,
|
||||
knockout: false,
|
||||
wave: false,
|
||||
});
|
||||
filter.animate = false;
|
||||
filter.animated = false;
|
||||
return filter;
|
||||
}
|
||||
|
||||
const alphaOutlineFilter = createAlphaOutlineFilter(colorNumber);
|
||||
if (alphaOutlineFilter) return alphaOutlineFilter;
|
||||
|
||||
const glowOverlayFilter =
|
||||
globalThis.GlowOverlayFilter ??
|
||||
globalThis.foundry?.canvas?.rendering?.filters?.GlowOverlayFilter;
|
||||
if (glowOverlayFilter?.create) {
|
||||
const filter = glowOverlayFilter.create({
|
||||
glowColor: colorToRgbArray(colorNumber),
|
||||
distance: HIGHLIGHT_LINE_WIDTH,
|
||||
outerStrength: 3,
|
||||
innerStrength: 0,
|
||||
alpha: 1,
|
||||
knockout: false,
|
||||
});
|
||||
filter.animated = false;
|
||||
return filter;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function createAlphaOutlineFilter(color) {
|
||||
const uniforms = {
|
||||
outlineColor: colorToRgbArray(color),
|
||||
thickness: HIGHLIGHT_LINE_WIDTH,
|
||||
alphaThreshold: HIGHLIGHT_ALPHA_THRESHOLD,
|
||||
};
|
||||
const baseFilter =
|
||||
globalThis.foundry?.canvas?.rendering?.filters?.AbstractBaseFilter ??
|
||||
globalThis.PIXI?.Filter;
|
||||
if (!baseFilter) return null;
|
||||
|
||||
try {
|
||||
const filter = new baseFilter(
|
||||
undefined,
|
||||
ALPHA_OUTLINE_FRAGMENT_SHADER,
|
||||
uniforms,
|
||||
);
|
||||
filter.padding = HIGHLIGHT_LINE_WIDTH;
|
||||
return filter;
|
||||
} catch (_error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function drawFallbackTokenHighlights(container, token, highlights) {
|
||||
highlights.forEach((aura, index) => {
|
||||
const bounds = token.bounds.clone().pad(index * HIGHLIGHT_RING_SPACING);
|
||||
const graphic = new PIXI.Graphics();
|
||||
|
||||
graphic.lineStyle(HIGHLIGHT_LINE_WIDTH, colorToNumber(aura.color), 0.9);
|
||||
graphic.drawRoundedRect(
|
||||
bounds.x,
|
||||
bounds.y,
|
||||
bounds.width,
|
||||
bounds.height,
|
||||
6 + index * 2,
|
||||
);
|
||||
container.addChild(graphic);
|
||||
});
|
||||
}
|
||||
|
||||
function getPixelsPerSceneUnit() {
|
||||
const activeCanvas = globalThis.canvas;
|
||||
const gridSize =
|
||||
activeCanvas.grid?.size ?? activeCanvas.dimensions?.size ?? 100;
|
||||
const gridDistance =
|
||||
Number(
|
||||
activeCanvas.scene?.grid?.distance ??
|
||||
activeCanvas.dimensions?.distance ??
|
||||
1,
|
||||
) || 1;
|
||||
return gridSize / gridDistance;
|
||||
}
|
||||
|
||||
function colorToNumber(color) {
|
||||
const value = String(color).replace("#", "");
|
||||
const parsed = Number.parseInt(value, 16);
|
||||
return Number.isFinite(parsed) ? parsed : 0xff0000;
|
||||
}
|
||||
|
||||
function colorToRgbArray(color) {
|
||||
return [
|
||||
((color >> 16) & 0xff) / 255,
|
||||
((color >> 8) & 0xff) / 255,
|
||||
(color & 0xff) / 255,
|
||||
1,
|
||||
];
|
||||
}
|
||||
|
||||
function activateAurasTab(root, group) {
|
||||
for (const tab of root.querySelectorAll(
|
||||
`.tab[data-group="${group}"], .tab[data-tab]`,
|
||||
)) {
|
||||
tab.classList.toggle("active", tab.dataset.tab === AURAS_TAB);
|
||||
}
|
||||
|
||||
for (const item of root.querySelectorAll(
|
||||
`[data-group="${group}"][data-tab], .tabs [data-tab]`,
|
||||
)) {
|
||||
item.classList.toggle("active", item.dataset.tab === AURAS_TAB);
|
||||
}
|
||||
}
|
||||
|
||||
function localize(path) {
|
||||
return game.i18n.localize(`BASIC_AURA_HIGHLIGHTING.${path}`);
|
||||
}
|
||||
|
||||
function randomId() {
|
||||
return (
|
||||
globalThis.foundry?.utils?.randomID?.() ??
|
||||
Math.random().toString(36).slice(2)
|
||||
);
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value).replace(
|
||||
/[&<>"']/g,
|
||||
(character) =>
|
||||
({
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': """,
|
||||
"'": "'",
|
||||
})[character],
|
||||
);
|
||||
}
|
||||
-885
@@ -1,885 +0,0 @@
|
||||
use std::sync::mpsc::{self, Receiver, TryRecvError};
|
||||
use std::thread;
|
||||
|
||||
use arboard::{Clipboard, ImageData};
|
||||
use eframe::egui::{
|
||||
self, Align2, Color32, ColorImage, Context, CornerRadius, DragValue, Event, FontId, Frame, Key,
|
||||
Response, RichText, Sense, Slider, Stroke, StrokeKind, TextureHandle, TextureOptions, Ui, Vec2,
|
||||
};
|
||||
use rand::Rng;
|
||||
|
||||
use crate::generator::{self, GeneratedImages, GenerationParams};
|
||||
|
||||
#[derive(Copy, Clone, Eq, PartialEq)]
|
||||
enum LeftTab {
|
||||
Generation,
|
||||
Advanced,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Eq, PartialEq)]
|
||||
enum PreviewFocus {
|
||||
TerrainComposite,
|
||||
TerrainColor,
|
||||
Heightmap,
|
||||
Bumpmap,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TextureSet {
|
||||
terrain_composite: TextureHandle,
|
||||
terrain_color: TextureHandle,
|
||||
heightmap: TextureHandle,
|
||||
bumpmap: TextureHandle,
|
||||
}
|
||||
|
||||
pub struct TerrainApp {
|
||||
params: GenerationParams,
|
||||
generation_tab: LeftTab,
|
||||
preview_focus: PreviewFocus,
|
||||
hovered_preview: Option<PreviewFocus>,
|
||||
textures: Option<TextureSet>,
|
||||
generated: Option<GeneratedImages>,
|
||||
generation_receiver: Option<Receiver<Result<GeneratedImages, String>>>,
|
||||
generation_in_progress: bool,
|
||||
copy_receiver: Option<Receiver<Result<String, String>>>,
|
||||
copy_in_progress: bool,
|
||||
export_receiver: Option<Receiver<Result<String, String>>>,
|
||||
export_in_progress: bool,
|
||||
status_message: String,
|
||||
}
|
||||
|
||||
impl TerrainApp {
|
||||
pub fn new(_cc: &eframe::CreationContext<'_>) -> Self {
|
||||
Self {
|
||||
params: GenerationParams::default(),
|
||||
generation_tab: LeftTab::Generation,
|
||||
preview_focus: PreviewFocus::TerrainComposite,
|
||||
hovered_preview: None,
|
||||
textures: None,
|
||||
generated: None,
|
||||
generation_receiver: None,
|
||||
generation_in_progress: false,
|
||||
copy_receiver: None,
|
||||
copy_in_progress: false,
|
||||
export_receiver: None,
|
||||
export_in_progress: false,
|
||||
status_message: String::from("Adjust parameters and click Generate."),
|
||||
}
|
||||
}
|
||||
|
||||
fn start_generation(&mut self) {
|
||||
if self.generation_in_progress {
|
||||
return;
|
||||
}
|
||||
|
||||
let params = self.params.clone();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.generation_receiver = Some(rx);
|
||||
self.generation_in_progress = true;
|
||||
self.status_message = format!(
|
||||
"Generating {}x{} terrain...",
|
||||
params.image_width, params.image_height
|
||||
);
|
||||
|
||||
thread::spawn(move || {
|
||||
let result = std::panic::catch_unwind(|| generator::generate(¶ms))
|
||||
.map_err(|_| String::from("Generation panicked unexpectedly."));
|
||||
let _ = tx.send(result);
|
||||
});
|
||||
}
|
||||
|
||||
fn poll_generation(&mut self, ctx: &Context) {
|
||||
let Some(receiver) = &self.generation_receiver else {
|
||||
return;
|
||||
};
|
||||
|
||||
match receiver.try_recv() {
|
||||
Ok(Ok(images)) => {
|
||||
self.status_message = format!(
|
||||
"Generated {}x{} heightmap, bumpmap, terrain color, and composite.",
|
||||
images.width, images.height
|
||||
);
|
||||
self.install_textures(ctx, &images);
|
||||
self.generated = Some(images);
|
||||
self.generation_receiver = None;
|
||||
self.generation_in_progress = false;
|
||||
}
|
||||
Ok(Err(error)) => {
|
||||
self.status_message = error;
|
||||
self.generation_receiver = None;
|
||||
self.generation_in_progress = false;
|
||||
}
|
||||
Err(TryRecvError::Empty) => {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
Err(TryRecvError::Disconnected) => {
|
||||
self.status_message = String::from("Generation worker disconnected.");
|
||||
self.generation_receiver = None;
|
||||
self.generation_in_progress = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_copy(&mut self, ctx: &Context) {
|
||||
let Some(receiver) = &self.copy_receiver else {
|
||||
return;
|
||||
};
|
||||
|
||||
match receiver.try_recv() {
|
||||
Ok(Ok(message)) => {
|
||||
self.status_message = message;
|
||||
self.copy_receiver = None;
|
||||
self.copy_in_progress = false;
|
||||
}
|
||||
Ok(Err(error)) => {
|
||||
self.status_message = error;
|
||||
self.copy_receiver = None;
|
||||
self.copy_in_progress = false;
|
||||
}
|
||||
Err(TryRecvError::Empty) => {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
Err(TryRecvError::Disconnected) => {
|
||||
self.status_message = String::from("Copy worker disconnected.");
|
||||
self.copy_receiver = None;
|
||||
self.copy_in_progress = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_export(&mut self, ctx: &Context) {
|
||||
let Some(receiver) = &self.export_receiver else {
|
||||
return;
|
||||
};
|
||||
|
||||
match receiver.try_recv() {
|
||||
Ok(Ok(message)) => {
|
||||
self.status_message = message;
|
||||
self.export_receiver = None;
|
||||
self.export_in_progress = false;
|
||||
}
|
||||
Ok(Err(error)) => {
|
||||
self.status_message = error;
|
||||
self.export_receiver = None;
|
||||
self.export_in_progress = false;
|
||||
}
|
||||
Err(TryRecvError::Empty) => {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
Err(TryRecvError::Disconnected) => {
|
||||
self.status_message = String::from("Export worker disconnected.");
|
||||
self.export_receiver = None;
|
||||
self.export_in_progress = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn start_export(&mut self, preview: PreviewFocus) {
|
||||
if self.export_in_progress {
|
||||
self.status_message = String::from("Export already in progress...");
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(generated) = &self.generated else {
|
||||
self.status_message = String::from("No generated image is available to export.");
|
||||
return;
|
||||
};
|
||||
|
||||
let label = preview_label(preview).to_lowercase().replace(' ', "_");
|
||||
let default_name = format!("{}.png", label);
|
||||
|
||||
let files = rfd::FileDialog::new()
|
||||
.add_filter("PNG Image", &["png"])
|
||||
.add_filter("JPEG Image", &["jpg", "jpeg"])
|
||||
.add_filter("WebP Image", &["webp"])
|
||||
.set_file_name(default_name)
|
||||
.save_file();
|
||||
|
||||
let Some(path) = files else {
|
||||
return;
|
||||
};
|
||||
|
||||
let generated = generated.clone();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.export_receiver = Some(rx);
|
||||
self.export_in_progress = true;
|
||||
self.status_message = format!("Exporting to {}...", path.display());
|
||||
|
||||
thread::spawn(move || {
|
||||
let result = (|| -> Result<String, String> {
|
||||
let format = match path.extension().and_then(|s| s.to_str()) {
|
||||
Some("jpg") | Some("jpeg") => image::ImageFormat::Jpeg,
|
||||
Some("webp") => image::ImageFormat::WebP,
|
||||
_ => image::ImageFormat::Png,
|
||||
};
|
||||
|
||||
match preview {
|
||||
PreviewFocus::TerrainComposite => generated
|
||||
.terrain_composite_image
|
||||
.save_with_format(&path, format),
|
||||
PreviewFocus::TerrainColor => generated
|
||||
.terrain_color_image
|
||||
.save_with_format(&path, format),
|
||||
PreviewFocus::Heightmap => {
|
||||
generated.heightmap_image.save_with_format(&path, format)
|
||||
}
|
||||
PreviewFocus::Bumpmap => {
|
||||
generated.bumpmap_image.save_with_format(&path, format)
|
||||
}
|
||||
}
|
||||
.map_err(|e| format!("Failed to save image: {}", e))?;
|
||||
|
||||
Ok(format!("Successfully exported to {}.", path.display()))
|
||||
})();
|
||||
let _ = tx.send(result);
|
||||
});
|
||||
}
|
||||
|
||||
fn start_batch_export(&mut self) {
|
||||
if self.export_in_progress {
|
||||
self.status_message = String::from("Export already in progress...");
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(generated) = &self.generated else {
|
||||
self.status_message = String::from("No generated images available to export.");
|
||||
return;
|
||||
};
|
||||
|
||||
let folder = rfd::FileDialog::new()
|
||||
.set_title("Select Export Folder")
|
||||
.pick_folder();
|
||||
let Some(path) = folder else {
|
||||
return;
|
||||
};
|
||||
|
||||
let generated = generated.clone();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.export_receiver = Some(rx);
|
||||
self.export_in_progress = true;
|
||||
self.status_message = format!("Exporting all layers to {}...", path.display());
|
||||
|
||||
thread::spawn(move || {
|
||||
let result = (|| -> Result<String, String> {
|
||||
let save = |img_rgba: Option<&image::RgbaImage>,
|
||||
img_gray: Option<&image::GrayImage>,
|
||||
name: &str| {
|
||||
let full_path = path.join(format!("{}.png", name));
|
||||
if let Some(img) = img_rgba {
|
||||
img.save(&full_path)
|
||||
} else if let Some(img) = img_gray {
|
||||
img.save(&full_path)
|
||||
} else {
|
||||
return Err(format!("No image data for {}", name));
|
||||
}
|
||||
.map_err(|e| format!("Failed to save {}: {}", name, e))
|
||||
};
|
||||
|
||||
save(
|
||||
Some(&generated.terrain_composite_image),
|
||||
None,
|
||||
"terrain_composite",
|
||||
)?;
|
||||
save(Some(&generated.terrain_color_image), None, "terrain_color")?;
|
||||
save(None, Some(&generated.heightmap_image), "heightmap")?;
|
||||
save(None, Some(&generated.bumpmap_image), "bumpmap")?;
|
||||
save(None, Some(&generated.grass_mask_image), "mask_grass")?;
|
||||
save(None, Some(&generated.water_mask_image), "mask_water")?;
|
||||
save(None, Some(&generated.rock_mask_image), "mask_rock")?;
|
||||
save(None, Some(&generated.snow_mask_image), "mask_snow")?;
|
||||
|
||||
Ok(format!(
|
||||
"Successfully exported 8 layers to {}.",
|
||||
path.display()
|
||||
))
|
||||
})();
|
||||
let _ = tx.send(result);
|
||||
});
|
||||
}
|
||||
|
||||
fn install_textures(&mut self, ctx: &Context, images: &GeneratedImages) {
|
||||
let heightmap = gray_to_color_image(&images.heightmap_image);
|
||||
let bumpmap = gray_to_color_image(&images.bumpmap_image);
|
||||
let terrain_composite = rgba_to_color_image(&images.terrain_composite_image);
|
||||
let terrain_color = rgba_to_color_image(&images.terrain_color_image);
|
||||
|
||||
self.textures = Some(TextureSet {
|
||||
terrain_composite: ctx.load_texture(
|
||||
"terrain_composite_preview",
|
||||
terrain_composite,
|
||||
TextureOptions::default(),
|
||||
),
|
||||
terrain_color: ctx.load_texture(
|
||||
"terrain_color_preview",
|
||||
terrain_color,
|
||||
TextureOptions::default(),
|
||||
),
|
||||
heightmap: ctx.load_texture("heightmap_preview", heightmap, TextureOptions::default()),
|
||||
bumpmap: ctx.load_texture("bumpmap_preview", bumpmap, TextureOptions::default()),
|
||||
});
|
||||
}
|
||||
|
||||
fn copy_preview(&mut self, preview: PreviewFocus) {
|
||||
if self.copy_in_progress {
|
||||
self.status_message = String::from("Copy already in progress...");
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(generated) = &self.generated else {
|
||||
self.status_message = String::from("No generated image is available to copy.");
|
||||
return;
|
||||
};
|
||||
|
||||
let image = preview_image_data(generated, preview);
|
||||
let success_message = match preview {
|
||||
PreviewFocus::TerrainComposite => {
|
||||
String::from("Terrain composite copied to clipboard.")
|
||||
}
|
||||
PreviewFocus::TerrainColor => String::from("Terrain color copied to clipboard."),
|
||||
PreviewFocus::Heightmap => String::from("Heightmap copied to clipboard."),
|
||||
PreviewFocus::Bumpmap => String::from("Bumpmap copied to clipboard."),
|
||||
};
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.copy_receiver = Some(rx);
|
||||
self.copy_in_progress = true;
|
||||
self.status_message = match preview {
|
||||
PreviewFocus::TerrainComposite => {
|
||||
String::from("Copying terrain composite to clipboard...")
|
||||
}
|
||||
PreviewFocus::TerrainColor => String::from("Copying terrain color to clipboard..."),
|
||||
PreviewFocus::Heightmap => String::from("Copying heightmap to clipboard..."),
|
||||
PreviewFocus::Bumpmap => String::from("Copying bumpmap to clipboard..."),
|
||||
};
|
||||
|
||||
thread::spawn(move || {
|
||||
let result = copy_image_to_clipboard(&image).map(|_| success_message);
|
||||
let _ = tx.send(result);
|
||||
});
|
||||
}
|
||||
|
||||
fn preview_context_menu(response: &Response) -> (bool, bool) {
|
||||
let mut should_copy = false;
|
||||
let mut should_export = false;
|
||||
response.context_menu(|ui| {
|
||||
if ui.button("Copy").clicked() {
|
||||
should_copy = true;
|
||||
ui.close();
|
||||
}
|
||||
if ui.button("Export").clicked() {
|
||||
should_export = true;
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
(should_copy, should_export)
|
||||
}
|
||||
|
||||
fn overlay_copy_button(ui: &mut Ui, anchor_rect: egui::Rect, preview: PreviewFocus) -> bool {
|
||||
let button_size = Vec2::new(28.0, 28.0);
|
||||
let button_rect = Align2::RIGHT_TOP
|
||||
.align_size_within_rect(button_size, anchor_rect.shrink2(Vec2::new(8.0, 8.0)));
|
||||
let response = ui.interact(
|
||||
button_rect,
|
||||
ui.make_persistent_id(("main_copy_button", preview == PreviewFocus::Bumpmap)),
|
||||
Sense::click(),
|
||||
);
|
||||
|
||||
let fill = if response.hovered() {
|
||||
Color32::from_rgba_premultiplied(70, 90, 120, 220)
|
||||
} else {
|
||||
Color32::from_rgba_premultiplied(40, 40, 40, 180)
|
||||
};
|
||||
ui.painter()
|
||||
.rect_filled(button_rect, CornerRadius::same(6), fill);
|
||||
ui.painter().rect_stroke(
|
||||
button_rect,
|
||||
CornerRadius::same(6),
|
||||
Stroke::new(1.0, Color32::from_rgba_premultiplied(255, 255, 255, 60)),
|
||||
StrokeKind::Outside,
|
||||
);
|
||||
ui.painter().text(
|
||||
button_rect.center(),
|
||||
Align2::CENTER_CENTER,
|
||||
"🗍",
|
||||
FontId::proportional(14.0),
|
||||
Color32::WHITE,
|
||||
);
|
||||
|
||||
let clicked = response.clicked();
|
||||
response.on_hover_text("Copy");
|
||||
let _ = preview;
|
||||
clicked
|
||||
}
|
||||
|
||||
fn overlay_export_button(ui: &mut Ui, anchor_rect: egui::Rect, preview: PreviewFocus) -> bool {
|
||||
let button_size = Vec2::new(28.0, 28.0);
|
||||
let button_rect = Align2::RIGHT_TOP
|
||||
.align_size_within_rect(button_size, anchor_rect.shrink2(Vec2::new(8.0 + 32.0, 8.0)));
|
||||
let response = ui.interact(
|
||||
button_rect,
|
||||
ui.make_persistent_id(("main_export_button", preview == PreviewFocus::Bumpmap)),
|
||||
Sense::click(),
|
||||
);
|
||||
|
||||
let fill = if response.hovered() {
|
||||
Color32::from_rgba_premultiplied(70, 90, 120, 220)
|
||||
} else {
|
||||
Color32::from_rgba_premultiplied(40, 40, 40, 180)
|
||||
};
|
||||
ui.painter()
|
||||
.rect_filled(button_rect, CornerRadius::same(6), fill);
|
||||
ui.painter().rect_stroke(
|
||||
button_rect,
|
||||
CornerRadius::same(6),
|
||||
Stroke::new(1.0, Color32::from_rgba_premultiplied(255, 255, 255, 60)),
|
||||
StrokeKind::Outside,
|
||||
);
|
||||
ui.painter().text(
|
||||
button_rect.center(),
|
||||
Align2::CENTER_CENTER,
|
||||
"📥",
|
||||
FontId::proportional(14.0),
|
||||
Color32::WHITE,
|
||||
);
|
||||
|
||||
let clicked = response.clicked();
|
||||
response.on_hover_text("Export");
|
||||
let _ = preview;
|
||||
clicked
|
||||
}
|
||||
|
||||
fn tab_button(ui: &mut Ui, current: &mut LeftTab, tab: LeftTab, label: &str) {
|
||||
let selected = *current == tab;
|
||||
if ui.selectable_label(selected, label).clicked() {
|
||||
*current = tab;
|
||||
}
|
||||
}
|
||||
|
||||
fn ui_left_panel(&mut self, ctx: &Context) {
|
||||
egui::SidePanel::left("controls_panel")
|
||||
.resizable(true)
|
||||
.default_width(320.0)
|
||||
.min_width(280.0)
|
||||
.show(ctx, |ui| {
|
||||
ui.heading("Advanced Erosion Terrain Generator");
|
||||
ui.add_space(8.0);
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
Self::tab_button(
|
||||
ui,
|
||||
&mut self.generation_tab,
|
||||
LeftTab::Generation,
|
||||
"Generation",
|
||||
);
|
||||
Self::tab_button(ui, &mut self.generation_tab, LeftTab::Advanced, "Advanced");
|
||||
});
|
||||
|
||||
ui.separator();
|
||||
|
||||
match self.generation_tab {
|
||||
LeftTab::Generation => self.ui_generation_tab(ui),
|
||||
LeftTab::Advanced => self.ui_advanced_tab(ui),
|
||||
}
|
||||
|
||||
ui.add_space(12.0);
|
||||
let button = ui.add_sized(
|
||||
[ui.available_width(), 56.0],
|
||||
egui::Button::new(RichText::new("Generate").size(20.0)),
|
||||
);
|
||||
if button.clicked() {
|
||||
self.start_generation();
|
||||
}
|
||||
|
||||
ui.add_space(8.0);
|
||||
if ui
|
||||
.add_sized(
|
||||
[ui.available_width(), 32.0],
|
||||
egui::Button::new("Export All Layers"),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
self.start_batch_export();
|
||||
}
|
||||
|
||||
if self.generation_in_progress {
|
||||
ui.add_space(8.0);
|
||||
ui.spinner();
|
||||
}
|
||||
if self.copy_in_progress {
|
||||
ui.add_space(4.0);
|
||||
ui.spinner();
|
||||
}
|
||||
if self.export_in_progress {
|
||||
ui.add_space(4.0);
|
||||
ui.spinner();
|
||||
}
|
||||
|
||||
ui.add_space(8.0);
|
||||
ui.label(&self.status_message);
|
||||
});
|
||||
}
|
||||
|
||||
fn ui_generation_tab(&mut self, ui: &mut Ui) {
|
||||
labeled_int_slider(ui, "Image Width", &mut self.params.image_width, 1..=5000);
|
||||
labeled_int_slider(ui, "Image Height", &mut self.params.image_height, 1..=5000);
|
||||
labeled_float_slider(
|
||||
ui,
|
||||
"Generation Scale",
|
||||
&mut self.params.generation_scale,
|
||||
0.1..=50.0,
|
||||
0.1,
|
||||
);
|
||||
labeled_float_slider(
|
||||
ui,
|
||||
"Erosion Scale",
|
||||
&mut self.params.erosion_scale,
|
||||
0.08..=0.25,
|
||||
0.01,
|
||||
);
|
||||
|
||||
ui.label("Random Seed");
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(
|
||||
DragValue::new(&mut self.params.random_seed)
|
||||
.range(0..=u64::MAX)
|
||||
.speed(1.0),
|
||||
);
|
||||
|
||||
if ui.button("Random").clicked() {
|
||||
self.params.random_seed = rand::rng().random::<u64>();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn ui_advanced_tab(&mut self, ui: &mut Ui) {
|
||||
labeled_float_slider(
|
||||
ui,
|
||||
"Strength",
|
||||
&mut self.params.erosion_strength,
|
||||
0.01..=0.10,
|
||||
0.01,
|
||||
);
|
||||
labeled_float_slider(
|
||||
ui,
|
||||
"Gully Weight",
|
||||
&mut self.params.erosion_gully_weight,
|
||||
0.0..=1.0,
|
||||
0.01,
|
||||
);
|
||||
labeled_float_slider(
|
||||
ui,
|
||||
"Detail",
|
||||
&mut self.params.erosion_detail,
|
||||
0.7..=3.0,
|
||||
0.1,
|
||||
);
|
||||
labeled_int_slider(ui, "Octaves", &mut self.params.erosion_octaves, 1..=8);
|
||||
labeled_int_slider(
|
||||
ui,
|
||||
"Snowline Height",
|
||||
&mut self.params.snowline_height,
|
||||
0..=255,
|
||||
);
|
||||
labeled_int_slider(
|
||||
ui,
|
||||
"Water Table Height",
|
||||
&mut self.params.water_table_height,
|
||||
0..=255,
|
||||
);
|
||||
labeled_float_slider(
|
||||
ui,
|
||||
"Rock Slope Angle",
|
||||
&mut self.params.rock_slope_angle_degrees,
|
||||
0.0..=89.0,
|
||||
1.0,
|
||||
);
|
||||
}
|
||||
|
||||
fn ui_right_panel(&mut self, ctx: &Context) {
|
||||
let mut pending_copy = None;
|
||||
let mut pending_export = None;
|
||||
let mut pending_focus = None;
|
||||
let mut pending_hover = None;
|
||||
let preview_focus = self.preview_focus;
|
||||
let textures = self.textures.clone();
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
let Some(textures) = &textures else {
|
||||
ui.centered_and_justified(|ui| {
|
||||
ui.label("No generated images yet.");
|
||||
});
|
||||
return;
|
||||
};
|
||||
let terrain_composite_texture = textures.terrain_composite.clone();
|
||||
let terrain_color_texture = textures.terrain_color.clone();
|
||||
let heightmap_texture = textures.heightmap.clone();
|
||||
let bumpmap_texture = textures.bumpmap.clone();
|
||||
|
||||
let available = ui.available_size();
|
||||
let bottom_strip_height = (available.y * 0.24).clamp(120.0, 220.0);
|
||||
let main_height = (available.y - bottom_strip_height - 8.0).max(100.0);
|
||||
|
||||
let main_texture = match preview_focus {
|
||||
PreviewFocus::TerrainComposite => &terrain_composite_texture,
|
||||
PreviewFocus::TerrainColor => &terrain_color_texture,
|
||||
PreviewFocus::Heightmap => &heightmap_texture,
|
||||
PreviewFocus::Bumpmap => &bumpmap_texture,
|
||||
};
|
||||
|
||||
let main_response =
|
||||
render_clickable_image(ui, main_texture, Vec2::new(available.x, main_height), true);
|
||||
if main_response.hovered() {
|
||||
pending_hover = Some(preview_focus);
|
||||
}
|
||||
|
||||
let (context_copy, context_export) = Self::preview_context_menu(&main_response);
|
||||
if context_copy || Self::overlay_copy_button(ui, main_response.rect, preview_focus) {
|
||||
pending_copy = Some(preview_focus);
|
||||
}
|
||||
if context_export || Self::overlay_export_button(ui, main_response.rect, preview_focus)
|
||||
{
|
||||
pending_export = Some(preview_focus);
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
|
||||
let thumb_width = (available.x * 0.26).clamp(120.0, 220.0);
|
||||
let panel_width = (thumb_width + 32.0).min(available.x);
|
||||
let secondary_previews = secondary_previews(preview_focus);
|
||||
|
||||
ui.horizontal_centered(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
for secondary_focus in secondary_previews {
|
||||
let secondary_texture = match secondary_focus {
|
||||
PreviewFocus::TerrainComposite => &terrain_composite_texture,
|
||||
PreviewFocus::TerrainColor => &terrain_color_texture,
|
||||
PreviewFocus::Heightmap => &heightmap_texture,
|
||||
PreviewFocus::Bumpmap => &bumpmap_texture,
|
||||
};
|
||||
let secondary_label = preview_label(secondary_focus);
|
||||
|
||||
Frame::group(ui.style()).show(ui, |ui| {
|
||||
ui.set_min_width(panel_width);
|
||||
ui.set_max_width(panel_width);
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.label(RichText::new(secondary_label).strong());
|
||||
ui.add_space(6.0);
|
||||
let secondary_response = render_clickable_image(
|
||||
ui,
|
||||
secondary_texture,
|
||||
Vec2::new(thumb_width, bottom_strip_height - 32.0),
|
||||
true,
|
||||
);
|
||||
if secondary_response.hovered() {
|
||||
pending_hover = Some(secondary_focus);
|
||||
}
|
||||
let (context_copy, context_export) =
|
||||
Self::preview_context_menu(&secondary_response);
|
||||
if context_copy {
|
||||
pending_copy = Some(secondary_focus);
|
||||
}
|
||||
if context_export {
|
||||
pending_export = Some(secondary_focus);
|
||||
}
|
||||
if secondary_response.clicked() {
|
||||
pending_focus = Some(secondary_focus);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
if let Some(preview) = pending_copy {
|
||||
self.copy_preview(preview);
|
||||
}
|
||||
if let Some(preview) = pending_export {
|
||||
self.start_export(preview);
|
||||
}
|
||||
if let Some(preview) = pending_focus {
|
||||
self.preview_focus = preview;
|
||||
}
|
||||
self.hovered_preview = pending_hover;
|
||||
}
|
||||
}
|
||||
|
||||
impl eframe::App for TerrainApp {
|
||||
fn update(&mut self, ctx: &Context, _frame: &mut eframe::Frame) {
|
||||
self.hovered_preview = None;
|
||||
self.poll_generation(ctx);
|
||||
self.poll_copy(ctx);
|
||||
self.poll_export(ctx);
|
||||
self.ui_left_panel(ctx);
|
||||
self.ui_right_panel(ctx);
|
||||
|
||||
let wants_keyboard_input = ctx.wants_keyboard_input();
|
||||
let should_copy = ctx.input(|input| {
|
||||
!wants_keyboard_input
|
||||
&& input.events.iter().any(|event| match event {
|
||||
Event::Copy => true,
|
||||
Event::Key {
|
||||
key: Key::C,
|
||||
pressed: true,
|
||||
modifiers,
|
||||
..
|
||||
} => modifiers.ctrl || modifiers.command,
|
||||
_ => false,
|
||||
})
|
||||
});
|
||||
|
||||
if should_copy {
|
||||
let preview = self.hovered_preview.unwrap_or(self.preview_focus);
|
||||
self.copy_preview(preview);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn gray_to_color_image(image: &image::GrayImage) -> ColorImage {
|
||||
let size = [image.width() as usize, image.height() as usize];
|
||||
let mut pixels = Vec::with_capacity(size[0] * size[1]);
|
||||
for pixel in image.pixels() {
|
||||
let value = pixel.0[0];
|
||||
pixels.push(Color32::from_gray(value));
|
||||
}
|
||||
ColorImage::new(size, pixels)
|
||||
}
|
||||
|
||||
fn rgba_to_color_image(image: &image::RgbaImage) -> ColorImage {
|
||||
let size = [image.width() as usize, image.height() as usize];
|
||||
let mut pixels = Vec::with_capacity(size[0] * size[1]);
|
||||
for pixel in image.pixels() {
|
||||
let [r, g, b, a] = pixel.0;
|
||||
pixels.push(Color32::from_rgba_unmultiplied(r, g, b, a));
|
||||
}
|
||||
ColorImage::new(size, pixels)
|
||||
}
|
||||
|
||||
fn preview_image_data(images: &GeneratedImages, preview: PreviewFocus) -> ImageData<'static> {
|
||||
match preview {
|
||||
PreviewFocus::TerrainComposite => {
|
||||
rgba_image_to_clipboard_data(&images.terrain_composite_image)
|
||||
}
|
||||
PreviewFocus::TerrainColor => rgba_image_to_clipboard_data(&images.terrain_color_image),
|
||||
PreviewFocus::Heightmap => gray_image_to_clipboard_data(&images.heightmap_image),
|
||||
PreviewFocus::Bumpmap => gray_image_to_clipboard_data(&images.bumpmap_image),
|
||||
}
|
||||
}
|
||||
|
||||
fn preview_label(preview: PreviewFocus) -> &'static str {
|
||||
match preview {
|
||||
PreviewFocus::TerrainComposite => "Composite",
|
||||
PreviewFocus::TerrainColor => "Terrain Color",
|
||||
PreviewFocus::Heightmap => "Heightmap",
|
||||
PreviewFocus::Bumpmap => "Bumpmap",
|
||||
}
|
||||
}
|
||||
|
||||
fn secondary_previews(preview: PreviewFocus) -> [PreviewFocus; 3] {
|
||||
match preview {
|
||||
PreviewFocus::TerrainComposite => [
|
||||
PreviewFocus::TerrainColor,
|
||||
PreviewFocus::Heightmap,
|
||||
PreviewFocus::Bumpmap,
|
||||
],
|
||||
PreviewFocus::TerrainColor => [
|
||||
PreviewFocus::TerrainComposite,
|
||||
PreviewFocus::Heightmap,
|
||||
PreviewFocus::Bumpmap,
|
||||
],
|
||||
PreviewFocus::Heightmap => [
|
||||
PreviewFocus::TerrainComposite,
|
||||
PreviewFocus::TerrainColor,
|
||||
PreviewFocus::Bumpmap,
|
||||
],
|
||||
PreviewFocus::Bumpmap => [
|
||||
PreviewFocus::TerrainComposite,
|
||||
PreviewFocus::TerrainColor,
|
||||
PreviewFocus::Heightmap,
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
fn labeled_int_slider<Num: egui::emath::Numeric>(
|
||||
ui: &mut Ui,
|
||||
label: &str,
|
||||
value: &mut Num,
|
||||
range: std::ops::RangeInclusive<Num>,
|
||||
) {
|
||||
ui.label(label);
|
||||
ui.add(Slider::new(value, range));
|
||||
}
|
||||
|
||||
fn labeled_float_slider(
|
||||
ui: &mut Ui,
|
||||
label: &str,
|
||||
value: &mut f32,
|
||||
range: std::ops::RangeInclusive<f32>,
|
||||
step: f32,
|
||||
) {
|
||||
ui.label(label);
|
||||
let slider = Slider::new(value, range).step_by(step as f64);
|
||||
ui.add(slider);
|
||||
}
|
||||
|
||||
fn render_clickable_image(
|
||||
ui: &mut Ui,
|
||||
texture: &TextureHandle,
|
||||
max_size: Vec2,
|
||||
clickable: bool,
|
||||
) -> Response {
|
||||
let image_size = texture.size_vec2();
|
||||
let scale = (max_size.x / image_size.x).min(max_size.y / image_size.y);
|
||||
let desired_size = image_size * scale.max(0.01);
|
||||
let image = egui::Image::new(texture)
|
||||
.fit_to_exact_size(desired_size)
|
||||
.sense(if clickable {
|
||||
Sense::click()
|
||||
} else {
|
||||
Sense::hover()
|
||||
});
|
||||
let response = ui.add(image);
|
||||
|
||||
if response.hovered() {
|
||||
ui.painter().rect_stroke(
|
||||
response.rect.expand(4.0),
|
||||
CornerRadius::same(8),
|
||||
Stroke::new(2.0, Color32::from_rgba_premultiplied(180, 220, 255, 180)),
|
||||
StrokeKind::Outside,
|
||||
);
|
||||
}
|
||||
|
||||
response
|
||||
}
|
||||
|
||||
fn gray_image_to_clipboard_data(image: &image::GrayImage) -> ImageData<'static> {
|
||||
let mut rgba = Vec::with_capacity((image.width() * image.height() * 4) as usize);
|
||||
for pixel in image.pixels() {
|
||||
let gray = pixel.0[0];
|
||||
rgba.extend_from_slice(&[gray, gray, gray, 255]);
|
||||
}
|
||||
|
||||
ImageData {
|
||||
width: image.width() as usize,
|
||||
height: image.height() as usize,
|
||||
bytes: rgba.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn rgba_image_to_clipboard_data(image: &image::RgbaImage) -> ImageData<'static> {
|
||||
let mut rgba = Vec::with_capacity((image.width() * image.height() * 4) as usize);
|
||||
for pixel in image.pixels() {
|
||||
rgba.extend_from_slice(&pixel.0);
|
||||
}
|
||||
|
||||
ImageData {
|
||||
width: image.width() as usize,
|
||||
height: image.height() as usize,
|
||||
bytes: rgba.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_image_to_clipboard(image: &ImageData<'static>) -> Result<(), String> {
|
||||
let mut clipboard = Clipboard::new().map_err(|error| error.to_string())?;
|
||||
clipboard
|
||||
.set_image(image.clone())
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
@@ -1,664 +0,0 @@
|
||||
use image::{GrayImage, Luma, Rgba, RgbaImage};
|
||||
use rayon::prelude::*;
|
||||
|
||||
const TAU: f32 = 6.283_185_5;
|
||||
const EROSION_LACUNARITY: f32 = 2.0;
|
||||
const EROSION_GAIN: f32 = 0.5;
|
||||
const EROSION_CELL_SCALE: f32 = 0.7;
|
||||
const EROSION_NORMALIZATION: f32 = 0.5;
|
||||
const EROSION_ROUNDING: [f32; 4] = [0.1, 0.0, 0.1, 2.0];
|
||||
const EROSION_ONSET: [f32; 4] = [1.25, 1.25, 2.8, 1.5];
|
||||
const EROSION_ASSUMED_SLOPE: [f32; 2] = [0.7, 1.0];
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GenerationParams {
|
||||
pub image_width: usize,
|
||||
pub image_height: usize,
|
||||
pub generation_scale: f32,
|
||||
pub erosion_scale: f32,
|
||||
pub random_seed: u64,
|
||||
pub erosion_strength: f32,
|
||||
pub erosion_gully_weight: f32,
|
||||
pub erosion_detail: f32,
|
||||
pub erosion_octaves: usize,
|
||||
pub snowline_height: u8,
|
||||
pub water_table_height: u8,
|
||||
pub rock_slope_angle_degrees: f32,
|
||||
}
|
||||
|
||||
impl Default for GenerationParams {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
image_width: 512,
|
||||
image_height: 512,
|
||||
generation_scale: 1.0,
|
||||
erosion_scale: 0.15,
|
||||
random_seed: 0,
|
||||
erosion_strength: 0.05,
|
||||
erosion_gully_weight: 0.5,
|
||||
erosion_detail: 1.5,
|
||||
erosion_octaves: 5,
|
||||
snowline_height: 220,
|
||||
water_table_height: 0,
|
||||
rock_slope_angle_degrees: 15.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct GeneratedImages {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub heightmap_image: GrayImage,
|
||||
pub bumpmap_image: GrayImage,
|
||||
pub terrain_color_image: RgbaImage,
|
||||
pub terrain_composite_image: RgbaImage,
|
||||
#[allow(dead_code)]
|
||||
pub grass_mask_image: GrayImage,
|
||||
#[allow(dead_code)]
|
||||
pub water_mask_image: GrayImage,
|
||||
#[allow(dead_code)]
|
||||
pub rock_mask_image: GrayImage,
|
||||
#[allow(dead_code)]
|
||||
pub snow_mask_image: GrayImage,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Default)]
|
||||
struct Vec2 {
|
||||
x: f32,
|
||||
y: f32,
|
||||
}
|
||||
|
||||
impl Vec2 {
|
||||
fn new(x: f32, y: f32) -> Self {
|
||||
Self { x, y }
|
||||
}
|
||||
|
||||
fn dot(self, other: Self) -> f32 {
|
||||
self.x * other.x + self.y * other.y
|
||||
}
|
||||
|
||||
fn length(self) -> f32 {
|
||||
self.dot(self).sqrt()
|
||||
}
|
||||
|
||||
fn normalize_safe(self) -> Self {
|
||||
let length = self.length();
|
||||
if length > 1e-10 {
|
||||
Self::new(self.x / length, self.y / length)
|
||||
} else {
|
||||
self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Add for Vec2 {
|
||||
type Output = Self;
|
||||
|
||||
fn add(self, rhs: Self) -> Self::Output {
|
||||
Self::new(self.x + rhs.x, self.y + rhs.y)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::AddAssign for Vec2 {
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.x += rhs.x;
|
||||
self.y += rhs.y;
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Sub for Vec2 {
|
||||
type Output = Self;
|
||||
|
||||
fn sub(self, rhs: Self) -> Self::Output {
|
||||
Self::new(self.x - rhs.x, self.y - rhs.y)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Mul<f32> for Vec2 {
|
||||
type Output = Self;
|
||||
|
||||
fn mul(self, rhs: f32) -> Self::Output {
|
||||
Self::new(self.x * rhs, self.y * rhs)
|
||||
}
|
||||
}
|
||||
|
||||
fn mix(a: f32, b: f32, t: f32) -> f32 {
|
||||
a + (b - a) * t
|
||||
}
|
||||
|
||||
fn mix2(a: Vec2, b: Vec2, t: f32) -> Vec2 {
|
||||
Vec2::new(mix(a.x, b.x, t), mix(a.y, b.y, t))
|
||||
}
|
||||
|
||||
fn clamp(x: f32, lo: f32, hi: f32) -> f32 {
|
||||
x.clamp(lo, hi)
|
||||
}
|
||||
|
||||
fn clamp01(x: f32) -> f32 {
|
||||
clamp(x, 0.0, 1.0)
|
||||
}
|
||||
|
||||
fn mix_u8(a: u8, b: u8, t: f32) -> u8 {
|
||||
mix(a as f32, b as f32, clamp01(t)).round() as u8
|
||||
}
|
||||
|
||||
fn hash22(p: Vec2, random_seed: u64) -> Vec2 {
|
||||
let scrambled_x = splitmix64(random_seed ^ 0x9E37_79B9_7F4A_7C15);
|
||||
let scrambled_y = splitmix64(random_seed ^ 0xBF58_476D_1CE4_E5B9);
|
||||
let seed_x = u64_to_unit_f64(scrambled_x) * 1024.0;
|
||||
let seed_y = u64_to_unit_f64(scrambled_y) * 1024.0;
|
||||
let kx = std::f64::consts::FRAC_1_PI;
|
||||
let ky = 0.367_879_4_f64;
|
||||
|
||||
let px = ((p.x as f64) + seed_x) * kx + ky;
|
||||
let py = ((p.y as f64) + seed_y) * ky + kx;
|
||||
let val = px * py * (px + py);
|
||||
let f_val = val - val.floor();
|
||||
|
||||
let rx = -1.0 + 2.0 * ((16.0 * kx * f_val) - (16.0 * kx * f_val).floor());
|
||||
let ry = -1.0 + 2.0 * ((16.0 * ky * f_val) - (16.0 * ky * f_val).floor());
|
||||
Vec2::new(rx as f32, ry as f32)
|
||||
}
|
||||
|
||||
fn splitmix64(mut x: u64) -> u64 {
|
||||
x = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
x ^ (x >> 31)
|
||||
}
|
||||
|
||||
fn u64_to_unit_f64(value: u64) -> f64 {
|
||||
const SCALE: f64 = 1.0 / (u64::MAX as f64);
|
||||
(value as f64) * SCALE
|
||||
}
|
||||
|
||||
fn noised(p: Vec2, random_seed: u64) -> (f32, Vec2) {
|
||||
let i = Vec2::new(p.x.floor(), p.y.floor());
|
||||
let f = Vec2::new(p.x - i.x, p.y - i.y);
|
||||
|
||||
let u = Vec2::new(
|
||||
f.x * f.x * f.x * (f.x * (f.x * 6.0 - 15.0) + 10.0),
|
||||
f.y * f.y * f.y * (f.y * (f.y * 6.0 - 15.0) + 10.0),
|
||||
);
|
||||
let du = Vec2::new(
|
||||
30.0 * f.x * f.x * (f.x * (f.x - 2.0) + 1.0),
|
||||
30.0 * f.y * f.y * (f.y * (f.y - 2.0) + 1.0),
|
||||
);
|
||||
|
||||
let ga = hash22(i + Vec2::new(0.0, 0.0), random_seed);
|
||||
let gb = hash22(i + Vec2::new(1.0, 0.0), random_seed);
|
||||
let gc = hash22(i + Vec2::new(0.0, 1.0), random_seed);
|
||||
let gd = hash22(i + Vec2::new(1.0, 1.0), random_seed);
|
||||
|
||||
let va = ga.dot(f - Vec2::new(0.0, 0.0));
|
||||
let vb = gb.dot(f - Vec2::new(1.0, 0.0));
|
||||
let vc = gc.dot(f - Vec2::new(0.0, 1.0));
|
||||
let vd = gd.dot(f - Vec2::new(1.0, 1.0));
|
||||
|
||||
let val = va + u.x * (vb - va) + u.y * (vc - va) + u.x * u.y * (va - vb - vc + vd);
|
||||
|
||||
let deriv_x = ga.x
|
||||
+ u.x * (gb.x - ga.x)
|
||||
+ u.y * (gc.x - ga.x)
|
||||
+ u.x * u.y * (ga.x - gb.x - gc.x + gd.x)
|
||||
+ du.x * (u.y * (va - vb - vc + vd) + (vb - va));
|
||||
let deriv_y = ga.y
|
||||
+ u.x * (gb.y - ga.y)
|
||||
+ u.y * (gc.y - ga.y)
|
||||
+ u.x * u.y * (ga.y - gb.y - gc.y + gd.y)
|
||||
+ du.y * (u.x * (va - vb - vc + vd) + (vc - va));
|
||||
|
||||
(val, Vec2::new(deriv_x, deriv_y))
|
||||
}
|
||||
|
||||
fn fractal_noise(
|
||||
p: Vec2,
|
||||
freq: f32,
|
||||
octaves: usize,
|
||||
lacunarity: f32,
|
||||
gain: f32,
|
||||
random_seed: u64,
|
||||
) -> (f32, Vec2) {
|
||||
let mut val = 0.0;
|
||||
let mut deriv = Vec2::default();
|
||||
let mut nf = freq;
|
||||
let mut na = 1.0;
|
||||
for _ in 0..octaves {
|
||||
let (v, d) = noised(p * nf, random_seed);
|
||||
val += v * na;
|
||||
deriv += d * (na * nf);
|
||||
na *= gain;
|
||||
nf *= lacunarity;
|
||||
}
|
||||
(val, deriv)
|
||||
}
|
||||
|
||||
fn phacelle_noise(
|
||||
p: Vec2,
|
||||
norm_dir: Vec2,
|
||||
freq: f32,
|
||||
offset: f32,
|
||||
normalization: f32,
|
||||
random_seed: u64,
|
||||
) -> (Vec2, Vec2) {
|
||||
let side_dir = Vec2::new(-norm_dir.y, norm_dir.x) * (freq * TAU);
|
||||
let offset_tau = offset * TAU;
|
||||
|
||||
let p_int = Vec2::new(p.x.floor(), p.y.floor());
|
||||
let p_frac = p - p_int;
|
||||
|
||||
let mut phase_dir = Vec2::default();
|
||||
let mut weight_sum = 0.0;
|
||||
|
||||
for i in -1..3 {
|
||||
for j in -1..3 {
|
||||
let grid_offset = Vec2::new(i as f32, j as f32);
|
||||
let grid_point = p_int + grid_offset;
|
||||
let random_offset = hash22(grid_point, random_seed) * 0.5;
|
||||
let vector_from_cell_point = p_frac - grid_offset - random_offset;
|
||||
let sqr_dist = vector_from_cell_point.dot(vector_from_cell_point);
|
||||
|
||||
let mut weight = (-sqr_dist * 2.0).exp();
|
||||
weight = weight.max(0.0) - 0.01111;
|
||||
weight = weight.max(0.0);
|
||||
weight_sum += weight;
|
||||
|
||||
let wave_input = vector_from_cell_point.dot(side_dir) + offset_tau;
|
||||
phase_dir.x += wave_input.cos() * weight;
|
||||
phase_dir.y += wave_input.sin() * weight;
|
||||
}
|
||||
}
|
||||
|
||||
if weight_sum < 1e-6 {
|
||||
return (Vec2::default(), side_dir);
|
||||
}
|
||||
|
||||
let interpolated = phase_dir * (1.0 / weight_sum);
|
||||
let magnitude = interpolated
|
||||
.dot(interpolated)
|
||||
.sqrt()
|
||||
.max(1.0 - normalization);
|
||||
(interpolated * (1.0 / magnitude), side_dir)
|
||||
}
|
||||
|
||||
fn pow_inv(t: f32, power: f32) -> f32 {
|
||||
1.0 - (1.0 - clamp01(t)).powf(power)
|
||||
}
|
||||
|
||||
fn ease_out(t: f32) -> f32 {
|
||||
let v = 1.0 - clamp01(t);
|
||||
1.0 - v * v
|
||||
}
|
||||
|
||||
fn smooth_start(t: f32, smoothing: f32) -> f32 {
|
||||
if t >= smoothing {
|
||||
t - 0.5 * smoothing
|
||||
} else {
|
||||
0.5 * t * t / smoothing
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate(params: &GenerationParams) -> GeneratedImages {
|
||||
let width = params.image_width;
|
||||
let height = params.image_height;
|
||||
let scale = params.erosion_scale;
|
||||
let strength_base = params.erosion_strength * scale;
|
||||
|
||||
let mut heightmap = vec![0.0_f32; width * height];
|
||||
heightmap
|
||||
.par_chunks_mut(width)
|
||||
.enumerate()
|
||||
.for_each(|(y, row)| {
|
||||
for (x, value) in row.iter_mut().enumerate() {
|
||||
let p = Vec2::new(x as f32 / width as f32, y as f32 / height as f32)
|
||||
* params.generation_scale;
|
||||
|
||||
let height_freq = 3.0;
|
||||
let height_amp = 0.125;
|
||||
let (val, deriv) = fractal_noise(p, height_freq, 3, 2.0, 0.1, params.random_seed);
|
||||
|
||||
let n_height = val * height_amp + 0.5;
|
||||
let curr_slope = deriv * height_amp;
|
||||
|
||||
let mut fade_target = clamp((n_height - 0.5) / (height_amp * 0.6), -1.0, 1.0);
|
||||
let mut freq = 1.0 / (scale * EROSION_CELL_SCALE);
|
||||
let slope_length = curr_slope.length().max(1e-10);
|
||||
|
||||
let rounding_for_input = mix(
|
||||
EROSION_ROUNDING[1],
|
||||
EROSION_ROUNDING[0],
|
||||
clamp01(fade_target + 0.5),
|
||||
) * EROSION_ROUNDING[2];
|
||||
let mut combi_mask = ease_out(smooth_start(
|
||||
slope_length * EROSION_ONSET[0],
|
||||
rounding_for_input * EROSION_ONSET[0],
|
||||
));
|
||||
|
||||
let mut gully_slope = mix2(
|
||||
curr_slope,
|
||||
curr_slope * (EROSION_ASSUMED_SLOPE[0] / slope_length),
|
||||
EROSION_ASSUMED_SLOPE[1],
|
||||
);
|
||||
|
||||
let mut strength = strength_base;
|
||||
let mut rounding_mult = 1.0;
|
||||
let mut total_h_delta = 0.0;
|
||||
let mut total_strength = 0.0;
|
||||
|
||||
for _ in 0..params.erosion_octaves {
|
||||
let (phacelle_vec, side_dir) = phacelle_noise(
|
||||
p * freq,
|
||||
gully_slope.normalize_safe(),
|
||||
EROSION_CELL_SCALE,
|
||||
0.25,
|
||||
EROSION_NORMALIZATION,
|
||||
params.random_seed,
|
||||
);
|
||||
|
||||
let p_deriv_dir = side_dir * -freq;
|
||||
let sloping = phacelle_vec.y.abs();
|
||||
gully_slope += p_deriv_dir
|
||||
* phacelle_vec.y.signum()
|
||||
* strength
|
||||
* params.erosion_gully_weight;
|
||||
|
||||
let gullies_h = phacelle_vec.x;
|
||||
let faded_gullies_h = mix(
|
||||
fade_target,
|
||||
gullies_h * params.erosion_gully_weight,
|
||||
combi_mask,
|
||||
);
|
||||
total_h_delta += faded_gullies_h * strength;
|
||||
total_strength += strength;
|
||||
fade_target = faded_gullies_h;
|
||||
|
||||
let rounding_for_octave = mix(
|
||||
EROSION_ROUNDING[1],
|
||||
EROSION_ROUNDING[0],
|
||||
clamp01(phacelle_vec.x + 0.5),
|
||||
) * rounding_mult;
|
||||
let new_mask = ease_out(smooth_start(
|
||||
sloping * EROSION_ONSET[1],
|
||||
rounding_for_octave * EROSION_ONSET[1],
|
||||
));
|
||||
combi_mask = pow_inv(combi_mask, params.erosion_detail) * new_mask;
|
||||
strength *= EROSION_GAIN;
|
||||
freq *= EROSION_LACUNARITY;
|
||||
rounding_mult *= EROSION_ROUNDING[3];
|
||||
}
|
||||
|
||||
let terrain_height_offset = [-0.65, 0.0];
|
||||
let final_fade_target = clamp((n_height - 0.5) / (height_amp * 0.6), -1.0, 1.0);
|
||||
let offset = mix(
|
||||
terrain_height_offset[0],
|
||||
-final_fade_target,
|
||||
terrain_height_offset[1],
|
||||
) * total_strength;
|
||||
|
||||
*value = n_height + total_h_delta + offset;
|
||||
}
|
||||
});
|
||||
|
||||
let heightmap_normalized = normalize_values(&heightmap);
|
||||
let bumpmap = apply_shading(&heightmap, width, height, 0.5);
|
||||
let heightmap_image = grayscale_image_from_values(&heightmap_normalized, width, height);
|
||||
let bumpmap_image = grayscale_image_from_values(&bumpmap, width, height);
|
||||
let terrain_layers = build_terrain_layers(
|
||||
&heightmap_normalized,
|
||||
width,
|
||||
height,
|
||||
params.snowline_height,
|
||||
params.water_table_height,
|
||||
params.rock_slope_angle_degrees,
|
||||
);
|
||||
let terrain_composite_image = build_soft_light_composite(
|
||||
&terrain_layers.terrain_color_image,
|
||||
&bumpmap_image,
|
||||
&heightmap_image,
|
||||
&terrain_layers.water_mask_image,
|
||||
);
|
||||
|
||||
GeneratedImages {
|
||||
width,
|
||||
height,
|
||||
heightmap_image,
|
||||
bumpmap_image,
|
||||
terrain_color_image: terrain_layers.terrain_color_image,
|
||||
terrain_composite_image,
|
||||
grass_mask_image: terrain_layers.grass_mask_image,
|
||||
water_mask_image: terrain_layers.water_mask_image,
|
||||
rock_mask_image: terrain_layers.rock_mask_image,
|
||||
snow_mask_image: terrain_layers.snow_mask_image,
|
||||
}
|
||||
}
|
||||
|
||||
struct TerrainLayers {
|
||||
terrain_color_image: RgbaImage,
|
||||
grass_mask_image: GrayImage,
|
||||
water_mask_image: GrayImage,
|
||||
rock_mask_image: GrayImage,
|
||||
snow_mask_image: GrayImage,
|
||||
}
|
||||
|
||||
fn normalize_values(values: &[f32]) -> Vec<f32> {
|
||||
let mut min_val = f32::INFINITY;
|
||||
let mut max_val = f32::NEG_INFINITY;
|
||||
for value in values {
|
||||
min_val = min_val.min(*value);
|
||||
max_val = max_val.max(*value);
|
||||
}
|
||||
|
||||
if (max_val - min_val).abs() < 1e-10 {
|
||||
return vec![0.0; values.len()];
|
||||
}
|
||||
|
||||
values
|
||||
.iter()
|
||||
.map(|value| (value - min_val) / (max_val - min_val))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn grayscale_image_from_values(values: &[f32], width: usize, height: usize) -> GrayImage {
|
||||
let mut image = GrayImage::new(width as u32, height as u32);
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let value = values[y * width + x].clamp(0.0, 1.0);
|
||||
image.put_pixel(x as u32, y as u32, Luma([(value * 255.0).round() as u8]));
|
||||
}
|
||||
}
|
||||
image
|
||||
}
|
||||
|
||||
fn build_terrain_layers(
|
||||
heightmap: &[f32],
|
||||
width: usize,
|
||||
height: usize,
|
||||
snowline_height: u8,
|
||||
water_table_height: u8,
|
||||
rock_slope_angle_degrees: f32,
|
||||
) -> TerrainLayers {
|
||||
let mut terrain_color_image = RgbaImage::new(width as u32, height as u32);
|
||||
let mut grass_mask_image = GrayImage::new(width as u32, height as u32);
|
||||
let mut water_mask_image = GrayImage::new(width as u32, height as u32);
|
||||
let mut rock_mask_image = GrayImage::new(width as u32, height as u32);
|
||||
let mut snow_mask_image = GrayImage::new(width as u32, height as u32);
|
||||
|
||||
let low_grass_color = [78, 146, 64];
|
||||
let high_grass_color = [150, 156, 88];
|
||||
let water_color = Rgba([40, 70, 150, 255]);
|
||||
let sand_color = [210, 195, 145];
|
||||
let rock_color = Rgba([122, 112, 98, 255]);
|
||||
let snow_color = Rgba([255, 250, 250, 255]);
|
||||
let slope_threshold_radians = rock_slope_angle_degrees.clamp(0.0, 89.9).to_radians();
|
||||
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let idx = y * width + x;
|
||||
let height_value = heightmap[idx].clamp(0.0, 1.0);
|
||||
let u8_height = (height_value * 255.0).round() as u8;
|
||||
|
||||
let left = sample_height(heightmap, width, height, x.saturating_sub(1), y);
|
||||
let right = sample_height(heightmap, width, height, (x + 1).min(width - 1), y);
|
||||
let up = sample_height(heightmap, width, height, x, y.saturating_sub(1));
|
||||
let down = sample_height(heightmap, width, height, x, (y + 1).min(height - 1));
|
||||
|
||||
let dx = (right - left) * 0.5 * width as f32;
|
||||
let dy = (down - up) * 0.5 * height as f32;
|
||||
let slope_angle = dx.hypot(dy).atan();
|
||||
|
||||
let grass_t = clamp01((height_value - 0.08) / 0.52);
|
||||
let grass_color = [
|
||||
mix_u8(low_grass_color[0], high_grass_color[0], grass_t),
|
||||
mix_u8(low_grass_color[1], high_grass_color[1], grass_t),
|
||||
mix_u8(low_grass_color[2], high_grass_color[2], grass_t),
|
||||
];
|
||||
let is_water = if water_table_height == 0 {
|
||||
false
|
||||
} else {
|
||||
u8_height < water_table_height
|
||||
};
|
||||
|
||||
let sand_width = 4.0;
|
||||
let sand_t = if water_table_height == 0 || is_water {
|
||||
0.0
|
||||
} else {
|
||||
let diff = (u8_height - water_table_height) as f32;
|
||||
(1.0 - (diff / sand_width)).clamp(0.0, 1.0)
|
||||
};
|
||||
|
||||
let base_color = Rgba([
|
||||
mix_u8(grass_color[0], sand_color[0], sand_t),
|
||||
mix_u8(grass_color[1], sand_color[1], sand_t),
|
||||
mix_u8(grass_color[2], sand_color[2], sand_t),
|
||||
255,
|
||||
]);
|
||||
|
||||
let is_snow = if snowline_height == 0 {
|
||||
true
|
||||
} else if snowline_height == u8::MAX {
|
||||
false
|
||||
} else {
|
||||
u8_height > snowline_height
|
||||
};
|
||||
let is_rock = slope_angle >= slope_threshold_radians;
|
||||
|
||||
grass_mask_image.put_pixel(x as u32, y as u32, Luma([255]));
|
||||
water_mask_image.put_pixel(x as u32, y as u32, Luma([if is_water { 255 } else { 0 }]));
|
||||
rock_mask_image.put_pixel(x as u32, y as u32, Luma([if is_rock { 255 } else { 0 }]));
|
||||
snow_mask_image.put_pixel(x as u32, y as u32, Luma([if is_snow { 255 } else { 0 }]));
|
||||
|
||||
let color = if is_water {
|
||||
water_color
|
||||
} else if is_snow {
|
||||
snow_color
|
||||
} else if is_rock {
|
||||
rock_color
|
||||
} else {
|
||||
base_color
|
||||
};
|
||||
|
||||
terrain_color_image.put_pixel(x as u32, y as u32, color);
|
||||
}
|
||||
}
|
||||
|
||||
TerrainLayers {
|
||||
terrain_color_image,
|
||||
grass_mask_image,
|
||||
water_mask_image,
|
||||
rock_mask_image,
|
||||
snow_mask_image,
|
||||
}
|
||||
}
|
||||
|
||||
fn build_soft_light_composite(
|
||||
color_image: &RgbaImage,
|
||||
bumpmap_image: &GrayImage,
|
||||
heightmap_image: &GrayImage,
|
||||
water_mask_image: &GrayImage,
|
||||
) -> RgbaImage {
|
||||
let mut composite = RgbaImage::new(color_image.width(), color_image.height());
|
||||
|
||||
for y in 0..color_image.height() {
|
||||
for x in 0..color_image.width() {
|
||||
let base = color_image.get_pixel(x, y).0;
|
||||
let is_water = water_mask_image.get_pixel(x, y).0[0] > 0;
|
||||
|
||||
let blend = if is_water {
|
||||
heightmap_image.get_pixel(x, y).0[0] as f32 / 255.0
|
||||
} else {
|
||||
bumpmap_image.get_pixel(x, y).0[0] as f32 / 255.0
|
||||
};
|
||||
|
||||
let r = soft_light_channel(base[0] as f32 / 255.0, blend);
|
||||
let g = soft_light_channel(base[1] as f32 / 255.0, blend);
|
||||
let b = soft_light_channel(base[2] as f32 / 255.0, blend);
|
||||
|
||||
composite.put_pixel(
|
||||
x,
|
||||
y,
|
||||
Rgba([
|
||||
(r * 255.0).round() as u8,
|
||||
(g * 255.0).round() as u8,
|
||||
(b * 255.0).round() as u8,
|
||||
base[3],
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
composite
|
||||
}
|
||||
|
||||
fn soft_light_channel(base: f32, blend: f32) -> f32 {
|
||||
let base = clamp01(base);
|
||||
let blend = clamp01(blend);
|
||||
let result = if blend <= 0.5 {
|
||||
base - (1.0 - 2.0 * blend) * base * (1.0 - base)
|
||||
} else {
|
||||
let d = if base <= 0.25 {
|
||||
((16.0 * base - 12.0) * base + 4.0) * base
|
||||
} else {
|
||||
base.sqrt()
|
||||
};
|
||||
base + (2.0 * blend - 1.0) * (d - base)
|
||||
};
|
||||
clamp01(result)
|
||||
}
|
||||
|
||||
fn apply_shading(heightmap: &[f32], width: usize, height: usize, strength: f32) -> Vec<f32> {
|
||||
let mut output = vec![0.0; width * height];
|
||||
|
||||
let lx = -1.0_f32;
|
||||
let ly = -1.0_f32;
|
||||
let lz = 1.0_f32;
|
||||
let l_len = (lx * lx + ly * ly + lz * lz).sqrt();
|
||||
let (lx, ly, lz) = (lx / l_len, ly / l_len, lz / l_len);
|
||||
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let left = sample_height(heightmap, width, height, x.saturating_sub(1), y);
|
||||
let right = sample_height(heightmap, width, height, (x + 1).min(width - 1), y);
|
||||
let up = sample_height(heightmap, width, height, x, y.saturating_sub(1));
|
||||
let down = sample_height(heightmap, width, height, x, (y + 1).min(height - 1));
|
||||
|
||||
let mut dx = (right - left) * 0.5 * strength;
|
||||
let mut dy = (down - up) * 0.5 * strength;
|
||||
dx *= width as f32;
|
||||
dy *= height as f32;
|
||||
|
||||
let n_len = (dx * dx + dy * dy + 1.0).sqrt();
|
||||
let nx = -dx / n_len;
|
||||
let ny = -dy / n_len;
|
||||
let nz = 1.0 / n_len;
|
||||
let dot = nx * lx + ny * ly + nz * lz;
|
||||
output[y * width + x] = dot.clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
output
|
||||
}
|
||||
|
||||
fn sample_height(heightmap: &[f32], width: usize, _height: usize, x: usize, y: usize) -> f32 {
|
||||
heightmap[y * width + x]
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
#![windows_subsystem = "windows"]
|
||||
|
||||
mod app;
|
||||
mod generator;
|
||||
|
||||
use app::TerrainApp;
|
||||
|
||||
fn main() -> eframe::Result<()> {
|
||||
let options = eframe::NativeOptions {
|
||||
viewport: eframe::egui::ViewportBuilder::default()
|
||||
.with_inner_size([1400.0, 900.0])
|
||||
.with_min_inner_size([1000.0, 720.0])
|
||||
.with_title("Advanced Erosion Terrain Generator"),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
eframe::run_native(
|
||||
"Advanced Erosion Terrain Generator",
|
||||
options,
|
||||
Box::new(|cc| Ok(Box::new(TerrainApp::new(cc)))),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
.basic-aura-highlighting {
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.basic-aura-highlighting__header {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.basic-aura-highlighting__add {
|
||||
flex: 0 0 auto;
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.basic-aura-highlighting__list {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
max-height: 480px;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
padding-right: 0.5rem;
|
||||
}
|
||||
|
||||
.basic-aura-highlighting__aura {
|
||||
border: 1px solid var(--color-border-light-tertiary);
|
||||
border-radius: 4px;
|
||||
margin: 0;
|
||||
padding: 0.75rem;
|
||||
}
|
||||
|
||||
.basic-aura-highlighting__aura legend {
|
||||
padding: 0 0.25rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.basic-aura-highlighting__delete {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.basic-aura-highlighting__empty[hidden] {
|
||||
display: none;
|
||||
}
|
||||
Reference in New Issue
Block a user