Compare commits

...

54 Commits

Author SHA1 Message Date
dfsek eca46a7c64 start working on mixins 2021-06-05 00:49:38 -07:00
dfsek 74fdf9a18e start working on internal stuff 2021-06-02 15:21:03 -07:00
dfsek c0f1ccb66a initialize earlier 2021-06-02 10:39:36 -07:00
dfsek 44410323af config loading w/o errors 2021-06-02 10:26:55 -07:00
dfsek aaf32709b4 set up sponge api8 project 2021-06-02 09:45:11 -07:00
solo c1c2ab6df8 General repository maintenance. (#94)
* Fixes #93

Add pull request and issue templates.

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* Add CODEOWNERS file

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* Fix yaml issues

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

fix yaml??

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

Fix name of issue template.

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* Testing if I can do this with prs too

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

Can I do this with pr templates too??

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

Can I do this with pr templates too??

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

Can I do this with pr templates too??

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* Move PULL_REQUEST_TEMPLATE/PULL_REQUEST.md to PULL_REQUEST_TEMPLATE.md, because github :poob:

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* I don't think I can... oof.

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* Oops, forgot to add this link.

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* Perform requested changes

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* Forgot one

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* Server software -> Platform & Merge platform + platform version

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* Inclusion of "addon" in language

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* compat with other terrain gen mods

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* inclusion of "addon" in FEATURE_REQUEST.md

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* Update CODEOWNERS

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* add discord link to config.yml

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* update PULL_REQUEST_TEMPLATE.md to no longer use "plugin"

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* Reintroduce stacktrace section

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* be more specific about compat issues

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* modify CODEOWNERS

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* Add CODE_OF_CONDUCT.md

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* Repo: add CONTRIBUTING.md file

Add CONTRIBUTING.md file with some basic guidelines on how to get started contributing.

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* Repo: Update git commit types

Update git commit types in CONTRIBUTING.md and sort them.

Add new entries under "types of changes" for PULL_REQUEST_TEMPLATE.md.

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>

* Repo: Performed requested changes

forgot some stuff lol

Signed-off-by: solonovamax <solonovamax@12oclockpoint.com>
2021-05-31 17:57:55 -07:00
dfsek fa164e5281 Merge pull request #199 from PolyhedralDev/dev/forge-tweaks
Forge Tweaks
2021-05-22 21:48:12 -07:00
dfsek ec3b0e5d04 implement vanilla mob override 2021-05-22 21:37:16 -07:00
dfsek 4c63c2681f implement ForgeChunkGeneratorWrapper#getBaseColumn 2021-05-22 21:34:28 -07:00
dfsek dd661feaf1 implement dimension type injection/caching 2021-05-22 21:24:25 -07:00
dfsek 1f17bfff1b delegate strongholds to vanilla if vanilla structures are enabled 2021-05-22 21:12:44 -07:00
dfsek 809a0b375d implement identifier loader 2021-05-22 21:11:52 -07:00
dfsek d55b3415ac implement structure locate override on Forge 2021-05-22 21:08:51 -07:00
dfsek edcb818842 basic compatibility stuff on Forge 2021-05-22 18:03:34 -07:00
dfsek 1e429e1bb3 create forge compatibility configs 2021-05-22 17:11:50 -07:00
dfsek 3472859afb remove unused event handlers 2021-05-22 17:10:50 -07:00
dfsek 26025ec276 remove unused class 2021-05-22 00:19:38 -07:00
dfsek 3b3905b513 mixin injection on client in forge 2021-05-21 23:36:20 -07:00
dfsek ce3d09cf2e add background to pack selection GUI 2021-05-19 09:23:20 -07:00
dfsek 5dd00db8d2 Merge pull request #191 from PolyhedralDev/dev/fabric-compat
Options for mod compatibility on Fabric
2021-05-18 20:07:24 -07:00
dfsek 2dc7b50141 implement getColumnSample 2021-05-18 19:50:05 -07:00
dfsek b2ebcc63aa Merge remote-tracking branch 'origin/dev/fabric-compat' into dev/fabric-compat 2021-05-18 18:26:34 -07:00
dfsek f45bc0a0cc Merge remote-tracking branch 'origin/dev/fabric-compat' into dev/fabric-compat 2021-05-18 18:25:46 -07:00
dfsek bbe53cbca3 fix height again 2021-05-18 18:25:31 -07:00
dfsek 7354155c52 bump version 2021-05-18 18:19:25 -07:00
dfsek c1acfee910 Merge pull request #189 from Shadowhackercz/master
Creating new locale for Czech
2021-05-18 17:56:31 -07:00
dfsek 5287323865 only inject carvers if vanilla.caves is enabled 2021-05-18 09:24:20 -07:00
dfsek b09d0e42aa fix biome specific exclusions 2021-05-18 09:06:43 -07:00
dfsek a3f14061dd fix structure location 2021-05-17 23:04:21 -07:00
dfsek 557098de17 use debug logger for feature info 2021-05-17 22:48:03 -07:00
dfsek 2fdb96a850 cleanup and add per-biome exclusions 2021-05-17 22:45:39 -07:00
dfsek d93d064d97 fix getHeight 2021-05-17 20:50:27 -07:00
dfsek ae76fb7dc4 use dimensiontype to get world 2021-05-17 20:16:32 -07:00
dfsek 2626afd066 override entity generation 2021-05-17 19:41:45 -07:00
dfsek c0042cfb6b switch to DimensionType map 2021-05-17 19:39:46 -07:00
dfsek a549d2ef34 move client init code to MinecraftClientMixin 2021-05-17 19:26:25 -07:00
dfsek 4aa20c32b8 fix fabric debuglogger 2021-05-17 17:35:56 -07:00
dfsek ce7033b4ca filter out non-Terra biomes in TerraBiomeSource 2021-05-17 10:07:22 -07:00
dfsek 41a54f4b25 vanilla structures 2021-05-17 10:07:06 -07:00
dfsek f96740f1fa refactor util classes 2021-05-17 08:38:03 -07:00
Shadowhacker 8844cd5069 Creating new locale for Czech
I've created a new localization file for Czech language
2021-05-17 03:53:07 +02:00
dfsek 800d846af4 carver and structure compatibility options 2021-05-16 16:47:17 -07:00
dfsek 95d50a0391 resolve merge conflicts 2021-05-16 00:42:29 -07:00
dfsek 5a83eab1fe Merge remote-tracking branch 'origin/master' into dev/fabric-compat
# Conflicts:
#	platforms/fabric/src/main/java/com/dfsek/terra/fabric/TerraFabricPlugin.java
#	platforms/forge/src/main/java/com/dfsek/terra/forge/TerraForgePlugin.java
2021-05-16 00:34:42 -07:00
dfsek bac026a1f4 Merge pull request #187 from PolyhedralDev/dev/fabric-no-api
Remove dependency on Fabric API
2021-05-15 21:18:27 -07:00
dfsek 65482c493a remove dependency on Fabric API 2021-05-15 20:30:06 -07:00
dfsek 242e56b1d8 conditional biome injection 2021-05-12 09:27:20 -07:00
dfsek 4c7aa11353 clean up TerraFabricPlugin 2021-05-12 08:39:43 -07:00
dfsek cac84ffe03 fix typo 2021-05-12 00:55:14 -07:00
dfsek cf66e1e226 registry injection 2021-05-12 00:53:25 -07:00
dfsek fa647e1e2c make loadConfig less jank 2021-05-12 00:48:38 -07:00
dfsek 4203121d40 basic feature loading implementation 2021-05-12 00:33:00 -07:00
dfsek 82fe6d5aa4 add api to load custom values from pack manifest. 2021-05-12 00:09:21 -07:00
dfsek 32db83f091 remove NotNullValidator 2021-05-11 23:56:08 -07:00
61 changed files with 2657 additions and 569 deletions
+19
View File
@@ -0,0 +1,19 @@
# Global owners, automatically request review when pull request is submitted
* @dfsek @solonovamax
# Platforms
## 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
# Gradle Stuff
## Most gradle stuff was written by solonovamax
/buildSrc/ @solonovamax
*.gradle.kts @solonovamax
+105
View File
@@ -0,0 +1,105 @@
---
name: "Bug Report"
about: "Open a bug report to help us identify issues with Terra."
title: "[Bug] <Put your title here>"
labels: "Type: Bug, Status: Pending"
assignees: ""
---
<!--
##############################################################################
## WARNING! ##
## IGNORING THE FOLLOWING TEMPLATE WILL RESULT IN YOUR ISSUE BEING CLOSED ##
##############################################################################
-->
## Pre-Issue Checklist
<!--
Please go through this checklist item by item and make sure you have successfully completed each of these steps.
- You must be on the LATEST version of Terra to receive any support. There is no support for older versions of Terra.
- 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 main project.
*General* compatibility (e.g. "Ability to pull Vanilla/Modded features from parent biomes") will be considered in the main project.
- Make sure that there are no already existing issues open with your problem. If you open a duplicate, it will be closed as such.
- Make sure that it is actually Terra causing the issue, and not another mod/plugin.
You can do this by testing to see if you can recreate the issue without Terra installed.
- Make sure that this is not an issue with a specific Terra *pack* or Terra *addon*, and instead applies to all of Terra.
- Make sure that you attach a copy of the latest.log file.
Putting *just* the exception IS NOT ENOUGH. We need to be able to check that there wasn't anything else before that caused it.
- Make sure that you have filled out all the required information and given descriptions of everything.
You must put an x in all the boxes you have completed. (Like this: [x])
To make sure that your issue is rendered properly, you may check the "Preview" tab (below the title) to see a rendered version of it before you submit it.
-->
- [ ] 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/TerraDefaultConfig/issues/new -->
- [ ] I have attached a copy of the `latest.log` file
- [ ] I have filled out and provided all the appropriate information.
## Environment
<!-- 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) -->
## Issue Description
<!--
Put a quick description of the issue here.
Example: 'When generating terrain, something causes the chunks to not load properly', etc.
-->
### Steps to reproduce
<!--
Describe what you were doing when this happened.
Make sure to include ALL information. Including anything you were doing before that may have caused it.
-->
1. <!-- Put step #1 here. -->
2. <!-- Put step #2 here. -->
3. <!-- etc. -->
### Expected behavior
<!-- Describe what you think *should* happen here: -->
### Actual behavior
<!-- Describe what *actually* happens here: -->
<!-- example: When I do _______, it actually does _______ -->
### Full stacktrace
<details>
<summary>Exception Stacktrace</summary>
<!--
If Terra logs an exception, please put it in the following section: (You will find any error logs in your console, or your latest.log)
Note: this *must* be included, in ADDITION to the latest.log file.
-->
```
```
</details>
### Additional details
<!-- Any other information you think should be added -->
+70
View File
@@ -0,0 +1,70 @@
---
name: "Feature Request"
about: "Give us suggestions of features we could add to Terra."
title: "[Feature] <Put your title here>"
labels: "Type: Enhancement, Status: Pending"
assignees: ""
---
<!--
########################################################################################
## WARNING! ##
## IGNORING THE FOLLOWING TEMPLATE WILL RESULT IN YOUR FEATURE REQUEST BEING CLOSED ##
########################################################################################
-->
### Pre-Request Checklist
<!--
Please go through this checklist item by item and make sure you have successfully completed each of these steps.
- You must be on the LATEST version of Terra to make sure your feature hasn't been added yet.
- Make sure that there are no already existing feature requests similar to yours. (Including closed!) If you open a duplicate, it will be closed as such.
- Make sure that this is actually in the scope of Terra.
- Make sure that this is not a feature request that should be made for a specific Terra *pack*, and instead applies to all of Terra.
- Make sure that you attach a copy of the latest.log file, if there are any exceptions thrown in the console.
Putting *just* the exception IS NOT ENOUGH. We need to be able to check that there wasn't anything else before that caused it.
You must put an x in all the boxes you have completed. (Like this: [x])
To make sure that your issue is rendered properly, you may check the "Preview" tab (below the title) to see a rendered version of it before you submit it.
-->
- [ ] 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 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.
## Feature Description
<!--
Quickly describe the basics of your feature request.
Example: 'More noise presets should be added to Terra.'
-->
### What Problem Does This Solve?
<!--
Describe here what the issue is that you have.
Examples: 'When I do _______, it annoys me that _______ does _______.' or 'There is not enough customization in _______ to do _______.'
NOTE: This should NOT be used for a bug report. If this is unintentional, then please submit a bug report instead.
-->
### A Solution You'd Like
<!-- Provide a clear and accurate description of how you would like this to be solved. -->
### Alternative Solutions
<!-- Provide a description of alternatives you have considered to this. -->
1. <!-- Alternative #1. -->
2. <!-- Alternative #2. -->
3. <!-- Alternative #3. -->
### Additonal Context
<!--
Is there any additional context you would like to add?
If not, you may remove this section.
-->
+11
View File
@@ -0,0 +1,11 @@
---
name: "Other Issue"
about: "Use this template if your issue doesn't accurately fit into any of the other categories."
title: ""
labels: "Type: Question, Status: Pending"
assignees: ""
---
## Describe the issue
<!-- Please describe the issue as clearly and as concisely as possible, without missing any details. -->
+11
View File
@@ -0,0 +1,11 @@
blank_issues_enabled: false
contact_links:
- name: Which Issue Template do I Choose?
url: https://github.com/PolyhedralDev/Terra/wiki/How-To-Choose-An-Issue-Template
about: Click this if you don't know which issue template to select. This will help you make sure you choose the right one and provide enough information for us to help you.
- name: Terra Wiki
url: https://github.com/PolyhedralDev/Terra/wiki
about: Documentation for all things Terra.
- name: Join the Support Discord
url: https://discord.dfsek.com
about: If you have a basic support question, join the Discord instead.
+114
View File
@@ -0,0 +1,114 @@
# Pull Request
## Brief description.
<!-- Please provide a brief description of the goals of your PR -->
<!--
###########################################################################
## 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.
-->
## 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
<!--
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 -->
- [ ] <!-- A requirement of the first thing. -->
- [ ] <!-- A second requirement of the first thing. -->
- [ ] <!-- Second thing -->
- [ ] <!-- etc. -->
## Affects of the PR
<!---
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])
-->
#### Types of changes
- [ ] 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. -->
#### Compatiblity
- [ ] 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.)
-->
#### 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
- [ ] My change requires a change to the documentation.
- [ ] I have updated the documentation accordingly.
#### Testing
- [ ] I have added tests to cover my changes.
- [ ] All new and existing tests passed.
<!--
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.
-->
+11 -14
View File
@@ -85,14 +85,14 @@ hs_err_pid*
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
.idea/artifacts
.idea/compiler.xml
.idea/jarRepositories.xml
.idea/modules.xml
.idea/*.iml
.idea/modules
*.iml
*.ipr
.idea/artifacts
.idea/compiler.xml
.idea/jarRepositories.xml
.idea/modules.xml
.idea/**.iml
.idea/modules
*.iml
*.ipr
# CMake
cmake-build-*/
@@ -137,10 +137,7 @@ build
.idea/modules/**.iml
!lib/*.jar
.idea/Terra.iml
/run/
.idea/**.iml
/lang/
/packs/
/config.yml
/region/
idea/**
testDir/
+337
View File
@@ -0,0 +1,337 @@
# Terra Community Code of Conduct
# TL;DR
Polyhedral Development is dedicated to providing a harassment-free experience for everyone, regardless of gender, gender identity and
expression, preferred pronouns, sexual orientation, disability, physical appearance, age, race, religion, etc. We do not tolerate harassment
of participants in any form.
This code of conduct applies to all Terra community spaces, including the github discussions tab, our
[community discord server](https://discord.gg/PXUEbbF), the [community subreddit](https://reddit.com/r/TerraGenerator), or any other Terra
space, both online and off. Anyone in violation of this code, as determined by the applicable moderators, may be subject to verbal warning,
expulsion from these spaces, or future events and activities for an undetermined amount of time.
Some Terra community spaces may have additional rules in place, which will be made clearly available to all participants. Participants are
responsible for knowing and abiding by these rules.
# Longer version
Polyhedral Development is dedicated to providing a harassment-free experience 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), 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 form, even outside of Terra.
Some Terra spaces may have additional rules in place, which will be made clearly available to participants. Participants are responsible for
knowing and abiding by these rules, in addition to this code of conduct.
## Expected Behavior
The following behaviors are expected of all members of the Terra community:
### Be Respectful
Value each other's ideas, styles and viewpoints. We may not always agree, but disagreement is no excuse for poor manners. Be open to
different possibilities and to being wrong. Be respectful in all interactions and communications, especially when debating the merits of
different options. Be aware of your impact and how intense interactions may be affecting people. Be direct, constructive and positive. Take
responsibility for your impact, and your mistakes if someone says they have been harmed through your words or actions, listen carefully,
apologize sincerely, and correct the behavior going forward.
#### Be Prepared to Admit When You are Wrong
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.
### Be Direct but Professional
We are likely to have some discussions about if and when criticism is respectful and when it's not. We must be able to speak directly when
we disagree and when we think we need to improve. We cannot withhold hard truths. Doing so respectfully is hard, doing so when others don't
seem to be listening is harder, and hearing such comments when one is the recipient can be even harder still. We need to be honest and
direct, as well as respectful.
### Be Inclusive
Seek diverse perspectives. Diversity of views and of people on teams powers innovation, even if it is not always comfortable. Encourage all
voices. Help new perspectives be heard and listen actively. If you find yourself dominating a discussion, it is especially important to step
back and encourage other voices to join in. Be aware of how much time is taken up by dominant members of the group. Provide alternative ways
to contribute or participate when possible.
Be inclusive of everyone in an interaction, respecting and facilitating people's participation whether they are:
- Not native language speakers
- Coming from a different culture
- Using pronouns other than "he", "she", or "they"
- Living in a different time zone
- Facing other challenges to participate
- Or anything else. Be respectful of *everyone* at *all times*.
Think about how you might facilitate alternative ways to contribute or participate. If you find yourself dominating a discussion, step back.
Make way for other voices and listen actively to them.
### Understand Different Perspectives
Our goal should not be to "win" every disagreement or argument. A more productive goal is to be open to ideas that make our own ideas
better. Strive to be an example for inclusive thinking. "Winning" is when different perspectives make our work richer and stronger. That
means, you must pay attention to all ideas proposed. Don't disregard one without giving it the attention it deserves.
### Appreciate and Accommodate Our Similarities and Differences
People come from many cultures and backgrounds. Cultural differences can encompass everything from official religious observances to
personal habits to clothing. Be respectful of anyone with different cultural practices, attitudes and beliefs. Work to eliminate your own
biases, prejudices and discriminatory practices. Think of others' needs from their point of view. Use preferred titles (including
pronouns<sup>[\[1\]](#1)</sup>) and the appropriate tone of voice. Respect people's right to privacy and confidentiality. Be open to
learning from and educating others as well as educating yourself; it is unrealistic to expect someone to know the cultural practices of
every ethnic and cultural group. Therefore we must be ready to correct someone if they make a mistake, and must be ready ourselves to change
and learn if we make a mistake.
### Lead by Example
By matching your actions with your words, you become a person others want to follow. Your actions influence others to behave and respond in
ways that are valuable and appropriate for our organizational outcomes. Design your community and your work for inclusion. Hold yourself and
others accountable for inclusive behaviors.
## Behavior That Will Not Be Tolerated
The following behaviors are considered to be unacceptable and will not be tolerated:
### Violence and Threats of Violence
Violence and threats of violence are not acceptable - online or offline. This includes incitement of violence toward any individual,
including encouraging a person to commit self-harm, engage in self-harm, or put themselves in a negative position (e.g. one which can lead
to an increase of depression, etc.).
### Personal Attacks
Conflicts will inevitably arise, but frustration should never turn into a personal attack. It is not okay to insult, demean or belittle
others. Attacking someone for their opinions, beliefs and ideas is not acceptable. It is important to speak directly when we disagree and
when we think we need to improve, but such discussions must be conducted respectfully and professionally, remaining focused on the issue at
hand.
### Derogatory Language
Offensive, unwelcome, or hurtful comments related to:
- Gender
- Gender identity or expression
- Preferred pronouns<sup>[\[1\]](#1)</sup>
- Marital status
- Sex
- Sexual orientation or identity
- Native language
- Age
- (Dis)ability
- Mental illness
- Neuro(a)typicality
- Race and/or ethnicity
- Physical appearance
- A person's lifestyle choices or practices,
- A person's physical condition
- A person's mental condition
- Socioeconomic status
- Religion
- Employment
- Or anything really. Just don't be offensive towards people, insult them, or make unwanted comments.
is not acceptable. This includes deliberately referring to someone by a gender that they do not identify with, and/or questioning the
legitimacy of an individual's gender identity. If you're unsure if a word is derogatory, don't use it. This also includes repeated subtle
and/or indirect discrimination; when asked to stop, stop the behavior in question.
### Unwelcome Sexual Attention or Physical Contact
Unwelcome sexual attention or unwelcome physical contact is not acceptable. This includes sexualized comments, jokes or imagery in
interactions, communications or presentation materials, as well as inappropriate touching, groping, or sexual advances. Additionally,
touching a person without permission, including sensitive areas such as their hair, pregnant stomach, mobility device (wheelchair, scooter,
etc) or tattoos is unacceptable. This includes physically blocking or intimidating another person. Physical contact or simulated physical
contact (e.g. emojis like ":&#8203;kiss:", ":hug:", or ":kiss_mark:", textual descriptions like "\*hug\*", "\*backrub\*", or "\*kisses
you\*", etc.) without affirmative consent or after a request to stop will not be accepted.
### Sexual Behaviour Where it is Not Appropriate
Uninvited or off-topic sexual images, text, or behaviour in spaces where they're not appropriate will not be accepted whatsoever. We are an
open community, which means spaces must be appropriate for all ages, and everybody must feel comfortable. Discussion of sexual things, will
be prohibited unless otherwise noted.
### Discussion of Sensitive Topics
Discussion of sensitive topics when asked to stop, or when not appropriate. Including, but not limited to:
- Anything sexual
- Gore
- Suicide
- Self harm
- Anything related to death
- Or really anything that someone may be sensitive about.
shall not be tolerated. As a community for all ages and all kinds of people, we must cater to everyone, and must make sure everyone feels
comfortable here. Repeatedly breaking someone else's boundaries will not be tolerated.
### Disruptive Behavior
Sustained disruption of events, forums, or meetings, online or otherwise, including talks and presentations, will not be tolerated. This
includes:
- 'Talking over', 'heckling', or otherwise disrupting speakers.
- Making derogatory comments about someone else's choices, pushing people to do something they do not wish to do, talking about their
choices or personal preferences to others, or pressuring them to do something they don't wish to - physically or through jeering.
- Behaviour that intentionally disrupts an event.
- Otherwise influencing actions that may cause hostility in the session.
### Influencing Unacceptable Behavior
We will treat influencing or leading such activities the same way we treat the activities themselves, and thus the same consequences apply.
To make someone do something bad is the same thing as if you were to do it yourself, and we will not tolerate it.
### Stalking or Following
Stalking or following in any form (offline or online) is unnacceptable. In addition, you may not take pictures or record video of others
without their express permission or when asked to stop. Any individual may also request for you to delete all footage you have of them, even
if you took it with their prior consent.
### Publication of Personal Information
The publication of personally identifying information (commonly known as "[doxxing](https://en.wikipedia.org/wiki/Doxing)") is directly
prohibited. You may not publish information that someone wants to keep private, unless it is necessary to protect vulnerable people from
intentional abuse. Addditionally, you may not deliberately "out" any aspect of a person's identity without their consent, this includes
gender, pronouns, sexual identity, etc.
Unless it pretains to a case of harassment, as outlined here, in which case some personally identifying information may need to be brought
up in private with the appropriate moderation team to help aid our efforts in keeping the community safe.
### Deliberate Misuse of Pronouns<sup>[\[1\]](#1)</sup> or Names
As an inclusive community, we must respect everyone. That means respecting the pronouns or names they wish for us to use. Deliberate
misgendering, misuse of preferred pronouns<sup>[\[1\]](#1)</sup>, or use of 'dead' or rejected names is not to be tolerated. (If someone
*accidentally* uses the incorrect pronouns, gender, or name, politely ask them to use the correct pronouns/gender/name. But if they are to
continue using the incorrect pronouns, gender, or name, then you should escalate and report them to us.)
### Not Stopping After Multiple Requests
If someone asks you to stop doing something, then you should stop. Continuing to do it may be considered harassment, and can lead you to be
removed from our community.
## Complains We May Ignore
Additionally, Terra prioritizes marginalized people's safety over privileged people's comfort. We reserve the right to ignore complaints
regarding:
- Claims of discrimination against non-marginalized or oppressed groups (eg. being 'superphobic', meaning to not support people who are
'superstraight', which is a dog whistle for transphobic groups, or being 'cisphobic' without large amounts of evidence, etc.), or claims
of discrimination with no evidence. (Basically, don't report 'cisphobia' to us, because it doesn't exist. But if someone is mocking you or
making fun of you for being cis, and it is *really* getting out of hand, then do tell us.)
- Reasonable communication of boundaries, such as "leave me alone," "go away," or "I'm not discussing this with you." (If someone is asking
you to stop, that is not reason for you to report them as harassing you.)
- Communicating in a 'tone' you don't find [congenial](https://www.thefreedictionary.com/congenial). (You may not report someone for
harassment for being 'annoyed with you' or 'talking sternly to you')
- Criticizing or calling out racist, sexist, discriminatory, or otherwise oppressive behavior or assumptions. (You may not say that someone
is harassing you if they are telling you to stop discriminating against someone.)
- Disagreements that do not qualify as harassment. If you have a simple disagreement with someone, and they have not been discriminating to
anyone, in any form, then we will not take action against them. Two people are allowed to disagree on things without it getting toxic.
We may also additionally choose to enact punishment for submitting a complaint in bad-faith or without adequate justification, if we deem
necessary; if you're submitting a complaint just to troll or to annoy people, we may choose to have you banned or removed from the community
spaces. Don't waste our time.
In order to protect volunteers from abuse and burnout, we reserve the right to reject any report we believe to have been made in bad faith
or with misintent. Reports intended to silence legitimate criticism may be deleted without response.
## Reporting
Terra has a global moderation team which is currently comprised of the following members:
- solonovamax
- discord: [@solonovamax#6983](https://discord.com/channels/@me/566146322273402881)*
- github: [@solonovamax](https://github.com/solonovamax)
- email: [solonovamax@12oclockpoint.com](mailto:solonovamax@12oclockpoint.com)
- dfsek
- 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)*
- github: [@duplexsystem](https://github.com/duplexsystem)
- email: [duplexsys@protonmail.com](mailto:duplexsys@protonmail.com)
\* The preferred method of communication is through discord. Although we will still be responsive on the other platforms, we will be more
responsive on discord.
These are people you can contact for anything regarding this code of conduct.
If you are being harassed by a member of the Terra community, or by someone in a Terra community space, notice that someone else is being
harassed, or have any other concerns, please contact a moderator of the platform it occurred on, or someone on the global moderation team.
If the person who is harassing you is on the global moderation team, they will [recuse](https://www.thefreedictionary.com/recuse) themselves
from handling your incident. (Meaning: if you are reporting someone on the team, they will not be involved in the discussion.) We will
respond within a reasonable time frame, but generally within about 1 day.
This code of conduct applies to Terra community spaces, but if you are being harassed by a member of Terra *outside* our spaces, we still
want to know about it as we may choose to take action within our community. We will take all good-faith reports seriously and will always
attempt to handle them appropriately. This includes harassment outside our spaces and harassment that took place at any point in time. The
moderation team reserves the right to exclude people from Terra communities based on their past behavior, including behavior outside Terra
spaces and behavior towards people who are not in Terra.
Note: although we only have the ability to moderate official community spaces, if you are being harassed by someone in a non-official
community space, and the moderation team of that platform refuses to do anything to help you (or even if they *do* help you), then you
should notify us so that we may take appropriate action.
We will respect confidentiality requests for the purpose of protecting victims of abuse. At our discretion, we may publicly name a person
which we have received harassment complaints about, or privately warn third parties about them, but only if we believe that doing so will
increase the safety of Terra community members or the general public. We will not name harassment victims or reporters of harassment
(assuming the report was made in good-faith) without their explicit consent; all reports will remain anonymous by default.
## Consequences of Unacceptable Behavior
Participants asked to stop any harassing behavior are expected to comply immediately. Whether or not you comply immediately, you may still
face consequences for you actions, but if the harasser doesn't comply immediately then we may choose to take additional actions to protect
the Terra community members or the individual being harassed.
Violation of this code can result in being asked to leave an event or online space, either temporarily or for the duration of the event, or
being banned from participation in spaces, or future events and activities in perpetuity. If a participant engages in harassing behavior,
the global moderation team may take any action they deem appropriate, up to and including expulsion from all Terra community spaces and
identification of the participant as a harasser to other Terra community members or the general public. Bad behavior from any community
member, including those with decision-making authority, will not be tolerated.
In addition, any participants who abuse the reporting process will be considered to be in violation of these guidelines and subject to
consequences. False reporting, especially to retaliate or exclude, will not be accepted or tolerated.
## Questions
if you have further questions for anything not addressed here, you may open an 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/).
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 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/)
- 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
#### \[1\]
You provide a set of pronouns that everyone is comfortable addressing you with. Although some people are comfortable
using [neopronouns](https://www.mypronouns.org/neopronouns), not everyone is. Therefore, if you use neopronouns, you should have at *least*
one set of more common pronouns (One of he/him, she/her, or they/them; it doesn't matter which one. Anyone who doesn't respect your basic
pronouns will be removed from the community.) that people may use, should they so choose, as some 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
'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.
+319
View File
@@ -0,0 +1,319 @@
# Contributing to Terra
First off, thank you for considering contributing to Terra. It's people like you that make Terra such a great tool.
Following these guidelines helps to effectively use the time of the developers managing and developing this open source project, making it
more enjoyable for all of us.
Terra is an open source project and we love to receive contributions from our community, you! There are many ways to contribute, from
writing tutorials or blog posts, improving the documentation, submitting bug reports and feature requests or writing code which can be
incorporated into Terra.
The following is a set of guidelines for contributing to Terra and its packages, which are hosted in
the [PolyhedralDev Organization](https://github.com/PolyhedralDev) on GitHub. These are mostly guidelines, not rules. Use your best
judgment, and feel free to propose changes to this document in a pull request.
#### Table Of Contents
[Code of Conduct](#code-of-conduct)
[I don't want to read this whole thing, I just have a question!!!](#i-dont-want-to-read-this-whole-thing-i-just-have-a-question)
[Getting Started](#getting-started)
- [Your First Contribution](#your-first-contribution)
- [Reporting Bugs](#reporting-bugs)
- [Before Submitting A Bug Report](#before-submitting-a-bug-report)
- [How Do I Submit A (Good) Bug Report?](#how-do-i-submit-a-good-bug-report)
- [Suggesting Enhancements](#suggesting-enhancements)
- [Before Submitting An Enhancement Suggestion](#before-submitting-an-enhancement-suggestion)
- [How Do I Submit A (Good) Enhancement Suggestion?](#how-do-i-submit-a-good-enhancement-suggestion)
- [Pull Requests](#pull-requests)
- [Before Submitting A Pull Request](#before-submitting-a-pull-request)
- [How Do I Submit A (Good) Pull Request?](#how-do-i-submit-a-good-pull-request)
[Styleguides](#styleguides)
- [Git Commits](#git-commits)
- [Committing](#committing)
- [Git Commit Messages](#git-commit-messages)
- [Code Styleguide](#code-styleguide)
- [Documentation Styleguide](#documentation-styleguide)
- TODO
[Coding Pratices](#coding-practices)
- [Compatibility](#compatibility)
- [General Compatibility](#general-compatibility)
- [Specific Compatibility](#specific-compatibility)
- [Platform-Agnostic Design](#platform-agnostic-design)
- [Data-Driven](#data-driven)
## Code of Conduct
This project and everyone participating in it is governed by the [Terra of Conduct](CODE_OF_CONDUCT.md). By participating, you are expected
to uphold this code. Please report unacceptable behavior 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.
We have an official discord server where you can request help from various users
- [The official PolyhedralDev discord server](https://discord.dfsek.com)
## Getting Started
### Your First Contribution
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.
- [Help wanted issues](https://github.com/PolyhedralDev/Terra/labels/Note%3A%20Help%20Wanted) - 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)
to get you up on your feet.
At this point, you're ready to make your changes! Feel free to ask for help; everyone is a beginner at first!
If a maintainer asks you to "rebase" your PR, they're saying that a lot of code has changed, and that you need to update your branch so it's
easier to merge.
### Reporting Bugs
This section guides you through submitting a bug report for Terra. Following these guidelines helps maintainers and the community understand
your report, and spend their time fixing the issue instead of understanding what you mean.
Before creating bug reports, please check [this list](#before-submitting-a-bug-report) as you might find out that 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.
#### Before Submitting A Bug Report
- Join the [discord server](https://discord.dfsek.com) to help resolve simple issues.
- You must be on the LATEST version of Terra to receive any support. There is no support for older versions of Terra.
- 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 main project.
*General* compatibility (e.g. "Ability to pull Vanilla/Modded features from 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.
- Make sure that it is actually Terra causing the issue, and not another mod/plugin. You can do this by testing to see if you can recreate
the issue without Terra installed.
- Double check that this is not an issue with a specific Terra *pack* or Terra *addon*, and instead applies to all of Terra.
- Include a copy of the latest.log file. Putting *just* the exception is not enough. We need to be able to check that there wasn't anything
else before that caused it.
- Be sure to fill out all the required information and give descriptions of everything.
#### How Do I Submit A (Good) Bug Report?
Bugs are tracked as [GitHub issues](https://guides.github.com/features/issues/)
. [Create an issue](https://github.com/PolyhedralDev/Terra/issues/new) and provide the prerequisite information by filling in the Bug Report
template.
Explain the problem and include additional details to help maintainers reproduce the problem:
- **Use a clear and descriptive title** for the issue to identify the problem.
- **Describe the exact steps which reproduce the problem** in as many details as possible. When listing steps, **don't just say what you
did, but explain how you did it**.
- **Provide specific examples to demonstrate the steps**.
- **Describe the behavior you observed after following the steps** and point out what exactly is the problem with that behavior.
- **Explain which behavior you expected to see instead and why.**
- **If the problem wasn't triggered by a specific action**, describe what you were doing before the problem happened and share more
information using the guidelines below.
Include details about your configuration and environment:
- **Which version of Terra are you using?** You can get the exact version by running `/te version`.
- **What's the name and version of the platform you're using**? (eg. Spigot, Fabric, Paper, etc.)
- **Which external plugins or mods do you have installed?**
- **Which Terra packs do you have installed?** You can get that list by running `/te packs`.
- **Which Terra addons do you have installed?** You can get that list by running `/te addons`.
### Suggesting Enhancements
This section guides you through submitting an enhancement suggestion for Terra, including completely new features and minor improvements to
existing functionality. Following these guidelines helps maintainers and the community understand your suggestion and find related
suggestions.
Before creating enhancement suggestions, please check [this list](#before-submitting-an-enhancement-suggestion) as you might find out that
you don't need to create one. When you are creating an enhancement suggestion,
please [include as many details as possible](#how-do-i-submit-a-good-enhancement-suggestion).
#### Before Submitting An Enhancement Suggestion
- You must be on the **LATEST** version of Terra to make sure your feature hasn't been added yet.
- Search for any [already existing issues](https://github.com/PolyhedralDev/Terra/issues?q=is%3Aissue+) (Including closed!) with your
problem. If you open a duplicate, it will be closed as such.
- Verify that this is actually within the scope of Terra.
- Be sure that this is not a feature request that should be made for a specific Terra *pack*, and instead applies to all of Terra.
- Be sure that this is not something that should be implemented as a Terra addon, and instead applies to all of Terra.
- Make sure that you attach a copy of the latest.log file, if there are any exceptions thrown in the console. Putting *just* the exception
**is not enough**. We need to be able to check that there wasn't anything else before that caused it.
#### How Do I Submit A (Good) Enhancement Suggestion?
Enhancement suggestions are tracked as [GitHub issues](https://guides.github.com/features/issues/). Create an issue on our main repository
and provide the following information:
- **Use a clear and descriptive title** for the issue to identify the suggestion.
- **Provide a step-by-step description of the suggested enhancement** in as many details as possible.
- **Provide specific examples to demonstrate the steps**.
- **Describe the current behavior** and **explain which behavior you expected to see instead** and why.
- **Explain why this enhancement would be useful** to most Terra users and isn't something that can or should be implemented as an addon.
### Pull Requests
This section guides you through submitting a pull request for Terra.
While the prerequisites above must be satisfied prior to having your pull request reviewed, the reviewer(s) may ask you to complete
additional design work, tests, or other changes before your pull request can be ultimately accepted.
#### Before Submitting A Pull Request
- You must be on the **LATEST** version of Terra to make sure your feature hasn't been added yet.
- Search for any [already existing issues](https://github.com/PolyhedralDev/Terra/issues?q=is%3Aissue+) (Including closed!) with your
problem. If you open a duplicate, it will be closed as such.
- Verify that this is actually within the scope of Terra.
- Be sure that this is not a feature request that should be made for a specific Terra *pack*, and instead applies to all of Terra.
- Be sure that this is not something that should be implemented as a Terra addon, and instead applies to all of Terra.
- Make sure that you attach a copy of the latest.log file, if there are any exceptions thrown in the console. Putting *just* the
exception **is not enough**. We need to be able to check that there wasn't anything else before that caused it.
#### How Do I Submit A (Good) Pull Request?
Pull Requests are tracked as [GitHub Pull Requests](https://guides.github.com/activities/forking/#making-a-pull-request). 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**.
- **Be sure that you are the owner of the code you contributed** or that it can be licensed under the GPLv3.
- **Provide a description goals and non-goals of the pull request** in as many details as possible.
- **Describe the current behavior** and **explain which behavior you expected to see instead** and why.
- **Explain why this enhancement would be useful** to most Terra users and isn't something that can or should be implemented as an addon.
## Styleguides
### Git Commits
Following this is not mandatory, but rather a set of guidelines. As long as your commit messages aren't absolutely awful, it's probably
fine. But it would be nice if you followed them.
#### Committing
When you commit code, try to avoid committing large amounts of code in a single go. Splitting up code into smaller commits is much nicer and
makes it easier to trace a feature to a single commit.
Try to stick to one feature/fix/etc. per commit. A good rule of thumb is if you need to use the word "and" in the subject line, then it
should probably™ be two commits.
#### Git Commit Messages
- Subject line must fit the following format: `<type>: <short summary>`. Type must be one of the following:
- Build: Changes that affect the build system or external dependencies.
- Docs: Documentation only changes.
- Feat: A new feature.
- Fix: A bug fix.
- Perf: Performance improvements.
- Refactor: Refactoring sections of the codebase.
- Repo: Changes to the repository structure that do not affect code. (Eg. modification of the `README.md` file, etc.)
- Revert: Revert a previous commit.
- Style: Code style updates.
- Test: Anything related to testing.
- Trans: Translation and localization of Terra to other languages.
- WIP: Work in progress.
- Separate the subject line from the body with a single blank line.
- Do not end subject line with a period.
- Limit the subject line to 50 or less.
- The subject line and all body lines should be in sentence case.
- Use the present tense. ("Add feature" not "Added feature")
- Use the imperative mood. ("Move cursor to..." not "Moves cursor to...")
- Reference relevant issues and pull requests in the body.
>
> Here is a template you can follow:
> ```
> Capitalized, short (50 chars or less) summary
>
> More detailed explanatory text, if necessary. Wrap it to about 72
> characters or so. In some contexts, the first line is treated as
> the subject of the commit and the rest of the text as the body. The
> blank line separating the summary from the body is critical (unless
> you omit the body entirely); various tools like `log`, `shortlog` and
> `rebase` can get confused if you run the two together.
>
> Explain the problem that this commit is solving. Focus on why you are
> making this change as opposed to how (the code explains that). Are
> there side effects or other unintuitive consequences of this
> change? Here's the place to explain them.
>
>
> Further paragraphs come after blank lines.
> - Bullet points are okay, too
> - Typically a hyphen or asterisk is used for the bullet, followed
> by a single space, with blank lines in between, but conventions vary
> here
> - Use a hanging indent
>
> Reference any relevant issues at the bottom, like so:
>
> Resolves: #123
> See also: #456, #789
> ```
### Code Styleguide
Use an IDE with support for `.editorconfig` files. There is an included editorconfig file in the base of the project so that your IDE should
automatically use the correct code style settings.
### Documentation Styleguide
TODO
## Coding Practices
### Compatibility
#### General Compatibility
General compatibility (example: injection of Vanilla structures/features/carvers 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. General-compatibility options should have config values attached which are disabled by default.
- These config options should also be *simple to use*. Think of the people who will be using these compatibility options. They want to flick
a switch and have things be compatible. That means that a majority of compatibility options should stay in `pack.yml`, to make it simple
to go into a pack and turn on specific compatibilities. This does *not* mean that more advanced compatibility options are off the table,
for example, look at Feature compatibility, where features can either be automatically injected, *or* configured individually per Terra
biome, depending on how much control the user wants.
#### Specific Compatibility
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 becomes a mess. Especially when most users will never need to use this feature.
We have designed an addon API for exactly this purpose. **Specific compatibilities are welcome and encouraged, in the form of addons.**
### Platform-Agnostic Design
Terra must, at all times, remain platform agnostic. This means it must be able to run on theoretically any voxel based platform. Including
non-minecraft games like Terasology.
When adding a new feature to `common`, make no assumptions about what platform it'll be running on.
Examples:
- Don't assume the world height is 256.
- Don't assume that a specific block, item, or entity exists. (Eg. don't assume there exists a block called `minecraft:grass_block`)
### Data-Driven
When adding a new feature, make it abstract. Don't make assumptions about "specific use cases." If you can only think of a few use cases,
your idea should probably be generalized.
You must use configs effectively. Make configs that are *powerful* but also *make sense* and are \[easy\] to use.
+1 -1
View File
@@ -1,6 +1,6 @@
import com.dfsek.terra.getGitHash
val versionObj = Version("5", "3", "2", true)
val versionObj = Version("5", "3", "3", true)
allprojects {
version = versionObj
@@ -1,5 +1,7 @@
package com.dfsek.terra.api.event.events.config;
import com.dfsek.tectonic.config.ConfigTemplate;
import com.dfsek.tectonic.exception.ConfigException;
import com.dfsek.terra.api.event.events.PackEvent;
import com.dfsek.terra.config.pack.ConfigPack;
@@ -8,13 +10,28 @@ import com.dfsek.terra.config.pack.ConfigPack;
*/
public abstract class ConfigPackLoadEvent implements PackEvent {
private final ConfigPack pack;
private final ExceptionalConsumer<ConfigTemplate> configLoader;
public ConfigPackLoadEvent(ConfigPack pack) {
public ConfigPackLoadEvent(ConfigPack pack, ExceptionalConsumer<ConfigTemplate> configLoader) {
this.pack = pack;
this.configLoader = configLoader;
}
@Override
public ConfigPack getPack() {
return pack;
}
/**
* Load a custom {@link ConfigTemplate} using the pack manifest.
*
* @param template Template to register.
*/
public void loadTemplate(ConfigTemplate template) throws ConfigException {
configLoader.accept(template);
}
public interface ExceptionalConsumer<T extends ConfigTemplate> {
void accept(T value) throws ConfigException;
}
}
@@ -1,12 +1,13 @@
package com.dfsek.terra.api.event.events.config;
import com.dfsek.tectonic.config.ConfigTemplate;
import com.dfsek.terra.config.pack.ConfigPack;
/**
* Called when a config pack has finished loading.
*/
public class ConfigPackPostLoadEvent extends ConfigPackLoadEvent {
public ConfigPackPostLoadEvent(ConfigPack pack) {
super(pack);
public ConfigPackPostLoadEvent(ConfigPack pack, ExceptionalConsumer<ConfigTemplate> loader) {
super(pack, loader);
}
}
@@ -1,12 +1,14 @@
package com.dfsek.terra.api.event.events.config;
import com.dfsek.tectonic.config.ConfigTemplate;
import com.dfsek.tectonic.exception.ConfigException;
import com.dfsek.terra.config.pack.ConfigPack;
/**
* Called before a config pack's registries are filled. At this point, the pack manifest has been loaded, and all registries are empty.
*/
public class ConfigPackPreLoadEvent extends ConfigPackLoadEvent {
public ConfigPackPreLoadEvent(ConfigPack pack) {
super(pack);
public ConfigPackPreLoadEvent(ConfigPack pack, ExceptionalConsumer<ConfigTemplate> configLoader) {
super(pack, configLoader);
}
}
@@ -1,8 +0,0 @@
package com.dfsek.terra.api.transform;
public class NotNullValidator<T> implements Validator<T> {
@Override
public boolean validate(T value) {
return !(value == null);
}
}
@@ -1,6 +1,12 @@
package com.dfsek.terra.api.transform;
import java.util.Objects;
public interface Validator<T> {
boolean validate(T value) throws TransformException;
static <T> Validator<T> notNull() {
return Objects::nonNull;
}
}
@@ -1,147 +0,0 @@
package com.dfsek.terra.config.builder;
import com.dfsek.paralithic.eval.parser.Scope;
import com.dfsek.paralithic.eval.tokenizer.ParseException;
import com.dfsek.terra.api.math.noise.NoiseSampler;
import com.dfsek.terra.api.math.noise.samplers.ExpressionSampler;
import com.dfsek.terra.api.math.noise.samplers.noise.ConstantSampler;
import com.dfsek.terra.api.util.seeded.NoiseSeeded;
import com.dfsek.terra.api.world.palette.holder.PaletteHolder;
import com.dfsek.terra.config.loaders.config.function.FunctionTemplate;
import com.dfsek.terra.world.generation.WorldGenerator;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class GeneratorBuilder {
private final Map<Long, WorldGenerator> gens = Collections.synchronizedMap(new HashMap<>());
private String noiseEquation;
private String elevationEquation;
private String carvingEquation;
private Scope varScope;
private Map<String, NoiseSeeded> noiseBuilderMap;
private Map<String, FunctionTemplate> functionTemplateMap;
private PaletteHolder palettes;
private PaletteHolder slantPalettes;
private boolean preventInterpolation;
private boolean interpolateElevation;
private NoiseSeeded biomeNoise;
private double elevationWeight;
private int blendDistance;
private int blendStep;
private double blendWeight;
public WorldGenerator build(long seed) {
synchronized(gens) {
return gens.computeIfAbsent(seed, k -> {
NoiseSampler noise;
NoiseSampler elevation;
NoiseSampler carving;
try {
noise = new ExpressionSampler(noiseEquation, varScope, seed, noiseBuilderMap, functionTemplateMap);
elevation = elevationEquation == null ? new ConstantSampler(0) : new ExpressionSampler(elevationEquation, varScope, seed, noiseBuilderMap, functionTemplateMap);
carving = new ExpressionSampler(carvingEquation, varScope, seed, noiseBuilderMap, functionTemplateMap);
} catch(ParseException e) {
throw new RuntimeException(e);
}
return new WorldGenerator(palettes, slantPalettes, noise, elevation, carving, biomeNoise.apply(seed), elevationWeight, blendDistance, blendStep, blendWeight);
});
}
}
public void setBlendWeight(double blendWeight) {
this.blendWeight = blendWeight;
}
public void setFunctionTemplateMap(Map<String, FunctionTemplate> functionTemplateMap) {
this.functionTemplateMap = functionTemplateMap;
}
public void setBlendStep(int blendStep) {
this.blendStep = blendStep;
}
public void setBlendDistance(int blendDistance) {
this.blendDistance = blendDistance;
}
public void setBiomeNoise(NoiseSeeded biomeNoise) {
this.biomeNoise = biomeNoise;
}
public void setElevationWeight(double elevationWeight) {
this.elevationWeight = elevationWeight;
}
public void setNoiseEquation(String noiseEquation) {
this.noiseEquation = noiseEquation;
}
public void setElevationEquation(String elevationEquation) {
this.elevationEquation = elevationEquation;
}
public void setCarvingEquation(String carvingEquation) {
this.carvingEquation = carvingEquation;
}
public Scope getVarScope() {
return varScope;
}
public void setVarScope(Scope varScope) {
this.varScope = varScope;
}
public void setNoiseBuilderMap(Map<String, NoiseSeeded> noiseBuilderMap) {
this.noiseBuilderMap = noiseBuilderMap;
}
public PaletteHolder getPalettes() {
return palettes;
}
public void setPalettes(PaletteHolder palettes) {
this.palettes = palettes;
}
public PaletteHolder getSlantPalettes() {
return slantPalettes;
}
public void setSlantPalettes(PaletteHolder slantPalettes) {
this.slantPalettes = slantPalettes;
}
public boolean isPreventInterpolation() {
return preventInterpolation;
}
public void setPreventInterpolation(boolean preventInterpolation) {
this.preventInterpolation = preventInterpolation;
}
public void setInterpolateElevation(boolean interpolateElevation) {
this.interpolateElevation = interpolateElevation;
}
public boolean interpolateElevation() {
return interpolateElevation;
}
}
@@ -2,6 +2,7 @@ package com.dfsek.terra.config.pack;
import com.dfsek.paralithic.eval.parser.Scope;
import com.dfsek.tectonic.abstraction.AbstractConfigLoader;
import com.dfsek.tectonic.config.Configuration;
import com.dfsek.tectonic.exception.ConfigException;
import com.dfsek.tectonic.exception.LoadException;
import com.dfsek.tectonic.loading.ConfigLoader;
@@ -110,6 +111,8 @@ public class ConfigPack implements LoaderRegistrar {
private final TerraPlugin main;
private final Loader loader;
private final Configuration configuration;
private final BiomeProvider.BiomeProviderBuilder biomeProviderBuilder;
@@ -130,11 +133,15 @@ public class ConfigPack implements LoaderRegistrar {
File pack = new File(folder, "pack.yml");
try {
selfLoader.load(template, new FileInputStream(pack));
configuration = new Configuration(new FileInputStream(pack));
selfLoader.load(template, configuration);
main.logger().info("Loading config pack \"" + template.getID() + "\"");
main.getEventManager().callEvent(new ConfigPackPreLoadEvent(this, template -> selfLoader.load(template, configuration)));
load(l, main);
ConfigPackPostTemplate packPostTemplate = new ConfigPackPostTemplate();
selfLoader.load(packPostTemplate, new FileInputStream(pack));
biomeProviderBuilder = packPostTemplate.getProviderBuilder();
@@ -174,9 +181,12 @@ public class ConfigPack implements LoaderRegistrar {
if(pack == null) throw new LoadException("No pack.yml file found in " + file.getName());
selfLoader.load(template, file.getInputStream(pack));
configuration = new Configuration(file.getInputStream(pack));
selfLoader.load(template, configuration);
main.logger().info("Loading config pack \"" + template.getID() + "\"");
main.getEventManager().callEvent(new ConfigPackPreLoadEvent(this, template -> selfLoader.load(template, configuration)));
load(l, main);
ConfigPackPostTemplate packPostTemplate = new ConfigPackPostTemplate();
@@ -211,8 +221,6 @@ public class ConfigPack implements LoaderRegistrar {
private void load(long start, TerraPlugin main) throws ConfigException {
main.getEventManager().callEvent(new ConfigPackPreLoadEvent(this));
for(Map.Entry<String, Double> var : template.getVariables().entrySet()) {
varScope.create(var.getKey(), var.getValue());
}
@@ -245,7 +253,7 @@ public class ConfigPack implements LoaderRegistrar {
.open("flora", ".yml").then(configs -> buildAll(new FloraFactory(), floraRegistry, abstractConfigLoader.loadConfigs(configs, FloraTemplate::new), main)).close()
.open("biomes", ".yml").then(configs -> buildAll(new BiomeFactory(this), biomeRegistry, abstractConfigLoader.loadConfigs(configs, () -> new BiomeTemplate(this, main)), main)).close();
main.getEventManager().callEvent(new ConfigPackPostLoadEvent(this));
main.getEventManager().callEvent(new ConfigPackPostLoadEvent(this, template -> selfLoader.load(template, configuration)));
main.logger().info("Loaded config pack \"" + template.getID() + "\" v" + template.getVersion() + " by " + template.getAuthor() + " in " + (System.nanoTime() - start) / 1000000D + "ms.");
}
+122
View File
@@ -0,0 +1,122 @@
enable:
- "Pokud se vám líbí Terra, můžete nás podpořit na Patreon!"
- "Získáte přístup k experimentálním funkcím, než budou vydány!"
- "Podpořit projekt můžete zde: https://www.patreon.com/dfsek"
disable:
- "Děkujeme, že používáte Terra!"
command:
debug-only: "Tento příkaz musí být použit se zapnutým debug modem!"
player-only: "Tento příkaz je pouze pro hráče!"
invalid: "Neznámý příkaz. (Očekáváno %1$s argumentů, nalezeno %2$s)."
players-only: "Příkaz je pouze pro použití hráčem."
world: "Tento příkaz musí být použit v Terra světě!"
reload: "Obnoven Terra konfig."
reload-error: "Nastaly chyby při obnově Terra konfigurace. Podívejte se do logů pro více informací."
version: "Na tomto serveru běží Terra verze \"%1$s\", na platformě \"%2$s\""
main-menu:
- "--------------------Terra--------------------"
- "reload - Obnoví konfigurační data"
- "biome - Ukáže aktuální biom"
- "ore - Generuje žílu rud v lokaci, ve směru kam se koukáte (Pro debugging)"
- "save-data - Uložit populační data"
- "structure - Nahrát a exportovat struktury"
- "profile - Profiler možnosti"
- "image - Obrázek/GUI možnosti"
biome:
biome-found: "Lokalizován biom na (%1$s, %2$s)"
unable-to-locate: "Nelze lokalizovat biom."
invalid-radius: "Nesprávný radius: \"%s\""
invalid: "Nesprávné ID bomu: \"%s\""
in: "Jste v \"%s\""
packs:
main: "Aktuální instalované konfigurační balíčky:"
pack: " - %1$s v%3$s od %2$s"
none: "Žádné konfigurační balíčky nejsou nainstalovány."
ore:
main-menu:
- "---------------Terra/ore---------------"
- "Generuje žílu rud na bloku, na který koukáte."
out-of-range: "Blok mimo dosah"
invalid-ore: "Nelze nalézt Rudu \"%s\""
geometry:
main-menu:
- "---------------Terra/geometry----------------"
- "Různé voxel geometrické debugging příkazy"
- "sphere - Generuje kouli"
- "deformsphere - Generuje deformovanou kouli"
- "tube - Generuje válec"
deform:
invalid-radius: "Nesprávný radius: \"%s\""
invalid-deform: "Nesprávná deformace: \"%s\""
invalid-frequency: "Nesprávná frekvence: \"%s\""
sphere:
invalid-radius: "Nesprávný radius: \"%s\""
tube:
invalid-radius: "Nesprávný radius: \"%s\""
image:
main-menu:
- "---------------Terra/image---------------"
- "render - Vykreslí obrázek s danou šířkou a výškou, který může být později importován jako svět."
- "gui - Otevřít debug GUI (Musí být zapnuto v konfigu)"
gui:
main-menu:
- "-------------Terra/image/gui-------------"
- "raw - Otevře GUI s raw Biom daty"
- "step - Znovu vykreslí data k lepšímu zobrazení borderu"
debug: "Debug mod musí být zapnutý pro použití této možnosti! Debug GUI NENÍ PRODUKČNĚ BEZPEČNÉ!"
render:
save: "Uložen obrázek jako \"%s\""
error: "Nastala chyba při generování obrázku!"
profile:
main-menu:
- "---------------Terra/profile---------------"
- "start - Zapne profiler"
- "stop - Vypne profiler"
- "query - Ukáže profiler data"
- "reset - Resetuje profiler data"
reset: "Profiler byl resetován."
start: "Profiler byl zapnut."
stop: "Profiler byl vypnut."
structure:
main-menu:
- "---------------Terra/structure---------------"
- "export - Export vašeho výběru WorldEdit jako Terra struktura."
- "load - Načíst Terra strukturu"
invalid-radius: "Nesprávný radius: \"%s\""
invalid-rotation: "Nesprávná rotace: \"%s\""
invalid: "Nesprávné ID struktury: \"%s\""
export: "Uložena struktura do \"%s\""
world-config:
load: "Načteny konfigurační hodnoty světa pro svět \"%s\"..."
not-found: "Konfigurace pro svět \"%s\" nenalezena. Kopíruji defaultní konfig."
using-image: "Načítám svět z obrázku."
error: "Nelze načíst konfigurace pro svět %s"
done: "Načítání světa \"%1$s\" dokončeno. Uplynulý čas: %2$sms"
config-pack:
loaded: "Konfigurační balíček %1$s v%4$s od %3$s byl načten za %2$sms."
config:
loaded: "Načten %1$s ze souboru %2$s"
loaded-all: "Načteno %1$s %2$s(s) za %3$sms."
error:
invalid-failover: "Nesprávný typ failover: \"%s\""
duplicate: "Duplikační ID nalezeno v souboru: %s"
file:
- "Konfigurační chyba pro Terra objekt. Soubor: %1$s"
- "%2$s"
- "Opravte jej před pokračováním!"
generic:
- "Nastala chyba při načítání konfigurace."
- "Prosíme nahlašte to na Terra."
warning:
no-population: "Žádné populační chunky nebyly načteny. Pokud je to poprvé, co zapínáte server s Terra, či vytváříte nový svět, je tohle normální."
error:
severe-config: "Vážná konfigurační chyba zabránila Terra ze správné generace terénu na koordinátech: %1$s, %2$s. Prosíme zkontrolujte konfiguraci pro chyby. Jakékoli konfigurační chyby jsou vypsány výše."
debug:
data-save : "Uložena populační data."
use-paper:
- "Vypadá to, že používáte Spigot/CraftBukkit."
- "Ačkoli Terra &ofunguje&r na Spigot, některé funkce budou ztraceny. (Terra je netestována na CraftBukkit; žádná podpora nebude dána pro CraftBukkit)."
- "Pro nejvíce funkcí s Terra, použijte Paper."
- "Navíc, Paper přináší obrovské výkonnostní zlepešení než Spigot, a všechny Spigot pluginy by měli fungovat s Paper!"
- "Pro nejlepší zážitek s Terra a všemi pluginy, použijte prosím Paper."
- "Více info najdete na stránce Paperu: https://papermc.io/"
-2
View File
@@ -27,8 +27,6 @@ dependencies {
"mappings"("net.fabricmc:yarn:1.16.5+build.5:v2")
"modImplementation"("net.fabricmc:fabric-loader:0.11.2")
"modImplementation"("net.fabricmc.fabric-api:fabric-api:0.31.0+1.16")
"modCompileOnly"("com.sk89q.worldedit:worldedit-fabric-mc1.16:7.2.0-SNAPSHOT") {
exclude(group = "com.google.guava", module = "guava")
exclude(group = "com.google.code.gson", module = "gson")
@@ -1,5 +1,7 @@
package com.dfsek.terra.fabric;
import com.dfsek.tectonic.exception.ConfigException;
import com.dfsek.tectonic.exception.LoadException;
import com.dfsek.tectonic.loading.TypeRegistry;
import com.dfsek.terra.api.TerraPlugin;
import com.dfsek.terra.api.addons.TerraAddon;
@@ -8,144 +10,131 @@ import com.dfsek.terra.api.addons.annotations.Author;
import com.dfsek.terra.api.addons.annotations.Version;
import com.dfsek.terra.api.command.CommandManager;
import com.dfsek.terra.api.command.TerraCommandManager;
import com.dfsek.terra.api.command.exception.CommandException;
import com.dfsek.terra.api.command.exception.MalformedCommandException;
import com.dfsek.terra.api.event.EventListener;
import com.dfsek.terra.api.event.EventManager;
import com.dfsek.terra.api.event.TerraEventManager;
import com.dfsek.terra.api.event.annotations.Global;
import com.dfsek.terra.api.event.annotations.Priority;
import com.dfsek.terra.api.event.events.config.ConfigPackPostLoadEvent;
import com.dfsek.terra.api.event.events.config.ConfigPackPreLoadEvent;
import com.dfsek.terra.api.platform.CommandSender;
import com.dfsek.terra.api.platform.block.BlockData;
import com.dfsek.terra.api.platform.entity.Entity;
import com.dfsek.terra.api.platform.handle.ItemHandle;
import com.dfsek.terra.api.platform.handle.WorldHandle;
import com.dfsek.terra.api.platform.world.Tree;
import com.dfsek.terra.api.platform.world.World;
import com.dfsek.terra.api.registry.CheckedRegistry;
import com.dfsek.terra.api.registry.LockedRegistry;
import com.dfsek.terra.api.transform.NotNullValidator;
import com.dfsek.terra.api.transform.Transformer;
import com.dfsek.terra.api.transform.Validator;
import com.dfsek.terra.api.util.generic.pair.Pair;
import com.dfsek.terra.api.util.logging.DebugLogger;
import com.dfsek.terra.api.util.logging.Logger;
import com.dfsek.terra.commands.CommandUtil;
import com.dfsek.terra.config.GenericLoaders;
import com.dfsek.terra.config.PluginConfig;
import com.dfsek.terra.config.builder.BiomeBuilder;
import com.dfsek.terra.config.lang.LangUtil;
import com.dfsek.terra.config.lang.Language;
import com.dfsek.terra.config.pack.ConfigPack;
import com.dfsek.terra.config.templates.BiomeTemplate;
import com.dfsek.terra.fabric.config.PostLoadCompatibilityOptions;
import com.dfsek.terra.fabric.config.PreLoadCompatibilityOptions;
import com.dfsek.terra.fabric.generation.FabricChunkGeneratorWrapper;
import com.dfsek.terra.fabric.generation.PopulatorFeature;
import com.dfsek.terra.fabric.generation.TerraBiomeSource;
import com.dfsek.terra.fabric.handle.FabricItemHandle;
import com.dfsek.terra.fabric.handle.FabricWorldHandle;
import com.dfsek.terra.fabric.mixin.access.BiomeEffectsAccessor;
import com.dfsek.terra.fabric.mixin.access.GeneratorTypeAccessor;
import com.dfsek.terra.fabric.util.FabricUtil;
import com.dfsek.terra.profiler.Profiler;
import com.dfsek.terra.profiler.ProfilerImpl;
import com.dfsek.terra.registry.exception.DuplicateEntryException;
import com.dfsek.terra.registry.master.AddonRegistry;
import com.dfsek.terra.registry.master.ConfigRegistry;
import com.dfsek.terra.world.TerraWorld;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v1.CommandRegistrationCallback;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.block.Blocks;
import net.minecraft.client.world.GeneratorType;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.text.LiteralText;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.BuiltinRegistries;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.registry.RegistryKey;
import net.minecraft.world.WorldAccess;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.BiomeEffects;
import net.minecraft.world.biome.GenerationSettings;
import net.minecraft.world.gen.GenerationStep;
import net.minecraft.world.gen.chunk.ChunkGenerator;
import net.minecraft.world.gen.chunk.ChunkGeneratorSettings;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.gen.decorator.Decorator;
import net.minecraft.world.gen.decorator.NopeDecoratorConfig;
import net.minecraft.world.gen.feature.ConfiguredFeature;
import net.minecraft.world.gen.feature.ConfiguredFeatures;
import net.minecraft.world.gen.feature.DefaultFeatureConfig;
import net.minecraft.world.gen.feature.FeatureConfig;
import net.minecraft.world.gen.surfacebuilder.SurfaceBuilder;
import net.minecraft.world.gen.surfacebuilder.TernarySurfaceConfig;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static net.minecraft.server.command.CommandManager.argument;
import static net.minecraft.server.command.CommandManager.literal;
public class TerraFabricPlugin implements TerraPlugin, ModInitializer {
private final org.apache.logging.log4j.Logger log4jLogger = LogManager.getLogger();
public static final PopulatorFeature POPULATOR_FEATURE = new PopulatorFeature(DefaultFeatureConfig.CODEC);
public static final ConfiguredFeature<?, ?> POPULATOR_CONFIGURED_FEATURE = POPULATOR_FEATURE.configure(FeatureConfig.DEFAULT).decorate(Decorator.NOPE.configure(NopeDecoratorConfig.INSTANCE));
private static TerraFabricPlugin instance;
private final Map<Long, TerraWorld> worldMap = new HashMap<>();
private final Map<DimensionType, Pair<ServerWorld, TerraWorld>> worldMap = new HashMap<>();
public Map<DimensionType, Pair<ServerWorld, TerraWorld>> getWorldMap() {
return worldMap;
}
private final EventManager eventManager = new TerraEventManager(this);
private final GenericLoaders genericLoaders = new GenericLoaders(this);
private final Profiler profiler = new ProfilerImpl();
private final Logger logger = new Logger() {
private final org.apache.logging.log4j.Logger logger = LogManager.getLogger();
@Override
public void info(String message) {
logger.info(message);
log4jLogger.info(message);
}
@Override
public void warning(String message) {
logger.warn(message);
log4jLogger.warn(message);
}
@Override
public void severe(String message) {
logger.error(message);
log4jLogger.error(message);
}
};
private final DebugLogger debugLogger = new DebugLogger(logger);
private final ItemHandle itemHandle = new FabricItemHandle();
private final WorldHandle worldHandle = new FabricWorldHandle();
private final ConfigRegistry registry = new ConfigRegistry();
private final CheckedRegistry<ConfigPack> checkedRegistry = new CheckedRegistry<>(registry);
private final AddonRegistry addonRegistry = new AddonRegistry(new FabricAddon(this), this);
private final FabricAddon fabricAddon = new FabricAddon(this);
private final AddonRegistry addonRegistry = new AddonRegistry(fabricAddon, this);
private final LockedRegistry<TerraAddon> addonLockedRegistry = new LockedRegistry<>(addonRegistry);
private final PluginConfig config = new PluginConfig();
private final Transformer<String, Biome> biomeFixer = new Transformer.Builder<String, Biome>()
.addTransform(id -> BuiltinRegistries.BIOME.get(Identifier.tryParse(id)), new NotNullValidator<>())
.addTransform(id -> BuiltinRegistries.BIOME.get(Identifier.tryParse("minecraft:" + id.toLowerCase())), new NotNullValidator<>()).build();
.addTransform(id -> BuiltinRegistries.BIOME.get(Identifier.tryParse(id)), Validator.notNull())
.addTransform(id -> BuiltinRegistries.BIOME.get(Identifier.tryParse("minecraft:" + id.toLowerCase())), Validator.notNull()).build();
private File dataFolder;
private final CommandManager manager = new TerraCommandManager(this);
public CommandManager getManager() {
return manager;
}
public static TerraFabricPlugin getInstance() {
return instance;
}
public static String createBiomeID(ConfigPack pack, String biomeID) {
return pack.getTemplate().getID().toLowerCase() + "/" + biomeID.toLowerCase(Locale.ROOT);
}
@Override
public WorldHandle getWorldHandle() {
return worldHandle;
@@ -153,15 +142,12 @@ public class TerraFabricPlugin implements TerraPlugin, ModInitializer {
@Override
public TerraWorld getWorld(World world) {
return worldMap.computeIfAbsent(world.getSeed(), w -> {
logger.info("Loading world " + w);
return new TerraWorld(world, ((FabricChunkGeneratorWrapper) world.getGenerator()).getPack(), this);
});
return getWorld(((WorldAccess) world).getDimension());
}
public TerraWorld getWorld(long seed) {
TerraWorld world = worldMap.get(seed);
if(world == null) throw new IllegalArgumentException("No world exists with seed " + seed);
public TerraWorld getWorld(DimensionType type) {
TerraWorld world = worldMap.get(type).getRight();
if(world == null) throw new IllegalArgumentException("No world exists with dimension type " + type);
return world;
}
@@ -182,7 +168,7 @@ public class TerraFabricPlugin implements TerraPlugin, ModInitializer {
@Override
public boolean isDebug() {
return true;
return config.isDebug();
}
@Override
@@ -205,14 +191,11 @@ public class TerraFabricPlugin implements TerraPlugin, ModInitializer {
config.load(this);
LangUtil.load(config.getLanguage(), this); // Load language.
boolean succeed = registry.loadAll(this);
Map<Long, TerraWorld> newMap = new HashMap<>();
worldMap.forEach((seed, tw) -> {
tw.getConfig().getSamplerCache().clear();
String packID = tw.getConfig().getTemplate().getID();
newMap.put(seed, new TerraWorld(tw.getWorld(), registry.get(packID), this));
worldMap.forEach((seed, pair) -> {
pair.getRight().getConfig().getSamplerCache().clear();
String packID = pair.getRight().getConfig().getTemplate().getID();
pair.setRight(new TerraWorld(pair.getRight().getWorld(), registry.get(packID), this));
});
worldMap.clear();
worldMap.putAll(newMap);
return succeed;
}
@@ -246,71 +229,19 @@ public class TerraFabricPlugin implements TerraPlugin, ModInitializer {
genericLoaders.register(registry);
registry
.registerLoader(BlockData.class, (t, o, l) -> worldHandle.createBlockData((String) o))
.registerLoader(com.dfsek.terra.api.platform.world.Biome.class, (t, o, l) -> biomeFixer.translate((String) o));
}
private Biome createBiome(BiomeBuilder biome) {
BiomeTemplate template = biome.getTemplate();
Map<String, Integer> colors = template.getColors();
Biome vanilla = (Biome) (new ArrayList<>(biome.getVanillaBiomes().getContents()).get(0)).getHandle();
GenerationSettings.Builder generationSettings = new GenerationSettings.Builder();
generationSettings.surfaceBuilder(SurfaceBuilder.DEFAULT.withConfig(new TernarySurfaceConfig(Blocks.GRASS_BLOCK.getDefaultState(), Blocks.DIRT.getDefaultState(), Blocks.GRAVEL.getDefaultState()))); // It needs a surfacebuilder, even though we dont use it.
generationSettings.feature(GenerationStep.Feature.VEGETAL_DECORATION, POPULATOR_CONFIGURED_FEATURE);
BiomeEffectsAccessor accessor = (BiomeEffectsAccessor) vanilla.getEffects();
BiomeEffects.Builder effects = new BiomeEffects.Builder()
.waterColor(colors.getOrDefault("water", accessor.getWaterColor()))
.waterFogColor(colors.getOrDefault("water-fog", accessor.getWaterFogColor()))
.fogColor(colors.getOrDefault("fog", accessor.getFogColor()))
.skyColor(colors.getOrDefault("sky", accessor.getSkyColor()))
.grassColorModifier(accessor.getGrassColorModifier());
if(colors.containsKey("grass")) {
effects.grassColor(colors.get("grass"));
} else {
accessor.getGrassColor().ifPresent(effects::grassColor);
}
if(colors.containsKey("foliage")) {
effects.foliageColor(colors.get("foliage"));
} else {
accessor.getFoliageColor().ifPresent(effects::foliageColor);
}
return new Biome.Builder()
.precipitation(vanilla.getPrecipitation())
.category(vanilla.getCategory())
.depth(vanilla.getDepth())
.scale(vanilla.getScale())
.temperature(vanilla.getTemperature())
.downfall(vanilla.getDownfall())
.effects(effects.build())
.spawnSettings(vanilla.getSpawnSettings())
.generationSettings(generationSettings.build())
.build();
.registerLoader(com.dfsek.terra.api.platform.world.Biome.class, (t, o, l) -> biomeFixer.translate((String) o))
.registerLoader(Identifier.class, (t, o, l) -> {
Identifier identifier = Identifier.tryParse((String) o);
if(identifier == null) throw new LoadException("Invalid identifier: " + o);
return identifier;
});
}
public void packInit() {
logger.info("Loading config packs...");
registry.loadAll(this);
registry.forEach(pack -> pack.getBiomeRegistry().forEach((id, biome) -> Registry.register(BuiltinRegistries.BIOME, new Identifier("terra", createBiomeID(pack, id)), createBiome(biome)))); // Register all Terra biomes.
if(FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) {
registry.forEach(pack -> {
final GeneratorType generatorType = new GeneratorType("terra." + pack.getTemplate().getID()) {
@Override
protected ChunkGenerator getChunkGenerator(Registry<Biome> biomeRegistry, Registry<ChunkGeneratorSettings> chunkGeneratorSettingsRegistry, long seed) {
return new FabricChunkGeneratorWrapper(new TerraBiomeSource(biomeRegistry, seed, pack), seed, pack);
}
};
//noinspection ConstantConditions
((GeneratorTypeAccessor) generatorType).setTranslationKey(new LiteralText("Terra:" + pack.getTemplate().getID()));
GeneratorTypeAccessor.getValues().add(generatorType);
});
}
registry.forEach(pack -> pack.getBiomeRegistry().forEach((id, biome) -> Registry.register(BuiltinRegistries.BIOME, new Identifier("terra", FabricUtil.createBiomeID(pack, id)), FabricUtil.createBiome(fabricAddon, biome, pack)))); // Register all Terra biomes.
logger.info("Loaded packs.");
}
@@ -322,6 +253,7 @@ public class TerraFabricPlugin implements TerraPlugin, ModInitializer {
this.dataFolder = new File(FabricLoader.getInstance().getConfigDir().toFile(), "Terra");
saveDefaultConfig();
config.load(this);
debugLogger.setDebug(config.isDebug());
LangUtil.load(config.getLanguage(), this);
logger.info("Initializing Terra...");
@@ -331,76 +263,22 @@ public class TerraFabricPlugin implements TerraPlugin, ModInitializer {
logger.info("Loaded addons.");
Registry.register(Registry.FEATURE, new Identifier("terra", "flora_populator"), POPULATOR_FEATURE);
RegistryKey<ConfiguredFeature<?, ?>> floraKey = RegistryKey.of(Registry.CONFIGURED_FEATURE_WORLDGEN, new Identifier("terra", "flora_populator"));
Registry.register(Registry.FEATURE, new Identifier("terra", "populator"), POPULATOR_FEATURE);
RegistryKey<ConfiguredFeature<?, ?>> floraKey = RegistryKey.of(Registry.CONFIGURED_FEATURE_WORLDGEN, new Identifier("terra", "populator"));
Registry.register(BuiltinRegistries.CONFIGURED_FEATURE, floraKey.getValue(), POPULATOR_CONFIGURED_FEATURE);
Registry.register(Registry.CHUNK_GENERATOR, new Identifier("terra:terra"), FabricChunkGeneratorWrapper.CODEC);
Registry.register(Registry.BIOME_SOURCE, new Identifier("terra:terra"), TerraBiomeSource.CODEC);
CommandManager manager = new TerraCommandManager(this);
try {
CommandUtil.registerAll(manager);
} catch(MalformedCommandException e) {
e.printStackTrace(); // TODO do something here even though this should literally never happen
}
CommandRegistrationCallback.EVENT.register((dispatcher, dedicated) -> {
int max = manager.getMaxArgumentDepth();
RequiredArgumentBuilder<ServerCommandSource, String> arg = argument("arg" + (max - 1), StringArgumentType.word());
for(int i = 0; i < max; i++) {
RequiredArgumentBuilder<ServerCommandSource, String> next = argument("arg" + (max - i - 1), StringArgumentType.word());
arg = next.then(assemble(arg, manager));
}
dispatcher.register(literal("terra").executes(context -> 1).then(assemble(arg, manager)));
dispatcher.register(literal("te").executes(context -> 1).then(assemble(arg, manager)));
//dispatcher.register(literal("te").redirect(root));
}
);
logger.info("Finished initialization.");
}
private RequiredArgumentBuilder<ServerCommandSource, String> assemble(RequiredArgumentBuilder<ServerCommandSource, String> in, CommandManager manager) {
return in.suggests((context, builder) -> {
List<String> args = parseCommand(context.getInput());
CommandSender sender = (CommandSender) context.getSource();
try {
sender = (Entity) context.getSource().getEntityOrThrow();
} catch(CommandSyntaxException ignore) {
}
try {
manager.tabComplete(args.remove(0), sender, args).forEach(builder::suggest);
} catch(CommandException e) {
sender.sendMessage(e.getMessage());
}
return builder.buildFuture();
}).executes(context -> {
List<String> args = parseCommand(context.getInput());
CommandSender sender = (CommandSender) context.getSource();
try {
sender = (Entity) context.getSource().getEntityOrThrow();
} catch(CommandSyntaxException ignore) {
}
try {
manager.execute(args.remove(0), sender, args);
} catch(CommandException e) {
context.getSource().sendError(new LiteralText(e.getMessage()));
}
return 1;
});
}
private List<String> parseCommand(String command) {
if(command.startsWith("/terra ")) command = command.substring("/terra ".length());
else if(command.startsWith("/te ")) command = command.substring("/te ".length());
List<String> c = new ArrayList<>(Arrays.asList(command.split(" ")));
if(command.endsWith(" ")) c.add("");
return c;
}
@Override
public EventManager getEventManager() {
@@ -415,10 +293,12 @@ public class TerraFabricPlugin implements TerraPlugin, ModInitializer {
@Addon("Terra-Fabric")
@Author("Terra")
@Version("1.0.0")
private static final class FabricAddon extends TerraAddon implements EventListener {
public static final class FabricAddon extends TerraAddon implements EventListener {
private final TerraPlugin main;
private final Map<ConfigPack, Pair<PreLoadCompatibilityOptions, PostLoadCompatibilityOptions>> templates = new HashMap<>();
private FabricAddon(TerraPlugin main) {
this.main = main;
}
@@ -451,6 +331,40 @@ public class TerraFabricPlugin implements TerraPlugin, ModInitializer {
injectTree(treeRegistry, "MEGA_SPRUCE", ConfiguredFeatures.MEGA_SPRUCE);
injectTree(treeRegistry, "CRIMSON_FUNGUS", ConfiguredFeatures.CRIMSON_FUNGI);
injectTree(treeRegistry, "WARPED_FUNGUS", ConfiguredFeatures.WARPED_FUNGI);
PreLoadCompatibilityOptions template = new PreLoadCompatibilityOptions();
try {
event.loadTemplate(template);
} catch(ConfigException e) {
e.printStackTrace();
}
if(template.doRegistryInjection()) {
BuiltinRegistries.CONFIGURED_FEATURE.getEntries().forEach(entry -> {
if(!template.getExcludedRegistryFeatures().contains(entry.getKey().getValue())) {
try {
event.getPack().getTreeRegistry().add(entry.getKey().getValue().toString(), (Tree) entry.getValue());
main.getDebugLogger().info("Injected ConfiguredFeature " + entry.getKey().getValue() + " as Tree.");
} catch(DuplicateEntryException ignored) {
}
}
});
}
templates.put(event.getPack(), Pair.of(template, null));
}
@Priority(Priority.HIGHEST)
@Global
public void createInjectionOptions(ConfigPackPostLoadEvent event) {
PostLoadCompatibilityOptions template = new PostLoadCompatibilityOptions();
try {
event.loadTemplate(template);
} catch(ConfigException e) {
e.printStackTrace();
}
templates.get(event.getPack()).setRight(template);
}
@@ -460,5 +374,9 @@ public class TerraFabricPlugin implements TerraPlugin, ModInitializer {
} catch(DuplicateEntryException ignore) {
}
}
public Map<ConfigPack, Pair<PreLoadCompatibilityOptions, PostLoadCompatibilityOptions>> getTemplates() {
return templates;
}
}
}
@@ -0,0 +1,30 @@
package com.dfsek.terra.fabric.config;
import com.dfsek.tectonic.annotations.Default;
import com.dfsek.tectonic.annotations.Value;
import com.dfsek.tectonic.config.ConfigTemplate;
import com.dfsek.terra.config.builder.BiomeBuilder;
import net.minecraft.util.Identifier;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@SuppressWarnings("FieldMayBeFinal")
public class PostLoadCompatibilityOptions implements ConfigTemplate {
@Value("structures.inject-biome.exclude-biomes")
@Default
private Map<BiomeBuilder, Set<Identifier>> excludedPerBiomeStructures = new HashMap<>();
@Value("features.inject-biome.exclude-biomes")
@Default
private Map<BiomeBuilder, Set<Identifier>> excludedPerBiomeFeatures = new HashMap<>();
public Map<BiomeBuilder, Set<Identifier>> getExcludedPerBiomeFeatures() {
return excludedPerBiomeFeatures;
}
public Map<BiomeBuilder, Set<Identifier>> getExcludedPerBiomeStructures() {
return excludedPerBiomeStructures;
}
}
@@ -0,0 +1,52 @@
package com.dfsek.terra.fabric.config;
import com.dfsek.tectonic.annotations.Default;
import com.dfsek.tectonic.annotations.Value;
import com.dfsek.tectonic.config.ConfigTemplate;
import net.minecraft.util.Identifier;
import java.util.HashSet;
import java.util.Set;
@SuppressWarnings("FieldMayBeFinal")
public class PreLoadCompatibilityOptions implements ConfigTemplate {
@Value("features.inject-registry.enable")
@Default
private boolean doRegistryInjection = false;
@Value("features.inject-biome.enable")
@Default
private boolean doBiomeInjection = false;
@Value("features.inject-registry.excluded-features")
@Default
private Set<Identifier> excludedRegistryFeatures = new HashSet<>();
@Value("features.inject-biome.excluded-features")
@Default
private Set<Identifier> excludedBiomeFeatures = new HashSet<>();
@Value("structures.inject-biome.excluded-features")
@Default
private Set<Identifier> excludedBiomeStructures = new HashSet<>();
public boolean doBiomeInjection() {
return doBiomeInjection;
}
public boolean doRegistryInjection() {
return doRegistryInjection;
}
public Set<Identifier> getExcludedBiomeFeatures() {
return excludedBiomeFeatures;
}
public Set<Identifier> getExcludedRegistryFeatures() {
return excludedRegistryFeatures;
}
public Set<Identifier> getExcludedBiomeStructures() {
return excludedBiomeStructures;
}
}
@@ -4,6 +4,7 @@ import com.dfsek.terra.api.platform.world.World;
import com.dfsek.terra.api.platform.world.generator.ChunkData;
import com.dfsek.terra.api.platform.world.generator.GeneratorWrapper;
import com.dfsek.terra.api.util.FastRandom;
import com.dfsek.terra.api.world.biome.UserDefinedBiome;
import com.dfsek.terra.api.world.generation.TerraChunkGenerator;
import com.dfsek.terra.api.world.locate.AsyncStructureFinder;
import com.dfsek.terra.config.pack.ConfigPack;
@@ -27,9 +28,13 @@ import net.minecraft.util.registry.Registry;
import net.minecraft.world.BlockView;
import net.minecraft.world.ChunkRegion;
import net.minecraft.world.Heightmap;
import net.minecraft.world.SpawnHelper;
import net.minecraft.world.WorldAccess;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.source.BiomeAccess;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.gen.ChunkRandom;
import net.minecraft.world.gen.GenerationStep;
import net.minecraft.world.gen.StructureAccessor;
import net.minecraft.world.gen.chunk.ChunkGenerator;
@@ -55,6 +60,7 @@ public class FabricChunkGeneratorWrapper extends ChunkGenerator implements Gener
PACK_CODEC.fieldOf("pack").stable().forGetter(generator -> generator.pack))
.apply(instance, instance.stable(FabricChunkGeneratorWrapper::new)));
private final ConfigPack pack;
private DimensionType dimensionType;
public ConfigPack getPack() {
return pack;
@@ -87,26 +93,31 @@ public class FabricChunkGeneratorWrapper extends ChunkGenerator implements Gener
}
public void setDimensionType(DimensionType dimensionType) {
this.dimensionType = dimensionType;
}
@Nullable
@Override
public BlockPos locateStructure(ServerWorld world, StructureFeature<?> feature, BlockPos center, int radius, boolean skipExistingChunks) {
String name = Objects.requireNonNull(Registry.STRUCTURE_FEATURE.getId(feature)).toString();
TerraWorld terraWorld = TerraFabricPlugin.getInstance().getWorld((World) world);
TerraStructure located = pack.getStructure(pack.getTemplate().getLocatable().get(name));
if(located != null) {
CompletableFuture<BlockPos> result = new CompletableFuture<>();
AsyncStructureFinder finder = new AsyncStructureFinder(terraWorld.getBiomeProvider(), located, FabricAdapter.adapt(center).toLocation((World) world), 0, 500, location -> {
result.complete(FabricAdapter.adapt(location));
}, TerraFabricPlugin.getInstance());
finder.run(); // Do this synchronously.
try {
return result.get();
} catch(InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
if(!pack.getTemplate().disableStructures()) {
String name = Objects.requireNonNull(Registry.STRUCTURE_FEATURE.getId(feature)).toString();
TerraWorld terraWorld = TerraFabricPlugin.getInstance().getWorld((World) world);
TerraStructure located = pack.getStructure(pack.getTemplate().getLocatable().get(name));
if(located != null) {
CompletableFuture<BlockPos> result = new CompletableFuture<>();
AsyncStructureFinder finder = new AsyncStructureFinder(terraWorld.getBiomeProvider(), located, FabricAdapter.adapt(center).toLocation((World) world), 0, 500, location -> {
result.complete(FabricAdapter.adapt(location));
}, TerraFabricPlugin.getInstance());
finder.run(); // Do this synchronously.
try {
return result.get();
} catch(InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
}
TerraFabricPlugin.getInstance().logger().warning("No overrides are defined for \"" + name + "\"");
return null;
return super.locateStructure(world, feature, center, radius, skipExistingChunks);
}
@Override
@@ -127,32 +138,32 @@ public class FabricChunkGeneratorWrapper extends ChunkGenerator implements Gener
@Override
public boolean isStrongholdStartingChunk(ChunkPos chunkPos) {
if(pack.getTemplate().vanillaStructures()) return super.isStrongholdStartingChunk(chunkPos);
return false;
}
@Override
public int getHeight(int x, int z, Heightmap.Type heightmapType) {
TerraWorld world = TerraFabricPlugin.getInstance().getWorld(seed);
TerraWorld world = TerraFabricPlugin.getInstance().getWorld(dimensionType);
Sampler sampler = world.getConfig().getSamplerCache().getChunk(FastMath.floorDiv(x, 16), FastMath.floorDiv(z, 16));
int cx = FastMath.floorMod(x, 16);
int cz = FastMath.floorMod(z, 16);
int height = world.getWorld().getMaxHeight();
while (height >= 0 && sampler.sample(cx, height - 1, cz) < 0) {
height--;
}
while(height >= 0 && sampler.sample(cx, height-1, cz) < 0) height--;
return height;
}
@Override
public BlockView getColumnSample(int x, int z) {
int height = 64; // TODO: implementation
TerraWorld world = TerraFabricPlugin.getInstance().getWorld(dimensionType);
int height = getHeight(x, z, Heightmap.Type.WORLD_SURFACE);
BlockState[] array = new BlockState[256];
for(int y = 255; y >= 0; y--) {
if(y > height) {
if(y > getSeaLevel()) {
if(y > ((UserDefinedBiome) world.getBiomeProvider().getBiome(x, z)).getConfig().getSeaLevel()) {
array[y] = Blocks.AIR.getDefaultState();
} else {
array[y] = Blocks.WATER.getDefaultState();
@@ -165,6 +176,18 @@ public class FabricChunkGeneratorWrapper extends ChunkGenerator implements Gener
return new VerticalBlockSample(array);
}
@Override
public void populateEntities(ChunkRegion region) {
if(pack.getTemplate().vanillaMobs()) {
int cx = region.getCenterChunkX();
int cy = region.getCenterChunkZ();
Biome biome = region.getBiome((new ChunkPos(cx, cy)).getStartPos());
ChunkRandom chunkRandom = new ChunkRandom();
chunkRandom.setPopulationSeed(region.getSeed(), cx << 4, cy << 4);
SpawnHelper.populateEntities(region, biome, cx, cy, chunkRandom);
}
}
@Override
public TerraChunkGenerator getHandle() {
return delegate;
@@ -4,6 +4,7 @@ import com.dfsek.terra.api.world.biome.UserDefinedBiome;
import com.dfsek.terra.api.world.biome.provider.BiomeProvider;
import com.dfsek.terra.config.pack.ConfigPack;
import com.dfsek.terra.fabric.TerraFabricPlugin;
import com.dfsek.terra.fabric.util.FabricUtil;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.util.Identifier;
@@ -11,8 +12,8 @@ import net.minecraft.util.registry.Registry;
import net.minecraft.util.registry.RegistryLookupCodec;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.source.BiomeSource;
import net.minecraft.world.gen.feature.StructureFeature;
import java.util.Objects;
import java.util.stream.Collectors;
public class TerraBiomeSource extends BiomeSource {
@@ -31,7 +32,9 @@ public class TerraBiomeSource extends BiomeSource {
private final ConfigPack pack;
public TerraBiomeSource(Registry<Biome> biomes, long seed, ConfigPack pack) {
super(biomes.stream().collect(Collectors.toList()));
super(biomes.stream()
.filter(biome -> Objects.requireNonNull(biomes.getId(biome)).getNamespace().equals("terra")) // Filter out non-Terra biomes.
.collect(Collectors.toList()));
this.biomeRegistry = biomes;
this.seed = seed;
this.grid = pack.getBiomeProviderBuilder().build(seed);
@@ -51,14 +54,6 @@ public class TerraBiomeSource extends BiomeSource {
@Override
public Biome getBiomeForNoiseGen(int biomeX, int biomeY, int biomeZ) {
UserDefinedBiome biome = (UserDefinedBiome) grid.getBiome(biomeX << 2, biomeZ << 2);
return biomeRegistry.get(new Identifier("terra", TerraFabricPlugin.createBiomeID(pack, biome.getID())));
return biomeRegistry.get(new Identifier("terra", FabricUtil.createBiomeID(pack, biome.getID())));
}
@Override
public boolean hasStructureFeature(StructureFeature<?> feature) {
return false;
}
}
@@ -0,0 +1,22 @@
package com.dfsek.terra.fabric.generation;
import com.dfsek.terra.config.pack.ConfigPack;
import net.minecraft.client.world.GeneratorType;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.chunk.ChunkGenerator;
import net.minecraft.world.gen.chunk.ChunkGeneratorSettings;
public class TerraGeneratorType extends GeneratorType {
private final ConfigPack pack;
public TerraGeneratorType(ConfigPack pack) {
super("terra." + pack.getTemplate().getID());
this.pack = pack;
}
@Override
protected ChunkGenerator getChunkGenerator(Registry<Biome> biomeRegistry, Registry<ChunkGeneratorSettings> chunkGeneratorSettingsRegistry, long seed) {
return new FabricChunkGeneratorWrapper(new TerraBiomeSource(biomeRegistry, seed, pack), seed, pack);
}
}
@@ -0,0 +1,86 @@
package com.dfsek.terra.fabric.mixin;
import com.dfsek.terra.api.command.exception.CommandException;
import com.dfsek.terra.api.platform.CommandSender;
import com.dfsek.terra.api.platform.entity.Entity;
import com.dfsek.terra.fabric.TerraFabricPlugin;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.text.LiteralText;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static net.minecraft.server.command.CommandManager.argument;
import static net.minecraft.server.command.CommandManager.literal;
@Mixin(CommandManager.class)
public abstract class CommandManagerMixin {
@Shadow
@Final
private CommandDispatcher<ServerCommandSource> dispatcher;
@Inject(method = "<init>", at = @At(value = "INVOKE", target = "Lcom/mojang/brigadier/CommandDispatcher;findAmbiguities(Lcom/mojang/brigadier/AmbiguityConsumer;)V", remap = false))
private void injectTerraCommands(CommandManager.RegistrationEnvironment environment, CallbackInfo ci) {
com.dfsek.terra.api.command.CommandManager manager = TerraFabricPlugin.getInstance().getManager();
int max = manager.getMaxArgumentDepth();
RequiredArgumentBuilder<ServerCommandSource, String> arg = argument("arg" + (max - 1), StringArgumentType.word());
for(int i = 0; i < max; i++) {
RequiredArgumentBuilder<ServerCommandSource, String> next = argument("arg" + (max - i - 1), StringArgumentType.word());
arg = next.then(assemble(arg, manager));
}
dispatcher.register(literal("terra").executes(context -> 1).then(assemble(arg, manager)));
dispatcher.register(literal("te").executes(context -> 1).then(assemble(arg, manager)));
}
private RequiredArgumentBuilder<ServerCommandSource, String> assemble(RequiredArgumentBuilder<ServerCommandSource, String> in, com.dfsek.terra.api.command.CommandManager manager) {
return in.suggests((context, builder) -> {
List<String> args = parseCommand(context.getInput());
CommandSender sender = (CommandSender) context.getSource();
try {
sender = (Entity) context.getSource().getEntityOrThrow();
} catch(CommandSyntaxException ignore) {
}
try {
manager.tabComplete(args.remove(0), sender, args).forEach(builder::suggest);
} catch(CommandException e) {
sender.sendMessage(e.getMessage());
}
return builder.buildFuture();
}).executes(context -> {
List<String> args = parseCommand(context.getInput());
CommandSender sender = (CommandSender) context.getSource();
try {
sender = (Entity) context.getSource().getEntityOrThrow();
} catch(CommandSyntaxException ignore) {
}
try {
manager.execute(args.remove(0), sender, args);
} catch(CommandException e) {
context.getSource().sendError(new LiteralText(e.getMessage()));
}
return 1;
});
}
private List<String> parseCommand(String command) {
if(command.startsWith("/terra ")) command = command.substring("/terra ".length());
else if(command.startsWith("/te ")) command = command.substring("/te ".length());
List<String> c = new ArrayList<>(Arrays.asList(command.split(" ")));
if(command.endsWith(" ")) c.add("");
return c;
}
}
@@ -0,0 +1,35 @@
package com.dfsek.terra.fabric.mixin;
import com.dfsek.terra.api.util.generic.pair.Pair;
import com.dfsek.terra.fabric.TerraFabricPlugin;
import com.dfsek.terra.fabric.generation.FabricChunkGeneratorWrapper;
import com.dfsek.terra.world.TerraWorld;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.WorldGenerationProgressListener;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.registry.RegistryKey;
import net.minecraft.world.World;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.gen.Spawner;
import net.minecraft.world.gen.chunk.ChunkGenerator;
import net.minecraft.world.level.ServerWorldProperties;
import net.minecraft.world.level.storage.LevelStorage;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.util.List;
import java.util.concurrent.Executor;
@Mixin(ServerWorld.class)
public abstract class ServerWorldMixin {
@Inject(method = "<init>", at = @At(value = "RETURN"))
public void injectConstructor(MinecraftServer server, Executor workerExecutor, LevelStorage.Session session, ServerWorldProperties properties, RegistryKey<World> registryKey, DimensionType dimensionType, WorldGenerationProgressListener worldGenerationProgressListener, ChunkGenerator chunkGenerator, boolean debugWorld, long l, List<Spawner> list, boolean bl, CallbackInfo ci) {
if(chunkGenerator instanceof FabricChunkGeneratorWrapper) {
TerraFabricPlugin.getInstance().getWorldMap().put(dimensionType, Pair.of((ServerWorld) (Object) this, new TerraWorld((com.dfsek.terra.api.platform.world.World) this, ((FabricChunkGeneratorWrapper) chunkGenerator).getPack(), TerraFabricPlugin.getInstance())));
((FabricChunkGeneratorWrapper) chunkGenerator).setDimensionType(dimensionType);
TerraFabricPlugin.getInstance().logger().info("Registered world " + this + " to dimension type " + dimensionType);
}
}
}
@@ -1,8 +1,12 @@
package com.dfsek.terra.fabric.mixin.init;
import com.dfsek.terra.fabric.TerraFabricPlugin;
import com.dfsek.terra.fabric.generation.TerraGeneratorType;
import com.dfsek.terra.fabric.mixin.access.GeneratorTypeAccessor;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.RunArgs;
import net.minecraft.client.world.GeneratorType;
import net.minecraft.text.LiteralText;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
@@ -15,5 +19,11 @@ public class MinecraftClientMixin {
shift = At.Shift.BEFORE))
public void injectConstructor(RunArgs args, CallbackInfo callbackInfo) {
TerraFabricPlugin.getInstance().packInit(); // Load during MinecraftClient construction, after other mods have registered blocks and stuff
TerraFabricPlugin.getInstance().getConfigRegistry().forEach(pack -> {
final GeneratorType generatorType = new TerraGeneratorType(pack);
//noinspection ConstantConditions
((GeneratorTypeAccessor) generatorType).setTranslationKey(new LiteralText("Terra:" + pack.getTemplate().getID()));
GeneratorTypeAccessor.getValues().add(1, generatorType);
});
}
}
@@ -0,0 +1,117 @@
package com.dfsek.terra.fabric.util;
import com.dfsek.terra.api.util.generic.pair.Pair;
import com.dfsek.terra.config.builder.BiomeBuilder;
import com.dfsek.terra.config.pack.ConfigPack;
import com.dfsek.terra.config.templates.BiomeTemplate;
import com.dfsek.terra.fabric.TerraFabricPlugin;
import com.dfsek.terra.fabric.config.PostLoadCompatibilityOptions;
import com.dfsek.terra.fabric.config.PreLoadCompatibilityOptions;
import com.dfsek.terra.fabric.mixin.access.BiomeEffectsAccessor;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.BuiltinRegistries;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.BiomeEffects;
import net.minecraft.world.biome.GenerationSettings;
import net.minecraft.world.gen.GenerationStep;
import net.minecraft.world.gen.carver.ConfiguredCarver;
import net.minecraft.world.gen.feature.ConfiguredFeature;
import net.minecraft.world.gen.feature.ConfiguredStructureFeature;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import java.util.function.Supplier;
public final class FabricUtil {
public static String createBiomeID(ConfigPack pack, String biomeID) {
return pack.getTemplate().getID().toLowerCase() + "/" + biomeID.toLowerCase(Locale.ROOT);
}
/**
* Clones a Vanilla biome and injects Terra data to create a Terra-vanilla biome delegate.
*
* @param fabricAddon The Fabric addon instance.
* @param biome The Terra BiomeBuilder.
* @param pack The ConfigPack this biome belongs to.
* @return The Minecraft delegate biome.
*/
public static Biome createBiome(TerraFabricPlugin.FabricAddon fabricAddon, BiomeBuilder biome, ConfigPack pack) {
BiomeTemplate template = biome.getTemplate();
Map<String, Integer> colors = template.getColors();
Biome vanilla = (Biome) (new ArrayList<>(biome.getVanillaBiomes().getContents()).get(0)).getHandle();
GenerationSettings.Builder generationSettings = new GenerationSettings.Builder();
generationSettings.surfaceBuilder(vanilla.getGenerationSettings().getSurfaceBuilder()); // It needs a surfacebuilder, even though we dont use it.
generationSettings.feature(GenerationStep.Feature.VEGETAL_DECORATION, TerraFabricPlugin.POPULATOR_CONFIGURED_FEATURE);
if(pack.getTemplate().vanillaCaves()) {
for(GenerationStep.Carver carver : GenerationStep.Carver.values()) {
for(Supplier<ConfiguredCarver<?>> configuredCarverSupplier : vanilla.getGenerationSettings().getCarversForStep(carver)) {
generationSettings.carver(carver, configuredCarverSupplier.get());
}
}
}
Pair<PreLoadCompatibilityOptions, PostLoadCompatibilityOptions> pair = fabricAddon.getTemplates().get(pack);
PreLoadCompatibilityOptions compatibilityOptions = pair.getLeft();
PostLoadCompatibilityOptions postLoadCompatibilityOptions = pair.getRight();
TerraFabricPlugin.getInstance().getDebugLogger().info("Injecting Vanilla structures and features into Terra biome " + biome.getTemplate().getID());
for(Supplier<ConfiguredStructureFeature<?, ?>> structureFeature : vanilla.getGenerationSettings().getStructureFeatures()) {
Identifier key = BuiltinRegistries.CONFIGURED_STRUCTURE_FEATURE.getId(structureFeature.get());
if(!compatibilityOptions.getExcludedBiomeStructures().contains(key) && !postLoadCompatibilityOptions.getExcludedPerBiomeStructures().getOrDefault(biome, Collections.emptySet()).contains(key)) {
generationSettings.structureFeature(structureFeature.get());
TerraFabricPlugin.getInstance().getDebugLogger().info("Injected structure " + key);
}
}
if(compatibilityOptions.doBiomeInjection()) {
for(int step = 0; step < vanilla.getGenerationSettings().getFeatures().size(); step++) {
for(Supplier<ConfiguredFeature<?, ?>> featureSupplier : vanilla.getGenerationSettings().getFeatures().get(step)) {
Identifier key = BuiltinRegistries.CONFIGURED_FEATURE.getId(featureSupplier.get());
if(!compatibilityOptions.getExcludedBiomeFeatures().contains(key) && !postLoadCompatibilityOptions.getExcludedPerBiomeFeatures().getOrDefault(biome, Collections.emptySet()).contains(key)) {
generationSettings.feature(step, featureSupplier);
TerraFabricPlugin.getInstance().getDebugLogger().info("Injected feature " + key + " at stage " + step);
}
}
}
}
BiomeEffectsAccessor accessor = (BiomeEffectsAccessor) vanilla.getEffects();
BiomeEffects.Builder effects = new BiomeEffects.Builder()
.waterColor(colors.getOrDefault("water", accessor.getWaterColor()))
.waterFogColor(colors.getOrDefault("water-fog", accessor.getWaterFogColor()))
.fogColor(colors.getOrDefault("fog", accessor.getFogColor()))
.skyColor(colors.getOrDefault("sky", accessor.getSkyColor()))
.grassColorModifier(accessor.getGrassColorModifier());
if(colors.containsKey("grass")) {
effects.grassColor(colors.get("grass"));
} else {
accessor.getGrassColor().ifPresent(effects::grassColor);
}
if(colors.containsKey("foliage")) {
effects.foliageColor(colors.get("foliage"));
} else {
accessor.getFoliageColor().ifPresent(effects::foliageColor);
}
return new Biome.Builder()
.precipitation(vanilla.getPrecipitation())
.category(vanilla.getCategory())
.depth(vanilla.getDepth())
.scale(vanilla.getScale())
.temperature(vanilla.getTemperature())
.downfall(vanilla.getDownfall())
.effects(effects.build())
.spawnSettings(vanilla.getSpawnSettings())
.generationSettings(generationSettings.build())
.build();
}
}
@@ -25,7 +25,6 @@
],
"depends": {
"fabricloader": ">=0.7.4",
"fabric": "*",
"minecraft": "1.16.x"
},
"accessWidener": "terra.accesswidener"
@@ -4,7 +4,9 @@
"package": "com.dfsek.terra.fabric.mixin",
"compatibilityLevel": "JAVA_8",
"mixins": [
"CommandManagerMixin",
"GeneratorOptionsMixin",
"ServerWorldMixin",
"access.BiomeEffectsAccessor",
"access.MobSpawnerLogicAccessor",
"access.StateAccessor",
@@ -1,36 +1,78 @@
package com.dfsek.terra.forge;
import com.dfsek.terra.api.util.generic.pair.Pair;
import com.dfsek.terra.config.builder.BiomeBuilder;
import com.dfsek.terra.config.pack.ConfigPack;
import com.dfsek.terra.config.templates.BiomeTemplate;
import net.minecraft.block.Blocks;
import com.dfsek.terra.forge.config.PostLoadCompatibilityOptions;
import com.dfsek.terra.forge.config.PreLoadCompatibilityOptions;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.WorldGenRegistries;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.BiomeAmbience;
import net.minecraft.world.biome.BiomeGenerationSettings;
import net.minecraft.world.gen.GenerationStage;
import net.minecraft.world.gen.surfacebuilders.SurfaceBuilder;
import net.minecraft.world.gen.surfacebuilders.SurfaceBuilderConfig;
import net.minecraft.world.gen.carver.ConfiguredCarver;
import net.minecraft.world.gen.feature.ConfiguredFeature;
import net.minecraft.world.gen.feature.StructureFeature;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import java.util.function.Supplier;
public final class ForgeUtil {
public static String createBiomeID(ConfigPack pack, String biomeID) {
return pack.getTemplate().getID().toLowerCase() + "/" + biomeID.toLowerCase(Locale.ROOT);
}
@SuppressWarnings("ConstantConditions")
public static Biome createBiome(BiomeBuilder biome) {
public static Biome createBiome(BiomeBuilder biome, ConfigPack pack, TerraForgePlugin.ForgeAddon forgeAddon) {
BiomeTemplate template = biome.getTemplate();
Map<String, Integer> colors = template.getColors();
Biome vanilla = (Biome) ((Object) new ArrayList<>(biome.getVanillaBiomes().getContents()).get(0));
Biome vanilla = (Biome) (new ArrayList<>(biome.getVanillaBiomes().getContents()).get(0)).getHandle();
BiomeGenerationSettings.Builder generationSettings = new BiomeGenerationSettings.Builder();
generationSettings.surfaceBuilder(SurfaceBuilder.DEFAULT.configured(new SurfaceBuilderConfig(Blocks.GRASS_BLOCK.defaultBlockState(), Blocks.DIRT.defaultBlockState(), Blocks.GRAVEL.defaultBlockState()))); // It needs a surfacebuilder, even though we dont use it.
generationSettings.surfaceBuilder(vanilla.getGenerationSettings().getSurfaceBuilder()); // It needs a surfacebuilder, even though we dont use it.
generationSettings.addFeature(GenerationStage.Decoration.VEGETAL_DECORATION, TerraForgePlugin.POPULATOR_CONFIGURED_FEATURE);
if(pack.getTemplate().vanillaCaves()) {
for(GenerationStage.Carving carver : GenerationStage.Carving.values()) {
for(Supplier<ConfiguredCarver<?>> configuredCarverSupplier : vanilla.getGenerationSettings().getCarvers(carver)) {
generationSettings.addCarver(carver, configuredCarverSupplier.get());
}
}
}
Pair<PreLoadCompatibilityOptions, PostLoadCompatibilityOptions> pair = forgeAddon.getTemplates().get(pack);
PreLoadCompatibilityOptions compatibilityOptions = pair.getLeft();
PostLoadCompatibilityOptions postLoadCompatibilityOptions = pair.getRight();
TerraForgePlugin.getInstance().getDebugLogger().info("Injecting Vanilla structures and features into Terra biome " + biome.getTemplate().getID());
for(Supplier<StructureFeature<?, ?>> structureFeature : vanilla.getGenerationSettings().structures()) {
ResourceLocation key = WorldGenRegistries.CONFIGURED_STRUCTURE_FEATURE.getKey(structureFeature.get());
if(!compatibilityOptions.getExcludedBiomeStructures().contains(key) && !postLoadCompatibilityOptions.getExcludedPerBiomeStructures().getOrDefault(biome, Collections.emptySet()).contains(key)) {
generationSettings.addStructureStart(structureFeature.get());
TerraForgePlugin.getInstance().getDebugLogger().info("Injected structure " + key);
}
}
if(compatibilityOptions.doBiomeInjection()) {
for(int step = 0; step < vanilla.getGenerationSettings().features().size(); step++) {
for(Supplier<ConfiguredFeature<?, ?>> featureSupplier : vanilla.getGenerationSettings().features().get(step)) {
ResourceLocation key = WorldGenRegistries.CONFIGURED_FEATURE.getKey(featureSupplier.get());
if(!compatibilityOptions.getExcludedBiomeFeatures().contains(key) && !postLoadCompatibilityOptions.getExcludedPerBiomeFeatures().getOrDefault(biome, Collections.emptySet()).contains(key)) {
generationSettings.addFeature(step, featureSupplier);
TerraForgePlugin.getInstance().getDebugLogger().info("Injected feature " + key + " at stage " + step);
}
}
}
}
BiomeAmbience vanillaEffects = vanilla.getSpecialEffects();
BiomeAmbience.Builder effects = new BiomeAmbience.Builder()
.waterColor(colors.getOrDefault("water", vanillaEffects.getWaterColor()))
@@ -44,7 +86,7 @@ public final class ForgeUtil {
} else {
vanillaEffects.getGrassColorOverride().ifPresent(effects::grassColorOverride);
}
vanillaEffects.getFoliageColorOverride().ifPresent(effects::foliageColorOverride);
if(colors.containsKey("foliage")) {
effects.foliageColorOverride(colors.get("foliage"));
} else {
@@ -61,6 +103,7 @@ public final class ForgeUtil {
.specialEffects(effects.build())
.mobSpawnSettings(vanilla.getMobSettings())
.generationSettings(generationSettings.build())
.build().setRegistryName("terra", createBiomeID(template.getPack(), template.getID()));
.build()
.setRegistryName("terra", createBiomeID(template.getPack(), template.getID()));
}
}
@@ -1,5 +1,7 @@
package com.dfsek.terra.forge;
import com.dfsek.tectonic.exception.ConfigException;
import com.dfsek.tectonic.exception.LoadException;
import com.dfsek.tectonic.loading.TypeRegistry;
import com.dfsek.terra.api.TerraPlugin;
import com.dfsek.terra.api.addons.TerraAddon;
@@ -14,6 +16,7 @@ import com.dfsek.terra.api.event.EventManager;
import com.dfsek.terra.api.event.TerraEventManager;
import com.dfsek.terra.api.event.annotations.Global;
import com.dfsek.terra.api.event.annotations.Priority;
import com.dfsek.terra.api.event.events.config.ConfigPackPostLoadEvent;
import com.dfsek.terra.api.event.events.config.ConfigPackPreLoadEvent;
import com.dfsek.terra.api.platform.block.BlockData;
import com.dfsek.terra.api.platform.handle.ItemHandle;
@@ -22,9 +25,10 @@ import com.dfsek.terra.api.platform.world.Tree;
import com.dfsek.terra.api.platform.world.World;
import com.dfsek.terra.api.registry.CheckedRegistry;
import com.dfsek.terra.api.registry.LockedRegistry;
import com.dfsek.terra.api.transform.NotNullValidator;
import com.dfsek.terra.api.transform.Transformer;
import com.dfsek.terra.api.transform.Validator;
import com.dfsek.terra.api.util.JarUtil;
import com.dfsek.terra.api.util.generic.pair.Pair;
import com.dfsek.terra.api.util.logging.DebugLogger;
import com.dfsek.terra.commands.CommandUtil;
import com.dfsek.terra.config.GenericLoaders;
@@ -32,6 +36,8 @@ import com.dfsek.terra.config.PluginConfig;
import com.dfsek.terra.config.lang.LangUtil;
import com.dfsek.terra.config.lang.Language;
import com.dfsek.terra.config.pack.ConfigPack;
import com.dfsek.terra.forge.config.PostLoadCompatibilityOptions;
import com.dfsek.terra.forge.config.PreLoadCompatibilityOptions;
import com.dfsek.terra.forge.generation.ForgeChunkGeneratorWrapper;
import com.dfsek.terra.forge.generation.PopulatorFeature;
import com.dfsek.terra.forge.generation.TerraBiomeSource;
@@ -45,6 +51,9 @@ import com.dfsek.terra.registry.master.ConfigRegistry;
import com.dfsek.terra.world.TerraWorld;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.registry.WorldGenRegistries;
import net.minecraft.world.DimensionType;
import net.minecraft.world.IWorld;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.feature.ConfiguredFeature;
import net.minecraft.world.gen.feature.Features;
@@ -52,10 +61,12 @@ import net.minecraft.world.gen.feature.IFeatureConfig;
import net.minecraft.world.gen.feature.NoFeatureConfig;
import net.minecraft.world.gen.placement.DecoratedPlacement;
import net.minecraft.world.gen.placement.NoPlacementConfig;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.ForgeRegistry;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.objectweb.asm.Type;
@@ -78,7 +89,7 @@ public class TerraForgePlugin implements TerraPlugin {
public static final ConfiguredFeature<?, ?> POPULATOR_CONFIGURED_FEATURE = POPULATOR_FEATURE.configured(IFeatureConfig.NONE).decorated(DecoratedPlacement.NOPE.configured(NoPlacementConfig.INSTANCE));
private static TerraForgePlugin INSTANCE;
private final Map<Long, TerraWorld> worldMap = new HashMap<>();
private final Map<DimensionType, Pair<ServerWorld, TerraWorld>> worldMap = new HashMap<>();
private final EventManager eventManager = new TerraEventManager(this);
private final GenericLoaders genericLoaders = new GenericLoaders(this);
private final Profiler profiler = new ProfilerImpl();
@@ -109,12 +120,15 @@ public class TerraForgePlugin implements TerraPlugin {
private final WorldHandle worldHandle = new ForgeWorldHandle();
private final ConfigRegistry registry = new ConfigRegistry();
private final CheckedRegistry<ConfigPack> checkedRegistry = new CheckedRegistry<>(registry);
private final AddonRegistry addonRegistry = new AddonRegistry(new ForgeAddon(this), this);
private final ForgeAddon addon = new ForgeAddon(this);
private final AddonRegistry addonRegistry = new AddonRegistry(addon, this);
private final LockedRegistry<TerraAddon> addonLockedRegistry = new LockedRegistry<>(addonRegistry);
private final PluginConfig config = new PluginConfig();
private final Transformer<String, Biome> biomeFixer = new Transformer.Builder<String, Biome>()
.addTransform(id -> ForgeRegistries.BIOMES.getValue(ResourceLocation.tryParse(id)), new NotNullValidator<>())
.addTransform(id -> ForgeRegistries.BIOMES.getValue(ResourceLocation.tryParse("minecraft:" + id.toLowerCase())), new NotNullValidator<>()).build();
.addTransform(id -> ForgeRegistries.BIOMES.getValue(ResourceLocation.tryParse(id)), Validator.notNull())
.addTransform(id -> ForgeRegistries.BIOMES.getValue(ResourceLocation.tryParse("minecraft:" + id.toLowerCase())), Validator.notNull()).build();
private final File dataFolder;
public TerraForgePlugin() {
@@ -123,6 +137,7 @@ public class TerraForgePlugin implements TerraPlugin {
this.dataFolder = Paths.get("config", "Terra").toFile();
saveDefaultConfig();
config.load(this);
debugLogger.setDebug(config.isDebug());
LangUtil.load(config.getLanguage(), this);
try {
CommandUtil.registerAll(manager);
@@ -143,7 +158,7 @@ public class TerraForgePlugin implements TerraPlugin {
});
}
public void setup() {
public void init() {
logger.info("Initializing Terra...");
if(!addonRegistry.loadAll()) {
@@ -153,6 +168,10 @@ public class TerraForgePlugin implements TerraPlugin {
registry.loadAll(this);
logger.info("Loaded packs.");
((ForgeRegistry<Biome>) ForgeRegistries.BIOMES).unfreeze(); // Evil
getConfigRegistry().forEach(pack -> pack.getBiomeRegistry().forEach((id, biome) -> ForgeRegistries.BIOMES.register(ForgeUtil.createBiome(biome, pack, addon)))); // Register all Terra biomes.
((ForgeRegistry<Biome>) ForgeRegistries.BIOMES).freeze();
}
@Override
@@ -162,10 +181,13 @@ public class TerraForgePlugin implements TerraPlugin {
@Override
public TerraWorld getWorld(World world) {
return worldMap.computeIfAbsent(world.getSeed(), w -> {
logger.info("Loading world " + w);
return new TerraWorld(world, ((ForgeChunkGeneratorWrapper) world.getGenerator()).getPack(), this);
});
return getWorld(((IWorld) world).dimensionType());
}
public TerraWorld getWorld(DimensionType type) {
TerraWorld world = worldMap.get(type).getRight();
if(world == null) throw new IllegalArgumentException("No world exists with dimension type " + type);
return world;
}
/**
@@ -191,12 +213,6 @@ public class TerraForgePlugin implements TerraPlugin {
return JarUtil.getJarFile();
}
public TerraWorld getWorld(long seed) {
TerraWorld world = worldMap.get(seed);
if(world == null) throw new IllegalArgumentException("No world exists with seed " + seed);
return world;
}
@Override
public com.dfsek.terra.api.util.logging.Logger logger() {
return logger;
@@ -237,14 +253,11 @@ public class TerraForgePlugin implements TerraPlugin {
config.load(this);
LangUtil.load(config.getLanguage(), this); // Load language.
boolean succeed = registry.loadAll(this);
Map<Long, TerraWorld> newMap = new HashMap<>();
worldMap.forEach((seed, tw) -> {
tw.getConfig().getSamplerCache().clear();
String packID = tw.getConfig().getTemplate().getID();
newMap.put(seed, new TerraWorld(tw.getWorld(), registry.get(packID), this));
worldMap.forEach((seed, pair) -> {
pair.getRight().getConfig().getSamplerCache().clear();
String packID = pair.getRight().getConfig().getTemplate().getID();
pair.setRight(new TerraWorld(pair.getRight().getWorld(), registry.get(packID), this));
});
worldMap.clear();
worldMap.putAll(newMap);
return succeed;
}
@@ -278,7 +291,12 @@ public class TerraForgePlugin implements TerraPlugin {
genericLoaders.register(registry);
registry
.registerLoader(BlockData.class, (t, o, l) -> worldHandle.createBlockData((String) o))
.registerLoader(com.dfsek.terra.api.platform.world.Biome.class, (t, o, l) -> biomeFixer.translate((String) o));
.registerLoader(com.dfsek.terra.api.platform.world.Biome.class, (t, o, l) -> biomeFixer.translate((String) o))
.registerLoader(ResourceLocation.class, (t, o, l) -> {
ResourceLocation identifier = ResourceLocation.tryParse((String) o);
if(identifier == null) throw new LoadException("Invalid identifier: " + o);
return identifier;
});
}
@Override
@@ -295,10 +313,16 @@ public class TerraForgePlugin implements TerraPlugin {
return manager;
}
public Map<DimensionType, Pair<ServerWorld, TerraWorld>> getWorldMap() {
return worldMap;
}
@Addon("Terra-Forge")
@Author("Terra")
@Version("1.0.0")
private static final class ForgeAddon extends TerraAddon implements EventListener {
public static final class ForgeAddon extends TerraAddon implements EventListener {
private final Map<ConfigPack, Pair<PreLoadCompatibilityOptions, PostLoadCompatibilityOptions>> templates = new HashMap<>();
private final TerraPlugin main;
@@ -334,6 +358,39 @@ public class TerraForgePlugin implements TerraPlugin {
injectTree(treeRegistry, "MEGA_SPRUCE", Features.MEGA_SPRUCE);
injectTree(treeRegistry, "CRIMSON_FUNGUS", Features.CRIMSON_FUNGI);
injectTree(treeRegistry, "WARPED_FUNGUS", Features.WARPED_FUNGI);
PreLoadCompatibilityOptions template = new PreLoadCompatibilityOptions();
try {
event.loadTemplate(template);
} catch(ConfigException e) {
e.printStackTrace();
}
if(template.doRegistryInjection()) {
WorldGenRegistries.CONFIGURED_FEATURE.entrySet().forEach(entry -> {
if(!template.getExcludedRegistryFeatures().contains(entry.getKey().getRegistryName())) {
try {
event.getPack().getTreeRegistry().add(entry.getKey().getRegistryName().toString(), (Tree) entry.getValue());
main.getDebugLogger().info("Injected ConfiguredFeature " + entry.getKey().getRegistryName() + " as Tree: " + entry.getValue());
} catch(DuplicateEntryException ignored) {
}
}
});
}
templates.put(event.getPack(), Pair.of(template, null));
}
@Priority(Priority.HIGHEST)
@Global
public void createInjectionOptions(ConfigPackPostLoadEvent event) {
PostLoadCompatibilityOptions template = new PostLoadCompatibilityOptions();
try {
event.loadTemplate(template);
} catch(ConfigException e) {
e.printStackTrace();
}
templates.get(event.getPack()).setRight(template);
}
@@ -343,5 +400,9 @@ public class TerraForgePlugin implements TerraPlugin {
} catch(DuplicateEntryException ignore) {
}
}
public Map<ConfigPack, Pair<PreLoadCompatibilityOptions, PostLoadCompatibilityOptions>> getTemplates() {
return templates;
}
}
}
@@ -0,0 +1,30 @@
package com.dfsek.terra.forge.config;
import com.dfsek.tectonic.annotations.Default;
import com.dfsek.tectonic.annotations.Value;
import com.dfsek.tectonic.config.ConfigTemplate;
import com.dfsek.terra.config.builder.BiomeBuilder;
import net.minecraft.util.ResourceLocation;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@SuppressWarnings("FieldMayBeFinal")
public class PostLoadCompatibilityOptions implements ConfigTemplate {
@Value("structures.inject-biome.exclude-biomes")
@Default
private Map<BiomeBuilder, Set<ResourceLocation>> excludedPerBiomeStructures = new HashMap<>();
@Value("features.inject-biome.exclude-biomes")
@Default
private Map<BiomeBuilder, Set<ResourceLocation>> excludedPerBiomeFeatures = new HashMap<>();
public Map<BiomeBuilder, Set<ResourceLocation>> getExcludedPerBiomeFeatures() {
return excludedPerBiomeFeatures;
}
public Map<BiomeBuilder, Set<ResourceLocation>> getExcludedPerBiomeStructures() {
return excludedPerBiomeStructures;
}
}
@@ -0,0 +1,52 @@
package com.dfsek.terra.forge.config;
import com.dfsek.tectonic.annotations.Default;
import com.dfsek.tectonic.annotations.Value;
import com.dfsek.tectonic.config.ConfigTemplate;
import net.minecraft.util.ResourceLocation;
import java.util.HashSet;
import java.util.Set;
@SuppressWarnings("FieldMayBeFinal")
public class PreLoadCompatibilityOptions implements ConfigTemplate {
@Value("features.inject-registry.enable")
@Default
private boolean doRegistryInjection = false;
@Value("features.inject-biome.enable")
@Default
private boolean doBiomeInjection = false;
@Value("features.inject-registry.excluded-features")
@Default
private Set<ResourceLocation> excludedRegistryFeatures = new HashSet<>();
@Value("features.inject-biome.excluded-features")
@Default
private Set<ResourceLocation> excludedBiomeFeatures = new HashSet<>();
@Value("structures.inject-biome.excluded-features")
@Default
private Set<ResourceLocation> excludedBiomeStructures = new HashSet<>();
public boolean doBiomeInjection() {
return doBiomeInjection;
}
public boolean doRegistryInjection() {
return doRegistryInjection;
}
public Set<ResourceLocation> getExcludedBiomeFeatures() {
return excludedBiomeFeatures;
}
public Set<ResourceLocation> getExcludedRegistryFeatures() {
return excludedRegistryFeatures;
}
public Set<ResourceLocation> getExcludedBiomeStructures() {
return excludedBiomeStructures;
}
}
@@ -4,32 +4,49 @@ import com.dfsek.terra.api.platform.world.World;
import com.dfsek.terra.api.platform.world.generator.ChunkData;
import com.dfsek.terra.api.platform.world.generator.GeneratorWrapper;
import com.dfsek.terra.api.util.FastRandom;
import com.dfsek.terra.api.world.biome.UserDefinedBiome;
import com.dfsek.terra.api.world.generation.TerraChunkGenerator;
import com.dfsek.terra.api.world.locate.AsyncStructureFinder;
import com.dfsek.terra.config.pack.ConfigPack;
import com.dfsek.terra.forge.ForgeAdapter;
import com.dfsek.terra.forge.TerraForgePlugin;
import com.dfsek.terra.world.TerraWorld;
import com.dfsek.terra.world.generation.generators.DefaultChunkGenerator3D;
import com.dfsek.terra.world.generation.math.samplers.Sampler;
import com.dfsek.terra.world.population.items.TerraStructure;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.jafama.FastMath;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.util.SharedSeedRandom;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.registry.DynamicRegistries;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.Blockreader;
import net.minecraft.world.DimensionType;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.IWorld;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.BiomeManager;
import net.minecraft.world.chunk.IChunk;
import net.minecraft.world.gen.ChunkGenerator;
import net.minecraft.world.gen.GenerationStage;
import net.minecraft.world.gen.Heightmap;
import net.minecraft.world.gen.WorldGenRegion;
import net.minecraft.world.gen.feature.structure.Structure;
import net.minecraft.world.gen.feature.structure.StructureManager;
import net.minecraft.world.gen.feature.template.TemplateManager;
import net.minecraft.world.gen.settings.DimensionStructuresSettings;
import net.minecraft.world.server.ServerWorld;
import net.minecraft.world.spawner.WorldEntitySpawner;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class ForgeChunkGeneratorWrapper extends ChunkGenerator implements GeneratorWrapper {
private final long seed;
@@ -49,6 +66,8 @@ public class ForgeChunkGeneratorWrapper extends ChunkGenerator implements Genera
return pack;
}
private DimensionType dimensionType;
public ForgeChunkGeneratorWrapper(TerraBiomeSource biomeSource, long seed, ConfigPack configPack) {
super(biomeSource, new DimensionStructuresSettings(false));
this.pack = configPack;
@@ -75,8 +94,32 @@ public class ForgeChunkGeneratorWrapper extends ChunkGenerator implements Genera
}
@Nullable
@Override
public BlockPos findNearestMapFeature(@NotNull ServerWorld world, @NotNull Structure<?> feature, @NotNull BlockPos center, int radius, boolean skipExistingChunks) {
if(!pack.getTemplate().disableStructures()) {
String name = Objects.requireNonNull(Registry.STRUCTURE_FEATURE.getKey(feature)).toString();
TerraWorld terraWorld = TerraForgePlugin.getInstance().getWorld((World) world);
TerraStructure located = pack.getStructure(pack.getTemplate().getLocatable().get(name));
if(located != null) {
CompletableFuture<BlockPos> result = new CompletableFuture<>();
AsyncStructureFinder finder = new AsyncStructureFinder(terraWorld.getBiomeProvider(), located, ForgeAdapter.adapt(center).toLocation((World) world), 0, 500, location -> {
result.complete(ForgeAdapter.adapt(location));
}, TerraForgePlugin.getInstance());
finder.run(); // Do this synchronously.
try {
return result.get();
} catch(InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
}
return super.findNearestMapFeature(world, feature, center, radius, skipExistingChunks);
}
@Override
public boolean hasStronghold(@NotNull ChunkPos p_235952_1_) {
if(pack.getTemplate().vanillaStructures()) return super.hasStronghold(p_235952_1_);
return false;
}
@@ -97,27 +140,26 @@ public class ForgeChunkGeneratorWrapper extends ChunkGenerator implements Genera
@Override
public int getBaseHeight(int x, int z, Heightmap.@NotNull Type p_222529_3_) {
TerraWorld world = TerraForgePlugin.getInstance().getWorld(seed);
TerraWorld world = TerraForgePlugin.getInstance().getWorld(dimensionType);
Sampler sampler = world.getConfig().getSamplerCache().getChunk(FastMath.floorDiv(x, 16), FastMath.floorDiv(z, 16));
int cx = FastMath.floorMod(x, 16);
int cz = FastMath.floorMod(z, 16);
int height = world.getWorld().getMaxHeight();
while (height >= 0 && sampler.sample(cx, height - 1, cz) < 0) {
height--;
}
while(height >= 0 && sampler.sample(cx, height - 1, cz) < 0) height--;
return height;
}
@Override
public @NotNull IBlockReader getBaseColumn(int p_230348_1_, int p_230348_2_) {
int height = 64; // TODO: implementation
public @NotNull IBlockReader getBaseColumn(int x, int z) {
TerraWorld world = TerraForgePlugin.getInstance().getWorld(dimensionType);
int height = getBaseHeight(x, z, Heightmap.Type.WORLD_SURFACE);
BlockState[] array = new BlockState[256];
for(int y = 255; y >= 0; y--) {
if(y > height) {
if(y > getSeaLevel()) {
if(y > ((UserDefinedBiome) world.getBiomeProvider().getBiome(x, z)).getConfig().getSeaLevel()) {
array[y] = Blocks.AIR.defaultBlockState();
} else {
array[y] = Blocks.WATER.defaultBlockState();
@@ -130,9 +172,24 @@ public class ForgeChunkGeneratorWrapper extends ChunkGenerator implements Genera
return new Blockreader(array);
}
@Override
public void spawnOriginalMobs(WorldGenRegion region) {
if(pack.getTemplate().vanillaMobs()) {
int cx = region.getCenterX();
int cy = region.getCenterZ();
Biome biome = region.getBiome((new ChunkPos(cx, cy)).getWorldPosition());
SharedSeedRandom chunkRandom = new SharedSeedRandom();
chunkRandom.setDecorationSeed(region.getSeed(), cx << 4, cy << 4);
WorldEntitySpawner.spawnMobsForChunkGeneration(region, biome, cx, cy, chunkRandom);
}
}
@Override
public TerraChunkGenerator getHandle() {
return delegate;
}
public void setDimensionType(DimensionType dimensionType) {
this.dimensionType = dimensionType;
}
}
@@ -0,0 +1,24 @@
package com.dfsek.terra.forge.generation;
import com.dfsek.terra.config.pack.ConfigPack;
import net.minecraft.client.gui.screen.BiomeGeneratorTypeScreens;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.ChunkGenerator;
import net.minecraft.world.gen.DimensionSettings;
import org.jetbrains.annotations.NotNull;
public class TerraGeneratorType extends BiomeGeneratorTypeScreens {
private final ConfigPack pack;
public TerraGeneratorType(ConfigPack pack) {
super(new StringTextComponent("Terra:" + pack.getTemplate().getID()));
this.pack = pack;
}
@Override
protected @NotNull ChunkGenerator generator(@NotNull Registry<Biome> biomeRegistry, @NotNull Registry<DimensionSettings> chunkGeneratorSettingsRegistry, long seed) {
return new ForgeChunkGeneratorWrapper(new TerraBiomeSource(biomeRegistry, seed, pack), seed, pack);
}
}
@@ -1,22 +0,0 @@
package com.dfsek.terra.forge.generation;
import com.dfsek.terra.config.pack.ConfigPack;
import com.dfsek.terra.forge.TerraForgePlugin;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.ChunkGenerator;
import net.minecraft.world.gen.DimensionSettings;
import net.minecraftforge.common.world.ForgeWorldType;
public class TerraLevelType implements ForgeWorldType.IChunkGeneratorFactory {
public static final TerraLevelType TERRA_LEVEL_TYPE = new TerraLevelType();
public static final ForgeWorldType FORGE_WORLD_TYPE = new ForgeWorldType(TERRA_LEVEL_TYPE).setRegistryName("terra", "world");
@Override
public ChunkGenerator createChunkGenerator(Registry<Biome> biomeRegistry, Registry<DimensionSettings> dimensionSettingsRegistry, long seed, String generatorSettings) {
System.out.println(generatorSettings);
dimensionSettingsRegistry.forEach(System.out::println);
ConfigPack pack = TerraForgePlugin.getInstance().getConfigRegistry().get("DEFAULT");
TerraForgePlugin.getInstance().logger().info("Creating generator for config pack " + pack.getTemplate().getID());
return new ForgeChunkGeneratorWrapper(new TerraBiomeSource(biomeRegistry, seed, pack), seed, pack);
}
}
@@ -1,50 +0,0 @@
package com.dfsek.terra.forge.listener;
import com.dfsek.terra.api.util.mutable.MutableInteger;
import com.dfsek.terra.config.pack.ConfigPack;
import com.dfsek.terra.forge.TerraForgePlugin;
import com.dfsek.terra.forge.generation.TerraLevelType;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.button.Button;
import net.minecraft.util.text.StringTextComponent;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.ForgeWorldTypeScreens;
import net.minecraftforge.common.world.ForgeWorldType;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
@Mod.EventBusSubscriber(value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
public class ClientListener {
private static final TerraForgePlugin INSTANCE = TerraForgePlugin.getInstance();
@SubscribeEvent
public static void register(FMLClientSetupEvent event) {
INSTANCE.logger().info("Client setup...");
ForgeWorldType world = TerraLevelType.FORGE_WORLD_TYPE;
ForgeWorldTypeScreens.registerFactory(world, (returnTo, dimensionGeneratorSettings) -> new Screen(world.getDisplayName()) {
private final MutableInteger num = new MutableInteger(0);
private final List<ConfigPack> packs = new ArrayList<>();
private final Button toggle = new Button(0, 25, 120, 20, new StringTextComponent(""), button -> {
num.increment();
if(num.get() >= packs.size()) num.set(0);
button.setMessage(new StringTextComponent("Pack: " + packs.get(num.get()).getTemplate().getID()));
});
@Override
protected void init() {
packs.clear();
INSTANCE.getConfigRegistry().forEach((Consumer<ConfigPack>) packs::add);
addButton(new Button(0, 0, 120, 20, new StringTextComponent("Close"), btn -> Minecraft.getInstance().setScreen(returnTo)));
toggle.setMessage(new StringTextComponent("Pack: " + packs.get(num.get()).getTemplate().getID()));
addButton(toggle);
}
});
}
}
@@ -1,31 +1,13 @@
package com.dfsek.terra.forge.listener;
import com.dfsek.terra.forge.ForgeUtil;
import com.dfsek.terra.forge.TerraForgePlugin;
import com.dfsek.terra.forge.generation.TerraLevelType;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.feature.Feature;
import net.minecraftforge.common.world.ForgeWorldType;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
@Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD)
public class RegistryListener {
private static final TerraForgePlugin INSTANCE = TerraForgePlugin.getInstance();
@SubscribeEvent
public static void registerLevels(RegistryEvent.Register<ForgeWorldType> event) {
INSTANCE.logger().info("Registering level types...");
event.getRegistry().register(TerraLevelType.FORGE_WORLD_TYPE);
}
@SubscribeEvent
public static void register(RegistryEvent.Register<Biome> event) {
INSTANCE.setup(); // Setup now because we need the biomes, and this event happens after blocks n stuff
INSTANCE.getConfigRegistry().forEach(pack -> pack.getBiomeRegistry().forEach((id, biome) -> event.getRegistry().register(ForgeUtil.createBiome(biome)))); // Register all Terra biomes.
}
@SubscribeEvent
public static void registerPop(RegistryEvent.Register<Feature<?>> event) {
event.getRegistry().register(TerraForgePlugin.POPULATOR_FEATURE);
@@ -0,0 +1,37 @@
package com.dfsek.terra.forge.mixin;
import com.dfsek.terra.api.util.generic.pair.Pair;
import com.dfsek.terra.forge.TerraForgePlugin;
import com.dfsek.terra.forge.generation.ForgeChunkGeneratorWrapper;
import com.dfsek.terra.world.TerraWorld;
import net.minecraft.world.DimensionType;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerChunkProvider;
import net.minecraft.world.server.ServerWorld;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(ServerWorld.class)
public abstract class ServerWorldMixin {
@Shadow
@Final
private ServerChunkProvider chunkSource;
@Shadow
protected abstract void initCapabilities();
@Redirect(method = "<init>", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/server/ServerWorld;initCapabilities()V"))
public void injectConstructor(ServerWorld serverWorld) {
if(chunkSource.getGenerator() instanceof ForgeChunkGeneratorWrapper) {
ForgeChunkGeneratorWrapper chunkGeneratorWrapper = (ForgeChunkGeneratorWrapper) chunkSource.getGenerator();
DimensionType dimensionType = ((World) (Object) this).dimensionType();
TerraForgePlugin.getInstance().getWorldMap().put(dimensionType, Pair.of((ServerWorld) (Object) this, new TerraWorld((com.dfsek.terra.api.platform.world.World) this, chunkGeneratorWrapper.getPack(), TerraForgePlugin.getInstance())));
chunkGeneratorWrapper.setDimensionType(dimensionType);
TerraForgePlugin.getInstance().logger().info("Registered world " + this + " to dimension type " + dimensionType);
}
initCapabilities();
}
}
@@ -0,0 +1,21 @@
package com.dfsek.terra.forge.mixin.access;
import net.minecraft.client.gui.screen.BiomeGeneratorTypeScreens;
import net.minecraft.util.text.ITextComponent;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Mutable;
import org.spongepowered.asm.mixin.gen.Accessor;
import java.util.List;
@Mixin(BiomeGeneratorTypeScreens.class)
public interface BiomeGeneratorTypeScreensAccessor {
@Accessor("PRESETS")
static List<BiomeGeneratorTypeScreens> getPresets() {
throw new UnsupportedOperationException();
}
@Mutable
@Accessor
void setDescription(ITextComponent description);
}
@@ -0,0 +1,29 @@
package com.dfsek.terra.forge.mixin.init;
import com.dfsek.terra.forge.TerraForgePlugin;
import com.dfsek.terra.forge.generation.TerraGeneratorType;
import com.dfsek.terra.forge.mixin.access.BiomeGeneratorTypeScreensAccessor;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screen.BiomeGeneratorTypeScreens;
import net.minecraft.resources.ResourcePackList;
import net.minecraft.util.text.StringTextComponent;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(Minecraft.class)
public abstract class MinecraftClientMixin {
@Redirect(method = "<init>", at = @At(value = "INVOKE",
target = "Lnet/minecraft/resources/ResourcePackList;reload()V" // sorta arbitrary position, after mod init, before window opens
))
public void injectConstructor(ResourcePackList resourcePackList) {
TerraForgePlugin.getInstance().init(); // Load during MinecraftClient construction, after other mods have registered blocks and stuff
TerraForgePlugin.getInstance().getConfigRegistry().forEach(pack -> {
final BiomeGeneratorTypeScreens generatorType = new TerraGeneratorType(pack);
//noinspection ConstantConditions
((BiomeGeneratorTypeScreensAccessor) generatorType).setDescription(new StringTextComponent("Terra:" + pack.getTemplate().getID()));
BiomeGeneratorTypeScreensAccessor.getPresets().add(1, generatorType);
});
resourcePackList.reload();
}
}
@@ -0,0 +1,16 @@
package com.dfsek.terra.forge.mixin.init;
import com.dfsek.terra.forge.TerraForgePlugin;
import net.minecraft.server.Main;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(Main.class)
public class MinecraftServerMixin {
@Inject(method = "main([Ljava/lang/String;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/util/registry/DynamicRegistries;builtin()Lnet/minecraft/util/registry/DynamicRegistries$Impl;"))
private static void injectConstructor(String[] args, CallbackInfo ci) {
TerraForgePlugin.getInstance().init(); // Load during MinecraftServer construction, after other mods have registered blocks and stuff
}
}
@@ -5,7 +5,9 @@
"refmap": "terra-refmap.json",
"mixins": [
"DimensionGeneratorSettingsMixin",
"ServerWorldMixin",
"access.AbstractSpawnerAccessor",
"access.BiomeGeneratorTypeScreensAccessor",
"implementations.BiomeMixin",
"implementations.ChunkGeneratorMixin",
"implementations.ConfiguredFeatureMixin",
@@ -31,6 +33,10 @@
"implementations.world.WorldGenRegionMixin"
],
"client": [
"init.MinecraftClientMixin"
],
"server": [
"init.MinecraftServerMixin"
],
"injectors": {
"defaultRequire": 1
+22 -1
View File
@@ -3,6 +3,7 @@ import com.dfsek.terra.configureCommon
plugins {
java
id("org.spongepowered.plugin").version("0.9.0")
id("org.spongepowered.gradle.vanilla").version("0.2")
}
configureCommon()
@@ -15,7 +16,11 @@ repositories {
}
dependencies {
"compileOnly"("org.spongepowered:spongeapi:7.2.0")
"compileOnly"("org.spongepowered:spongeapi:8.0.0-SNAPSHOT")
"annotationProcessor"("org.spongepowered:mixin:0.8.2:processor")
"compileOnly"("org.spongepowered:mixin:0.8.2")
"shadedApi"(project(":common"))
"shadedImplementation"("org.yaml:snakeyaml:1.27")
"shadedImplementation"("com.googlecode.json-simple:json-simple:1.1.1")
@@ -25,4 +30,20 @@ sponge {
plugin {
id = "terra"
}
}
minecraft {
version("1.16.5")
runs {
server()
client()
}
}
tasks.named<Jar>("jar") {
manifest {
attributes(
mapOf("MixinConfigs" to "terra.mixins.json")
)
}
}
@@ -1,15 +0,0 @@
package com.dfsek.terra.sponge;
import com.dfsek.terra.api.platform.block.BlockData;
import com.dfsek.terra.sponge.world.block.data.SpongeBlockData;
import org.spongepowered.api.block.BlockState;
public final class SpongeAdapter {
public static BlockData adapt(BlockState state) {
return new SpongeBlockData(state);
}
public static BlockState adapt(BlockData data) {
return ((SpongeBlockData) data).getHandle();
}
}
@@ -3,9 +3,9 @@ package com.dfsek.terra.sponge;
import com.dfsek.terra.api.util.logging.Logger;
public class SpongeLogger implements Logger {
private final org.slf4j.Logger logger;
private final org.apache.logging.log4j.Logger logger;
public SpongeLogger(org.slf4j.Logger logger) {
public SpongeLogger(org.apache.logging.log4j.Logger logger) {
this.logger = logger;
}
@@ -3,77 +3,124 @@ package com.dfsek.terra.sponge;
import com.dfsek.tectonic.loading.TypeRegistry;
import com.dfsek.terra.api.TerraPlugin;
import com.dfsek.terra.api.addons.TerraAddon;
import com.dfsek.terra.api.addons.annotations.Addon;
import com.dfsek.terra.api.addons.annotations.Author;
import com.dfsek.terra.api.addons.annotations.Version;
import com.dfsek.terra.api.event.EventListener;
import com.dfsek.terra.api.event.EventManager;
import com.dfsek.terra.api.event.TerraEventManager;
import com.dfsek.terra.api.event.annotations.Global;
import com.dfsek.terra.api.event.events.config.ConfigPackPreLoadEvent;
import com.dfsek.terra.api.platform.block.BlockData;
import com.dfsek.terra.api.platform.handle.ItemHandle;
import com.dfsek.terra.api.platform.handle.WorldHandle;
import com.dfsek.terra.api.platform.world.Biome;
import com.dfsek.terra.api.platform.world.Tree;
import com.dfsek.terra.api.platform.world.World;
import com.dfsek.terra.api.registry.CheckedRegistry;
import com.dfsek.terra.api.registry.LockedRegistry;
import com.dfsek.terra.api.util.generic.pair.Pair;
import com.dfsek.terra.api.util.logging.DebugLogger;
import com.dfsek.terra.config.GenericLoaders;
import com.dfsek.terra.config.PluginConfig;
import com.dfsek.terra.config.lang.Language;
import com.dfsek.terra.config.pack.ConfigPack;
import com.dfsek.terra.profiler.Profiler;
import com.dfsek.terra.profiler.ProfilerImpl;
import com.dfsek.terra.registry.exception.DuplicateEntryException;
import com.dfsek.terra.registry.master.AddonRegistry;
import com.dfsek.terra.registry.master.ConfigRegistry;
import com.dfsek.terra.sponge.world.SpongeWorldHandle;
import com.dfsek.terra.sponge.handle.SpongeItemHandle;
import com.dfsek.terra.sponge.handle.SpongeWorldHandle;
import com.dfsek.terra.sponge.intern.util.SpongeUtil;
import com.dfsek.terra.sponge.world.SpongeTree;
import com.dfsek.terra.world.TerraWorld;
import com.google.inject.Inject;
import org.slf4j.Logger;
import org.spongepowered.api.config.ConfigDir;
import net.minecraft.world.level.LevelReader;
import net.minecraft.world.level.dimension.DimensionType;
import org.spongepowered.api.Server;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.game.state.GameStartedServerEvent;
import org.spongepowered.api.plugin.Plugin;
import org.spongepowered.api.event.lifecycle.StartedEngineEvent;
import org.spongepowered.api.event.lifecycle.StartingEngineEvent;
import org.spongepowered.api.registry.Registry;
import org.spongepowered.api.world.biome.Biomes;
import org.spongepowered.api.world.server.ServerWorld;
import org.spongepowered.plugin.PluginContainer;
import org.spongepowered.plugin.jvm.Plugin;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
@Plugin(id = "terra", name = "Terra-Sponge", version = "", description = "Terra")
@Plugin("terra")
public class TerraSpongePlugin implements TerraPlugin {
private final ConfigRegistry configRegistry = new ConfigRegistry();
private final CheckedRegistry<ConfigPack> packCheckedRegistry = new CheckedRegistry<>(configRegistry);
private final PluginConfig config = new PluginConfig();
private final AddonRegistry addonRegistry = new AddonRegistry(this);
private final LockedRegistry<TerraAddon> addonLockedRegistry = new LockedRegistry<>(addonRegistry);
private final SpongeWorldHandle spongeWorldHandle = new SpongeWorldHandle();
private final EventManager eventManager = new TerraEventManager(this);
private final AddonRegistry addonRegistry;
private final LockedRegistry<TerraAddon> addonLockedRegistry;
private static TerraSpongePlugin INSTANCE;
private final Map<DimensionType, Pair<ServerWorld, TerraWorld>> worldMap = new HashMap<>();
private final PluginContainer plugin;
private final GenericLoaders loaders = new GenericLoaders(this);
private final WorldHandle worldHandle = new SpongeWorldHandle();
private final Profiler profiler = new ProfilerImpl();
@Inject
@ConfigDir(sharedRoot = false)
private Path privateConfigDir;
@Inject
private Logger logger;
public TerraSpongePlugin(PluginContainer plugin) {
this.plugin = plugin;
this.addonRegistry = new AddonRegistry(new SpongeAddon(this), this);
this.addonLockedRegistry = new LockedRegistry<>(addonRegistry);
INSTANCE = this;
}
public static TerraSpongePlugin getInstance() {
return INSTANCE;
}
@Listener
public void initialize(GameStartedServerEvent event) {
public void initialize(StartingEngineEvent<Server> event) {
plugin.logger().info("Loading Terra...");
addonRegistry.loadAll();
configRegistry.loadAll(this);
}
@Override
public void register(TypeRegistry registry) {
loaders.register(registry);
registry.registerLoader(BlockData.class, (t, o, l) -> worldHandle.createBlockData((String) o))
.registerLoader(Biome.class, (t, o, l) -> SpongeUtil.BIOME_FIXER.translate((String) o));
}
@Override
public WorldHandle getWorldHandle() {
return spongeWorldHandle;
return worldHandle;
}
@Override
public TerraWorld getWorld(World world) {
return null;
return getWorld(((LevelReader) world).dimensionType());
}
public TerraWorld getWorld(DimensionType type) {
TerraWorld world = worldMap.get(type).getRight();
if(world == null) throw new IllegalArgumentException("No world exists with dimension type " + type);
return world;
}
@Override
public com.dfsek.terra.api.util.logging.Logger logger() {
return new SpongeLogger(logger);
return new SpongeLogger(plugin.logger());
}
@Override
@@ -83,7 +130,7 @@ public class TerraSpongePlugin implements TerraPlugin {
@Override
public File getDataFolder() {
return privateConfigDir.toFile();
return Sponge.configManager().pluginConfig(plugin).directory().toFile();
}
@Override
@@ -117,7 +164,7 @@ public class TerraSpongePlugin implements TerraPlugin {
@Override
public ItemHandle getItemHandle() {
return null;
return new SpongeItemHandle();
}
@Override
@@ -132,7 +179,7 @@ public class TerraSpongePlugin implements TerraPlugin {
@Override
public DebugLogger getDebugLogger() {
return null;
return new DebugLogger(logger());
}
@Override
@@ -142,6 +189,59 @@ public class TerraSpongePlugin implements TerraPlugin {
@Override
public Profiler getProfiler() {
return null;
return profiler;
}
public Map<DimensionType,Pair<ServerWorld, TerraWorld>> getWorldMap() {
return worldMap;
}
@Addon("Terra-Sponge")
@Author("Terra")
@Version("1.0.0")
private static final class SpongeAddon extends TerraAddon implements EventListener {
private final TerraPlugin main;
private SpongeAddon(TerraPlugin main) {
this.main = main;
}
@Override
public void initialize() {
main.getEventManager().registerListener(this, this);
}
@Global
public void onPackLoad(ConfigPackPreLoadEvent event) {
CheckedRegistry<Tree> treeRegistry = event.getPack().getTreeRegistry();
injectTree(treeRegistry, "BROWN_MUSHROOM", new SpongeTree());
injectTree(treeRegistry, "RED_MUSHROOM", new SpongeTree());
injectTree(treeRegistry, "JUNGLE", new SpongeTree());
injectTree(treeRegistry, "JUNGLE_COCOA", new SpongeTree());
injectTree(treeRegistry, "LARGE_OAK", new SpongeTree());
injectTree(treeRegistry, "LARGE_SPRUCE", new SpongeTree());
injectTree(treeRegistry, "SMALL_JUNGLE", new SpongeTree());
injectTree(treeRegistry, "SWAMP_OAK", new SpongeTree());
injectTree(treeRegistry, "TALL_BIRCH", new SpongeTree());
injectTree(treeRegistry, "ACACIA", new SpongeTree());
injectTree(treeRegistry, "BIRCH", new SpongeTree());
injectTree(treeRegistry, "DARK_OAK", new SpongeTree());
injectTree(treeRegistry, "OAK", new SpongeTree());
injectTree(treeRegistry, "CHORUS_PLANT", new SpongeTree());
injectTree(treeRegistry, "SPRUCE", new SpongeTree());
injectTree(treeRegistry, "JUNGLE_BUSH", new SpongeTree());
injectTree(treeRegistry, "MEGA_SPRUCE", new SpongeTree());
injectTree(treeRegistry, "CRIMSON_FUNGUS", new SpongeTree());
injectTree(treeRegistry, "WARPED_FUNGUS", new SpongeTree());
}
private void injectTree(CheckedRegistry<Tree> registry, String id, Tree tree) {
try {
registry.add(id, tree);
} catch(DuplicateEntryException e) {
e.printStackTrace();
}
}
}
}
@@ -0,0 +1,24 @@
package com.dfsek.terra.sponge.handle;
import com.dfsek.terra.api.platform.handle.ItemHandle;
import com.dfsek.terra.api.platform.inventory.Item;
import com.dfsek.terra.api.platform.inventory.item.Enchantment;
import java.util.Set;
public class SpongeItemHandle implements ItemHandle {
@Override
public Item createItem(String data) {
return null;
}
@Override
public Enchantment getEnchantment(String id) {
return null;
}
@Override
public Set<Enchantment> getEnchantments() {
return null;
}
}
@@ -1,16 +1,16 @@
package com.dfsek.terra.sponge.world;
package com.dfsek.terra.sponge.handle;
import com.dfsek.terra.api.platform.block.BlockData;
import com.dfsek.terra.api.platform.entity.EntityType;
import com.dfsek.terra.api.platform.handle.WorldHandle;
import com.dfsek.terra.sponge.SpongeAdapter;
import com.dfsek.terra.sponge.intern.util.SpongeAdapter;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.block.BlockState;
public class SpongeWorldHandle implements WorldHandle {
@Override
public BlockData createBlockData(String data) {
return SpongeAdapter.adapt(Sponge.getRegistry().getType(BlockState.class, data).orElseThrow(() -> new IllegalArgumentException("Invalid block data \"" + data + "\"")));
return SpongeAdapter.adapt(BlockState.fromString(data));
}
@Override
@@ -0,0 +1,200 @@
package com.dfsek.terra.sponge.intern;
import com.dfsek.terra.api.platform.world.World;
import com.dfsek.terra.api.platform.world.generator.ChunkData;
import com.dfsek.terra.api.platform.world.generator.GeneratorWrapper;
import com.dfsek.terra.api.util.FastRandom;
import com.dfsek.terra.api.world.biome.UserDefinedBiome;
import com.dfsek.terra.api.world.generation.TerraChunkGenerator;
import com.dfsek.terra.api.world.locate.AsyncStructureFinder;
import com.dfsek.terra.config.pack.ConfigPack;
import com.dfsek.terra.sponge.TerraSpongePlugin;
import com.dfsek.terra.sponge.intern.util.SpongeAdapter;
import com.dfsek.terra.world.TerraWorld;
import com.dfsek.terra.world.generation.generators.DefaultChunkGenerator3D;
import com.dfsek.terra.world.generation.math.samplers.Sampler;
import com.dfsek.terra.world.population.items.TerraStructure;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.jafama.FastMath;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Registry;
import net.minecraft.core.RegistryAccess;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.WorldGenRegion;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.NaturalSpawner;
import net.minecraft.world.level.NoiseColumn;
import net.minecraft.world.level.StructureFeatureManager;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeManager;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.level.levelgen.GenerationStep;
import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.level.levelgen.StructureSettings;
import net.minecraft.world.level.levelgen.WorldgenRandom;
import net.minecraft.world.level.levelgen.feature.StructureFeature;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.api.world.biome.provider.BiomeProvider;
import org.spongepowered.api.world.generation.config.structure.StructureGenerationConfig;
import org.spongepowered.api.world.server.ServerWorld;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class SpongeChunkGeneratorWrapper extends ChunkGenerator implements GeneratorWrapper {
private final long seed;
private final DefaultChunkGenerator3D delegate;
private final TerraBiomeSource biomeSource;
public static final Codec<ConfigPack> PACK_CODEC = (RecordCodecBuilder.create(config -> config.group(
Codec.STRING.fieldOf("pack").forGetter(pack -> pack.getTemplate().getID())
).apply(config, config.stable(TerraSpongePlugin.getInstance().getConfigRegistry()::get))));
public static final Codec<SpongeChunkGeneratorWrapper> CODEC = RecordCodecBuilder.create(instance -> instance.group(
TerraBiomeSource.CODEC.fieldOf("biome_source").forGetter(generator -> generator.biomeSource),
Codec.LONG.fieldOf("seed").stable().forGetter(generator -> generator.seed),
PACK_CODEC.fieldOf("pack").stable().forGetter(generator -> generator.pack))
.apply(instance, instance.stable(SpongeChunkGeneratorWrapper::new)));
private final ConfigPack pack;
public ConfigPack getPack() {
return pack;
}
private DimensionType dimensionType;
public SpongeChunkGeneratorWrapper(TerraBiomeSource biomeSource, long seed, ConfigPack configPack) {
super(biomeSource, new StructureSettings(configPack.getTemplate().vanillaStructures()));
this.pack = configPack;
this.delegate = new DefaultChunkGenerator3D(pack, TerraSpongePlugin.getInstance());
delegate.getMain().logger().info("Loading world with config pack " + pack.getTemplate().getID());
this.biomeSource = biomeSource;
this.seed = seed;
}
@Override
protected @NotNull Codec<? extends ChunkGenerator> codec() {
return CODEC;
}
@Override
public @NotNull ChunkGenerator withSeed(long seed) {
return new SpongeChunkGeneratorWrapper((TerraBiomeSource) this.biomeSource.withSeed(seed), seed, pack);
}
@Override
public void buildSurfaceAndBedrock(WorldGenRegion worldGenRegion, ChunkAccess chunkAccess) {
}
@Nullable
@Override
public BlockPos findNearestMapFeature(ServerLevel world, StructureFeature<?> feature, BlockPos center, int param3, boolean param4) {
if(!pack.getTemplate().disableStructures()) {
String name = Objects.requireNonNull(Registry.STRUCTURE_FEATURE.getKey(feature)).toString();
TerraWorld terraWorld = TerraSpongePlugin.getInstance().getWorld((World) world);
TerraStructure located = pack.getStructure(pack.getTemplate().getLocatable().get(name));
if(located != null) {
CompletableFuture<BlockPos> result = new CompletableFuture<>();
AsyncStructureFinder finder = new AsyncStructureFinder(terraWorld.getBiomeProvider(), located, SpongeAdapter.adapt(center).toLocation((World) world), 0, 500, location -> {
result.complete(SpongeAdapter.adapt(location));
}, TerraSpongePlugin.getInstance());
finder.run(); // Do this synchronously.
try {
return result.get();
} catch(InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
}
return super.findNearestMapFeature(world, feature, center, param3, param4);
}
@Override
public boolean hasStronghold(@NotNull ChunkPos p_235952_1_) {
if(pack.getTemplate().vanillaStructures()) return super.hasStronghold(p_235952_1_);
return false;
}
@Override
public void createStructures(RegistryAccess param0, StructureFeatureManager param1, ChunkAccess param2, StructureManager param3, long param4) {
if(pack.getTemplate().vanillaStructures()) super.createStructures(param0, param1, param2, param3, param4);
}
@Override
public void applyCarvers(long param0, BiomeManager param1, ChunkAccess param2, GenerationStep.Carving param3) {
if(pack.getTemplate().vanillaCaves()) super.applyCarvers(param0, param1, param2, param3);
}
@Override
public void fillFromNoise(@NotNull LevelAccessor world, @NotNull StructureFeatureManager p_230352_2_, @NotNull ChunkAccess chunk) {
delegate.generateChunkData((World) world, new FastRandom(), chunk.getPos().x, chunk.getPos().z, (ChunkData) chunk);
}
@Override
public int getBaseHeight(int x, int z, Heightmap.@NotNull Types p_222529_3_) {
TerraWorld world = TerraSpongePlugin.getInstance().getWorld(dimensionType);
Sampler sampler = world.getConfig().getSamplerCache().getChunk(FastMath.floorDiv(x, 16), FastMath.floorDiv(z, 16));
int cx = FastMath.floorMod(x, 16);
int cz = FastMath.floorMod(z, 16);
int height = world.getWorld().getMaxHeight();
while(height >= 0 && sampler.sample(cx, height - 1, cz) < 0) height--;
return height;
}
@Override
public @NotNull BlockGetter getBaseColumn(int x, int z) {
TerraWorld world = TerraSpongePlugin.getInstance().getWorld(dimensionType);
int height = getBaseHeight(x, z, Heightmap.Types.WORLD_SURFACE);
BlockState[] array = new BlockState[256];
for(int y = 255; y >= 0; y--) {
if(y > height) {
if(y > ((UserDefinedBiome) world.getBiomeProvider().getBiome(x, z)).getConfig().getSeaLevel()) {
array[y] = Blocks.AIR.defaultBlockState();
} else {
array[y] = Blocks.WATER.defaultBlockState();
}
} else {
array[y] = Blocks.STONE.defaultBlockState();
}
}
return new NoiseColumn(array);
}
@Override
public void spawnOriginalMobs(WorldGenRegion region) {
if(pack.getTemplate().vanillaMobs()) {
int cx = region.getCenterX();
int cy = region.getCenterZ();
Biome biome = region.getBiome((new ChunkPos(cx, cy)).getWorldPosition());
WorldgenRandom chunkRandom = new WorldgenRandom();
chunkRandom.setDecorationSeed(region.getSeed(), cx << 4, cy << 4);
NaturalSpawner.spawnMobsForChunkGeneration(region, biome, cx, cy, chunkRandom);
}
}
@Override
public TerraChunkGenerator getHandle() {
return delegate;
}
public void setDimensionType(DimensionType dimensionType) {
this.dimensionType = dimensionType;
}
}
@@ -0,0 +1,63 @@
package com.dfsek.terra.sponge.intern;
import com.dfsek.terra.api.world.biome.TerraBiome;
import com.dfsek.terra.api.world.biome.UserDefinedBiome;
import com.dfsek.terra.api.world.biome.provider.BiomeProvider;
import com.dfsek.terra.config.pack.ConfigPack;
import com.dfsek.terra.config.pack.WorldConfig;
import com.dfsek.terra.sponge.TerraSpongePlugin;
import com.dfsek.terra.sponge.intern.util.SpongeUtil;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.core.Registry;
import net.minecraft.resources.RegistryLookupCodec;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeSource;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
public class TerraBiomeSource extends BiomeSource {
public static final Codec<ConfigPack> PACK_CODEC = (RecordCodecBuilder.create(config -> config.group(
Codec.STRING.fieldOf("pack").forGetter(pack -> pack.getTemplate().getID())
).apply(config, config.stable(TerraSpongePlugin.getInstance().getConfigRegistry()::get))));
public static final Codec<TerraBiomeSource> CODEC = RecordCodecBuilder.create(instance -> instance.group(
RegistryLookupCodec.create(Registry.BIOME_REGISTRY).forGetter(source -> source.biomeRegistry),
Codec.LONG.fieldOf("seed").stable().forGetter(source -> source.seed),
PACK_CODEC.fieldOf("pack").stable().forGetter(source -> source.pack))
.apply(instance, instance.stable(TerraBiomeSource::new)));
private final Registry<Biome> biomeRegistry;
private final long seed;
private final BiomeProvider grid;
private final ConfigPack pack;
public TerraBiomeSource(Registry<Biome> biomes, long seed, ConfigPack pack) {
super(biomes.stream().collect(Collectors.toList()));
this.biomeRegistry = biomes;
this.seed = seed;
this.grid = pack.getBiomeProviderBuilder().build(seed);
this.pack = pack;
}
@Override
protected @NotNull Codec<TerraBiomeSource> codec() {
return CODEC;
}
@Override
public BiomeSource withSeed(long seed) {
return new TerraBiomeSource(this.biomeRegistry, seed, pack);
}
@Override
public @NotNull Biome getNoiseBiome(int biomeX, int biomeY, int biomeZ) {
UserDefinedBiome biome = (UserDefinedBiome) grid.getBiome(biomeX << 2, biomeZ << 2);
return Objects.requireNonNull(biomeRegistry.get(new ResourceLocation("terra", SpongeUtil.createBiomeID(pack, biome.getID()))));
}
}
@@ -0,0 +1,35 @@
package com.dfsek.terra.sponge.intern.mixin;
import com.dfsek.terra.api.util.generic.pair.Pair;
import com.dfsek.terra.sponge.TerraSpongePlugin;
import com.dfsek.terra.sponge.intern.SpongeChunkGeneratorWrapper;
import com.dfsek.terra.world.TerraWorld;
import net.minecraft.server.level.ServerChunkCache;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.dimension.DimensionType;
import org.spongepowered.api.world.server.ServerWorld;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;
@Mixin(ServerLevel.class)
public abstract class ServerLevelMixin {
@Shadow
@Final
private ServerChunkCache chunkSource;
@Redirect(method = "<init>", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;updateSkyBrightness()V"))
public void injectConstructor(Level level) {
if(chunkSource.getGenerator() instanceof SpongeChunkGeneratorWrapper) {
SpongeChunkGeneratorWrapper chunkGeneratorWrapper = (SpongeChunkGeneratorWrapper) chunkSource.getGenerator();
DimensionType dimensionType = ((Level) (Object) this).dimensionType();
TerraSpongePlugin.getInstance().getWorldMap().put(dimensionType, Pair.of((ServerWorld) this, new TerraWorld((com.dfsek.terra.api.platform.world.World) this, chunkGeneratorWrapper.getPack(), TerraSpongePlugin.getInstance())));
chunkGeneratorWrapper.setDimensionType(dimensionType);
TerraSpongePlugin.getInstance().logger().info("Registered world " + this + " to dimension type " + dimensionType);
}
((Level) (Object) this).updateSkyBrightness();
}
}
@@ -0,0 +1,6 @@
/**
* Stuff that accesses the internal server.
* <p>
* Should be replaced with API stuff when API is complete.
*/
package com.dfsek.terra.sponge.intern;
@@ -0,0 +1,21 @@
package com.dfsek.terra.sponge.intern.util;
import com.dfsek.terra.api.math.vector.Vector3;
import com.dfsek.terra.api.platform.block.BlockData;
import com.dfsek.terra.sponge.world.block.data.SpongeBlockData;
import net.minecraft.core.BlockPos;
import org.spongepowered.api.block.BlockState;
public final class SpongeAdapter {
public static Vector3 adapt(BlockPos pos) {
return new Vector3(pos.getX(), pos.getY(), pos.getZ());
}
public static BlockPos adapt(Vector3 vec) {
return new BlockPos(vec.getBlockX(), vec.getBlockY(), vec.getBlockZ());
}
public static BlockData adapt(BlockState state) {
return new SpongeBlockData(state);
}
}
@@ -0,0 +1,21 @@
package com.dfsek.terra.sponge.intern.util;
import com.dfsek.terra.api.transform.Transformer;
import com.dfsek.terra.api.transform.Validator;
import com.dfsek.terra.config.pack.ConfigPack;
import net.minecraft.data.BuiltinRegistries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.biome.Biome;
import java.util.Locale;
public final class SpongeUtil {
public static String createBiomeID(ConfigPack pack, String biomeID) {
return pack.getTemplate().getID().toLowerCase() + "/" + biomeID.toLowerCase(Locale.ROOT);
}
public static final Transformer<String, Biome> BIOME_FIXER = new Transformer.Builder<String, Biome>()
.addTransform(id -> BuiltinRegistries.BIOME.get(ResourceLocation.tryParse(id)), Validator.notNull())
.addTransform(id -> BuiltinRegistries.BIOME.get(ResourceLocation.tryParse("minecraft:" + id.toLowerCase())), Validator.notNull()).build();
}
@@ -0,0 +1,19 @@
package com.dfsek.terra.sponge.world;
import com.dfsek.terra.api.math.vector.Location;
import com.dfsek.terra.api.platform.world.Tree;
import com.dfsek.terra.api.util.collections.MaterialSet;
import java.util.Random;
public class SpongeTree implements Tree {
@Override
public boolean plant(Location l, Random r) {
return false;
}
@Override
public MaterialSet getSpawnable() {
return MaterialSet.empty();
}
}
@@ -0,0 +1 @@
MixinConfigs: terra.mixins.json
@@ -0,0 +1,18 @@
{
"plugins": [
{
"loader": "java_plain",
"id": "terra",
"name": "Terra",
"version": "@VERSION@",
"main-class": "com.dfsek.terra.sponge.TerraSpongePlugin",
"description": "@DESCRIPTION@",
"dependencies": [
{
"id": "spongeapi",
"version": "8.0.0"
}
]
}
]
}
@@ -0,0 +1,17 @@
{
"required": true,
"package": "com.dfsek.terra.sponge.intern.mixin",
"compatibilityLevel": "JAVA_8",
"refmap": "terra-refmap.json",
"mixins": [
"ServerLevelMixin"
],
"client": [
],
"server": [
],
"injectors": {
"defaultRequire": 1
},
"minVersion": "0.8"
}