Compare commits

..

12 Commits

Author SHA1 Message Date
dfsek 414d5dae3b implement RegistryArgument 2021-09-06 15:52:42 -07:00
dfsek d8377915d7 remove DoubleArgumentParser 2021-09-06 14:38:54 -07:00
dfsek a0b4841bf9 make cloud "api" dependency 2021-09-06 14:38:46 -07:00
dfsek 814d3fe7c2 remove command exceptions 2021-09-06 14:35:03 -07:00
dfsek f71fbeda84 remove CommandManager 2021-09-06 14:34:12 -07:00
dfsek 3bd78b9658 remove BukkitCommandAdapter 2021-09-06 14:34:01 -07:00
dfsek b398febee3 remove CommandUtil 2021-09-06 14:33:41 -07:00
dfsek 5e0775850a remove TerraCommandManager 2021-09-06 14:33:22 -07:00
dfsek c9f19937c9 fabric cloud impl 2021-09-06 14:31:40 -07:00
dfsek bdb486188e bukkit commandregistrationevent 2021-09-06 13:50:43 -07:00
dfsek 320a7595f6 create CommandRegistrationEvent 2021-09-06 13:40:46 -07:00
dfsek 0706a4d0b7 depend on Cloud API 2021-09-06 13:34:53 -07:00
1459 changed files with 26539 additions and 43684 deletions
+7 -7
View File
@@ -8,7 +8,7 @@ indent_style = space
insert_final_newline = false
max_line_length = 140
tab_width = 4
ij_continuation_indent_size = 4
ij_continuation_indent_size = 8
ij_formatter_off_tag = @formatter:off
ij_formatter_on_tag = @formatter:on
ij_formatter_tags_enabled = false
@@ -25,12 +25,12 @@ ij_java_align_multiline_annotation_parameters = true
ij_java_align_multiline_array_initializer_expression = true
ij_java_align_multiline_assignment = true
ij_java_align_multiline_binary_operation = true
ij_java_align_multiline_chained_methods = false
ij_java_align_multiline_chained_methods = true
ij_java_align_multiline_extends_list = true
ij_java_align_multiline_for = true
ij_java_align_multiline_method_parentheses = false
ij_java_align_multiline_method_parentheses = true
ij_java_align_multiline_parameters = true
ij_java_align_multiline_parameters_in_calls = false
ij_java_align_multiline_parameters_in_calls = true
ij_java_align_multiline_parenthesized_expression = true
ij_java_align_multiline_records = true
ij_java_align_multiline_resources = true
@@ -127,7 +127,7 @@ ij_java_keep_blank_lines_in_declarations = 2
ij_java_keep_builder_methods_indents = true
ij_java_keep_control_statement_in_one_line = true
ij_java_keep_first_column_comment = false
ij_java_keep_indents_on_empty_lines = false
ij_java_keep_indents_on_empty_lines = true
ij_java_keep_line_breaks = true
ij_java_keep_multiple_expressions_in_one_line = false
ij_java_keep_simple_blocks_in_one_line = true
@@ -577,14 +577,14 @@ ij_properties_keep_blank_lines = false
ij_properties_key_value_delimiter = equals
ij_properties_spaces_around_key_value_delimiter = false
[{*.yml, *.yaml}]
[{*.yaml, *.yml}]
indent_size = 2
ij_visual_guides = none
ij_yaml_align_values_properties = do_not_align
ij_yaml_autoinsert_sequence_marker = true
ij_yaml_block_mapping_on_new_line = false
ij_yaml_indent_sequence_value = true
ij_yaml_keep_indents_on_empty_lines = false
ij_yaml_keep_indents_on_empty_lines = true
ij_yaml_keep_line_breaks = true
ij_yaml_sequence_on_new_line = false
ij_yaml_space_before_colon = false
+12 -7
View File
@@ -1,14 +1,19 @@
# Global owners, automatically request review when pull request is submitted
* @dfsek @solonovamax @duplexsystem @astrsh @justaureus
* @dfsek @solonovamax
# Platforms
/platforms/ @dfsek @solonovamax @duplexsystem @justaureus
/platforms/bukkit @dfsek @solonovamax @duplexsystem @justaureus @OakLoaf
## dfsek wrote the majority of the platform impls
/platforms/bukkit/ @dfsek
/platforms/fabric/ @dfsek
/platforms/forge/ @dfsek
/platforms/sponge/ @dfsek
## solonovamax is working on the region generator (unless duplexsystem takes it over)
/platforms/region/ @solonovamax
# Common
/common/ @dfsek @solonovamax @duplexsystem @astrsh
/common/ @dfsek @solonovamax
# Gradle Stuff
/buildSrc/ @dfsek @solonovamax @duplexsystem
*.gradle.kts @dfsek @solonovamax @duplexsystem
/gradle/ @dfsek @solonovamax @duplexsystem
## Most gradle stuff was written by solonovamax
/buildSrc/ @solonovamax
*.gradle.kts @solonovamax
+11 -14
View File
@@ -37,13 +37,10 @@ assignees: ""
-->
- [ ] I have checked that I am on the latest version of Terra.
- [ ] I have searched the github issue tracker for similar issues, including
closed ones.
- [ ] I have made sure that this is not a bug with another mod or plugin, and it
is Terra that is causing the issue.
- [ ] I have checked that this is an issue with Terra and not an issue with the
pack I am using.
<!-- If this is an issue with the default Terra pack, please open an issue on the pack repo: https://github.com/PolyhedralDev/TerraOverworldConfig/issues/new -->
- [ ] I have searched the github issue tracker for similar issues, including closed ones.
- [ ] I have made sure that this is not a bug with another mod or plugin, and it is Terra that is causing the issue.
- [ ] I have checked that this is an issue with Terra and not an issue with the pack I am using.
<!-- If this is an issue with the default Terra pack, please open an issue on the pack repo: https://github.com/PolyhedralDev/TerraDefaultConfig/issues/new -->
- [ ] I have attached a copy of the `latest.log` file
- [ ] I have filled out and provided all the appropriate information.
@@ -51,13 +48,13 @@ assignees: ""
<!-- You can fill out the different items by putting the correct value beside each cell. -->
| Name | Value |
|------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Terra Version | <!-- Put your Terra version here. (remove the comment) -->
| Platform / Platform Version | <!-- Put your platform and platform version here. (remove the comment) (eg. Spigot, Fabric, Paper, etc.) (If you are using the Region generator, put that here instead) -->
| Any External Plugins or Mods | <!-- Put a list of all the plugins or mods you have installed here. (remove the comment) (Make sure to NOT include any new lines) -->
| Terra Packs In Use | <!-- Put a list of all the Terra packs you have installed here. (remove the comment) (Make sure to NOT include any new lines) (/te packs may be used to get a list) -->
| Terra Addons In Use | <!-- Put a list of all the Terra addons you have installed here. (remove the comment) (Make sure to NOT include any new lines) (/te addons may be used to get a list) -->
| Name | Value |
|------------------------------|-------|
| Terra Version | <!-- Put your Terra version here. (remove the comment) -->
| Platform / Platform Version | <!-- Put your platform and platform version here. (remove the comment) (eg. Spigot, Fabric, Paper, etc.) (If you are using the Region generator, put that here instead) -->
| Any External Plugins or Mods | <!-- Put a list of all the plugins or mods you have installed here. (remove the comment) (Make sure to NOT include any new lines) -->
| Terra Packs In Use | <!-- Put a list of all the Terra packs you have installed here. (remove the comment) (Make sure to NOT include any new lines) (/te packs may be used to get a list) -->
| Terra Addons In Use | <!-- Put a list of all the Terra addons you have installed here. (remove the comment) (Make sure to NOT include any new lines) (/te addons may be used to get a list) -->
## Issue Description
+2 -4
View File
@@ -31,11 +31,9 @@ assignees: ""
-->
- [ ] I have checked that I am on the latest version of Terra.
- [ ] I have searched github for similar features requests, including closed
ones, and found none.
- [ ] I have searched github for similar features requests, including closed ones, and found none.
- [ ] I believe this is within the scope of Terra.
- [ ] This feature request is for *all* of Terra, and isn't something that
should be implemented by a pack or addon.
- [ ] This feature request is for *all* of Terra, and isn't something that should be implemented by a pack or addon.
## Feature Description
+1 -2
View File
@@ -1,7 +1,6 @@
---
name: "Other Issue"
about: "Use this template if your issue doesn't accurately fit into any of the
other categories."
about: "Use this template if your issue doesn't accurately fit into any of the other categories."
title: ""
labels: "Type: Question, Status: Pending"
assignees: ""
+79 -69
View File
@@ -1,19 +1,56 @@
# Pull Request
## Description
## Brief description.
<!-- Include a description of the PR here -->
<!-- Please provide a brief description of the goals of your PR -->
<!--
If applicable, include 'Fixes #XXXX' or 'Closes #XXXX' for any related open issues.
This helps us relate, track, and close the relevant issues.
###########################################################################
## WARNING! ##
## IGNORING THE FOLLOWING TEMPLATE WILL RESULT IN YOUR PR BEING CLOSED ##
###########################################################################
-->
<!--
Please go through this checklist item by item and make sure you have successfully completed each of these steps.
- Your pull request MUST be either on the latest version of Terra, or on a branch for a future release.
- Make sure that there are no already existing PRs that fix this. If so, it will be closed as a duplicate.
- Make sure that this change is actually within the scope of Terra and is something a terrain generator should be doing.
- Make sure that this is not an issue with a specific Terra *pack*, and instead applies to all of Terra.
- Make sure that you have filled out all the required information and given descriptions of everything.
-->
<!-- You can erase any parts of this template not applicable to your Pull Request. -->
### What Issues Does This Fix?
<!--
Put Fix #XXXX or Closes #XXXX here if there are any open issues that this PR fixes.
This is to automatically close the relevant issues.
You may remove this if there is no issue for this PR.
But unless this is a very small change, you should make an issue for it.
-->
### Changelog
## Licensing
<!-- In order to be accepted, your changes must be under the GPLv3 license. Please check one of the following: -->
- [ ] I am the original author of this code, and I am willing to release it under [GPLv3](https://www.gnu.org/licenses/gpl-3.0.en.html).
- [ ] I am not the original author of this code, but it is in public domain or released
under [GPLv3](https://www.gnu.org/licenses/gpl-3.0.en.html) or a compatible license.
<!--
Please provide reliable evidence of this.
NOTE: for compatible licenses, you must make sure to add the included license somewhere in the program, if so required.
(And even if it's not required, it's still nice to do it. Also add attribution somewhere.)
-->
## Goal of the PR
<!--
Fill out a changelog below of what has been done, and what might be planned to be done.
You may delete this if your PR is not adding new features, only fixing bugs or adding translations.
What is the goal of the PR?
Put a checklist here of what has been done
(and what *hasn't*, but you plan to do),
so we can easily know what was changed.
Note: this is only required for PRs that add new features.
If your PR is not adding new features, only fixing bugs or adding translations, then you may delete this section.
-->
- [ ] <!-- First thing -->
@@ -22,58 +59,45 @@ You may delete this if your PR is not adding new features, only fixing bugs or a
- [ ] <!-- Second thing -->
- [ ] <!-- etc. -->
## Checklist
## Affects of the PR
<!--
Select the options below that apply.
You must put an x in all the boxes that it applies to. (Like this: [x])
<!---
What types of changes does your code introduce? (Select any that apply. You may select multiple.)
You must put an x in all the boxes that it applies to. (Like this: [x])
-->
#### Mandatory checks
- [ ] The base branch of this PR is an unreleased version branch (that has a `ver/` prefix)
or is a branch that is intended to be merged into a version branch.
<!--
This is not applicable if the PR is a version branch itself.
PRs for new versions should use the `master` branch instead.
-->
- [ ] There are no already existing PRs that provide the same changes.
<!-- If this is not applicable, the PR will be removed as a duplicate. -->
- [ ] The PR is within the scope of Terra (i.e. is something a configurable terrain generator should be doing).
- [ ] Changes follow the code style for this project.
<!-- There is an included `.editorconfig` file in the base of the repo. Please use a plugin for your IDE of choice that follows those settings. -->
- [ ] I have read the [`CONTRIBUTING.md`](https://github.com/PolyhedralDev/Terra/blob/master/CONTRIBUTING.md)
document in the root of the git repository.
#### Types of changes
- [ ] Bug Fix <!-- Changes include bug fixes. -->
- [ ] Build system <!-- Changes the build system. -->
- [ ] Documentation <!-- Changes add to or improve documentation. -->
- [ ] New Feature <!-- Changes add new functionality to Terra. -->
- [ ] Performance <!-- Changes improve the performance of Terra. -->
- [ ] Refactoring <!-- Changes do not add any new code, only moves code around. -->
- [ ] Repository <!-- Changes affect the repository. E.g. changes to the `README.md` file. -->
- [ ] Revert <!-- Changes revert previous commits. -->
- [ ] Style <!-- Changes update style, namely the .editorconfig file. -->
- [ ] Tests <!-- Changes add or update tests. -->
- [ ] Translation <!-- Changes include translations to other languages for Terra. -->
- [ ] Bug Fix <!-- Anything which fixes an issue in Terra. -->
- [ ] Build system <!-- Anything which pretain to the build system. -->
- [ ] Documentation <!-- Anything which adds or improves documentation for existing features. -->
- [ ] New Feature <!-- Anything which adds new functionality to Terra. -->
- [ ] Performance <!-- Anything which is imrpoves the performance of Terra. -->
- [ ] Refactoring <!-- Anything which does not add any new code, only moves code around. -->
- [ ] Repository <!-- Anything which affects the repository. Eg. changes to the `README.md` file. -->
- [ ] Revert <!-- Anything which reverts previous commits. -->
- [ ] Style <!-- Anything which updates style. -->
- [ ] Tests <!-- Anything which adds or updates tests. -->
- [ ] Translation <!-- Anything which is internationalizing the Terra program to other languages. -->
#### Compatibility
#### Compatiblity
<!-- The following options determine if the PR pertains to a major, minor, or patch version bump -->
- [ ] Breaking change <!-- A fix, or a feature, that breaks some previous functionality to Terra. -->
- [ ] Non-Breaking change.
<!--
A change which does not break *any* previous functionality of Terra.
(ie. is backwards compatible and will work with *any* previously existing supported features.
Note: if a feature is annotated with @Incubating, @Preview, @Experimental,
or is in a package called something similar to the previous annotations,
then you may push breaking changes to only THOSE parts of Terra.)
-->
- [ ] Introduces a breaking change
<!--
Breaking changes are any fix or feature that breaks some previous functionality to Terra / is not backwards compatible.
Breaking changes do not include:
- changes that are backwards compatible and will work with *any* previously existing supported features.
- changes to code marked as in a pre-release
state (annotated with @Incubating, @Preview, @Experimental
or in a package called something similar to the previous annotations)
-->
- [ ] Introduces new functionality in a backwards compatible way.
- [ ] Introduces bug fixes
#### Contribution Guidelines.
- [ ] I have read the [`CONTRIBUTING.md`](https://github.com/PolyhedralDev/Terra/blob/master/CONTRIBUTING.md) document in the root of the
git repository.
- [ ] My code follows the code style for this
project. <!-- There is an included `.editorconfig` file in the base of the repo. Please use a plugin for your IDE of choice that follows those settings. -->
#### Documentation
@@ -84,21 +108,7 @@ You must put an x in all the boxes that it applies to. (Like this: [x])
- [ ] I have added tests to cover my changes.
- [ ] All new and existing tests passed.
<!--
Tests are typically not necessary for small changes.
Including *some* testing is recommended for large changes where applicable.
-->
#### Licensing
<!-- In order to be accepted, your changes must be under the GPLv3 license. Please check one of the following: -->
- [ ] I am the original author of this code, and I am willing to
release it under [GPLv3](https://www.gnu.org/licenses/gpl-3.0.en.html).
- [ ] I am not the original author of this code, but it is in public domain or
released under [GPLv3](https://www.gnu.org/licenses/gpl-3.0.en.html) or a compatible license.
<!--
Please provide reliable evidence of this.
NOTE: for compatible licenses, you must make sure to add the included license somewhere in the program, if so required.
(And even if it's not required, it's still nice to do it. Also add attribution somewhere.)
-->
<!--
If it only introduces small changes, you don't need to add tests.
But if you add big changes, you should probably at least write *some* testing, where applicable.
-->
-47
View File
@@ -1,47 +0,0 @@
# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.
# This workflow will build a package using Gradle and then publish it to GitHub packages when a release is created
# For more information see: https://github.com/actions/setup-java/blob/main/docs/advanced-usage.md#Publishing-using-gradle
name: Gradle Build
on: [ pull_request ]
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4.2.2
- name: Set up JDK 21
uses: actions/setup-java@v4.7.1
with:
java-version: '21'
distribution: 'temurin'
server-id: github # Value of the distributionManagement/repository/id field of the pom.xml
settings-path: ${{ github.workspace }} # location for the settings.xml file
- uses: burrunan/gradle-cache-action@v3.0.1
name: Build Terra
with:
# Specifies arguments for Gradle execution
# If arguments is missing or empty, then Gradle is not executed
arguments: build
# arguments can be multi-line for better readability
# arguments: |
# --no-paralell
# build
# -x test
# Gradle version to use for execution:
# wrapper (default), current, rc, nightly, release-nightly, or
# versions like 6.6 (see https://services.gradle.org/versions/all)
gradle-version: wrapper
# Properties are passed as -Pname=value
properties: |
kotlin.js.compiler=ir
kotlin.parallel.tasks.in.project=true
+10 -120
View File
@@ -65,8 +65,6 @@ hs_err_pid*
.idea/**/dictionaries
.idea/**/shelf
.idea/
# Generated files
.idea/**/contentModel.xml
@@ -129,125 +127,17 @@ fabric.properties
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Windows template
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
# Ignore Gradle build output directory
build
/target/
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
### macOS template
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### Linux template
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### Application
# Archive love files
*.log.gz
# binary files
*.bin
# Database files
*.db
# Cache files
*.meta
*.data
### JEnv template
# JEnv local Java version configuration file
.java-version
# Used by previous versions of JEnv
.jenv-version
### VisualStudioCode template
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
### NetBeans template
**/nbproject/private/
**/nbproject/Makefile-*.mk
**/nbproject/Package-*.bash
build/
nbbuild/
dist/
nbdist/
.nb-gradle/
###
**/target/
.idea/sonarlint/**
.idea/codeStyles/**
.idea/**.xml
.idea/modules/**.iml
!lib/*.jar
/run/
idea/**
**/testDir/
platforms/**/run/**
#Vale Config File
**/.vale.ini
testDir/
+38 -18
View File
@@ -27,8 +27,8 @@ for everyone. We do not tolerate harassment of participants in any form.
## When and How to Use These Guidelines
This code of conduct applies to all Terra community spaces, both online and off.
This applies to the github discussion tab, the
[Polyhedral Development community discord server](https://discord.gg/PXUEbbF),
This applies to the github discussion tab, the
[Polyhedral Development community discord server](https://discord.gg/PXUEbbF),
and any other Terra community. In addition, we may choose to invoke them in
instances of harassment outside the Terra communities, and we will punish the
responsible individuals appropriately. We will not tolerate harassment in any
@@ -58,8 +58,8 @@ listen carefully, apologize sincerely, and correct the behavior going forward.
Any member of the Terra community should always be open to new ideas and must
always be open to the possibility of being wrong. Nobody can always be right,
and we are only human; we are
[fallible](https://www.merriam-webster.com/dictionary/fallible) by nature. It is
okay to make mistakes, but we must be willing to admit when we make one.
[fallible](https://www.merriam-webster.com/dictionary/fallible) by nature.
It is okay to make mistakes, but we must be willing to admit when we make one.
### Be Direct but Professional
@@ -315,15 +315,19 @@ Terra has a global moderation team which is currently comprised of the following
members:
- solonovamax
- discord: [@solonovamax#6983](https://discord.com/channels/@me/566146322273402881)*
-
discord: [@solonovamax#6983](https://discord.com/channels/@me/566146322273402881)*
- github: [@solonovamax](https://github.com/solonovamax)
- email: [solonovamax@12oclockpoint.com](mailto:solonovamax@12oclockpoint.com)
-
email: [solonovamax@12oclockpoint.com](mailto:solonovamax@12oclockpoint.com)
- dfsek
- discord: [@dfsek#4208](https://discord.com/channels/@me/378350362236682240)*
-
discord: [@dfsek#4208](https://discord.com/channels/@me/378350362236682240)*
- github: [@dfsek](https://github.com/dfsek)
- email: [dfsek@protonmail.com](mailto:dfsek@protonmail.com)
- duplex (duplexsystem)
- discord: [@Duplex#0797](https://discord.com/channels/@me/356822848641171456)*
-
discord: [@Duplex#0797](https://discord.com/channels/@me/356822848641171456)*
- github: [@duplexsystem](https://github.com/duplexsystem)
- email: [duplexsys@protonmail.com](mailto:duplexsys@protonmail.com)
@@ -397,17 +401,32 @@ issue on this github repo, or contact a member of the global moderation team.
## License and Attribution
This set of guidelines is distributed under a
[Creative Commons Attribution-ShareAlike license](https://creativecommons.org/licenses/by-sa/3.0/).
[Creative Commons Attribution-ShareAlike license](https://creativecommons.org/licenses/by-sa/3.0/)
.
These guidelines have been adapted with modifications from the following sources:
These guidelines have been adapted from
[Mozilla's Community Participation Guidelines](https://www.mozilla.org/en-US/about/governance/policies/participation/)
, which were adapted from:
- [Mozilla's Community Participation Guidelines](https://www.mozilla.org/en-US/about/governance/policies/participation/)
- Mozilla's original Community Participation Guidelines
- The [Ubuntu Code of Conduct](https://ubuntu.com/community/code-of-conduct)
- Mozilla's [View Source Conference Code of Conduct](https://viewsourceconf.org/berlin-2016/code-of-conduct/)
- The [Rust Language Code of Conduct](https://www.rust-lang.org/policies/code-of-conduct)
- The [Stumptown Syndicate's Citizen Code of Conduct](http://citizencodeofconduct.org/)
- The [LGBTQ in Technology Code of Conduct](https://lgbtq.technology/coc.html)
- The [WisCon code of conduct](http://wiscon.net/policies/anti-harassment/code-of-conduct/)
-
Mozilla's [View Source Conference Code of Conduct](https://viewsourceconf.org/berlin-2016/code-of-conduct/)
- And
the [Rust Language Code of Conduct](https://www.rust-lang.org/policies/code-of-conduct)
which in turn were based
on [Stumptown Syndicate's Citizen Code of Conduct](http://citizencodeofconduct.org/)
, along with some adapted text from
the [LGBTQ in Technology Code of Conduct](https://lgbtq.technology/coc.html) and
the [WisCon code of conduct](http://wiscon.net/policies/anti-harassment/code-of-conduct/)
.
It was then modified by solonovamax with various inclusions from
the [LGBTQ in Technology Code of Conduct](https://lgbtq.technology/coc.html) and
a few other sources.
## Notes
@@ -424,6 +443,7 @@ people are not comfortable
using [neopronouns](https://www.mypronouns.org/neopronouns). But if someone
refuses to use your more common pronouns, you should report them to us.
Additionally, you may not ask people to use unreasonable pronouns, such as '
acab/acabself', 'that/bitch', 'ur/mom', or anything else that may be considered
disrectful. Doing so will be considered mockery of individuals who use
acab/acabself', 'that/bitch', 'ur/mom', or
'dream/dreamself' (pronouns related to real people, eg. the minecraft youtuber '
dreamwastaken'). Doing so will be considered mockery of individuals who use
non-standard pronouns and is very disrespectful.
+11 -15
View File
@@ -63,8 +63,7 @@ to [Terra global moderation team](CODE_OF_CONDUCT.md#Reporting).
## I don't want to read this whole thing I just have a question!!!
> **Note:** Please don't file an issue to ask a question. You'll get faster
> results by using the resources below.
> **Note:** Please don't file an issue to ask a question. You'll get faster results by using the resources below.
We have an official discord server where you can request help from various users
@@ -78,9 +77,9 @@ Unsure where to begin contributing to Terra? You can start by looking through "
beginner" and "help wanted" issues:
- [Beginner issues](https://github.com/PolyhedralDev/Terra/labels/Note%3A%20Good%20First%20Issue)
- issues which should be friendly to anyone new to terra.
- issues which should be friendly to anyone new to terra.
- [Help wanted issues](https://github.com/PolyhedralDev/Terra/labels/Note%3A%20Help%20Wanted)
- issues which should be a bit more involved than "beginner" issues.
- issues which should be a bit more involved than "beginner" issues.
New to github? Working on your first Pull Request? Check
out [How to Contribute to an Open Source Project on GitHub](https://app.egghead.io/playlists/how-to-contribute-to-an-open-source-project-on-github)
@@ -104,9 +103,7 @@ you don't need to create one. When you are creating a bug report,
please [include as many details as possible](#how-do-i-submit-a-good-bug-report)
.
> **Note:** If you find a **Closed** issue that seems like it is the same thing
> that you're experiencing, open a new issue and include a link to the original
> issue in the body of your new one.
> **Note:** If you find a **Closed** issue that seems like it is the same thing that you're experiencing, open a new issue and include a link to the original issue in the body of your new one.
#### Before Submitting A Bug Report
@@ -117,9 +114,9 @@ please [include as many details as possible](#how-do-i-submit-a-good-bug-report)
- Make sure that this is not a *specific* compatibility issue with another
terrain generation mod. Do not request *specific* compatibility with mods or
plugins (e.g. "Compatibility with TechCraft v7"). That should be implemented
in an addon, **not** in the platform project.
in an addon, **not** in the main project.
*General* compatibility (e.g. "Ability to pull Vanilla/Modded features from
parent biomes") will be considered in the platform project.
parent biomes") will be considered in the main project.
- Search for
any [already existing issues](https://github.com/PolyhedralDev/Terra/issues?q=is%3Aissue+)
open with your problem. If you open a duplicate, it will be closed as such.
@@ -203,7 +200,7 @@ please [include as many details as possible](#how-do-i-submit-a-good-enhancement
Enhancement suggestions are tracked
as [GitHub issues](https://guides.github.com/features/issues/). Create an issue
on our platform repository and provide the following information:
on our main repository and provide the following information:
- **Use a clear and descriptive title** for the issue to identify the
suggestion.
@@ -246,7 +243,7 @@ accepted.
Pull Requests are tracked
as [GitHub Pull Requests](https://guides.github.com/activities/forking/#making-a-pull-request)
. Create a pr on our platform repository and provide the following information:
. Create a pr on our main repository and provide the following information:
- **Use a clear and descriptive title** to identify the pull request.
- **State what this pull request adds/fixes**.
@@ -350,7 +347,7 @@ TODO
#### General Compatibility
General compatibility (example: injection of Vanilla structures/features/carvers
into packs) is acceptable in the platform project.
into packs) is acceptable in the main project.
- General compatibility features should be *disabled by default*. Having things
auto-injected causes unpredictable behaviour that is annoying to diagnose.
@@ -368,9 +365,8 @@ into packs) is acceptable in the platform project.
#### Specific Compatibility
Specific compatibility should *not* be put in the platform project. (Example:
Adding the ability to generate TechCraft v7's doo-dads with a TerraScript
function)
Specific compatibility should *not* be put in the main project. (Example: Adding
the ability to generate TechCraft v7's doo-dads with a TerraScript function)
Having specific compatibilities leads to tons of extra dependencies to keep
track of, as well as adding lots of additional stuff to maintain. It quickly
Vendored
-149
View File
@@ -1,149 +0,0 @@
pipeline {
agent any
tools {
jdk "Temurin Java 21"
}
triggers {
githubPush()
}
environment {
DISCORD_WEBHOOK_URL = credentials('polydev-discord-webhook-url')
}
stages {
stage('Checkout') {
steps {
scmSkip(deleteBuild: true)
}
}
stage('Setup Gradle') {
steps {
sh 'chmod +x gradlew'
}
}
stage('Build') {
steps {
withGradle {
sh './gradlew build --rerun-tasks -x check'
sh './gradlew javadoc'
}
}
post {
success {
archiveArtifacts artifacts: 'platforms/fabric/build/libs/Terra-fabric*.jar,platforms/bukkit/build/libs/Terra-bukkit*-shaded.jar,platforms/allay/build/libs/Terra-allay*.jar,platforms/minestom/build/libs/Terra-minestom*.jar', fingerprint: true, onlyIfSuccessful: true
javadoc javadocDir: 'common/api/build/docs/javadoc', keepAll: true
}
}
}
stage('Tests') {
steps {
withGradle {
sh './gradlew test --rerun-tasks'
}
}
}
// stage('Deploy to snapshots repositories') {
// when {
// allOf {
// not { buildingTag() }
// not { expression { env.TAG_NAME != null && env.TAG_NAME.matches('v\\d+\\.\\d+\\.\\d+') } }
// }
// }
//
// steps {
// withCredentials([
// string(credentialsId: 'maven-signing-key', variable: 'ORG_GRADLE_PROJECT_signingKey'),
// string(credentialsId: 'maven-signing-key-password', variable: 'ORG_GRADLE_PROJECT_signingPassword'),
// usernamePassword(
// credentialsId: 'solo-studios-maven',
// passwordVariable: 'ORG_GRADLE_PROJECT_SoloStudiosSnapshotsPassword',
// usernameVariable: 'ORG_GRADLE_PROJECT_SoloStudiosSnapshotsUsername'
// )
// ]) {
// withGradle {
// sh './gradlew publishAllPublicationsToSoloStudiosSnapshotsRepository'
// }
// }
// }
// }
stage('Deploy to releases repositories') {
// when {
// allOf {
// buildingTag()
// expression { env.TAG_NAME != null && env.TAG_NAME.matches('v\\d+\\.\\d+\\.\\d+') }
// }
// }
steps {
withCredentials([
string(credentialsId: 'maven-signing-key', variable: 'ORG_GRADLE_PROJECT_signingKey'),
string(credentialsId: 'maven-signing-key-password', variable: 'ORG_GRADLE_PROJECT_signingPassword'),
usernamePassword(
credentialsId: 'solo-studios-maven',
passwordVariable: 'ORG_GRADLE_PROJECT_SoloStudiosReleasesPassword',
usernameVariable: 'ORG_GRADLE_PROJECT_SoloStudiosReleasesUsername'
),
// TODO: does not yet exist (uncomment once added)
// usernamePassword(
// credentialsId: 'sonatype-maven-credentials',
// passwordVariable: 'ORG_GRADLE_PROJECT_SonatypePassword',
// usernameVariable: 'ORG_GRADLE_PROJECT_SonatypeUsername'
// ),
// usernamePassword(
// credentialsId: 'codemc-maven-credentials',
// passwordVariable: 'ORG_GRADLE_PROJECT_CodeMCPassword',
// usernameVariable: 'ORG_GRADLE_PROJECT_CodeMCUsername'
// )
]) {
withGradle {
sh './gradlew publish'
//sh './gradlew publishAllPublicationsToSoloStudiosReleasesRepository'
// sh './gradlew publishAllPublicationsToSonatypeRepository'
// sh './gradlew publishAllPublicationsToCodeMCRepository'
}
}
}
}
}
post {
always {
discoverReferenceBuild()
// junit testResults: '**/build/test-results/*/TEST-*.xml'
recordIssues(
aggregatingResults: true,
enabledForFailure: true,
minimumSeverity: 'ERROR',
sourceCodeEncoding: 'UTF-8',
checksAnnotationScope: 'ALL',
sourceCodeRetention: 'LAST_BUILD',
tools: [java(), javaDoc()]
)
discordSend(
title: env.JOB_NAME + ' ' + env.BUILD_DISPLAY_NAME,
showChangeset: true,
enableArtifactsList: true,
link: env.BUILD_URL,
result: currentBuild.currentResult,
customAvatarUrl: 'https://github.com/PolyhedralDev.png',
customUsername: 'Solo Studios Jenkins',
webhookURL: env.DISCORD_WEBHOOK_URL,
)
cleanWs()
}
}
}
+670 -17
View File
@@ -1,21 +1,674 @@
MIT License
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (c) 2020-2025 Polyhedral Development
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
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:
Preamble
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
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.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+14 -57
View File
@@ -1,30 +1,15 @@
<img align="left" width="64" height="64" src="https://raw.githubusercontent.com/wiki/PolyhedralDev/Terra/images/terra_logo.png" alt="Terra Logo">
# Terra
Terra is a modern world generation modding platform, primarily for Minecraft.
Terra allows complete customization of world generation with an advanced API,
tightly integrated with a powerful configuration system.
Terra consists of several parts:
* A voxel world generation API with emphasis on configuration and extensibility
* Several platform implementations, the layer between the API and the platform
it's running on.
* An addon loader, which allows addons to interface with the Terra API in a
platform-agnostic setting
* Several "core addons," which implement the "default" configurations of Terra.
These addons can be thought of as the config "standard library"
Terra currently officially supports the Fabric mod loader and the Bukkit API
(Paper and friends). We welcome Pull Requests implementing additional platforms!
Terra is an incredibly powerful free & open-source data-driven,
platform-agnostic world generator. It allows you to create a world exactly to
your specifications, with no knowledge of Java required.
## Downloads:
* Fabric: [Modrinth](https://modrinth.com/mod/terra)
/ [CurseForge](https://www.curseforge.com/minecraft/mc-mods/terra-world-generator)
* Paper+ servers (Paper, Tuinity, Purpur,
etc): [SpigotMC](https://www.spigotmc.org/resources/85151/)
* Fabric: [Modrinth](https://modrinth.com/mod/terra)
/ [CurseForge](https://www.curseforge.com/minecraft/mc-mods/terra-world-generator)
## Building and Running Terra
@@ -47,11 +32,19 @@ JARs are produced in `platforms/<platform>/build/libs`.
To run Minecraft with Terra in the IDE (for testing) use the following tasks:
* Bukkit
* `runServer` - Run the Paper test server with Terra installed.
* `installPaper` - Install a [Paper](https://github.com/PaperMC/Paper) test
server. (Only needs to be run once).
* `installPurpur` - Install a [Purpur](https://github.com/pl3xgaming/Purpur)
test server. (Only needs to be run once).
* `runPaper` - Run the Paper test server with Terra (`installPaper` must
have been run previously).
* `runPurpur` - Run the Purpur test server with Terra (`installPurpur` must
have been run previously).
* Fabric
* `runClient` - Run a Minecraft Fabric client with Terra installed.
* `runServer` - Run a Minecraft Fabric server with Terra installed.
## Contributing
Contributions are welcome! If you want to see a feature in Terra, please, open
@@ -59,43 +52,7 @@ an issue, or implement it yourself and submit a PR!
Join the discord [here](https://discord.gg/PXUEbbF) if you would like to talk
more about the project!
## Licensing
Parts of Terra are licensed under either the MIT License or the GNU General
Public License, version 3.0.
* Our API is licensed under the [MIT License](LICENSE), to ensure that everyone
is able to freely use it however they want.
* Our core addons are also licensed under the [MIT License](LICENSE), to ensure
that people can freely use code from them to learn and make their own addons,
without worrying about GPL infection.
* Our platform-agnostic implementations and platform implementations are
licensed under
the [GNU General Public License, version 3.0](common/implementation/LICENSE),
to ensure that they remain free software wherever they are used.
If you're not sure which license a particular file is under, check:
* The file's header
* The LICENSE file in the closest parent folder of the file in question
## Beta
Terra is still in beta! While it is stable, it is not feature-complete. There is
a lot to be added!
## Special Thanks
[![YourKit-Logo](https://www.yourkit.com/images/yklogo.png)](https://www.yourkit.com/)
YourKit has granted Polyhedral Development an open-source license to their
outstanding Java profiler, allowing us to make our software as performant as it
can be!
YourKit supports open source projects with innovative and intelligent tools for
monitoring and profiling Java and .NET applications. YourKit is the creator of
the
[YourKit Java Profiler](https://www.yourkit.com/java/profiler/),
[YourKit .NET Profiler](https://www.yourkit.com/.net/profiler/),
and [YourKit YouMonitor](https://www.yourkit.com/youmonitor/).
+29 -36
View File
@@ -1,60 +1,53 @@
preRelease(true)
versionProjects(":common:api", version("7.0.0"))
versionProjects(":common:implementation", version("7.0.0"))
versionProjects(":platforms", version("7.0.0"))
import com.dfsek.terra.configureCompilation
import com.dfsek.terra.configureDependencies
import com.dfsek.terra.configureDistribution
import com.dfsek.terra.configurePublishing
import com.dfsek.terra.getGitHash
val versionObj = Version("6", "0", "0", true)
allprojects {
version = versionObj
group = "com.dfsek.terra"
configureCompilation()
configureDependencies()
configureCompilation()
configurePublishing()
tasks.withType<JavaCompile>().configureEach {
options.isFork = true
options.isIncremental = true
options.release.set(21)
}
tasks.withType<Test>().configureEach {
useJUnitPlatform()
maxHeapSize = "2G"
ignoreFailures = false
failFast = true
maxParallelForks = (Runtime.getRuntime().availableProcessors() - 1).takeIf { it > 0 } ?: 1
reports.html.required.set(false)
reports.junitXml.required.set(false)
}
tasks.withType<Copy>().configureEach {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
tasks.withType<Jar>().configureEach {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
}
afterEvaluate {
forImmediateSubProjects(":platforms") {
configureDistribution()
}
project(":platforms:bukkit:common").configureDistribution()
project(":platforms:minestom:example").configureDistribution()
forSubProjects(":common:addons") {
apply(plugin = "com.gradleup.shadow")
tasks.named("build") {
finalizedBy(tasks.named("shadowJar"))
}
dependencies {
"compileOnly"(project(":common:api"))
"testImplementation"(project(":common:api"))
}
project(":platforms").subprojects.forEach { // Platform projects are where distribution happens
it.configureDistribution()
}
}
/**
* Version class that does version stuff.
*/
@Suppress("MemberVisibilityCanBePrivate")
class Version(val major: String, val minor: String, val revision: String, val preRelease: Boolean = false) {
override fun toString(): String {
return if (!preRelease)
"$major.$minor.$revision"
else //Only use git hash if it's a prerelease.
"$major.$minor.$revision-BETA+${getGitHash()}"
}
}
+2 -20
View File
@@ -6,27 +6,9 @@ plugins {
repositories {
mavenCentral()
gradlePluginPortal()
maven("https://maven.solo-studios.ca/releases") {
name = "Solo Studios"
}
maven("https://maven.solo-studios.ca/snapshots") {
name = "Solo Studios"
}
maven("https://repo.codemc.org/repository/maven-public") {
name = "CodeMC"
}
maven("https://repo.papermc.io/repository/maven-public/") {
name = "PaperMC"
}
}
dependencies {
//TODO Allow pulling from Versions.kt
implementation("com.gradleup.shadow", "shadow-gradle-plugin", "8.3.9")
implementation("io.papermc.paperweight.userdev", "io.papermc.paperweight.userdev.gradle.plugin", "2.0.0-beta.18")
implementation("org.ow2.asm", "asm", "9.9")
implementation("org.ow2.asm", "asm-tree", "9.9")
implementation("com.dfsek.tectonic", "common", "4.3.1")
implementation("org.yaml", "snakeyaml", "2.5")
"implementation"("com.github.jengelman.gradle.plugins:shadow:+")
"implementation"("org.yaml:snakeyaml:1.27")
}
-47
View File
@@ -1,47 +0,0 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import java.io.File
import java.util.function.Predicate
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.kotlin.dsl.extra
import kotlin.streams.asStream
/**
* Configures a directory where addons will be put.
*/
fun Project.addonDir(dir: File, task: Task) {
val moveAddons = tasks.register("moveAddons" + task.name) {
dependsOn("compileAddons")
doLast {
dir.parentFile.mkdirs()
matchingAddons(dir) {
it.name.startsWith("Terra-") // Assume everything that starts with Terra- is a core addon.
}.forEach {
logger.info("Deleting old addon: " + it.absolutePath)
it.delete()
}
forSubProjects(":common:addons") {
val jar = tasks.named("shadowJar").get() as ShadowJar
val boot = if (extra.has("bootstrap") && extra.get("bootstrap") as Boolean) "bootstrap/" else ""
val target = File(dir, boot + jar.archiveFileName.get())
val base = "${jar.archiveBaseName.get()}-${version}"
logger.info("Copying addon ${jar.archiveFileName.get()} to ${target.absolutePath}. Base name: $base")
jar.archiveFile.orNull?.asFile?.copyTo(target)
}
}
}
task.dependsOn(moveAddons)
}
fun matchingAddons(dir: File, matcher: Predicate<File>): Set<File> {
val matching = HashSet<File>()
dir.walk().asStream().filter(matcher).forEach(matching::add)
return matching
}
@@ -1,73 +0,0 @@
import org.gradle.api.Project
import org.gradle.kotlin.dsl.creating
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.getValue
import org.gradle.kotlin.dsl.getting
import org.gradle.kotlin.dsl.maven
import org.gradle.kotlin.dsl.repositories
fun Project.configureDependencies() {
val testImplementation by configurations.getting
val compileOnly by configurations.getting
val api by configurations.getting
val implementation by configurations.getting
val shaded by configurations.creating
@Suppress("UNUSED_VARIABLE")
val shadedApi by configurations.creating {
shaded.extendsFrom(this)
api.extendsFrom(this)
}
@Suppress("UNUSED_VARIABLE")
val shadedImplementation by configurations.creating {
shaded.extendsFrom(this)
implementation.extendsFrom(this)
}
repositories {
mavenCentral()
gradlePluginPortal()
maven("https://maven.solo-studios.ca/releases") {
name = "Solo Studios"
}
maven("https://maven.solo-studios.ca/snapshots") {
name = "Solo Studios"
}
maven("https://maven.fabricmc.net/") {
name = "FabricMC"
}
maven("https://repo.codemc.org/repository/maven-public") {
name = "CodeMC"
}
maven("https://repo.papermc.io/repository/maven-public/") {
name = "PaperMC"
}
maven("https://files.minecraftforge.net/maven/") {
name = "Forge"
}
maven("https://maven.quiltmc.org/repository/release/") {
name = "Quilt"
}
maven("https://jitpack.io") {
name = "JitPack"
}
maven("https://s01.oss.sonatype.org/content/repositories/snapshots/") {
name = "Sonatype Snapshots"
}
maven("https://repo.onarandombox.com/multiverse-releases") {
name = "onarandombox"
}
}
dependencies {
testImplementation("org.junit.jupiter", "junit-jupiter", Versions.Libraries.Internal.junit)
"testRuntimeOnly"("org.junit.platform", "junit-platform-launcher")
compileOnly("org.jetbrains", "annotations", Versions.Libraries.Internal.jetBrainsAnnotations)
compileOnly("com.google.guava", "guava", Versions.Libraries.Internal.guava)
testImplementation("com.google.guava", "guava", Versions.Libraries.Internal.guava)
}
}
@@ -1,192 +0,0 @@
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import io.papermc.paperweight.util.path
import java.io.File
import java.io.FileWriter
import java.net.URL
import java.nio.file.FileSystems
import java.nio.file.Path
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.plugins.BasePluginExtension
import org.gradle.jvm.tasks.Jar
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.extra
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.named
import org.yaml.snakeyaml.DumperOptions
import org.yaml.snakeyaml.Yaml
import kotlin.io.path.copyTo
import kotlin.io.path.createDirectories
import kotlin.io.path.createFile
import kotlin.io.path.exists
private fun Project.installAddonsInto(dest: Path) {
FileSystems.newFileSystem(dest, mapOf("create" to "false"), null).use { fs ->
forSubProjects(":common:addons") {
val jar = getJarTask()
logger.info("Packaging addon ${jar.archiveFileName.get()} to $dest. size: ${jar.archiveFile.get().asFile.length() / 1024}KB")
val boot = if (extra.has("bootstrap") && extra.get("bootstrap") as Boolean) "bootstrap/" else ""
val addonPath = fs.getPath("/addons/$boot${jar.archiveFileName.get()}")
if (!addonPath.exists()) {
addonPath.parent.createDirectories()
addonPath.createFile()
jar.archiveFile.get().asFile.toPath().copyTo(addonPath, overwrite = true)
}
}
}
}
fun Project.configureDistribution() {
apply(plugin = "com.gradleup.shadow")
val downloadDefaultPacks = tasks.create("downloadDefaultPacks") {
group = "terra"
doFirst {
try {
file("${buildDir}/resources/main/packs/").deleteRecursively()
file("${buildDir}/resources/main/metapacks/").deleteRecursively()
val overworldPackUrl =
URL("https://github.com/PolyhedralDev/TerraOverworldConfig/releases/download/" + Versions.Terra.overworldConfig + "/Overworld.zip")
val reimagENDPackUrl =
URL("https://github.com/PolyhedralDev/ReimagEND/releases/download/" + Versions.Terra.reimagENDConfig + "/ReimagEND.zip")
val tartarusPackUrl =
URL("https://github.com/PolyhedralDev/Tartarus/releases/download/" + Versions.Terra.tartarusConfig + "/Tartarus.zip")
val defaultPackUrl =
URL("https://github.com/PolyhedralDev/DefaultMetapack/releases/download/" + Versions.Terra.defaultConfig + "/default.zip")
downloadPack(overworldPackUrl, project)
downloadPack(reimagENDPackUrl, project)
downloadPack(tartarusPackUrl, project)
downloadPack(defaultPackUrl, project, true)
} catch (_: Exception) {
}
}
}
val compileAddons = tasks.create("compileAddons") {
forSubProjects(":common:addons") {
afterEvaluate {
dependsOn(getJarTask())
}
}
}
val installAddons = tasks.create("installAddons") {
group = "terra"
dependsOn(compileAddons)
doLast {
// https://github.com/johnrengelman/shadow/issues/111
val dest = tasks.named<ShadowJar>("shadowJar").get().archiveFile.get().path
installAddonsInto(dest)
}
}
tasks.create("installAddonsIntoDefaultJar") {
group = "terra"
dependsOn(compileAddons)
doLast {
val dest = tasks.named<Jar>("jar").get().archiveFile.get().path
installAddonsInto(dest)
}
}
val generateResourceManifest = tasks.create("generateResourceManifest") {
group = "terra"
doLast {
val resources = HashMap<String, MutableList<String>>()
val packsDir = File("${project.buildDir}/resources/main/packs/")
packsDir.walkTopDown().forEach {
if (it.isDirectory || !it.name.endsWith(".zip")) return@forEach
resources.computeIfAbsent("packs") { ArrayList() }.add(it.name)
}
val metaPacksDir = File("${project.buildDir}/resources/main/metapacks/")
metaPacksDir.walkTopDown().forEach {
if (it.isDirectory || !it.name.endsWith(".zip")) return@forEach
resources.computeIfAbsent("metapacks") { ArrayList() }.add(it.name)
}
val langDir = File("${project(":common:implementation").buildDir}/resources/main/lang/")
langDir.walkTopDown().forEach {
if (it.isDirectory || !it.name.endsWith(".yml")) return@forEach
resources.computeIfAbsent("lang") { ArrayList() }.add(it.name)
}
forSubProjects(":common:addons") {
val jar = getJarTask().archiveFileName.get()
resources.computeIfAbsent(
if (extra.has("bootstrap") && extra.get("bootstrap") as Boolean) "addons/bootstrap"
else "addons"
) { ArrayList() }.add(jar)
}
val options = DumperOptions()
options.indent = 2
options.indentWithIndicator = true
options.indicatorIndent = 2
options.isPrettyFlow = true
options.defaultFlowStyle = DumperOptions.FlowStyle.BLOCK
options.defaultScalarStyle = DumperOptions.ScalarStyle.DOUBLE_QUOTED
val yaml = Yaml(options)
val manifest = File("${project.buildDir}/resources/main/resources.yml")
if (manifest.exists()) manifest.delete()
manifest.parentFile.mkdirs()
manifest.createNewFile()
FileWriter(manifest).use {
yaml.dump(resources, it)
}
}
}
tasks.named("processResources") {
generateResourceManifest.mustRunAfter(downloadDefaultPacks)
finalizedBy(downloadDefaultPacks)
finalizedBy(generateResourceManifest)
}
tasks.named<ShadowJar>("shadowJar") {
// Tell shadow to download the packs
dependsOn(downloadDefaultPacks)
configurations = listOf(project.configurations["shaded"])
archiveClassifier.set("shaded")
version = project.version
relocate("org.apache.commons", "com.dfsek.terra.lib.commons")
relocate("org.objectweb.asm", "com.dfsek.terra.lib.asm")
relocate("org.json", "com.dfsek.terra.lib.json")
relocate("org.yaml", "com.dfsek.terra.lib.yaml")
finalizedBy(installAddons)
}
configure<BasePluginExtension> {
archivesName.set(project.name)
}
tasks.named<DefaultTask>("build") {
dependsOn(tasks["shadowJar"])
}
}
fun downloadPack(packUrl: URL, project: Project, metapack: Boolean = false) {
val fileName = packUrl.file.substring(packUrl.file.lastIndexOf("/"))
val resourceType = if (metapack) "metapacks" else "packs"
val file = File("${project.buildDir}/resources/main/${resourceType}/${fileName}")
file.parentFile.mkdirs()
file.outputStream().write(packUrl.readBytes())
}
fun Project.getJarTask() = tasks.named("shadowJar").get() as ShadowJar
-56
View File
@@ -1,56 +0,0 @@
import java.io.ByteArrayOutputStream
import org.gradle.api.Action
import org.gradle.api.Project
var isPrerelease = false
fun Project.getGitHash(): String {
val stdout = ByteArrayOutputStream()
exec {
commandLine = mutableListOf("git", "rev-parse", "--short", "HEAD")
standardOutput = stdout
}
return stdout.toString().trim()
}
fun Project.gitClone(name: String) {
val stdout = ByteArrayOutputStream()
exec {
commandLine = mutableListOf("git", "clone", name)
standardOutput = stdout
}
}
fun Project.forSubProjects(project: String, action: Action<Project>) {
project(project).subprojects.forEach {
action.execute(it)
}
}
fun Project.forImmediateSubProjects(project: String, action: Action<Project>) {
project(project).childProjects.forEach {
action.execute(it.value)
}
}
fun preRelease(preRelease: Boolean) {
isPrerelease = preRelease
}
fun Project.versionProjects(project: String, version: String) {
forSubProjects(project) {
this.version = version
logger.info("Setting version of $path to $version")
}
project(project).version = version
logger.info("Setting version of $project to $version")
}
fun Project.version(version: String): String {
return if (!isPrerelease)
version
else //Only use git hash if it's a prerelease.
"$version-BETA+${getGitHash()}"
}
-101
View File
@@ -1,101 +0,0 @@
object Versions {
object Terra {
const val overworldConfig = "latest"
const val reimagENDConfig = "latest"
const val tartarusConfig = "latest"
const val defaultConfig = "latest"
}
object Libraries {
const val tectonic = "4.3.1"
const val paralithic = "2.0.1"
const val strata = "1.3.2"
const val seismic = "2.5.7"
const val cloud = "2.0.0"
const val caffeine = "3.2.2"
const val slf4j = "2.0.17"
object Internal {
const val shadow = "8.3.9"
const val apacheText = "1.14.0"
const val apacheIO = "2.20.0"
const val guava = "33.5.0-jre"
const val asm = "9.9"
const val snakeYml = "2.5"
const val jetBrainsAnnotations = "26.0.2-1"
const val junit = "6.0.0"
const val nbt = "6.1"
}
}
object Fabric {
const val fabricAPI = "0.134.1+${Mod.minecraft}"
const val cloud = "2.0.0-beta.13"
}
//
// object Quilt {
// const val quiltLoader = "0.20.2"
// const val fabricApi = "7.3.1+0.89.3-1.20.1"
// }
object Mod {
const val mixin = "0.16.4+mixin.0.8.7"
const val mixinExtras = "0.5.0"
const val minecraft = "1.21.10"
const val yarn = "$minecraft+build.1"
const val fabricLoader = "0.18.2"
const val architecuryLoom = "1.11.451"
const val architecturyPlugin = "3.4.162"
}
//
// object Forge {
// const val forge = "${Mod.minecraft}-48.0.13"
// const val burningwave = "12.63.0"
// }
object Bukkit {
const val minecraft = "1.21.10"
const val nms = "$minecraft-R0.1"
const val paperBuild = "$nms-20251012.013929-7"
const val paper = paperBuild
const val paperLib = "1.0.8"
const val reflectionRemapper = "0.1.3"
const val paperDevBundle = paperBuild
const val runPaper = "2.3.1"
const val paperWeight = "2.0.0-beta.19"
const val cloud = "2.0.0-beta.12"
const val multiverse = "5.3.0"
}
//
// object Sponge {
// const val sponge = "9.0.0-SNAPSHOT"
// const val mixin = "0.8.2"
// const val minecraft = "1.17.1"
// }
//
object CLI {
const val logback = "1.5.19"
const val picocli = "4.7.7"
}
object Allay {
const val api = "0.13.0"
const val gson = "2.13.2"
const val mappings = "15398c1"
const val mappingsGenerator = "8fa6058"
const val mcmeta = "e85a17c"
}
object Minestom {
const val minestom = "2025.10.04-1.21.8"
}
}
@@ -0,0 +1,41 @@
package com.dfsek.terra
import java.io.File
import java.util.function.Predicate
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.jvm.tasks.Jar
import kotlin.streams.asStream
/**
* Configures a directory where addons will be put.
*/
fun Project.addonDir(dir: File, task: Task) {
task.doFirst {
dir.parentFile.mkdirs()
matchingAddons(dir) {
it.name.startsWith("Terra-") // Assume everything that starts with Terra- is a core addon.
}.forEach {
println("Deleting old addon: " + it.absolutePath)
it.delete()
}
project(":common:addons").subprojects.forEach { addonProject ->
val jar = (addonProject.tasks.named("jar").get() as Jar)
val target = File(dir, jar.archiveFileName.get())
val base = "${jar.archiveBaseName.get()}-${project.version}"
println("Copying addon ${jar.archiveFileName.get()} to ${target.absolutePath}. Base name: $base")
jar.archiveFile.orNull?.asFile?.copyTo(target)
}
}
}
fun matchingAddons(dir: File, matcher: Predicate<File>): Set<File> {
val matching = HashSet<File>()
dir.walk().maxDepth(1).asStream().filter(matcher).forEach(matching::add)
return matching
}
@@ -0,0 +1,21 @@
package com.dfsek.terra
import java.io.ByteArrayOutputStream
import org.gradle.api.Project
fun Project.getGitHash(): String {
val stdout = ByteArrayOutputStream()
exec {
commandLine = mutableListOf("git", "rev-parse", "--short", "HEAD")
standardOutput = stdout
}
return stdout.toString().trim()
}
fun Project.gitClone(name: String) {
val stdout = ByteArrayOutputStream()
exec {
commandLine = mutableListOf("git", "clone", name)
standardOutput = stdout
}
}
@@ -1,5 +1,5 @@
import com.dfsek.terra.tectonicdoc.TectonicDocPlugin
import org.apache.tools.ant.filters.ReplaceTokens
package com.dfsek.terra
import org.gradle.api.JavaVersion
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginExtension
@@ -13,25 +13,16 @@ import org.gradle.kotlin.dsl.getByName
import org.gradle.kotlin.dsl.register
import org.gradle.kotlin.dsl.withType
import org.gradle.language.jvm.tasks.ProcessResources
import org.gradle.plugins.ide.idea.model.IdeaModel
fun Project.configureCompilation() {
apply(plugin = "maven-publish")
apply(plugin = "java")
apply(plugin = "java-library")
apply(plugin = "idea")
apply<TectonicDocPlugin>()
configure<IdeaModel> {
module {
isDownloadJavadoc = true
isDownloadSources = true
}
}
configure<JavaPluginExtension> {
sourceCompatibility = JavaVersion.VERSION_21
targetCompatibility = JavaVersion.VERSION_21
sourceCompatibility = JavaVersion.VERSION_16
targetCompatibility = JavaVersion.VERSION_16
}
tasks.withType<JavaCompile> {
@@ -43,26 +34,16 @@ fun Project.configureCompilation() {
tasks.withType<ProcessResources> {
include("**/*.*")
filter<ReplaceTokens>(
filter<org.apache.tools.ant.filters.ReplaceTokens>(
"tokens" to mapOf(
"DESCRIPTION" to properties["terra.description"],
"WIKI" to properties["terra.wiki"],
"SOURCE" to properties["terra.source"],
"ISSUES" to properties["terra.issues"],
"LICENSE" to properties["terra.license"]
"VERSION" to project.version.toString(),
"DESCRIPTION" to project.properties["terra.description"],
"WIKI" to project.properties["terra.wiki"],
"SOURCE" to project.properties["terra.source"],
"ISSUES" to project.properties["terra.issues"],
"LICENSE" to project.properties["terra.license"]
)
)
}
afterEvaluate {
tasks.withType<ProcessResources> {
include("**/*.*")
filter<ReplaceTokens>(
"tokens" to mapOf(
"VERSION" to version.toString()
)
)
}
)
}
tasks.withType<Javadoc> {
@@ -0,0 +1,48 @@
package com.dfsek.terra
import org.gradle.api.Project
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.dependencies
import org.gradle.kotlin.dsl.invoke
import org.gradle.kotlin.dsl.project
import org.gradle.kotlin.dsl.repositories
fun Project.configureDependencies() {
apply(plugin = "java")
apply(plugin = "java-library")
configurations {
val shaded = create("shaded")
val shadedApi = create("shadedApi")
shaded.extendsFrom(shadedApi)
getByName("api").extendsFrom(shadedApi)
val shadedImplementation = create("shadedImplementation")
shaded.extendsFrom(shadedImplementation)
getByName("implementation").extendsFrom(shadedImplementation)
}
repositories {
maven { url = uri("https://maven.enginehub.org/repo/") }
maven { url = uri("https://repo.codemc.org/repository/maven-public") }
maven { url = uri("https://papermc.io/repo/repository/maven-public/") }
maven { url = uri("https://maven.fabricmc.net/") }
gradlePluginPortal()
mavenCentral()
}
dependencies {
"testImplementation"("org.junit.jupiter:junit-jupiter-api:5.7.0")
"testImplementation"("org.junit.jupiter:junit-jupiter-engine:5.7.0")
"compileOnly"("org.jetbrains:annotations:20.1.0")
"compileOnly"("com.google.guava:guava:30.0-jre")
"testImplementation"("com.google.guava:guava:30.0-jre")
}
if (project(":common:addons").subprojects.contains(this)) { // If this is an addon project, depend on the API.
dependencies {
"compileOnly"(project(":common:api"))
"testImplementation"(project(":common:api"))
}
}
}
@@ -0,0 +1,144 @@
package com.dfsek.terra
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.FileWriter
import java.net.URL
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.plugins.BasePluginExtension
import org.gradle.jvm.tasks.Jar
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.get
import org.gradle.kotlin.dsl.named
import org.yaml.snakeyaml.DumperOptions
import org.yaml.snakeyaml.Yaml
fun Project.configureDistribution() {
apply(plugin = "com.github.johnrengelman.shadow")
val downloadDefaultPacks = tasks.create("downloadDefaultPacks") {
group = "terra"
doFirst {
file("${buildDir}/resources/main/packs/").deleteRecursively()
val defaultPackUrl = URL("https://github.com/PolyhedralDev/TerraDefaultConfig/releases/download/latest/default.zip")
downloadPack(defaultPackUrl, project)
val netherPackUrl = URL("https://github.com/PolyhedralDev/TerraDefaultConfig/releases/download/latest/nether.zip")
downloadPack(netherPackUrl, project)
}
}
val installAddons = tasks.create("installAddons") {
group = "terra"
project(":common:addons").subprojects.forEach {
it.afterEvaluate {
dependsOn(it.tasks.getByName("build")) // Depend on addon JARs
}
}
doFirst {
// The addons are copied into a JAR because of a ShadowJar bug
// which expands *all* JARs, even resource ones, into the fat JAR.
// To get around this, we copy all addon JARs into a *new* JAR,
// then, ShadowJar expands the newly created JAR, putting the original
// JARs where they should go.
//
// https://github.com/johnrengelman/shadow/issues/111
val dest = File(buildDir, "/resources/main/addons.jar")
dest.parentFile.mkdirs()
val zip = ZipOutputStream(FileOutputStream(dest))
project(":common:addons").subprojects.forEach { addonProject ->
val jar = (addonProject.tasks.named("jar").get() as Jar)
println("Packaging addon ${jar.archiveFileName.get()} to ${dest.absolutePath}.")
val entry = ZipEntry("addons/${jar.archiveFileName.get()}")
zip.putNextEntry(entry)
FileInputStream(jar.archiveFile.get().asFile).copyTo(zip)
zip.closeEntry()
}
zip.close()
}
}
val generateResourceManifest = tasks.create("generateResourceManifest") {
group = "terra"
dependsOn(downloadDefaultPacks)
dependsOn(installAddons)
doFirst {
val resources = HashMap<String, MutableList<String>>()
val packsDir = File("${project.buildDir}/resources/main/packs/")
packsDir.walkTopDown().forEach {
if (it.isDirectory || !it.name.endsWith(".zip")) return@forEach
resources.computeIfAbsent("packs") { ArrayList() }.add(it.name)
}
val langDir = File("${project(":common:implementation").buildDir}/resources/main/lang/")
langDir.walkTopDown().forEach {
if (it.isDirectory || !it.name.endsWith(".yml")) return@forEach
resources.computeIfAbsent("lang") { ArrayList() }.add(it.name)
}
project(":common:addons").subprojects.forEach { addonProject ->
val jar = (addonProject.tasks.named("jar").get() as Jar).archiveFileName.get()
resources.computeIfAbsent("addons") { ArrayList() }.add(jar)
}
val options = DumperOptions()
options.indent = 2
options.indentWithIndicator = true
options.indicatorIndent = 2
options.isPrettyFlow = true
options.defaultFlowStyle = DumperOptions.FlowStyle.BLOCK
options.defaultScalarStyle = DumperOptions.ScalarStyle.DOUBLE_QUOTED
val yaml = Yaml(options)
val manifest = File("${project.buildDir}/resources/main/resources.yml")
if (manifest.exists()) manifest.delete()
manifest.createNewFile()
yaml.dump(resources, FileWriter(manifest))
}
}
tasks["processResources"].dependsOn(generateResourceManifest)
tasks.named<ShadowJar>("shadowJar") {
// Tell shadow to download the packs
dependsOn(downloadDefaultPacks)
configurations = listOf(project.configurations["shaded"])
archiveClassifier.set("shaded")
setVersion(project.version)
relocate("org.apache.commons", "com.dfsek.terra.lib.commons")
relocate("org.objectweb.asm", "com.dfsek.terra.lib.asm")
relocate("org.json", "com.dfsek.terra.lib.json")
relocate("org.yaml", "com.dfsek.terra.lib.yaml")
}
configure<BasePluginExtension> {
archivesName.set(project.name)
}
tasks.named<DefaultTask>("build") {
dependsOn(tasks["shadowJar"])
}
}
fun downloadPack(packUrl: URL, project: Project) {
val fileName = packUrl.file.substring(packUrl.file.lastIndexOf("/"))
val file = File("${project.buildDir}/resources/main/packs/${fileName}")
file.parentFile.mkdirs()
file.outputStream().write(packUrl.readBytes())
}
@@ -1,3 +1,5 @@
package com.dfsek.terra
import org.gradle.api.Project
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
@@ -11,22 +13,22 @@ fun Project.configurePublishing() {
configure<PublishingExtension> {
publications {
create<MavenPublication>("mavenJava") {
from(components["java"])
artifact(tasks["sourcesJar"])
artifact(tasks["jar"])
}
}
repositories {
val mavenUrl = "https://maven.solo-studios.ca/releases/"
val mavenUrl = "https://repo.codemc.io/repository/maven-releases/"
//val mavenSnapshotUrl = "https://repo.codemc.io/repository/maven-snapshots/"
maven(mavenUrl) {
val SoloStudiosReleasesUsername: String? by project
val SoloStudiosReleasesPassword: String? by project
if (SoloStudiosReleasesUsername != null && SoloStudiosReleasesPassword != null) {
val mavenUsername: String? by project
val mavenPassword: String? by project
if (mavenUsername != null && mavenPassword != null) {
credentials {
username = SoloStudiosReleasesUsername
password = SoloStudiosReleasesPassword
username = mavenUsername
password = mavenPassword
}
}
}
@@ -1,20 +0,0 @@
package com.dfsek.terra.tectonicdoc
class DocumentedTemplate(private val name: String) {
private val template = HashMap<String, String>()
fun add(name: String, content: String) {
template[name] = content
}
fun format(): String {
val builder = StringBuilder("# ").append(name).append("\n\n")
template.forEach { name, content ->
builder
.append("### $name\n\n")
.append(content)
.append("\n\n")
}
return builder.toString()
}
}
@@ -1,150 +0,0 @@
package com.dfsek.terra.tectonicdoc
import com.dfsek.tectonic.api.config.template.annotations.Description
import com.dfsek.tectonic.api.config.template.annotations.Final
import com.dfsek.tectonic.api.config.template.annotations.Value
import java.io.File
import java.io.FileInputStream
import java.io.InputStream
import org.gradle.api.DefaultTask
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.tasks.TaskAction
import org.objectweb.asm.ClassReader
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.FieldNode
abstract class GenerateDocsTask : DefaultTask() {
@TaskAction
fun generateDocs() {
project.extensions.getByType(JavaPluginExtension::class.java).sourceSets.forEach { sources ->
val classes = HashMap<String, ClassNode>()
sources.java.classesDirectory.get().asFileTree.forEach { file ->
if (file.name.endsWith(".class")) {
val node = createClassNode(FileInputStream(file))
if (node.fields.stream().anyMatch { field ->
field.visibleAnnotations?.stream()?.anyMatch {
it.desc.equals(descriptor(Value::class.java.canonicalName))
} == true
}) {
var name = sources
.java
.classesDirectory
.get()
.asFile
.toPath()
.relativize(file.toPath())
.toString()
.substringBeforeLast('.')
if (name.endsWith("Template")) {
name = name.substringBeforeLast("Template")
}
classes[name] = node
}
}
}
val docsDir = File(project.buildDir, "tectonic")
docsDir.mkdirs()
classes.forEach { (name, clazz) ->
val template = DocumentedTemplate(name.substringAfterLast('/'))
clazz.fields
.stream()
.filter { field ->
field.visibleAnnotations?.stream()?.anyMatch {
it.desc.equals(descriptor(Value::class.java.canonicalName))
} == true
}.forEach { field ->
val annotations = field.visibleAnnotations
val description = StringBuilder()
annotations.stream().filter {
it.desc.equals(descriptor(Description::class.java.canonicalName))
}.forEach {
description.append(it.values[1])
}
val keyName = StringBuilder()
if (annotations.stream().anyMatch { it.desc.equals(descriptor(Final::class.java.canonicalName)) }) {
keyName.append("final ")
}
keyName.append(getType(field))
.append(" ")
annotations.stream().filter {
it.desc.equals(descriptor(Value::class.java.canonicalName))
}.forEach {
keyName.append(it.values[1])
}
template.add(keyName.toString(), description.toString().ifBlank {
logger.info("No description provided for field " + field.name + " in class " + name)
"*No description provided.*"
})
}
val save = File(docsDir, "$name.md")
if (save.exists()) save.delete()
save.parentFile.mkdirs()
save.createNewFile()
save.writeText(template.format())
}
}
}
private fun getType(node: FieldNode): String {
if (node.signature != null) {
return generic(node.signature)
}
return descriptorToHumanReadable(node.desc).substringAfterLast('.')
}
private fun generic(type: String): String {
val clean = descriptorToHumanReadable(type)
if (clean.contains('<')) {
val typeIndex = clean.indexOf('<')
return clean.substring(0, typeIndex + 1).substringAfterLast('.') + generic(clean.substring(typeIndex + 1)) + "\\>"
}
return clean.substringAfterLast('.')
}
private fun createClassNode(input: InputStream): ClassNode {
val reader = ClassReader(input)
val node = ClassNode()
try {
reader.accept(node, ClassReader.EXPAND_FRAMES)
} catch (e: Exception) {
reader.accept(node, ClassReader.SKIP_FRAMES or ClassReader.SKIP_DEBUG)
}
return node
}
private fun descriptorToHumanReadable(descriptor: String): String {
if (descriptor.startsWith('L')) {
return descriptor.substring(1).substringBeforeLast(';').replace('/', '.')
}
if (descriptor.startsWith("[")) {
return "${descriptorToHumanReadable(descriptor.substring(1))}[]"
}
return when (descriptor) {
"B" -> "byte"
"C" -> "char"
"I" -> "int"
"D" -> "double"
"F" -> "float"
"J" -> "long"
"S" -> "short"
"Z" -> "boolean"
else -> descriptor
}
}
private fun descriptor(name: String): String = "L${name.replace('.', '/')};"
}
@@ -1,10 +0,0 @@
package com.dfsek.terra.tectonicdoc
import org.gradle.api.Plugin
import org.gradle.api.Project
class TectonicDocPlugin : Plugin<Project> {
override fun apply(project: Project) {
project.tasks.create("generateDocs", GenerateDocsTask::class.java)
}
}
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2020-2025 Polyhedral Development
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:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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.
-3
View File
@@ -1,3 +0,0 @@
# api addon loader
Loads dependencies as addons
@@ -1,12 +0,0 @@
version = version("0.1.0")
dependencies {
}
tasks.withType<Jar> {
manifest {
attributes("Terra-Bootstrap-Addon-Entry-Point" to "com.dfsek.terra.addon.loader.ApiAddonLoader")
}
}
project.extra.set("bootstrap", true)
@@ -1,26 +0,0 @@
package com.dfsek.terra.addon.loader;
import ca.solostudios.strata.version.Version;
import com.dfsek.terra.api.addon.BaseAddon;
public class ApiAddon implements BaseAddon {
private final Version version;
private final String id;
public ApiAddon(Version version, String id) {
this.version = version;
this.id = id;
}
@Override
public Version version() {
return version;
}
@Override
public String getID() {
return id;
}
}
@@ -1,22 +0,0 @@
/*
* Copyright (c) 2020-2025 Polyhedral Development
*
* The Terra Core Addons are licensed under the terms of the MIT License. For more details,
* reference the LICENSE file in this module's root directory.
*/
package com.dfsek.terra.addon.loader;
import java.net.URL;
import java.net.URLClassLoader;
public class ApiAddonClassLoader extends URLClassLoader {
static {
ClassLoader.registerAsParallelCapable();
}
public ApiAddonClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
}
}
@@ -1,39 +0,0 @@
/*
* Copyright (c) 2020-2025 Polyhedral Development
*
* The Terra Core Addons are licensed under the terms of the MIT License. For more details,
* reference the LICENSE file in this module's root directory.
*/
package com.dfsek.terra.addon.loader;
import ca.solostudios.strata.Versions;
import ca.solostudios.strata.version.Version;
import java.nio.file.Path;
import java.util.Collections;
import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.addon.bootstrap.BootstrapAddonClassLoader;
import com.dfsek.terra.api.addon.bootstrap.BootstrapBaseAddon;
public class ApiAddonLoader implements BootstrapBaseAddon<BaseAddon> {
private static final Version VERSION = Versions.getVersion(1, 0, 0);
@Override
public Iterable<BaseAddon> loadAddons(Path addonsFolder, BootstrapAddonClassLoader parent) {
return Collections.emptySet();
}
@Override
public String getID() {
return "API";
}
@Override
public Version version() {
return VERSION;
}
}
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2020-2025 Polyhedral Development
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:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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,14 +0,0 @@
version = version("1.0.0")
dependencies {
api("commons-io", "commons-io", Versions.Libraries.Internal.apacheIO)
implementation("com.dfsek.tectonic", "yaml", Versions.Libraries.tectonic)
}
tasks.withType<Jar> {
manifest {
attributes("Terra-Bootstrap-Addon-Entry-Point" to "com.dfsek.terra.addons.manifest.impl.ManifestAddonLoader")
}
}
project.extra.set("bootstrap", true)
@@ -1,13 +0,0 @@
/*
* Copyright (c) 2020-2025 Polyhedral Development
*
* The Terra Core Addons are licensed under the terms of the MIT License. For more details,
* reference the LICENSE file in this module's root directory.
*/
package com.dfsek.terra.addons.manifest.api;
public interface AddonInitializer {
void initialize();
}
@@ -1,77 +0,0 @@
/*
* Copyright (c) 2020-2025 Polyhedral Development
*
* The Terra Core Addons are licensed under the terms of the MIT License. For more details,
* reference the LICENSE file in this module's root directory.
*/
package com.dfsek.terra.addons.manifest.impl;
import ca.solostudios.strata.version.Version;
import ca.solostudios.strata.version.VersionRange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
import com.dfsek.terra.addons.manifest.api.AddonInitializer;
import com.dfsek.terra.addons.manifest.impl.config.AddonManifest;
import com.dfsek.terra.api.Platform;
import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.inject.Injector;
import com.dfsek.terra.api.inject.annotations.Inject;
public class ManifestAddon implements BaseAddon {
private static final Logger logger = LoggerFactory.getLogger(ManifestAddon.class);
private final AddonManifest manifest;
private final List<AddonInitializer> initializers;
@Inject
private Platform platform;
public ManifestAddon(AddonManifest manifest, List<AddonInitializer> initializers) {
this.manifest = manifest;
this.initializers = initializers;
}
public AddonManifest getManifest() {
return manifest;
}
@Override
public String getID() {
return manifest.getID();
}
public void initialize() {
Injector<BaseAddon> addonInjector = Injector.get(this);
addonInjector.addExplicitTarget(BaseAddon.class);
Injector<Platform> platformInjector = Injector.get(platform);
platformInjector.addExplicitTarget(Platform.class);
logger.debug("Initializing addon {}", getID());
initializers.forEach(initializer -> {
Injector<Logger> loggerInjector = Injector.get(LoggerFactory.getLogger(initializer.getClass()));
loggerInjector.addExplicitTarget(Logger.class);
logger.debug("Invoking entry point {}", initializer.getClass());
addonInjector.inject(initializer);
platformInjector.inject(initializer);
loggerInjector.inject(initializer);
initializer.initialize();
});
}
@Override
public Map<String, VersionRange> dependencies() {
return manifest.getDependencies();
}
@Override
public Version version() {
return manifest.getVersion();
}
}
@@ -1,22 +0,0 @@
/*
* Copyright (c) 2020-2025 Polyhedral Development
*
* The Terra Core Addons are licensed under the terms of the MIT License. For more details,
* reference the LICENSE file in this module's root directory.
*/
package com.dfsek.terra.addons.manifest.impl;
import java.net.URL;
import java.net.URLClassLoader;
public class ManifestAddonClassLoader extends URLClassLoader {
static {
ClassLoader.registerAsParallelCapable();
}
public ManifestAddonClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
}
}
@@ -1,138 +0,0 @@
/*
* Copyright (c) 2020-2025 Polyhedral Development
*
* The Terra Core Addons are licensed under the terms of the MIT License. For more details,
* reference the LICENSE file in this module's root directory.
*/
package com.dfsek.terra.addons.manifest.impl;
import ca.solostudios.strata.Versions;
import ca.solostudios.strata.version.Version;
import ca.solostudios.strata.version.VersionRange;
import com.dfsek.tectonic.api.exception.LoadException;
import com.dfsek.tectonic.api.loader.ConfigLoader;
import com.dfsek.tectonic.yaml.YamlConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.dfsek.terra.addons.manifest.api.AddonInitializer;
import com.dfsek.terra.addons.manifest.impl.config.AddonManifest;
import com.dfsek.terra.addons.manifest.impl.config.WebsiteConfig;
import com.dfsek.terra.addons.manifest.impl.config.loaders.VersionLoader;
import com.dfsek.terra.addons.manifest.impl.config.loaders.VersionRangeLoader;
import com.dfsek.terra.addons.manifest.impl.exception.AddonException;
import com.dfsek.terra.addons.manifest.impl.exception.ManifestException;
import com.dfsek.terra.addons.manifest.impl.exception.ManifestNotPresentException;
import com.dfsek.terra.api.addon.bootstrap.BootstrapAddonClassLoader;
import com.dfsek.terra.api.addon.bootstrap.BootstrapBaseAddon;
public class ManifestAddonLoader implements BootstrapBaseAddon<ManifestAddon> {
private static final Logger logger = LoggerFactory.getLogger(ManifestAddonLoader.class);
private static final Version VERSION = Versions.getVersion(1, 0, 0);
private final ConfigLoader manifestLoader = new ConfigLoader()
.registerLoader(Version.class, new VersionLoader())
.registerLoader(VersionRange.class, new VersionRangeLoader())
.registerLoader(WebsiteConfig.class, WebsiteConfig::new);
public ManifestAddon loadAddon(Path addonPath, ClassLoader loader) {
try(JarFile jar = new JarFile(addonPath.toFile())) {
logger.debug("Loading addon from JAR {}", addonPath);
JarEntry manifestEntry = jar.getJarEntry("terra.addon.yml");
if(manifestEntry == null) {
throw new ManifestNotPresentException("Addon " + addonPath + " does not contain addon manifest.");
}
//noinspection NestedTryStatement
try {
AddonManifest manifest = manifestLoader.load(new AddonManifest(),
new YamlConfiguration(jar.getInputStream(manifestEntry),
"terra.addon.yml"));
logger.debug("Loading addon {}@{}", manifest.getID(), manifest.getVersion().getFormatted());
if(manifest.getSchemaVersion() != 1) {
throw new AddonException("Addon " + manifest.getID() + " has unknown schema version: " + manifest.getSchemaVersion());
}
List<AddonInitializer> initializers = manifest.getEntryPoints().stream().map(entryPoint -> {
try {
Object in = loader.loadClass(entryPoint).getConstructor().newInstance();
if(!(in instanceof AddonInitializer)) {
throw new AddonException(in.getClass() + " does not extend " + AddonInitializer.class);
}
return (AddonInitializer) in;
} catch(InvocationTargetException e) {
throw new AddonException("Exception occurred while instantiating addon", e);
} catch(NoSuchMethodException | IllegalAccessException | InstantiationException e) {
throw new AddonException(String.format("No valid default constructor found in entry point %s", entryPoint), e);
} catch(ClassNotFoundException e) {
throw new AddonException(String.format("Entry point %s not found in JAR.", entryPoint), e);
}
}).collect(Collectors.toList());
return new ManifestAddon(manifest, initializers);
} catch(LoadException e) {
throw new ManifestException("Failed to load addon manifest", e);
}
} catch(IOException e) {
throw new AddonException("Failed to load addon from JAR " + addonPath, e);
}
}
@Override
public Iterable<ManifestAddon> loadAddons(Path addonsFolder, BootstrapAddonClassLoader parent) {
logger.debug("Loading addons...");
try(Stream<Path> files = Files.walk(addonsFolder, 1, FileVisitOption.FOLLOW_LINKS)) {
List<Path> addons = files
.filter(path -> path.toFile().isFile())
.filter(path -> path.toFile().canRead())
.filter(path -> !path.getFileName().startsWith(".")) // ignore hidden files.
.filter(path -> path.toString().endsWith(".jar"))
.toList();
addons.stream().map(path -> {
try {
return path.toUri().toURL();
} catch(MalformedURLException e) {
throw new UncheckedIOException(e);
}
}).forEach(parent::addURL);
return addons.stream()
.map(jar -> loadAddon(jar, parent))
.collect(Collectors.toList());
} catch(IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public String getID() {
return "MANIFEST";
}
@Override
public Version version() {
return VERSION;
}
}
@@ -1,84 +0,0 @@
/*
* Copyright (c) 2020-2025 Polyhedral Development
*
* The Terra Core Addons are licensed under the terms of the MIT License. For more details,
* reference the LICENSE file in this module's root directory.
*/
package com.dfsek.terra.addons.manifest.impl.config;
import ca.solostudios.strata.version.Version;
import ca.solostudios.strata.version.VersionRange;
import com.dfsek.tectonic.api.config.template.ConfigTemplate;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
@SuppressWarnings("FieldMayBeFinal")
public class AddonManifest implements ConfigTemplate, StringIdentifiable {
@Value("schema-version")
private int schemaVersion;
@Value("id")
private String id;
@Value("version")
private Version version;
@Value("license")
private String license;
@Value("contributors")
@Default
private List<String> contributors = Collections.emptyList();
@Value("entrypoints")
private List<String> entryPoints;
@Value("depends")
@Default
private Map<String, VersionRange> dependencies = Collections.emptyMap();
@Value("website")
@Default
private WebsiteConfig website;
@Override
public String getID() {
return id;
}
public int getSchemaVersion() {
return schemaVersion;
}
public Version getVersion() {
return version;
}
public List<String> getContributors() {
return contributors;
}
public List<String> getEntryPoints() {
return entryPoints;
}
public String getLicense() {
return license;
}
public WebsiteConfig getWebsite() {
return website;
}
public Map<String, VersionRange> getDependencies() {
return dependencies;
}
}
@@ -1,40 +0,0 @@
/*
* Copyright (c) 2020-2025 Polyhedral Development
*
* The Terra Core Addons are licensed under the terms of the MIT License. For more details,
* reference the LICENSE file in this module's root directory.
*/
package com.dfsek.terra.addons.manifest.impl.config;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
public class WebsiteConfig implements ObjectTemplate<WebsiteConfig> {
@Value("issues")
private String issues;
@Value("source")
private String source;
@Value("docs")
private String docs;
public String getDocs() {
return docs;
}
public String getIssues() {
return issues;
}
public String getSource() {
return source;
}
@Override
public WebsiteConfig get() {
return this;
}
}
@@ -1,32 +0,0 @@
/*
* Copyright (c) 2020-2025 Polyhedral Development
*
* The Terra Core Addons are licensed under the terms of the MIT License. For more details,
* reference the LICENSE file in this module's root directory.
*/
package com.dfsek.terra.addons.manifest.impl.config.loaders;
import ca.solostudios.strata.Versions;
import ca.solostudios.strata.parser.tokenizer.ParseException;
import ca.solostudios.strata.version.Version;
import com.dfsek.tectonic.api.depth.DepthTracker;
import com.dfsek.tectonic.api.exception.LoadException;
import com.dfsek.tectonic.api.loader.ConfigLoader;
import com.dfsek.tectonic.api.loader.type.TypeLoader;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.AnnotatedType;
public class VersionLoader implements TypeLoader<Version> {
@Override
public Version load(@NotNull AnnotatedType t, @NotNull Object c, @NotNull ConfigLoader loader, DepthTracker depthTracker)
throws LoadException {
try {
return Versions.parseVersion((String) c);
} catch(ParseException e) {
throw new LoadException("Failed to parse version", e, depthTracker);
}
}
}
@@ -1,32 +0,0 @@
/*
* Copyright (c) 2020-2025 Polyhedral Development
*
* The Terra Core Addons are licensed under the terms of the MIT License. For more details,
* reference the LICENSE file in this module's root directory.
*/
package com.dfsek.terra.addons.manifest.impl.config.loaders;
import ca.solostudios.strata.Versions;
import ca.solostudios.strata.parser.tokenizer.ParseException;
import ca.solostudios.strata.version.VersionRange;
import com.dfsek.tectonic.api.depth.DepthTracker;
import com.dfsek.tectonic.api.exception.LoadException;
import com.dfsek.tectonic.api.loader.ConfigLoader;
import com.dfsek.tectonic.api.loader.type.TypeLoader;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.AnnotatedType;
public class VersionRangeLoader implements TypeLoader<VersionRange> {
@Override
public VersionRange load(@NotNull AnnotatedType t, @NotNull Object c, @NotNull ConfigLoader loader, DepthTracker depthTracker)
throws LoadException {
try {
return Versions.parseVersionRange((String) c);
} catch(ParseException e) {
throw new LoadException("Failed to parse version range", e, depthTracker);
}
}
}
@@ -1,24 +0,0 @@
/*
* Copyright (c) 2020-2025 Polyhedral Development
*
* The Terra Core Addons are licensed under the terms of the MIT License. For more details,
* reference the LICENSE file in this module's root directory.
*/
package com.dfsek.terra.addons.manifest.impl.exception;
import java.io.Serial;
public class AddonException extends RuntimeException {
@Serial
private static final long serialVersionUID = -4201912399458420090L;
public AddonException(String message) {
super(message);
}
public AddonException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -1,24 +0,0 @@
/*
* Copyright (c) 2020-2025 Polyhedral Development
*
* The Terra Core Addons are licensed under the terms of the MIT License. For more details,
* reference the LICENSE file in this module's root directory.
*/
package com.dfsek.terra.addons.manifest.impl.exception;
import java.io.Serial;
public class ManifestException extends AddonException {
@Serial
private static final long serialVersionUID = -2458077663176544645L;
public ManifestException(String message) {
super(message);
}
public ManifestException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -1,24 +0,0 @@
/*
* Copyright (c) 2020-2025 Polyhedral Development
*
* The Terra Core Addons are licensed under the terms of the MIT License. For more details,
* reference the LICENSE file in this module's root directory.
*/
package com.dfsek.terra.addons.manifest.impl.exception;
import java.io.Serial;
public class ManifestNotPresentException extends ManifestException {
@Serial
private static final long serialVersionUID = -2116663180747013810L;
public ManifestNotPresentException(String message) {
super(message);
}
public ManifestNotPresentException(String message, Throwable cause) {
super(message, cause);
}
}
-4
View File
@@ -1,4 +0,0 @@
# Biome Query API
This addon contains an API to allow other addons to quickly query
Biome data, by baking queries and using Contexts on biomes.
@@ -1,5 +0,0 @@
version = version("1.0.0")
dependencies {
compileOnlyApi(project(":common:addons:addon-loader-manifest"))
}
@@ -1,46 +0,0 @@
package com.dfsek.terra.addons.biome.query;
import java.util.Collection;
import com.dfsek.terra.addons.biome.query.impl.BiomeTagFlattener;
import com.dfsek.terra.addons.biome.query.impl.BiomeTagHolder;
import com.dfsek.terra.addons.manifest.api.AddonInitializer;
import com.dfsek.terra.api.Platform;
import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.event.events.config.pack.ConfigPackPostLoadEvent;
import com.dfsek.terra.api.event.functional.FunctionalEventHandler;
import com.dfsek.terra.api.inject.annotations.Inject;
import com.dfsek.terra.api.properties.Context;
import com.dfsek.terra.api.properties.PropertyKey;
import com.dfsek.terra.api.world.biome.Biome;
public class BiomeQueryAPIAddon implements AddonInitializer {
public static PropertyKey<BiomeTagHolder> BIOME_TAG_KEY = Context.create(BiomeTagHolder.class);
@Inject
private Platform platform;
@Inject
private BaseAddon addon;
@Override
public void initialize() {
platform.getEventManager()
.getHandler(FunctionalEventHandler.class)
.register(addon, ConfigPackPostLoadEvent.class)
.then(event -> {
Collection<Biome> biomes = event
.getPack()
.getRegistry(Biome.class)
.entries();
BiomeTagFlattener flattener = new BiomeTagFlattener(biomes
.stream()
.flatMap(biome -> biome.getTags().stream())
.toList());
biomes.forEach(biome -> biome.getContext().put(BIOME_TAG_KEY, new BiomeTagHolder(biome, flattener)));
})
.global();
}
}
@@ -1,17 +0,0 @@
package com.dfsek.terra.addons.biome.query.api;
import java.util.function.Predicate;
import com.dfsek.terra.addons.biome.query.impl.SingleTagQuery;
import com.dfsek.terra.api.world.biome.Biome;
public final class BiomeQueries {
private BiomeQueries() {
}
public static Predicate<Biome> has(String tag) {
return new SingleTagQuery(tag);
}
}
@@ -1,20 +0,0 @@
package com.dfsek.terra.addons.biome.query.impl;
import java.util.List;
public class BiomeTagFlattener {
private final List<String> tags;
public BiomeTagFlattener(List<String> tags) {
this.tags = tags;
}
public int index(String tag) {
return tags.indexOf(tag);
}
public int size() {
return tags.size();
}
}
@@ -1,26 +0,0 @@
package com.dfsek.terra.addons.biome.query.impl;
import com.dfsek.terra.api.properties.Properties;
import com.dfsek.terra.api.world.biome.Biome;
public class BiomeTagHolder implements Properties {
private final boolean[] tags;
private final BiomeTagFlattener flattener;
public BiomeTagHolder(Biome biome, BiomeTagFlattener flattener) {
this.tags = new boolean[flattener.size()];
this.flattener = flattener;
for(String tag : biome.getTags()) {
tags[flattener.index(tag)] = true;
}
}
boolean get(int index) {
return tags[index];
}
public BiomeTagFlattener getFlattener() {
return flattener;
}
}
@@ -1,31 +0,0 @@
package com.dfsek.terra.addons.biome.query.impl;
import java.util.function.Predicate;
import com.dfsek.terra.addons.biome.query.BiomeQueryAPIAddon;
import com.dfsek.terra.api.world.biome.Biome;
public class SingleTagQuery implements Predicate<Biome> {
private final String tag;
private int tagIndex = -1;
public SingleTagQuery(String tag) {
this.tag = tag;
}
@Override
public boolean test(Biome biome) {
if(tagIndex < 0) {
tagIndex = biome
.getContext()
.get(BiomeQueryAPIAddon.BIOME_TAG_KEY)
.getFlattener()
.index(tag);
}
return biome
.getContext()
.get(BiomeQueryAPIAddon.BIOME_TAG_KEY)
.get(tagIndex);
}
}
@@ -1,12 +0,0 @@
schema-version: 1
contributors:
- Terra contributors
id: api-biome-query
version: @VERSION@
entrypoints:
- "com.dfsek.terra.addons.biome.query.BiomeQueryAPIAddon"
website:
issues: https://github.com/PolyhedralDev/Terra/issues
source: https://github.com/PolyhedralDev/Terra
docs: https://terra.polydev.org
license: MIT License
+10
View File
@@ -0,0 +1,10 @@
# api-features
Contains the API for feature generation.
This API implemented in:
* `config-feature`
* `generation-stage-feature`
* `config-locators`
* `config-distributors`
@@ -0,0 +1,2 @@
dependencies {
}
-7
View File
@@ -1,7 +0,0 @@
version = version("1.1.0")
dependencies {
compileOnlyApi(project(":common:addons:addon-loader-manifest"))
}
@@ -1,89 +0,0 @@
package com.dfsek.terra.addons.image;
import com.dfsek.seismic.type.sampler.Sampler;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import java.util.function.Supplier;
import com.dfsek.terra.addons.image.colorsampler.ColorSampler;
import com.dfsek.terra.addons.image.config.ColorLoader;
import com.dfsek.terra.addons.image.config.ColorLoader.ColorString;
import com.dfsek.terra.addons.image.config.ImageLibraryPackConfigTemplate;
import com.dfsek.terra.addons.image.config.colorsampler.ConstantColorSamplerTemplate;
import com.dfsek.terra.addons.image.config.colorsampler.image.SingleImageColorSamplerTemplate;
import com.dfsek.terra.addons.image.config.colorsampler.image.TileImageColorSamplerTemplate;
import com.dfsek.terra.addons.image.config.colorsampler.mutate.RotateColorSamplerTemplate;
import com.dfsek.terra.addons.image.config.colorsampler.mutate.TranslateColorSamplerTemplate;
import com.dfsek.terra.addons.image.config.image.ImageTemplate;
import com.dfsek.terra.addons.image.config.image.StitchedImageTemplate;
import com.dfsek.terra.addons.image.config.sampler.ChannelSamplerTemplate;
import com.dfsek.terra.addons.image.config.sampler.DistanceTransformSamplerTemplate;
import com.dfsek.terra.addons.image.image.Image;
import com.dfsek.terra.addons.image.operator.DistanceTransform;
import com.dfsek.terra.addons.manifest.api.AddonInitializer;
import com.dfsek.terra.api.Platform;
import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.event.events.config.pack.ConfigPackPreLoadEvent;
import com.dfsek.terra.api.event.functional.FunctionalEventHandler;
import com.dfsek.terra.api.inject.annotations.Inject;
import com.dfsek.terra.api.registry.CheckedRegistry;
import com.dfsek.terra.api.util.reflection.TypeKey;
public class ImageLibraryAddon implements AddonInitializer {
public static final TypeKey<Supplier<ObjectTemplate<Image>>> IMAGE_REGISTRY_KEY = new TypeKey<>() {
};
public static final TypeKey<Supplier<ObjectTemplate<ColorSampler>>> COLOR_PICKER_REGISTRY_KEY = new TypeKey<>() {
};
public static final TypeKey<Supplier<ObjectTemplate<Sampler>>> NOISE_SAMPLER_TOKEN = new TypeKey<>() {
};
@Inject
private Platform platform;
@Inject
private BaseAddon addon;
@Override
public void initialize() {
platform.getEventManager()
.getHandler(FunctionalEventHandler.class)
.register(addon, ConfigPackPreLoadEvent.class)
.priority(10)
.then(event -> {
ImageLibraryPackConfigTemplate config = event.loadTemplate(new ImageLibraryPackConfigTemplate());
event.getPack().getContext().put(config);
})
.then(event -> {
ConfigPack pack = event.getPack();
CheckedRegistry<Supplier<ObjectTemplate<Image>>> imageRegistry = pack.getOrCreateRegistry(IMAGE_REGISTRY_KEY);
imageRegistry.register(addon.key("BITMAP"), () -> new ImageTemplate(pack));
imageRegistry.register(addon.key("STITCHED_BITMAP"), () -> new StitchedImageTemplate(pack));
})
.then(event -> {
event.getPack()
.applyLoader(DistanceTransform.CostFunction.class,
(type, o, loader, depthTracker) -> DistanceTransform.CostFunction.valueOf((String) o))
.applyLoader(DistanceTransform.Normalization.class,
(type, o, loader, depthTracker) -> DistanceTransform.Normalization.valueOf((String) o))
.applyLoader(ColorString.class, new ColorLoader());
CheckedRegistry<Supplier<ObjectTemplate<Sampler>>> noiseRegistry = event.getPack().getOrCreateRegistry(
NOISE_SAMPLER_TOKEN);
noiseRegistry.register(addon.key("DISTANCE_TRANSFORM"), DistanceTransformSamplerTemplate::new);
noiseRegistry.register(addon.key("CHANNEL"), ChannelSamplerTemplate::new);
})
.then(event -> {
CheckedRegistry<Supplier<ObjectTemplate<ColorSampler>>> colorSamplerRegistry = event.getPack().getOrCreateRegistry(
COLOR_PICKER_REGISTRY_KEY);
colorSamplerRegistry.register(addon.key("SINGLE_IMAGE"), SingleImageColorSamplerTemplate::new);
colorSamplerRegistry.register(addon.key("TILED_IMAGE"), TileImageColorSamplerTemplate::new);
colorSamplerRegistry.register(addon.key("COLOR"), ConstantColorSamplerTemplate::new);
colorSamplerRegistry.register(addon.key("ROTATE"), RotateColorSamplerTemplate::new);
colorSamplerRegistry.register(addon.key("TRANSLATE"), TranslateColorSamplerTemplate::new);
});
}
}
@@ -1,13 +0,0 @@
package com.dfsek.terra.addons.image.colorsampler;
@FunctionalInterface
public interface ColorSampler {
/**
* @param x World x coordinate
* @param z World z coordinate
*
* @return Integer representing a web color
*/
int apply(int x, int z);
}
@@ -1,29 +0,0 @@
package com.dfsek.terra.addons.image.colorsampler.image;
import com.dfsek.terra.addons.image.colorsampler.ColorSampler;
import com.dfsek.terra.addons.image.colorsampler.image.transform.ImageTransformation;
import com.dfsek.terra.addons.image.image.Image;
public class SingleImageColorSampler implements ColorSampler {
private final Image image;
private final ColorSampler fallback;
private final ImageTransformation transformation;
public SingleImageColorSampler(Image image, ColorSampler fallback, ImageTransformation transformation) {
this.image = image;
this.fallback = fallback;
this.transformation = transformation;
}
@Override
public int apply(int x, int z) {
var nx = transformation.transformX(image, x);
var nz = transformation.transformZ(image, z);
if(nx < 0 || nz < 0 || nx >= image.getWidth() || nz >= image.getHeight()) return fallback.apply(x, z);
return image.getRGB(nx, nz);
}
}
@@ -1,25 +0,0 @@
package com.dfsek.terra.addons.image.colorsampler.image;
import com.dfsek.terra.addons.image.colorsampler.ColorSampler;
import com.dfsek.terra.addons.image.colorsampler.image.transform.ImageTransformation;
import com.dfsek.terra.addons.image.image.Image;
public class TileImageColorSampler implements ColorSampler {
private final Image image;
private final ImageTransformation transformation;
public TileImageColorSampler(Image image, ImageTransformation transformation) {
this.image = image;
this.transformation = transformation;
}
@Override
public int apply(int x, int z) {
x = transformation.transformX(image, x);
z = transformation.transformZ(image, z);
return image.getRGB(Math.floorMod(x, image.getWidth()), Math.floorMod(z, image.getHeight()));
}
}
@@ -1,30 +0,0 @@
package com.dfsek.terra.addons.image.colorsampler.image.transform;
import com.dfsek.terra.addons.image.image.Image;
public enum Alignment implements ImageTransformation {
NONE() {
@Override
public int transformX(Image image, int x) {
return x;
}
@Override
public int transformZ(Image image, int z) {
return z;
}
},
CENTER {
@Override
public int transformX(Image image, int x) {
return x + image.getWidth() / 2;
}
@Override
public int transformZ(Image image, int z) {
return z + image.getHeight() / 2;
}
};
}
@@ -1,11 +0,0 @@
package com.dfsek.terra.addons.image.colorsampler.image.transform;
import com.dfsek.terra.addons.image.image.Image;
public interface ImageTransformation {
int transformX(Image image, int x);
int transformZ(Image image, int z);
}
@@ -1,62 +0,0 @@
package com.dfsek.terra.addons.image.colorsampler.mutate;
import com.dfsek.seismic.math.trigonometry.TrigonometryFunctions;
import com.dfsek.terra.addons.image.colorsampler.ColorSampler;
public class RotateColorSampler implements ColorSampler {
private final ColorSampler sampler;
private final double radians;
private final RotationMethod rotationMethod;
public RotateColorSampler(ColorSampler sampler, double degrees) {
this.sampler = sampler;
double normalizedDegrees = degrees % 360.0;
if(normalizedDegrees < 0) normalizedDegrees += 360.0;
if(normalizedDegrees == 0.0)
rotationMethod = RotationMethod.DEG_0;
else if(normalizedDegrees == 90.0)
rotationMethod = RotationMethod.DEG_90;
else if(normalizedDegrees == 180.0)
rotationMethod = RotationMethod.DEG_180;
else if(normalizedDegrees == 270.0)
rotationMethod = RotationMethod.DEG_270;
else
rotationMethod = RotationMethod.RAD_ANY;
this.radians = Math.toRadians(degrees);
}
@Override
public int apply(int x, int z) {
int rx = switch(rotationMethod) {
case DEG_0 -> x;
case DEG_90 -> -z;
case DEG_180 -> -x;
case DEG_270 -> z;
case RAD_ANY -> (int) (x * TrigonometryFunctions.cos(radians) - z * TrigonometryFunctions.sin(radians));
};
int rz = switch(rotationMethod) {
case DEG_0 -> z;
case DEG_90 -> x;
case DEG_180 -> -z;
case DEG_270 -> -x;
case RAD_ANY -> (int) (z * TrigonometryFunctions.cos(radians) + x * TrigonometryFunctions.sin(radians));
};
return sampler.apply(rx, rz);
}
private enum RotationMethod {
DEG_0,
DEG_90,
DEG_180,
DEG_270,
RAD_ANY,
}
}
@@ -1,21 +0,0 @@
package com.dfsek.terra.addons.image.colorsampler.mutate;
import com.dfsek.terra.addons.image.colorsampler.ColorSampler;
public class TranslateColorSampler implements ColorSampler {
private final ColorSampler sampler;
private final int translateX, translateZ;
public TranslateColorSampler(ColorSampler sampler, int translateX, int translateZ) {
this.sampler = sampler;
this.translateX = translateX;
this.translateZ = translateZ;
}
@Override
public int apply(int x, int z) {
return sampler.apply(x - translateX, z - translateZ);
}
}
@@ -1,92 +0,0 @@
package com.dfsek.terra.addons.image.config;
import com.dfsek.tectonic.api.depth.DepthTracker;
import com.dfsek.tectonic.api.exception.LoadException;
import com.dfsek.tectonic.api.loader.ConfigLoader;
import com.dfsek.tectonic.api.loader.type.TypeLoader;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.AnnotatedType;
import com.dfsek.terra.addons.image.config.ColorLoader.ColorString;
import com.dfsek.terra.addons.image.util.ColorUtil;
public class ColorLoader implements TypeLoader<ColorString> {
@Override
public ColorString load(@NotNull AnnotatedType annotatedType, @NotNull Object o, @NotNull ConfigLoader configLoader,
DepthTracker depthTracker) throws LoadException {
return new ColorString((String) o);
}
public static class ColorString {
private final int argb;
public ColorString(String string) throws IllegalArgumentException {
this.argb = parse(string);
}
private static int parse(String string) throws IllegalArgumentException {
if(string.length() == 0)
throw new IllegalArgumentException("Empty string cannot be parsed as a valid color");
String[] split = string.split(",");
if(split.length == 1)
return parseHex(string);
else if(split.length == 3)
return parseChannels("255", split[0], split[1], split[2]);
else if(split.length == 4)
return parseChannels(split[0], split[1], split[2], split[3]);
else
throw new IllegalArgumentException("Invalid channels provided, required format RED,GREEN,BLUE or ALPHA,RED,GREEN,BLUE");
}
private static int parseHex(String hex) throws IllegalArgumentException {
if(hex.startsWith("#"))
hex = hex.substring(1);
int alpha = 255;
int red = 0;
int green = 0;
int blue = 0;
try {
if(hex.length() == 8) {
alpha = Integer.parseInt(hex.substring(0, 2), 16);
hex = hex.substring(2);
}
if(hex.length() != 6)
throw new IllegalArgumentException("Invalid color channels, required format AARRGGBB or RRGGBB");
red = Integer.parseInt(hex.substring(0, 2), 16);
green = Integer.parseInt(hex.substring(2, 4), 16);
blue = Integer.parseInt(hex.substring(4, 6), 16);
return ColorUtil.argbValidated(alpha, red, green, blue);
} catch(NumberFormatException e) {
throw new IllegalArgumentException("Failed to parse hex color", e);
}
}
private static int parseChannels(String alpha, String red, String green, String blue) throws IllegalArgumentException {
try {
int a = Integer.decode(alpha);
int r = Integer.decode(red);
int g = Integer.decode(green);
int b = Integer.decode(blue);
return ColorUtil.argbValidated(a, r, g, b);
} catch(NumberFormatException e) {
throw new IllegalArgumentException("Invalid channel value", e);
}
}
public int getColor() {
return argb;
}
}
}
@@ -1,39 +0,0 @@
package com.dfsek.terra.addons.image.config;
import com.dfsek.tectonic.api.config.template.ConfigTemplate;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Description;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.terra.api.properties.Properties;
public class ImageLibraryPackConfigTemplate implements ConfigTemplate, Properties {
// TODO - These would be better as plugin wide config parameters in config.yml
@Value("images.cache.load-on-use")
@Description("If set to true, images will load into memory upon use rather than on pack load.")
@Default
private boolean loadOnUse = false;
@Value("images.cache.timeout")
@Description("How many seconds to keep images loaded in the image cache for. " +
"If set to a number greater than 0, images will be removed from memory if not used after the timeout, otherwise images " +
"will stay loaded in memory. " +
"Setting the timeout to greater than 0 will trade decreased memory consumption when not performing any image reads for a" +
" period of time for extra processing time required to perform cache lookups.")
@Default
private int cacheTimeout = 0;
public boolean loadOnUse() {
return loadOnUse;
}
public boolean unloadOnTimeout() {
return cacheTimeout > 0;
}
public int getCacheTimeout() {
return cacheTimeout;
}
}
@@ -1,19 +0,0 @@
package com.dfsek.terra.addons.image.config.colorsampler;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import com.dfsek.terra.addons.image.colorsampler.ColorSampler;
import com.dfsek.terra.addons.image.config.ColorLoader.ColorString;
public class ConstantColorSamplerTemplate implements ObjectTemplate<ColorSampler> {
@Value("color")
private ColorString color;
@Override
public ColorSampler get() {
return ((x, z) -> color.getColor());
}
}
@@ -1,21 +0,0 @@
package com.dfsek.terra.addons.image.config.colorsampler.image;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import com.dfsek.terra.addons.image.colorsampler.ColorSampler;
import com.dfsek.terra.addons.image.colorsampler.image.transform.Alignment;
import com.dfsek.terra.addons.image.image.Image;
public abstract class ImageColorSamplerTemplate implements ObjectTemplate<ColorSampler> {
@Value("image")
protected Image image;
@Value("align")
@Default
protected Alignment alignment = Alignment.NONE;
}
@@ -1,17 +0,0 @@
package com.dfsek.terra.addons.image.config.colorsampler.image;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.terra.addons.image.colorsampler.ColorSampler;
import com.dfsek.terra.addons.image.colorsampler.image.SingleImageColorSampler;
public class SingleImageColorSamplerTemplate extends ImageColorSamplerTemplate {
@Value("outside-sampler")
private ColorSampler fallback;
@Override
public ColorSampler get() {
return new SingleImageColorSampler(image, fallback, alignment);
}
}
@@ -1,13 +0,0 @@
package com.dfsek.terra.addons.image.config.colorsampler.image;
import com.dfsek.terra.addons.image.colorsampler.ColorSampler;
import com.dfsek.terra.addons.image.colorsampler.image.TileImageColorSampler;
public class TileImageColorSamplerTemplate extends ImageColorSamplerTemplate {
@Override
public ColorSampler get() {
return new TileImageColorSampler(image, alignment);
}
}
@@ -1,13 +0,0 @@
package com.dfsek.terra.addons.image.config.colorsampler.mutate;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import com.dfsek.terra.addons.image.colorsampler.ColorSampler;
public abstract class MutateColorSamplerTemplate implements ObjectTemplate<ColorSampler> {
@Value("color-sampler")
protected ColorSampler sampler;
}
@@ -1,18 +0,0 @@
package com.dfsek.terra.addons.image.config.colorsampler.mutate;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.terra.addons.image.colorsampler.ColorSampler;
import com.dfsek.terra.addons.image.colorsampler.mutate.RotateColorSampler;
public class RotateColorSamplerTemplate extends MutateColorSamplerTemplate {
@Value("angle")
private double degrees;
@Override
public ColorSampler get() {
return new RotateColorSampler(sampler, degrees);
}
}
@@ -1,21 +0,0 @@
package com.dfsek.terra.addons.image.config.colorsampler.mutate;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.terra.addons.image.colorsampler.ColorSampler;
import com.dfsek.terra.addons.image.colorsampler.mutate.TranslateColorSampler;
public class TranslateColorSamplerTemplate extends MutateColorSamplerTemplate {
@Value("x")
private int translateX;
@Value("z")
private int translateZ;
@Override
public ColorSampler get() {
return new TranslateColorSampler(sampler, translateX, translateZ);
}
}
@@ -1,16 +0,0 @@
package com.dfsek.terra.addons.image.config.converter;
import com.dfsek.terra.addons.image.converter.ClosestMatchColorConverter;
import com.dfsek.terra.addons.image.converter.ColorConverter;
import com.dfsek.terra.addons.image.converter.mapping.ColorMapping;
public abstract class ClosestColorConverterTemplate<T> implements ColorConverterTemplate<T> {
protected abstract ColorMapping<T> getMapping();
@Override
public ColorConverter<T> get() {
return new ClosestMatchColorConverter<T>(getMapping().get());
}
}
@@ -1,9 +0,0 @@
package com.dfsek.terra.addons.image.config.converter;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import com.dfsek.terra.addons.image.converter.ColorConverter;
public interface ColorConverterTemplate<T> extends ObjectTemplate<ColorConverter<T>> {
}
@@ -1,20 +0,0 @@
package com.dfsek.terra.addons.image.config.converter;
import com.dfsek.terra.addons.image.converter.ColorConverter;
import com.dfsek.terra.addons.image.converter.ExactColorConverter;
import com.dfsek.terra.addons.image.converter.mapping.ColorMapping;
public abstract class ExactColorConverterTemplate<T> implements ColorConverterTemplate<T> {
protected abstract ColorMapping<T> getMapping();
protected abstract T getFallback();
protected abstract boolean ignoreAlpha();
@Override
public ColorConverter<T> get() {
return new ExactColorConverter<T>(getMapping().get(), getFallback(), ignoreAlpha());
}
}
@@ -1,56 +0,0 @@
package com.dfsek.terra.addons.image.config.image;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.github.benmanes.caffeine.cache.Scheduler;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
import com.dfsek.terra.addons.image.config.ImageLibraryPackConfigTemplate;
import com.dfsek.terra.addons.image.image.BufferedImageWrapper;
import com.dfsek.terra.addons.image.image.Image;
import com.dfsek.terra.addons.image.image.SuppliedImage;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.properties.Properties;
import com.dfsek.terra.api.util.generic.Memo;
import static com.dfsek.terra.api.util.cache.CacheUtils.CACHE_EXECUTOR;
/*
* Cache prevents configs from loading the same image multiple times into memory
*/
record ImageCache(LoadingCache<String, Image> cache) implements Properties {
public static Image load(String path, ConfigPack pack) throws IOException {
ImageLibraryPackConfigTemplate config = pack.getContext().get(ImageLibraryPackConfigTemplate.class);
ImageCache images;
if(!pack.getContext().has(ImageCache.class)) {
var cacheBuilder = Caffeine.newBuilder().executor(CACHE_EXECUTOR).scheduler(Scheduler.systemScheduler());
if(config.unloadOnTimeout()) cacheBuilder.expireAfterAccess(config.getCacheTimeout(), TimeUnit.SECONDS);
images = new ImageCache(cacheBuilder.build(s -> loadImage(s, pack.getRootPath())));
pack.getContext().put(images);
} else images = pack.getContext().get(ImageCache.class);
if(config.loadOnUse()) {
if(config.unloadOnTimeout()) { // Grab directly from cache if images are to unload on timeout
return new SuppliedImage(() -> images.cache.get(path));
} else {
// If images do not time out, image can be lazily loaded once instead of performing cache lookups for each image operation
Memo<Image> lazyImage = Memo.lazy(() -> images.cache.get(path));
return new SuppliedImage(lazyImage::value);
}
}
return images.cache.get(path);
}
private static Image loadImage(String path, Path directory) throws IOException {
InputStream is = Files.newInputStream(directory.resolve(path));
return new BufferedImageWrapper(ImageIO.read(is));
}
}
@@ -1,30 +0,0 @@
package com.dfsek.terra.addons.image.config.image;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import java.io.IOException;
import com.dfsek.terra.addons.image.image.Image;
import com.dfsek.terra.api.config.ConfigPack;
public class ImageTemplate implements ObjectTemplate<Image> {
private final ConfigPack pack;
@Value("path")
private String path;
public ImageTemplate(ConfigPack pack) {
this.pack = pack;
}
@Override
public Image get() {
try {
return ImageCache.load(path, pack);
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
@@ -1,68 +0,0 @@
package com.dfsek.terra.addons.image.config.image;
import com.dfsek.tectonic.api.config.template.ValidatedConfigTemplate;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import com.dfsek.tectonic.api.exception.ValidationException;
import java.io.IOException;
import com.dfsek.terra.addons.image.image.Image;
import com.dfsek.terra.addons.image.image.StitchedImage;
import com.dfsek.terra.api.config.ConfigPack;
public class StitchedImageTemplate implements ObjectTemplate<Image>, ValidatedConfigTemplate {
private final ConfigPack pack;
@Value("path-format")
private String path;
@Value("rows")
private int rows;
@Value("columns")
private int cols;
@Value("zero-indexed")
@Default
private boolean zeroIndexed = false;
public StitchedImageTemplate(ConfigPack pack) {
this.pack = pack;
}
@Override
public Image get() {
Image[][] grid = new Image[rows][cols];
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
try {
grid[i][j] = ImageCache.load(getFormattedPath(i, j), pack);
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
return new StitchedImage(grid, zeroIndexed);
}
private String getFormattedPath(int row, int column) {
if(!zeroIndexed) {
row++;
column++;
}
return path.replaceFirst("\\{row}", String.valueOf(row)).replaceFirst("\\{column}", String.valueOf(column));
}
@Override
public boolean validate() throws ValidationException {
if(!path.contains("{row}"))
throw new ValidationException("Path format does not contain sequence '{row}'");
if(!path.contains("{column}"))
throw new ValidationException("Path format does not contain sequence '{column}'");
if(rows < 1)
throw new ValidationException("Must have at least one row");
if(cols < 1)
throw new ValidationException("Must have at least one column");
return true;
}
}
@@ -1,41 +0,0 @@
package com.dfsek.terra.addons.image.config.sampler;
import com.dfsek.seismic.type.sampler.Sampler;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import com.dfsek.terra.addons.image.colorsampler.ColorSampler;
import com.dfsek.terra.addons.image.sampler.ChannelSampler;
import com.dfsek.terra.addons.image.util.ColorUtil.Channel;
public class ChannelSamplerTemplate implements ObjectTemplate<Sampler> {
@Value("color-sampler")
private ColorSampler colorSampler;
@Value("channel")
private Channel channel;
/*
* If the channel should be normalized to range [-1, 1] or not
*/
@Value("normalize")
@Default
private boolean normalize = true;
/*
* Whether to multiply color channels by the alpha channel or not. If users
* are expecting pixel transparency to reduce the output value then this should
* be set to true.
*/
@Value("premultiply")
@Default
private boolean premultiply = false;
@Override
public Sampler get() {
return new ChannelSampler(colorSampler, channel, normalize, premultiply);
}
}
@@ -1,75 +0,0 @@
package com.dfsek.terra.addons.image.config.sampler;
import com.dfsek.seismic.type.sampler.Sampler;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.tectonic.api.config.template.object.ObjectTemplate;
import com.dfsek.terra.addons.image.image.Image;
import com.dfsek.terra.addons.image.operator.DistanceTransform;
import com.dfsek.terra.addons.image.operator.DistanceTransform.CostFunction;
import com.dfsek.terra.addons.image.operator.DistanceTransform.Normalization;
import com.dfsek.terra.addons.image.util.ColorUtil.Channel;
public class DistanceTransformSamplerTemplate implements ObjectTemplate<Sampler> {
@Value("image")
private Image image;
/**
* The threshold value applied to the channel specified in the 'channel' parameter that splits
* the image into a binary image. This parameter is only used for cost functions that utilize
* a binary image.
*/
@Value("threshold")
@Default
private int threshold = 127;
/**
* If set to true, distances calculated will be clamped to stay above the largest
* distance calculated on the edges of the image. This ensures output values do not
* appear to be cut off at the image boundaries. It is recommended to leave padding
* around the image if this is in use, such that larger evaluated distances do not
* get cut out by smaller evaluated distances close to borders. Doing so will yield
* better results.
*/
@Value("clamp-to-max-edge")
@Default
private boolean clampToEdge = false;
/**
* The target channel to run distance calculations on.
*/
@Value("channel")
@Default
private Channel channel = Channel.GRAYSCALE;
/**
* The method of image processing applied to the specified image prior to calculating
* distances.
*/
@Value("cost-function")
@Default
private CostFunction costFunction = CostFunction.Channel;
/**
* Inverts the resulting binary image that may be used as a cost function.
*/
@Value("invert-threshold")
@Default
private boolean invertThreshold = false;
/**
* How the final distance calculation should be redistributed.
*/
@Value("normalization")
@Default
private Normalization normalization = Normalization.None;
@Override
public Sampler get() {
return new DistanceTransform.Noise(new DistanceTransform(image, channel, threshold, clampToEdge, costFunction, invertThreshold),
normalization);
}
}
@@ -1,41 +0,0 @@
package com.dfsek.terra.addons.image.converter;
import java.util.Map;
import com.dfsek.terra.addons.image.util.ColorUtil;
public class ClosestMatchColorConverter<T> implements ColorConverter<T> {
private final Map<Integer, T> map;
private final Integer[] colors;
public ClosestMatchColorConverter(Map<Integer, T> map) {
this.map = map;
this.colors = map.keySet().toArray(new Integer[0]);
}
@Override
public T apply(int color) {
int closest = 0;
int smallestDistance = Integer.MAX_VALUE;
for(int compare : colors) {
if(color == compare) {
closest = compare;
break;
}
int distance = ColorUtil.distance(color, compare);
if(distance < smallestDistance) {
smallestDistance = distance;
closest = compare;
}
}
return map.get(closest);
}
@Override
public Iterable<T> getEntries() {
return map.values();
}
}
@@ -1,8 +0,0 @@
package com.dfsek.terra.addons.image.converter;
public interface ColorConverter<T> {
T apply(int color);
Iterable<T> getEntries();
}
@@ -1,42 +0,0 @@
package com.dfsek.terra.addons.image.converter;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.dfsek.terra.addons.image.util.ColorUtil;
import com.dfsek.terra.addons.image.util.MapUtil;
public class ExactColorConverter<T> implements ColorConverter<T> {
private final Map<Integer, T> map;
private final T fallback;
private final boolean ignoreAlpha;
public ExactColorConverter(Map<Integer, T> map, T fallback, boolean ignoreAlpha) {
if(ignoreAlpha) {
map = MapUtil.mapKeys(map, ColorUtil::zeroAlpha);
}
this.map = map;
this.fallback = fallback;
this.ignoreAlpha = ignoreAlpha;
}
@Override
public T apply(int color) {
if(ignoreAlpha) {
color = ColorUtil.zeroAlpha(color);
}
T lookup = map.get(color);
return lookup != null ? lookup : fallback;
}
@Override
public Iterable<T> getEntries() {
Set<T> entries = new HashSet<>(map.values());
entries.add(fallback);
return entries;
}
}
@@ -1,39 +0,0 @@
package com.dfsek.terra.addons.image.converter.mapping;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.dfsek.terra.api.registry.Registry;
import com.dfsek.terra.api.world.biome.Biome;
public class BiomeDefinedColorMapping<T> implements ColorMapping<T> {
Registry<Biome> biomeRegistry;
Function<Biome, T> converter;
public BiomeDefinedColorMapping(Registry<Biome> biomeRegistry, Function<Biome, T> converter) {
this.biomeRegistry = biomeRegistry;
this.converter = converter;
}
@Override
public Map<Integer, T> get() {
Map<Biome, Integer> colorMap = new HashSet<>(biomeRegistry.entries()).stream().collect(Collectors.toMap(b -> b, Biome::getColor));
Map<Integer, Biome> output = new HashMap<>();
colorMap.forEach(((biome, color) -> {
if(!output.containsKey(color)) {
output.put(color, biome);
} else {
throw new IllegalArgumentException(
String.format("Biome %s has same color as %s: %x", biome.getID(), output.get(color).getID(), color));
}
}));
return output.entrySet().stream().collect(Collectors.toMap(Entry::getKey, e -> converter.apply(e.getValue())));
}
}
@@ -1,8 +0,0 @@
package com.dfsek.terra.addons.image.converter.mapping;
import java.util.Map;
import java.util.function.Supplier;
public interface ColorMapping<T> extends Supplier<Map<Integer, T>> {
}
@@ -1,28 +0,0 @@
package com.dfsek.terra.addons.image.image;
import java.awt.image.BufferedImage;
public class BufferedImageWrapper implements Image {
private final BufferedImage image;
public BufferedImageWrapper(BufferedImage image) {
this.image = image;
}
@Override
public int getRGB(int x, int y) {
return image.getRGB(x, y);
}
@Override
public int getWidth() {
return image.getWidth();
}
@Override
public int getHeight() {
return image.getHeight();
}
}
@@ -1,9 +0,0 @@
package com.dfsek.terra.addons.image.image;
public interface Image {
int getRGB(int x, int y);
int getWidth();
int getHeight();
}
@@ -1,74 +0,0 @@
package com.dfsek.terra.addons.image.image;
public class StitchedImage implements Image {
private final Image[][] images;
private final int[] rowOffsets, columnOffsets;
private final int width, height;
public StitchedImage(Image[][] images, boolean zeroIndexed) throws IllegalArgumentException {
int width = 0;
int height = 0;
int rows = images.length;
int columns = images[0].length;
this.rowOffsets = new int[rows];
this.columnOffsets = new int[columns];
for(int i = 0; i < rows; i++) {
int rowHeight = images[i][0].getHeight();
rowOffsets[i] = height;
height += rowHeight;
for(int j = 1; j < columns; j++) {
if(images[i][j].getHeight() != rowHeight)
throw new IllegalArgumentException("Image heights in row " + (i + (zeroIndexed ? 0 : 1)) + " do not match");
}
}
for(int i = 0; i < columns; i++) {
int columnWidth = images[0][i].getWidth();
columnOffsets[i] = width;
width += columnWidth;
for(int j = 1; j < rows; j++) {
if(images[i][j].getWidth() != columnWidth)
throw new IllegalArgumentException("Image widths in column " + (i + (zeroIndexed ? 0 : 1)) + " do not match");
}
}
this.width = width;
this.height = height;
this.images = images;
}
private int getColumn(int x) {
for(int i = columnOffsets.length - 1; i > 0; i--) {
if(x >= columnOffsets[i])
return i;
}
return 0;
}
private int getRow(int y) {
for(int i = rowOffsets.length - 1; i > 0; i--) {
if(y >= rowOffsets[i])
return i;
}
return 0;
}
@Override
public int getRGB(int x, int y) {
int row = getRow(y);
int column = getColumn(x);
return images[row][column].getRGB(x - columnOffsets[column], y - rowOffsets[row]);
}
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return height;
}
}
@@ -1,28 +0,0 @@
package com.dfsek.terra.addons.image.image;
import java.util.function.Supplier;
public class SuppliedImage implements Image {
private final Supplier<Image> imageSupplier;
public SuppliedImage(Supplier<Image> imageSupplier) {
this.imageSupplier = imageSupplier;
}
@Override
public int getRGB(int x, int y) {
return imageSupplier.get().getRGB(x, y);
}
@Override
public int getWidth() {
return imageSupplier.get().getWidth();
}
@Override
public int getHeight() {
return imageSupplier.get().getHeight();
}
}
@@ -1,245 +0,0 @@
package com.dfsek.terra.addons.image.operator;
import com.dfsek.seismic.math.floatingpoint.FloatingPointFunctions;
import com.dfsek.seismic.type.sampler.Sampler;
import com.dfsek.terra.addons.image.image.Image;
import com.dfsek.terra.addons.image.util.ColorUtil;
import com.dfsek.terra.addons.image.util.ColorUtil.Channel;
import static com.dfsek.terra.addons.image.util.MathUtil.lerp;
/**
* Computes a 2D distance transform of a given image and stores the result in a 2D array of distances.
* Implementation based on the algorithm described in the paper
* <a href="https://cs.brown.edu/people/pfelzens/papers/dt-final.pdf">Distance Transforms of Sampled Functions</a>
* by Pedro F. Felzenszwalb and Daniel P. Huttenlocher.
*/
public class DistanceTransform {
private static final double MAX_DISTANCE_CAP = 10_000_000; // Arbitrarily large value, doubtful someone would
private final double[][] distances;
/**
* Size bounds matching the provided image.
*/
private final int width, height;
/**
* Min and max distances of the distance computation. These may change after {@link #normalize(Normalization)} calls.
*/
private double minDistance, maxDistance;
// ever use an image large enough to exceed this.
public DistanceTransform(Image image, Channel channel, int threshold, boolean clampToMaxEdgeDistance, CostFunction costFunction,
boolean invertThreshold) {
// Construct binary image based on threshold value
boolean[][] binaryImage = new boolean[image.getWidth()][image.getHeight()];
for(int x = 0; x < image.getWidth(); x++) {
for(int y = 0; y < image.getHeight(); y++) {
binaryImage[x][y] = ColorUtil.getChannel(image.getRGB(x, y), channel) > threshold ^ invertThreshold;
}
}
// Get edges of binary image
boolean[][] binaryImageEdge = new boolean[image.getWidth()][image.getHeight()];
for(int x = 0; x < image.getWidth(); x++) {
for(int y = 0; y < image.getHeight(); y++) {
if(!binaryImage[x][y])
binaryImageEdge[x][y] = false;
else
// If cell borders any false cell
binaryImageEdge[x][y] = x > 0 && !binaryImage[x - 1][y] ||
y > 0 && !binaryImage[x][y - 1] ||
x < image.getWidth() - 1 && !binaryImage[x + 1][y] ||
y < image.getHeight() - 1 && !binaryImage[x][y + 1];
}
}
double[][] function = new double[image.getWidth()][image.getHeight()];
for(int x = 0; x < image.getWidth(); x++) {
for(int y = 0; y < image.getHeight(); y++) {
function[x][y] = switch(costFunction) {
case Channel -> ColorUtil.getChannel(image.getRGB(x, y), channel);
case Threshold -> binaryImage[x][y] ? MAX_DISTANCE_CAP : 0;
case ThresholdEdge, ThresholdEdgeSigned -> binaryImageEdge[x][y] ? 0 : MAX_DISTANCE_CAP;
};
}
}
distances = calculateDistance2D(function);
if(costFunction == CostFunction.ThresholdEdgeSigned) {
for(int x = 0; x < image.getWidth(); x++) {
for(int y = 0; y < image.getHeight(); y++) {
distances[x][y] *= binaryImage[x][y] ? 1 : -1;
}
}
}
if(clampToMaxEdgeDistance) {
// Find the largest value on the edge of the image
double max = Double.NEGATIVE_INFINITY;
for(int x = 0; x < image.getWidth(); x++) {
max = Math.max(max, distances[x][0]);
max = Math.max(max, distances[x][image.getHeight() - 1]);
}
for(int y = 0; y < image.getHeight(); y++) {
max = Math.max(max, distances[0][y]);
max = Math.max(max, distances[image.getWidth() - 1][y]);
}
// Clamp to that largest value
for(int x = 0; x < image.getWidth(); x++) {
for(int y = 0; y < image.getHeight(); y++) {
distances[x][y] = Math.max(max, distances[x][y]);
}
}
}
this.width = image.getWidth();
this.height = image.getHeight();
setOutputRange();
}
private double[][] calculateDistance2D(double[][] f) {
double[][] d = new double[f.length][f[0].length];
// Distance pass for each column
for(int x = 0; x < f.length; x++) {
d[x] = calculateDistance1D(f[x]);
}
// Distance pass for each row
double[] row = new double[f.length];
for(int y = 0; y < f[0].length; y++) {
for(int x = 0; x < f[0].length; x++)
row[x] = d[x][y];
row = calculateDistance1D(row);
for(int x = 0; x < f[0].length; x++) {
d[x][y] = Math.sqrt(row[x]);
}
}
return d;
}
private double[] calculateDistance1D(double[] f) {
double[] d = new double[f.length];
int[] v = new int[f.length];
double[] z = new double[f.length + 1];
int k = 0;
v[0] = 0;
z[0] = Integer.MIN_VALUE;
z[1] = Integer.MAX_VALUE;
for(int q = 1; q <= f.length - 1; q++) {
double fqPlusQ2 = (f[q] + Math.pow(q, 2));
double twoQ = 2 * q;
double s = (fqPlusQ2 - (f[v[k]] + Math.pow(v[k], 2))) / (twoQ - 2 * v[k]);
while(s <= z[k]) {
k--;
s = (fqPlusQ2 - (f[v[k]] + Math.pow(v[k], 2))) / (twoQ - 2 * v[k]);
}
k++;
v[k] = q;
z[k] = s;
z[k + 1] = Integer.MAX_VALUE;
}
k = 0;
for(int q = 0; q <= f.length - 1; q++) {
while(z[k + 1] < q)
k++;
d[q] = Math.pow(q - v[k], 2) + f[v[k]];
}
return d;
}
/**
* Redistributes the stored distance computation according to the provided {@link Normalization} method.
*/
private void normalize(Normalization normalization) {
for(int x = 0; x < width; x++) {
for(int y = 0; y < height; y++) {
double d = distances[x][y];
distances[x][y] = switch(normalization) {
case None -> distances[x][y];
case Linear -> lerp(d, minDistance, -1, maxDistance, 1);
case SmoothPreserveZero -> {
if(minDistance > 0 || maxDistance < 0) {
// Can't preserve zero if it is not contained in range so just lerp
yield lerp(distances[x][y], minDistance, -1, maxDistance, 1);
} else {
if(d > 0) {
yield Math.pow(d / maxDistance, 2);
} else if(d < 0) {
yield -Math.pow(d / minDistance, 2);
} else {
yield 0;
}
}
}
};
}
}
setOutputRange();
}
private void setOutputRange() {
double minDistance = Double.POSITIVE_INFINITY;
double maxDistance = Double.NEGATIVE_INFINITY;
for(int x = 0; x < width; x++) {
for(int y = 0; y < height; y++) {
minDistance = Math.min(minDistance, distances[x][y]);
maxDistance = Math.max(maxDistance, distances[x][y]);
}
}
this.minDistance = minDistance;
this.maxDistance = maxDistance;
}
public enum CostFunction {
Channel,
Threshold,
ThresholdEdge,
ThresholdEdgeSigned,
}
public enum Normalization {
/**
* Return the raw calculated distances.
*/
None,
/**
* Redistribute the output values to fit in the range [-1, 1]
*/
Linear,
/**
* Redistributes smoothly to the range [-1, 1], such that areas where distance = 0 stay 0.
* This is only really applicable to signed distance calculations, and will fall back to linear
* redistribution if the input range does not contain both positive and negative values.
*/
SmoothPreserveZero,
}
public static class Noise implements Sampler {
private final DistanceTransform transform;
public Noise(DistanceTransform transform, Normalization normalization) {
this.transform = transform;
transform.normalize(normalization);
}
@Override
public double getSample(long seed, double x, double y) {
if(x < 0 || y < 0 || x >= transform.width || y >= transform.height) return transform.minDistance;
return transform.distances[FloatingPointFunctions.floor(x)][FloatingPointFunctions.floor(y)];
}
@Override
public double getSample(long seed, double x, double y, double z) {
return getSample(seed, x, z);
}
}
}
@@ -1,41 +0,0 @@
package com.dfsek.terra.addons.image.sampler;
import com.dfsek.seismic.type.sampler.Sampler;
import com.dfsek.terra.addons.image.colorsampler.ColorSampler;
import com.dfsek.terra.addons.image.util.ColorUtil;
import com.dfsek.terra.addons.image.util.ColorUtil.Channel;
import static com.dfsek.terra.addons.image.util.MathUtil.lerp;
public class ChannelSampler implements Sampler {
private final ColorSampler colorSampler;
private final Channel channel;
private final boolean normalize;
private final boolean premultiply;
public ChannelSampler(ColorSampler colorSampler, Channel channel, boolean normalize, boolean premultiply) {
this.colorSampler = colorSampler;
this.channel = channel;
this.normalize = normalize;
this.premultiply = premultiply;
}
@Override
public double getSample(long seed, double x, double y) {
int sample = colorSampler.apply((int) x, (int) y);
int premultiplied = premultiply ? ColorUtil.premultiply(sample) : sample;
double channelValue = channel.from(premultiplied);
return normalize ? lerp(channelValue, 0, -1, 255, 1) : channelValue;
}
@Override
public double getSample(long seed, double x, double y, double z) {
return getSample(seed, x, z);
}
}
@@ -1,340 +0,0 @@
package com.dfsek.terra.addons.image.util;
/**
* Utility class for manipulating 8 bit ARGB colors
*/
public class ColorUtil {
private ColorUtil() { }
public static int distance(int a, int b) {
return Math.abs(getRed(a) - getRed(b)) +
Math.abs(getGreen(a) - getGreen(b)) +
Math.abs(getBlue(a) - getBlue(b));
}
/**
* Returns the red channel value of a given ARGB color value.
*
* @param argb the ARGB color value to extract the red channel value from
*
* @return the red channel value of the given ARGB color value, in the range 0-255
*/
public static int getRed(int argb) {
return argb >> 16 & 255;
}
/**
* Returns the green channel value of a given ARGB color value.
*
* @param argb the ARGB color value to extract the green channel value from
*
* @return the green channel value of the given ARGB color value, in the range 0-255
*/
public static int getGreen(int argb) {
return argb >> 8 & 255;
}
/**
* Returns the blue channel value of a given ARGB color value.
*
* @param argb the ARGB color value to extract the blue channel value from
*
* @return the blue channel value of the given ARGB color value, in the range 0-255
*/
public static int getBlue(int argb) {
return argb & 255;
}
/**
* Returns the alpha channel value of a given ARGB color value.
*
* @param argb the ARGB color value to extract the blue channel value from
*
* @return the alpha channel value of the given ARGB color value, in the range 0-255
*/
public static int getAlpha(int argb) {
return argb >> 24 & 255;
}
/**
* Returns the grayscale value of a given ARGB color value.
*
* @param argb the ARGB color value to convert to grayscale
*
* @return the grayscale value of the given ARGB color value, in the range 0-255
*/
public static int getGrayscale(int argb) {
return (getRed(argb) + getGreen(argb) + getBlue(argb)) / 3;
}
/**
* Returns the value of the specified channel for a given ARGB color value.
*
* @param argb the ARGB color value to extract the channel value from
* @param channel the channel to extract the value from
*
* @return the value of the specified channel for the given ARGB color value, in the range 0-255
*/
public static int getChannel(int argb, Channel channel) {
return channel.from(argb);
}
/**
* Sets the red channel value of a given ARGB color value to zero.
*
* @param argb the ARGB color value to zero the red channel of
*
* @return the resulting ARGB color value with the red channel set to zero
*/
public static int zeroRed(int argb) {
return argb & ~0x00FF0000;
}
/**
* Sets the green channel value of a given ARGB color value to zero.
*
* @param argb the ARGB color value to zero the green channel of
*
* @return the resulting ARGB color value with the green channel set to zero
*/
public static int zeroGreen(int argb) {
return argb & ~0x0000FF00;
}
/**
* Sets the blue channel value of a given ARGB color value to zero.
*
* @param argb the ARGB color value to zero the blue channel of
*
* @return the resulting ARGB color value with the blue channel set to zero
*/
public static int zeroBlue(int argb) {
return argb & ~0x000000FF;
}
/**
* Sets the alpha channel value of a given ARGB color value to zero.
* This is the same as setting the color to fully transparent.
*
* @param argb the ARGB color value to zero the alpha channel of
*
* @return the resulting ARGB color value with the alpha channel set to zero
*/
public static int zeroAlpha(int argb) {
return argb & ~0xFF000000;
}
/**
* Sets the color channels of a given ARGB color value to zero.
* This is the same as setting the color to black, while preserving the alpha.
*
* @param argb the ARGB color value to zero the color channel of
*
* @return the resulting ARGB color value with the color channels set to zero
*/
public static int zeroGrayscale(int argb) {
return argb & ~0x00FFFFFF;
}
/**
* Sets the specified channel value of a given ARGB color value to zero.
*
* @param argb the ARGB color value to zero the specified channel of
* @param channel the channel to zero the value of
*
* @return the resulting ARGB color value with the specified channel value set to zero
*/
public static int zeroChannel(int argb, Channel channel) {
return channel.zero(argb);
}
/**
* Multiply the RGB channels of a given ARGB color value by its alpha channel value.
*
* @param argb the ARGB color value to premultiply the RGB channels of
*
* @return the resulting premultiplied ARGB color value
*/
public static int premultiply(int argb) {
int alpha = getAlpha(argb);
int red = (getRed(argb) * alpha + 127) / 255;
int green = (getGreen(argb) * alpha + 127) / 255;
int blue = (getBlue(argb) * alpha + 127) / 255;
return argb(alpha, red, green, blue);
}
/**
* Returns an ARGB color value with the specified values for alpha, red, green, and blue channels.
*
* @param alpha the alpha value, between 0 and 255, to set in the ARGB color value
* @param red the red value, between 0 and 255, to set in the ARGB color value
* @param green the green value, between 0 and 255, to set in the ARGB color value
* @param blue the blue value, between 0 and 255, to set in the ARGB color value
*
* @return the resulting ARGB color value with the specified values for alpha, red, green, and blue channels
*/
public static int argb(int alpha, int red, int green, int blue) {
return argbAlpha(alpha) | argbRed(red) | argbGreen(green) | argbBlue(blue);
}
/**
* Returns an ARGB color value with the specified values for alpha, red, green, and blue channels,
* after validating that each channel value is in the range 0-255.
*
* @param alpha the alpha value, between 0 and 255, to set in the ARGB color value
* @param red the red value, between 0 and 255, to set in the ARGB color value
* @param green the green value, between 0 and 255, to set in the ARGB color value
* @param blue the blue value, between 0 and 255, to set in the ARGB color value
*
* @return the resulting ARGB color value with the specified values for alpha, red, green, and blue channels
*
* @throws IllegalArgumentException if any channel value is outside the range 0-255
*/
public static int argbValidated(int alpha, int red, int green, int blue) throws IllegalArgumentException {
if(alpha < 0 || alpha > 255 ||
red < 0 || red > 255 ||
green < 0 || green > 255 ||
blue < 0 || blue > 255
) throw new IllegalArgumentException("Channel values must be in range 0-255");
return argb(alpha, red, green, blue);
}
/**
* Returns the ARGB color value with the specified alpha channel value and zero
* for the red, green, and blue channels.
*
* @param alpha the alpha channel value to set in the ARGB color value
*
* @return the resulting ARGB color value
*/
public static int argbAlpha(int alpha) { return alpha << 24; }
/**
* Returns the ARGB color value with the specified red channel value and zero
* for the alpha, green, and blue channels.
*
* @param red the red channel value to set in the ARGB color value
*
* @return the resulting ARGB color value
*/
public static int argbRed(int red) { return red << 16; }
/**
* Returns the ARGB color value with the specified red channel value and zero
* for the alpha, red, and blue channels.
*
* @param green the green channel value to set in the ARGB color value
*
* @return the resulting ARGB color value
*/
public static int argbGreen(int green) { return green << 8; }
/**
* Returns the ARGB color value with the specified blue channel value and zero
* for the alpha, red, and green channels.
*
* @param blue the blue channel value to set in the ARGB color value
*
* @return the resulting ARGB color value
*/
public static int argbBlue(int blue) { return blue; }
/**
* Returns an ARGB color value with the specified grayscale value for all four channels.
*
* @param value the grayscale value to set in all four channels of the ARGB color value
*
* @return the resulting ARGB color value with the specified grayscale value for all four channels
*/
public static int argbGrayscale(int value) { return argb(value, value, value, value); }
public enum Channel {
RED {
@Override
public int from(int argb) {
return getRed(argb);
}
@Override
public int zero(int argb) {
return zeroRed(argb);
}
@Override
public int argb(int value) {
return argbRed(value);
}
},
GREEN {
@Override
public int from(int argb) {
return getGreen(argb);
}
@Override
public int zero(int argb) {
return zeroGreen(argb);
}
@Override
public int argb(int value) {
return argbGreen(value);
}
},
BLUE {
@Override
public int from(int argb) {
return getBlue(argb);
}
@Override
public int zero(int argb) {
return zeroBlue(argb);
}
@Override
public int argb(int value) {
return argbBlue(value);
}
},
GRAYSCALE {
@Override
public int from(int argb) {
return getGrayscale(argb);
}
@Override
public int zero(int argb) {
return zeroGrayscale(argb);
}
@Override
public int argb(int value) {
return argbAlpha(value);
}
},
ALPHA {
@Override
public int from(int argb) {
return getAlpha(argb);
}
@Override
public int zero(int argb) {
return zeroAlpha(argb);
}
@Override
public int argb(int value) {
return argbAlpha(value);
}
};
public abstract int from(int argb);
public abstract int zero(int argb);
public abstract int argb(int value);
}
}
@@ -1,25 +0,0 @@
package com.dfsek.terra.addons.image.util;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collectors;
public class MapUtil {
private MapUtil() { }
/**
* Utility method for applying transformations on a map's keys.
*/
public static <O, N, T> Map<N, T> mapKeys(Map<O, T> map, Function<O, N> mappingFunction) {
return map
.entrySet()
.stream()
.collect(Collectors.toMap(
e -> mappingFunction.apply(e.getKey()),
Entry::getValue
));
}
}
@@ -1,9 +0,0 @@
package com.dfsek.terra.addons.image.util;
public class MathUtil {
private MathUtil() { }
public static double lerp(double x, double x1, double y1, double x2, double y2) {
return (((y1 - y2) * (x - x1)) / (x1 - x2)) + y1;
}
}
@@ -1,12 +0,0 @@
schema-version: 1
contributors:
- Terra contributors
id: api-image
version: @VERSION@
entrypoints:
- "com.dfsek.terra.addons.image.ImageLibraryAddon"
website:
issues: https://github.com/PolyhedralDev/Terra/issues
source: https://github.com/PolyhedralDev/Terra
docs: https://terra.polydev.org
license: MIT License
@@ -1,6 +0,0 @@
version = version("1.0.0")
dependencies {
compileOnlyApi(project(":common:addons:addon-loader-manifest"))
compileOnlyApi(project(":common:addons:api-biome-query"))
}

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