Commits vergleichen

...

643 Commits

Autor SHA1 Nachricht Datum
6d6de3ee3f Fix 1.19.3 ChunkSections
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
2023-08-21 16:55:36 +02:00
54fd91c7f7 Fix 1.19
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
2023-08-19 20:02:26 +02:00
2b870902a3 Fix 1.19.3
Einige Prüfungen sind fehlgeschlagen
SteamWarCI Build failed
2023-08-19 19:58:16 +02:00
6ab048cd7b Revert "Drop support for minor 1.19 versions (#2316)"
Einige Prüfungen sind fehlgeschlagen
SteamWarCI Build failed
This reverts commit 770bb008
2023-08-19 19:50:30 +02:00
5b5fd8a229 Rollback 1.19.4 to 1.19.3
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
2023-08-19 19:43:39 +02:00
f0509896e0 Rollback 1.19.4 to 1.19.3
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
2023-08-19 19:39:12 +02:00
bdad5ca1b6 Fix CI
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
2023-08-19 19:29:00 +02:00
c0f935ef55 Merge remote-tracking branch 'upstream/main'
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
2023-08-19 12:43:25 +02:00
Alexander Brandes
fe33be5795
Update userdev 2023-08-18 13:40:16 +02:00
Maddy Miller
a088e6a96b Remove the Bukkit legacy data folder migration code from 11 years ago (#2383)
(cherry picked from commit EngineHub/WorldEdit@7f81aad028)
2023-08-10 19:10:04 -04:00
Alexander Brandes
acb79469fb
[ci skip] Update towny 2023-08-09 20:59:27 +02:00
Alexander Brandes
7b3c674e1c
[ci skip] Ignore snakeyaml updates 2023-08-09 20:56:15 +02:00
Alexander Brandes
a3e855882c
[ci skip] Ignore snakeyaml updates 2023-08-09 20:54:46 +02:00
Alexander Brandes
e81980651e
Cleanup dependencies 2023-08-09 20:52:18 +02:00
Jeff P
50e45f07f0
fix: Do not tab complete if command not owned by FAWE (#2386) 2023-08-02 14:08:58 +02:00
renovate[bot]
a6f1c6ac82
Update dependency com.palmergames.bukkit.towny:towny to v0.99.5.7 (#2390)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-08-02 14:07:35 +02:00
renovate[bot]
4ca0a95e18
Update dependency com.sk89q.worldguard:worldguard-bukkit to v7.0.9 (#2391)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-08-02 14:07:27 +02:00
renovate[bot]
0dbc0db43f
Update plugin com.modrinth.minotaur to v2.8.3 (#2392)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-08-02 14:07:19 +02:00
Alexander Brandes
9ae04b8d40
Update v7 notification 2023-07-31 11:44:14 +02:00
Jordan
d42854845a
fix: disallowed regions can be length 0 (#2368) 2023-07-27 11:02:41 +02:00
Jordan
8b39e41a1a
fix: don't warn on release build (#2369) 2023-07-27 10:59:11 +02:00
dordsor21
48be6ac94b
fix: processorExtent can be null when setting masks too
- fixes #2379
2023-07-22 17:44:05 +01:00
dordsor21
2f6de996e3
fix: processorExtent can be null in editsession
- fixes #2375
2023-07-22 13:14:01 +01:00
Alexander Brandes
006ccd6887
Back to snapshot for development 2023-07-22 12:44:37 +02:00
Alexander Brandes
37bfe426bc
Release 2.7.0 2023-07-22 12:27:54 +02:00
renovate[bot]
f58f00e97f
Update plugin com.modrinth.minotaur to v2.8.2 (#2374)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-07-22 12:21:08 +02:00
renovate[bot]
34a98a03c1
Update dependency gradle to v8.2.1 (#2373)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-07-22 10:02:22 +00:00
Alexander Brandes
c91b477e29
Update PlotSquared integration to v7 (#2075)
Co-authored-by: dordsor21 <dordsor21@gmail.com>
2023-07-22 12:01:33 +02:00
renovate[bot]
4bdcf9a510
Update dependency com.palmergames.bukkit.towny:towny to v0.99.5.4 (#2372)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-07-22 10:00:15 +00:00
Jordan
9543adc776
Implement async notify queue that submits to a KeyQueuedExecutorService (#2334) 2023-07-20 17:58:01 +02:00
Jordan
18df87a4e8
feat: implement a new "type swap" pattern (#2346) 2023-07-20 17:57:48 +02:00
Jordan
0a8a479214
fix: do not clash ChunkHolder recycling with processors that extend outside the chunk (#2353) 2023-07-20 17:57:29 +02:00
Jordan
fe1859e9d2
fix: do not retain clipboards that completed exceptionally (#2358) 2023-07-20 17:56:30 +02:00
Jordan
f65c4743bd
fix: make IdMask thread-safe (#2361) 2023-07-20 17:56:11 +02:00
Jordan
cdd546ee5e
fix: correct NBT for spawners (#2362) 2023-07-20 17:55:59 +02:00
Paul
5167073326
fix: regions not trimming Y correctly when restricted (#2363) 2023-07-17 21:47:47 +01:00
Chris Lang
e0507e6440
Added cone generation command (#2251)
* Added cone generation command

* Fix formatting problems

---------

Co-authored-by: Madeline Miller <mnmiller1@me.com>
2023-07-15 21:18:09 +01:00
Jordan
b1e0ad4ef7
feat: re-submit chunk load request after 10s after checking world is loaded (#2339)
- #2332 makes it seem like paper forgets to load a chunk sometimes
 - resubmit chunk load request after a second to attempt to counter this
2023-07-15 16:41:04 +01:00
Jordan
e6b1308590
feat: synchronise disk clipboard loading and deletion to clipboardLock (#2342)
- another possible help towards the OverlappingFileLockException
2023-07-15 16:40:52 +01:00
Jordan
f4da4b0287
fix: fix adding/getting masks to/from MaskExtent when it is a processor (#2351)
- fixes #2350
2023-07-15 16:40:29 +01:00
dordsor21
8da530ee80
gracefully handle error in EntityInBlockRemovingProcessor
-  ensures edit continues on chunk correctly
2023-07-15 12:27:33 +01:00
Alexander Brandes
1745c50878
Improve error behaviour of //generate 2023-07-15 09:26:00 +02:00
dordsor21
a680c7ce97
fix: fix #2352 2023-07-13 17:08:18 +01:00
dordsor21
0a19f643b6
fix #2349 2023-07-11 16:39:53 +01:00
Jordan
c0e20a6fe5
feat: provide some information upon OverlappingFileLockException (#2341) 2023-07-10 23:16:05 +02:00
Jordan
1f29ab3b79
fix: fix command brush (#2347) 2023-07-10 22:04:33 +01:00
Jordan
685248d8de
chore: deprecate some methods that ought to be removed (#2340) 2023-07-09 15:16:30 +01:00
Hannes Greule
68eb4e214a
refactor: use HttpClient for update check (#2331) 2023-07-08 18:41:20 +01:00
Alexander Brandes
90587e56fc
Deprecate support for 1.16.5 (#2338) 2023-07-07 16:38:10 +00:00
Jordan
d78092b4ca
fix: ensure chunk is loaded when getting entities (#2323) 2023-07-07 18:36:12 +02:00
Jordan
6fbdef5252
feat: allow bracketless '%' pattern definition (#2322) 2023-07-07 18:36:02 +02:00
Jordan
f38c81aa2a
fix: correctly invalidate mask after a plot is merged (#2333) 2023-07-07 18:27:10 +02:00
Jordan
888683d83b
fix: ignore clipboard origin when pasting to match P2 behaviour (#2336) 2023-07-07 18:23:37 +02:00
dordsor21
a669be2041
fix #2319 2023-07-05 22:03:13 +01:00
Alexander Brandes
67fd31ce4c
Update bom 2023-07-05 16:06:15 +02:00
renovate[bot]
ccdb002ade
Update dependency gradle to v8.2 (#2326)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-07-05 15:50:49 +02:00
renovate[bot]
34ead35e03
Update dependency net.minecrell.plugin-yml.bukkit to v0.6.0 (#2327)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-07-05 15:50:20 +02:00
renovate[bot]
52a51753dd
Update dependency com.palmergames.bukkit.towny:towny to v0.99.2.7 (#2329)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-07-05 15:50:09 +02:00
Jordan
d7cc65d2f2
refactor: some changes that may help #2289 (#2307) 2023-07-03 16:37:42 +01:00
renovate[bot]
a0acbc7168
Update dependency org.mockito:mockito-core to v5.4.0 (#2328)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-07-01 18:49:40 +02:00
renovate[bot]
e680e8fe1f
Update dependency com.palmergames.bukkit.towny:towny to v0.99.2.5 (#2325)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-07-01 08:47:03 +00:00
renovate[bot]
4583acda6b
Update auto.value to v1.10.2 (#2324)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-07-01 08:46:19 +00:00
Alexander Brandes
c880badaf4
[ci skip] Update renovate.json 2023-07-01 10:32:39 +02:00
dordsor21
83a4987252
chore: queue progress messages are not implemented 2023-06-30 19:36:35 +01:00
Alexander Brandes
903064fd41
Back to snapshot for development 2023-06-29 12:46:35 +02:00
Alexander Brandes
e5cbf33317
Release 2.6.4 2023-06-29 12:29:37 +02:00
Alexander Brandes
770bb0087a
Drop support for minor 1.19 versions (#2316)
* Drop support for minor 1.19 versions

* More work
2023-06-29 12:23:26 +02:00
Jordan
24325d91ba
feat: improve (region) fawe mask handling (#2312)
* feat: improve fawe mask handling
 - Actually cache masks, even if the player has left the region
 - Fix P2 isValid test for single plots
 - Fixes #1946

* Fix incorrect delegated method
2023-06-28 09:24:20 +01:00
Jordan
0554b31f11
feat: implement removal of entities if they would be in a block after the edit (#2311)
- Includes some refactoring to EditSessionBuilder to prevent doubling-up of processors that are also extents
 - Better ordering of the EditSessionBuilder process/extent code to match where extents actually end up in the stack
 - Fixes #1941
2023-06-27 18:37:09 +02:00
Jordan
476ba4ab41
refactor: efficiency improvements to some editsession methods (#2304) 2023-06-27 18:36:54 +02:00
Alexander Brandes
97ee71bbd0
Update settings name in queue.target_size warning 2023-06-27 13:56:30 +02:00
dordsor21
924805af8f
fix: fix obnoxious error message if using p2 v7 with FAWE main branch 2023-06-25 13:52:13 +01:00
dordsor21
05d5ad161a
chore: add obnoxious error message if using p2 v7 with FAWE main branch 2023-06-23 21:57:51 +01:00
Alexander Brandes
c0037aa083
[ci skip] Remove unsupported versions from template 2023-06-23 14:56:47 +02:00
Jordan
9f0a0dbd35
fix: ensure mask is initialised upon visiting a point in BreadthFirstSearch (#2314)
fix: ensure mask is initialised upon visiting a point in BreadFirstSearch
2023-06-22 21:32:54 +02:00
Jordan
d961aa91bc
fix: fix regex block masking (#2242) 2023-06-22 11:24:03 +01:00
Jordan
88533118bc
fix: uncache the chunk SET at a better time in ChunkHolder to prevent "lost" changes (#2300)
- blocks could still be set to the ChunkHolder during a call
 - create a new chunk SET in that case
 - make cached get/set volatile to improve thread safety
2023-06-19 22:46:10 +02:00
Jordan
8ca25fa7d7
fix: towny max bounds are exclusive (#2301)
fix: towny max bounds are exlusive
 - Fixes #2293
2023-06-19 22:46:01 +02:00
Jordan
01be53ed65
fix: add missing BlockType constructor (#2306)
- Deprecate public BlockType constructors
 - People really should not be initialising their own block types. This can and most likely will cause issues.
 - Fixes #2290
2023-06-19 14:36:47 +01:00
Jordan
a8c8a0fbd6
fix: always return the changeset from EditSessionBuilder (#2302)
- Ensure history will actually always be closed if combine-stages is false
- Fixes #2148
2023-06-19 14:34:54 +01:00
Jordan
1ede11b129
fix: use new array when creating palette (#2305)
- Fixes #2291
2023-06-19 14:34:02 +01:00
Jordan
39de48cdb1
chore: Address kotlin String#capitalize() deprecation (#2308)
* chore: Address kotlin String#capitalize() deprecation
 - Fixes #2283
 - Don't bother with the longer version that allows Locales, we don't need that

* Address comments
2023-06-18 16:31:49 +00:00
Jordan
f0aef98870
fix: don't "double-up" a setblocks if a region is being set (#2299)
- Fixes #2294
2023-06-18 18:08:31 +02:00
dordsor21
135c77cfb5
chore: minor changes
- null check get tile in ThreadUnsafeCharBlocks
 - 0 to reserved ID
2023-06-18 15:03:51 +01:00
renovate[bot]
78fb74665f
Update plugin com.modrinth.minotaur to v2.8.1 (#2298)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-06-17 16:36:57 +02:00
Alexander Brandes
7a7373fd3d
Update paperweight 2023-06-17 16:16:16 +02:00
Jordan
51e238c352
feat: add new tree types to tree tool and brush (#2286)
* feat: add new tree types
 - implements #2197

* Remove nonsensical test case

---------

Co-authored-by: Alexander Brandes <mc.cache@web.de>
2023-06-15 10:18:01 +02:00
Jordan
79a2c14caa
fix #2292 2023-06-13 19:12:24 +02:00
Alexander Brandes
d9463ce8b5
Add support for 1.20.1 2023-06-12 16:36:06 +02:00
Jordan
dae6c69e54
feat: send one of an error message during edits if otherwise squashed by LimitExtent (#2246)
* feat: send one of an error message during edits if otherwise squashed by LimitExtent

* no region is not ingorable
2023-06-12 12:14:24 +02:00
Alexander Brandes
ed128797ec
Back to snapshot for development 2023-06-12 12:13:49 +02:00
Alexander Brandes
956a518238
Release 2.6.3 2023-06-12 11:58:38 +02:00
Jordan
e449910af5
feat: prevent edits outside +/- 30,000,000 blocks (#2285)
* feat: prevent edits outside +/- 30,000,000 blocks

* Remove import
2023-06-12 11:27:07 +02:00
LlmDl
ca4080eea7
Update & Fix TownyFeature support. (#2279) 2023-06-11 22:55:11 +01:00
Alexander Brandes
71c172cced
[ci skip] Update bug_report.yml 2023-06-11 12:09:27 +02:00
Hannes Greule
083f8a4dd8
Set proper field access and use mappings for entities on spigot (#2282)
set proper field access and use mappings
2023-06-10 22:47:22 +02:00
Alexander Brandes
689c7f62b8
Fixed setting sign text on 1.20 2023-06-09 15:27:02 +02:00
Alexander Brandes
bb14d93a8d
Add Console/CommandBlock support to Fabric/Forge/Sponge (2317) 2023-06-09 13:58:45 +02:00
Alexander Brandes
e7876c4eba
Update to 1.20 (#2276)
* Towards 1.20

* Init bukkit

* Update YAML to 2.0

* Fixes for 1.20 adapters

* Update obfuscated field names

* Remove getHandle workaround

* entityManager is obfuscated

* Update paperweight

* [ci-skip] Add 1.20 to modrinth task

---------

Co-authored-by: Phillipp Glanz <p.glanz@madfix.me>
Co-authored-by: SirYwell <hannesgreule@outlook.de>
2023-06-09 12:53:42 +02:00
Hannes Greule
152d870cdb
Improve exception handling on adapter loading (#2277) 2023-06-08 08:24:44 +00:00
Alexander Brandes
9be1a58bf3
Back to snapshot for development 2023-06-07 11:30:06 +02:00
Alexander Brandes
3b7d126718
Release 2.6.2 2023-06-07 11:11:54 +02:00
Alexander Brandes
832f93c0f3
Optimize PR builds (#2273)
* Optimize PR build

* Update codeql.yml
2023-06-07 00:51:56 +02:00
renovate[bot]
c5f66c342b
Update dependency com.palmergames.bukkit.towny:towny to v0.99.1.2 (#2272)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-06-07 00:35:50 +02:00
Jordan
1356cd5caa
feat: implement a player-specific queue for clipboard IO tasks (#2267)
* feat: implement a player-specific queue for clipboard IO tasks
 - Addresses #2222 (hopefully fixes)

* Address comments

* Add since

---------

Co-authored-by: Alexander Brandes <mc.cache@web.de>
2023-06-07 00:35:37 +02:00
Jordan
84872cf9a2
chore: improve queue documentation and submit history to better queue (#2266) 2023-06-06 19:22:25 +02:00
Jordan
b7719d17bd
fix: correctly processSet with blacklist when required (#2270)
* fix: correctly processSet with blacklist when required

* Fix incorrect region
2023-06-06 19:21:18 +02:00
Jordan
5504811f11
chore: minor improvements to processing-related code (#2271) 2023-06-06 19:21:02 +02:00
Alexander Brandes
bdb170a5ca
Explicit call repository task 2023-06-06 19:18:01 +02:00
dordsor21
5da5b216f3
fix #2268
-.-
2023-06-05 22:26:41 +01:00
Alexander Brandes
4b06796e76
Archive PR artifacts (#2269)
* Archive PR artifacts

* Fix artifact path
2023-06-05 10:51:26 +02:00
dordsor21
e5d27c27bb
chore: replace some hardcoded ordinals 2023-06-05 00:17:13 +01:00
dordsor21
46e8a37cf0
fix: improve test for polygonal region containment of cuboid
- Possibly fixes #2265
2023-06-04 23:57:51 +01:00
Jordan
e9fed5a066
feat: improve error when loading biomes (#2241) 2023-06-04 18:50:08 +02:00
Jordan
0e215e98d5
fix: minor changes to fix loading blocks outside stored range in ThreadUnsafeCharBlocks (#2260)
- Fixes #2258
2023-06-04 17:22:21 +02:00
EpicPlayerA10
97d4244126
Fix BlockEntity#remove spigot mapping (#2264)
Fix spigot mapping
2023-06-04 13:14:50 +00:00
Alexander Brandes
b7dc5f7ae5
[ci skip] Update Java tooling name 2023-06-04 13:29:07 +02:00
Alexander Brandes
c9a4a9c8b4
Update gradle to 8 (#2262)
* Update gradle to 8

* Update codeql.yml
2023-06-04 12:34:03 +02:00
dordsor21
048dcaf327
fix: do not always set random rotate to true
- Fixes #2259
 - How'd that even get through
2023-06-03 16:34:23 +01:00
Hannes Greule
4fa927f996
Extract common code when resizing arrays (#2257) 2023-06-02 19:39:00 +02:00
renovate[bot]
82418155f6
Update dependency com.github.TownyAdvanced:Towny to v0.99.1.0 (#2254)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: dordsor21 <dordsor21@gmail.com>
2023-06-02 12:21:16 +00:00
Hannes Greule
7646a067eb
Avoid many threads blocking on AbstractChangeSet#processSet (#2226) 2023-06-02 10:40:34 +01:00
renovate[bot]
03c4bafc45
Update antlr4 to v4.13.0 (#2256)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-06-01 23:01:56 +02:00
Jordan
228e84e555
fix: Improve edit processing (#2247) 2023-06-01 15:11:16 +01:00
renovate[bot]
7ce17e5834
Update dependency com.sk89q.worldguard:worldguard-bukkit to v7.0.8 (#2255)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-06-01 09:23:17 +02:00
Jordan
03487718e7
feat: configurable image hosts (#2243) 2023-05-31 16:48:45 +01:00
Jordan
a553961c05
refactor: switch to EnumSet for heightmaps to improve performance (#2248) 2023-05-27 14:25:07 +02:00
Jordan
3041ff3e50
feat: add -r (random rotate) flag to schem load and clipboard brush (#2244)
- Implements #1873
2023-05-25 19:06:20 +02:00
dordsor21
362f6cc6e1
fix #2009 2023-05-22 19:43:21 +01:00
Jordan
5dca925bc3
feat: make more commands unqueued (#2235)
* feat: make more commands unqueued
 - Effectively fixes the very specific "issue" in #2223 I guess
 - Use this opportunity to clean up the command classes a bit

* Address comments
2023-05-22 20:33:59 +02:00
Jordan
435161d566
fix: only send invalid region messages with debug true (#2238)
- Addresses #2188
2023-05-22 20:33:15 +02:00
Jordan
7c01c1e95e
feat: allow captions in SuggestInputParseException (#2239)
- Deprecate for removal methods using string message
 - Fixes #2026
2023-05-22 20:32:56 +02:00
Jordan
74aff920a8
fix: fix universal disallowed blocks logic in limit and EditSession compilation (#2237)
- Fixes #2184
2023-05-22 20:32:36 +02:00
Alexander Brandes
2bdc925b0f
Add regression tests to the round Expression function 2023-05-21 09:51:59 +02:00
Alexander Brandes
4c0b535e6e
Ensure non-Double types are boxed in expression function calls. 2023-05-21 09:50:10 +02:00
Alexander Brandes
86f06b7527
Add -Penginehub.obf.none=true gradle property to build mojmap worldedit-bukkit. 2023-05-20 21:01:34 +02:00
Alexander Brandes
5e3222c55d
Ensure blockmap uniqueness across TE values 2023-05-20 21:00:35 +02:00
Alexander Brandes
7f43e448d5
fix(core): Properly reinit convex CUI selection on primary click 2023-05-20 20:58:47 +02:00
Jordan
2c7b529f67
fix: create single threaded executor for use with non-concurrent generators (#2236)
- Fixes #2228
2023-05-20 20:56:46 +02:00
Alexander Brandes
3cac28ea84
Keep extending cuboid selector after //cli selectworld 2023-05-20 20:56:37 +02:00
Alexander Brandes
85214c944f
Keep extending cuboid selector after //paste -s/n 2023-05-20 20:54:52 +02:00
Alexander Brandes
264185a323
Add method to check initialize state in PlatformManager, deny access to registries when uninitialized 2023-05-20 20:52:03 +02:00
Jordan
85f5006a0b
fix: correctly handle creation of extents in EditSessionBuilder (#2232)
- Add regionExtent process to the queue (fixes #2227)
 - Correctly wrap extents in each other
2023-05-20 20:33:18 +02:00
Jordan
1b0fb9ed48
fix: more intuitive limit permissions (#2233)
- immediately return limit if unlimited (limit combination take the "higher" value)
 - add fawe.limit.unlimited permission and it's an intuitive permission to give
2023-05-20 20:32:38 +02:00
Jordan
3a13c4aaa7
chore: remove firework-chunk-loading prevention and default tick limiter to false (#2234)
- It's very resource-intensive and probably doesn't work anyway
 - Tick limiter should not be enabled by default, it confuses a lot of people with the console logs
2023-05-20 16:25:24 +02:00
Jordan
e9b781d127
fix: correctly in initialise unlimited limit (#2231) 2023-05-20 16:22:02 +02:00
Jordan
2a08ad28a4
fix: correct issues with processor scopes (#2230) 2023-05-20 16:21:11 +02:00
Marco Neuhaus
52723439dd
Fix reading of tile entities with "id" instead of "Id" tag (#2211) 2023-05-20 09:57:13 +00:00
Hannes Greule
a14035d430
Revert "Actually delegate in AbstractDelegateExtent" (#2229) 2023-05-16 10:32:03 +02:00
Alexander Brandes
319cb636e5
Simplify Java location in Jenkinsfile (#2221) 2023-05-12 23:46:38 +02:00
Hannes Greule
71bac009db
Properly scale the random in SimpleRandomCollection (#2220) 2023-05-12 23:13:35 +02:00
Phillipp Glanz
c57fee5b86
Fixes command context for bukkit console command sender (#2193) 2023-05-12 12:12:08 +01:00
dordsor21
dd6197922c
fix: remove invalid file length check
- NBT is stored at the end of the clipboard file
 - Fixes #2209
2023-05-10 17:27:44 +01:00
Hannes Greule
2987550e9b
Actually delegate in AbstractDelegateExtent (#2196)
* actually delegate in AbstractDelegateExtent

* exclude enableHistory method
2023-05-04 18:33:04 +02:00
Phillipp Glanz
e08720b310
Improve git ignore (#2206)
* Exclude run-server for all version

* Exclude run-server for all version

* Exclude run-server for all version

* Exclude run-server for all version

* Exclude run-server for all version

* Remove unsless entry
2023-05-04 18:30:10 +02:00
renovate[bot]
92a6ff5f88
Update dependency io.papermc.paperweight.userdev:io.papermc.paperweight.userdev.gradle.plugin to v1.5.5 (#2201)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-05-01 10:22:27 +02:00
renovate[bot]
950a3f9430
Update dependency com.github.TownyAdvanced:Towny to v0.99.0.5 (#2202)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-05-01 10:22:18 +02:00
renovate[bot]
4779bd4916
Update plugin xyz.jpenilla.run-paper to v2.1.0 (#2205)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-05-01 10:20:24 +02:00
renovate[bot]
909b7d27b8
Update dependency org.ajoberstar.grgit:grgit-gradle to v5.2.0 (#2203)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-05-01 10:04:49 +02:00
renovate[bot]
ffe704d890
Update dependency org.mockito:mockito-core to v5.3.1 (#2204)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-05-01 10:03:49 +02:00
Alexander Brandes
9f3c909254
Back to snapshot for development 2023-04-23 23:01:03 +02:00
Alexander Brandes
abe120291f
Release 2.6.1 2023-04-23 22:47:30 +02:00
Hannes Greule
c86dfe45df
Ensure regen step not running on the main thread (#2185) 2023-04-23 22:15:37 +02:00
360shvit
488a2e5de4
Add an explanation to Disallowed-Blocks Comment (#2186)
Improve user experience by adding an explanation to Disallowed-Blocks Configblock (#2183)
2023-04-22 16:48:59 +00:00
Jordan
8cfb8cb322
chore: add chunk tickets to all chunks accessed (#2163)
- This isn't necessarily targeting any fix, but I think we should be ensuring a ticket is being added to chunks "access asynchronously", as done by the getChunkAtAsync method
2023-04-22 09:45:02 +00:00
Hannes Greule
05afaf00a9
Address incompatibilities after CraftChunk changes in spigot (#2179) 2023-04-21 23:21:50 +01:00
Hannes Greule
86acb1c4d4
Simplify command dispatch to ensure command order (#2131) 2023-04-18 16:28:38 +01:00
Jordan
5cd9616507
fix: Ensure BaseBlock is not returned when a BlockState is wanted in BlockTransformExtent (#2161
- NBT will be handled appropriately at another point
 - Fixes #2085
2023-04-13 17:34:16 +01:00
Jordan
e4158ac084
fix: invalidate cached FaweMask when a plot is unlinked (#2157)
* fix: invalidate cached FaweMask when a plot is unlinked
 - Fixes IntellectualSites/PlotSquared#3998

* Use a weakly-referenced copy of the copnncted plots set
2023-04-13 17:34:05 +01:00
6a7f51bba0 Update CI + Rebuild
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
2023-04-11 12:50:25 +02:00
cdd4df37c6 Merge remote-tracking branch 'upstream/main'
Einige Prüfungen sind fehlgeschlagen
SteamWarCI Build failed
2023-04-11 11:58:22 +02:00
Phillipp Glanz
da4d966d9e
Fix Misaligned SVG In IJ project view (#2174) 2023-04-10 11:54:46 +02:00
Alexander Brandes
a42864e780
[ci skip] Move renovate config to .github folder 2023-04-07 15:12:55 +02:00
Alexander Brandes
2dc8f7bca9
Update paperweight version for 1.19.4 (#2166)
Update paperweight version
2023-04-07 15:11:12 +02:00
renovate[bot]
bb8c9d216b
Update dependency org.bstats:bstats-base to v3.0.2 (#2170)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-04-07 15:10:46 +02:00
Phillipp Glanz
2b51896a01
Improve testability by adding more versions of runPaper to the build scripts (#2172)
* Improve testability

* Change to import
2023-04-07 15:10:14 +02:00
Alexander Brandes
b42f6a2f5e
Update renovate.json (#2167) 2023-04-01 17:53:36 +02:00
Jordan
a9e1d5009c
fix: add null-check for brush in traceMask (#2160)
* fix: add null-check for brush in traceMask
 - Fixes #2149

* Switch to print from printError

Co-authored-by: Alexander Brandes <mc.cache@web.de>

---------

Co-authored-by: Alexander Brandes <mc.cache@web.de>
2023-03-31 20:45:34 +02:00
Jordan
508b94ddc3
feat: improvements to clipboard on disk (#2162)
* feat: improvements to clipboard on disk
 - close clipboard on instantiation failure
 - set canHaveBiomes when loading clipboard from disk (only possible cause I can find for #2151 ..?)
 - check file length and give more appropriate error if it exceeds maximum. Fixes #2151 I guess?#
 - set byteBuffer to null before invoking cleaning. Addresses #1985
 - don't catch and print all exceptions when getBlock fails - prevents large console output for what is likely to be a failed operation anyway

* Fix comments
2023-03-30 00:13:50 +02:00
dordsor21
d82bf0527e
fix: use correct string for disallowed property use 2023-03-22 17:28:50 +00:00
Alexander Brandes
eb1c9dc4db
Apply stash 2023-03-19 10:34:49 +01:00
Alexander Brandes
9d63cb8102
Release 2.6.0 2023-03-19 00:34:10 +01:00
Alexander Brandes
efc917e6df
Add support for 1.19.4 (#2154)
* Add paper adapter for 1.19.4

* Add paper module for 1.19.4

* Port 1.19.3 to 1.19.4

* Switch to Paperweight release

* Update worldedit-bukkit/adapters/adapter-1_19_4/src/main/java/com/sk89q/worldedit/bukkit/adapter/ext/fawe/v1_19_R3/PaperweightAdapter.java

Co-authored-by: Antti Koponen <koponen942@outlook.com>

* Update worldedit-bukkit/adapters/adapter-1_19_4/src/main/java/com/sk89q/worldedit/bukkit/adapter/impl/fawe/v1_19_R3/regen/PaperweightRegen.java

Co-authored-by: Antti Koponen <koponen942@outlook.com>

* Add 1.19.4 to release template

* Update refractions for regen support

* Bump paperweight

---------

Co-authored-by: TheMeinerLP <p.glanz@madfix.me>
Co-authored-by: Antti Koponen <koponen942@outlook.com>
2023-03-18 15:25:04 +01:00
Phillipp Glanz
b54e3a5112
Add nether tress into floating tree remover (#2146)
* Add nether tress into floating tree remover

* Add nether stems
2023-03-17 21:58:53 +00:00
Alexander Brandes
09b899c7a9
[ci skip] Temp disable dc workflow 2023-03-17 22:25:41 +01:00
Jordan
7ab04317fa
fix: clear above and below plot gen heights if build heights are larger (#2153) 2023-03-17 21:56:48 +01:00
Phillipp Glanz
e32a8c40c6
Bump run paper to 1.19.3 and replace path with better solution (#2150) 2023-03-16 09:45:22 +00:00
renovate[bot]
df99226313
Update dependency com.github.TechFortress:GriefPrevention to v16.18.1 (#2142)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-03-13 17:09:18 +01:00
renovate[bot]
5313f9c588
Update dependency org.mockito:mockito-core to v5.2.0 (#2144)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-03-13 17:08:23 +01:00
renovate[bot]
0146b952c6
Update plugin io.github.gradle-nexus.publish-plugin to v1.3.0 (#2145)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-03-13 17:08:11 +01:00
Alexander Brandes
bfd919b3cb
Update paperweight 2023-03-07 15:39:22 +01:00
Alexander Brandes
b05e64a7ec
Fetch userdev plugin from plugin portal (#2136) 2023-03-07 15:35:33 +01:00
Alexander Brandes
ccb503e49d
[ci skip] Update CF workflow 2023-03-07 00:14:47 +01:00
Alexander Brandes
f7026338e9
Update adventure javadoc URL 2023-03-07 00:04:44 +01:00
Alexander Brandes
992eaf2b4c
Misc. dependency update to align with libs.versions.toml (#2134) 2023-03-06 15:44:21 +01:00
Hannes Greule
90baa790c3
Make custom toArray methods fulfill the method contract (#2089)
* Make PropertyKeySet#toArray(T) fulfill the method contract

* Make LocalBlockVectorSet#toArray(T) fulfill the method contract
2023-03-06 13:57:40 +01:00
Alexander Brandes
a63037b92d
Update renovate.json 2023-03-06 13:55:02 +01:00
Hannes Greule
8a3052683e
Use unsynchronized buffered OutputStream for history (#2127)
* Use unsychronized buffered OutputStream

* Add note

* Avoid synchronization on DataOutputStream#write
2023-03-06 13:54:35 +01:00
eztaK-red
211e8034ff
Fix off by one error for negative coordinates when using -r with //deform (#2092)
The problem: Off by one error for negative coordinates. Source: Behaviour of rounding coordinates (doubles) after deform.

The off by error came down to rounding using casts (int) and rounding using Math.floor()

(int)( 1.8) = 1
(int)(-1.8) = -1
(int)Math.floor( 1.8) = 1
(int)Math.floor(-1.8) = -2

Looking at the original WorldEdit implementation a Math.floor call is present too. It was missing FAWE which resulted in the bug.

Co-authored-by: Alexander Brandes <mc.cache@web.de>
2023-03-06 13:53:07 +01:00
Alexander Brandes
94f57799d0
Pin GH actions to SHA to avoid mutable refs (#2126) 2023-03-06 13:51:53 +01:00
renovate[bot]
7152fd2032
Update dependency io.papermc.paperweight.userdev:io.papermc.paperweight.userdev.gradle.plugin to v1.5.3 (#2129)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-03-06 13:47:13 +01:00
Alexander Brandes
84e1886672
Update developers field 2023-03-02 20:52:12 +01:00
Alexander Brandes
a1d35e26fa
Update developers field 2023-03-02 20:50:01 +01:00
renovate[bot]
214495f8f5
Update dependency io.papermc.paperweight.userdev:io.papermc.paperweight.userdev.gradle.plugin to v1.5.2 (#2122)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-03-02 00:47:41 +01:00
Hannes Greule
526e1902ca
Fix FAWE using exclusive build height from PlotSquared (#2123)
Use inclusive build height maximum
2023-03-02 00:47:28 +01:00
renovate[bot]
6a31f4179c
Update dependency gradle to v7.6.1 (#2111)
* Update dependency gradle to v7.6.1

* Update gradle/wrapper/gradle-wrapper.properties

---------

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Alexander Brandes <mc.cache@web.de>
2023-02-27 21:22:51 +01:00
Hannes Greule
1904b1fdd6
Fix reading block states in no redo mode (#2119) 2023-02-27 16:31:15 +01:00
renovate[bot]
c0dc42ed3f
Update dependency org.bstats:bstats-base to v3.0.1 (#2093)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-02-25 11:11:09 +01:00
renovate[bot]
f95383e837
Update dependency org.ajoberstar.grgit:grgit-gradle to v5 (#2114)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-02-25 11:10:23 +01:00
Alexander Brandes
c7ddee12d9
Revert "Update dependency gradle to v8 (#2094)"
This reverts commit b293a5eea3.
2023-02-25 10:42:01 +01:00
Alexander Brandes
7f6a27d083
Revert "Update dependency gradle.plugin.com.github.johnrengelman:shadow to v8 (#2113)"
This reverts commit 7a667131ba.
2023-02-25 10:41:49 +01:00
Alexander Brandes
184eb215b6
Move Jenkinsfile from ps-v7 to general branch (#2098)
* Move Jenkinsfile from ps-v7 to general branch

* Update Jenkinsfile
2023-02-25 10:31:33 +01:00
renovate[bot]
7a667131ba
Update dependency gradle.plugin.com.github.johnrengelman:shadow to v8 (#2113)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-02-25 10:26:24 +01:00
renovate[bot]
b293a5eea3
Update dependency gradle to v8 (#2094)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-02-25 10:01:24 +01:00
renovate[bot]
f70e1a215a
Update dependency net.minecrell.plugin-yml.bukkit to v0.5.3 (#2112)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-02-25 01:07:59 +01:00
9d5e96946c Merge pull request 'main' (#6) from Mirrors/FastAsyncWorldEdit:main into main
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
Reviewed-on: #6
2023-02-23 10:18:59 +01:00
renovate[bot]
a464f1271d
Update plugin io.github.gradle-nexus.publish-plugin to v1.2.0 (#2109)
Einige Prüfungen sind fehlgeschlagen
SteamWarCI Build failed
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-02-22 23:46:11 +01:00
renovate[bot]
b72c6902e2
Update antlr4 to v4.12.0 (#2103)
Einige Prüfungen sind fehlgeschlagen
SteamWarCI Build failed
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-02-20 10:49:54 +01:00
renovate[bot]
8832820b6c
Update dependency io.papermc.paperweight.userdev:io.papermc.paperweight.userdev.gradle.plugin to v1.5.1 (#2095)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-02-19 12:11:04 +01:00
renovate[bot]
783dc353c4
Update dependency io.papermc.paperweight.userdev:io.papermc.paperweight.userdev.gradle.plugin to v1.5.0 (#2090)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-02-10 16:48:52 +01:00
Alexander Brandes
1e5b2fe0de
Back to snapshot for development 2023-02-07 23:25:17 +01:00
Alexander Brandes
19ed349740
Release 2.5.2 2023-02-07 23:13:05 +01:00
Hannes Greule
321a39f121
Remove PlayerMoveEvent listener and deprecate MovableTool (#2083)
Remove PlayerMoveEventListener and deprecate MovableTool
2023-02-07 23:07:57 +01:00
Hannes Greule
f9d6b127e6
Use Pattern Matching for instanceof in PropertyKeySet (#2086) 2023-02-07 23:07:31 +01:00
Alexander Brandes
07217d0b81
[ci skip] Document metrics addition 2023-02-07 22:50:21 +01:00
Alexander Brandes
b65f3ce1f8
Add metrics for Residence (#2081) 2023-02-07 10:47:49 +01:00
9f97dc2a3c Merge pull request 'Update upstream (for 1.19.3 support)' (#4) from upstream into main
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
Reviewed-on: #4
2023-02-02 11:32:52 +01:00
1889f94a39 Fix ci
Einige Prüfungen sind fehlgeschlagen
SteamWarCI Build failed
2023-02-02 11:32:08 +01:00
b87a861098 Merge remote-tracking branch 'upstream/main' into upstream
Einige Prüfungen sind fehlgeschlagen
SteamWarCI Build failed
2023-02-02 11:20:09 +01:00
renovate[bot]
cd00bf9771
Update dependency org.mockito:mockito-core to v5.1.1 (#2078)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-01-31 11:21:29 +01:00
Hannes Greule
158e51191f
Linear Patterns require flooring division (#2079)
Use floorDiv in linear patterns
2023-01-31 11:21:11 +01:00
Alexander Brandes
214954bb09
Back to snapshot for development 2023-01-23 12:51:38 +01:00
Alexander Brandes
09d405935a
Release 2.5.1 2023-01-23 12:37:45 +01:00
95a06eb639 „steamwarci.yml“ ändern
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
2023-01-18 21:04:30 +01:00
0c9317bb8c Deploy to maven repo
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
2023-01-18 20:53:13 +01:00
Bernhard
5e8bc5c2ad
fix regex and remove forbidden windows characters (#2012)
refactor: fix regex and remove forbidden windows characters
2023-01-16 00:34:53 +01:00
TheJonstone✓
0f558425f5
Fix: remove unnecessary bypass permission (#2060)
Fix: remove unnecessary permission
2023-01-16 00:34:28 +01:00
Jordan
ae57ac5d50
fix: don't quash a cancellation FaweException in LimitExtent (#2068)
- This allowed some edits to continue after a player left the server when they shouldn't
 - Possible sort-of fix for #1985
 - Possible fix for #1955
2023-01-16 00:33:44 +01:00
Alexander Brandes
98c2d2124e
Split workflows (#2071) 2023-01-16 00:33:13 +01:00
Alexander Brandes
c0563b6574
Terminate process if .git folder does not exist (#2070)
Terminate process if folder is not a repository
2023-01-15 20:24:51 +01:00
renovate[bot]
606ffad12b
Update dependency org.mockito:mockito-core to v5 (#2069)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-01-14 10:46:24 +01:00
Hannes Greule
bb0e201c52
Remove usages of JoinedCharSequence (#2062) 2023-01-11 00:07:24 +01:00
renovate[bot]
452f968f07
Update antlr4 to v4.11.1 (#2064)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-01-09 16:52:48 +01:00
renovate[bot]
3ad70a8ef4
Update dependency io.papermc.paperweight.userdev:io.papermc.paperweight.userdev.gradle.plugin to v1.4.1 (#2063)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-01-09 16:33:32 +01:00
renovate[bot]
afe601bf93
Update dependency com.github.TownyAdvanced:Towny to v0.98.4.18 (#2057)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-12-31 01:02:41 +01:00
renovate[bot]
7db1e9c7d6
Update dependency com.github.TownyAdvanced:Towny to v0.98.4.17 (#2053)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-12-29 13:44:41 +01:00
renovate[bot]
b98c3efc88
Update dependency org.mockito:mockito-core to v4.11.0 (#2055)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-12-29 13:42:56 +01:00
Alexander Brandes
a9ed8431cd
Use the connection field on 1.19->1.19.3 rather than networkManager 2022-12-27 14:05:41 +01:00
renovate[bot]
a7c402d8dd
Update dependency com.github.TownyAdvanced:Towny to v0.98.4.15 (#2050)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-12-24 12:01:29 +01:00
renovate[bot]
f8acaf5ec2
Update dependency org.mockito:mockito-core to v4.10.0 (#2047)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-12-15 22:38:17 +01:00
Alexander Brandes
b0ac500fa1
Bump paperweight 2022-12-13 22:52:30 +01:00
renovate[bot]
83e0c84616
Update dependency io.papermc.paperweight.userdev:io.papermc.paperweight.userdev.gradle.plugin to v1.4.0 (#2044)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-12-13 22:44:47 +01:00
Alexander Brandes
26d5f10c04
Back to snapshot for development 2022-12-11 19:28:44 +01:00
Alexander Brandes
d6599fd332
Release 2.5.0 2022-12-11 19:10:40 +01:00
Bernhard
c3ce162fd5
Feature: add "h" as alias for "hand" and "oh" for "offhand" (#2033) 2022-12-11 18:36:33 +01:00
Alexander Brandes
f98e526fa0
Add support for 1.19.3 (#2042)
* 1.19.3

* More fixes

* fix: compile time issues for 1.19.3

* fix: new mappings and GeneratorStructureState

* Add 1.19.3 to release and issue template

* Update dependencies for 1.19.3

* Update worldedit-bukkit/adapters/adapter-1_19_3/build.gradle.kts

Co-authored-by: Pierre Maurice Schwang <mail@pschwang.eu>
2022-12-11 18:36:13 +01:00
Alexander Brandes
62f561cb56
Update dev bundle versions (#2040) 2022-12-09 12:38:10 +01:00
renovate[bot]
62345bb64e
Update plugin xyz.jpenilla.run-paper to v2.0.1 (#2039)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-12-09 10:10:09 +01:00
Hannes Greule
79c23e06c3
Clean up starlight usage (#2029)
clean up starlight usage
2022-12-04 18:56:41 +01:00
renovate[bot]
e0e66ce2db
Update dependency com.github.TownyAdvanced:Towny to v0.98.4.4 (#2028)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-11-30 10:09:39 +01:00
Alexander Brandes
41ea21f91d
Run announcement workflow after release workflow 2022-11-28 11:34:09 +01:00
Alexander Brandes
faa0908ba8
Run announcement workflow after 'build' workflow 2022-11-28 11:30:32 +01:00
renovate[bot]
eda5bced65
Update dependency gradle to v7.6 (#2027)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-11-25 19:25:01 +01:00
renovate[bot]
c1bfadd328
Update dependency com.github.TownyAdvanced:Towny to v0.98.4.3 (#2025)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-11-25 19:24:10 +01:00
renovate[bot]
b432faef36
Update dependency io.papermc.paperweight.userdev:io.papermc.paperweight.userdev.gradle.plugin to v1.3.11 (#2023)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-11-20 00:49:37 +01:00
renovate[bot]
6cb9f0e485
Update auto-value to v1.10.1 (#2019)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-11-20 00:44:22 +01:00
renovate[bot]
6f6c0508df
Update dependency io.papermc.paperweight.userdev:io.papermc.paperweight.userdev.gradle.plugin to v1.3.10 (#2022)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-11-20 00:39:43 +01:00
Alexander Brandes
15b351930d
Back to snapshot for development 2022-11-16 11:29:57 +01:00
Alexander Brandes
1771a04ef9
Release 2.4.10 2022-11-15 19:35:25 +01:00
Alexander Brandes
34dbaa633a
Add CF upload task (#2018) 2022-11-15 19:25:03 +01:00
renovate[bot]
fc701b9260
Update plugin xyz.jpenilla.run-paper to v2 (#2017)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-11-15 19:12:08 +01:00
renovate[bot]
77b1c7eb9c
Update dependency org.mockito:mockito-core to v4.9.0 (#2016)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-11-15 19:04:13 +01:00
Pierre Maurice Schwang
f33d93591a
Fix Chorus-Plant tree type generation (#2015)
fix: chorusplant tree type must generate inside end_stone
2022-11-14 22:58:54 +01:00
renovate[bot]
f9527ce2b7
Update plugin xyz.jpenilla.run-paper to v1.1.0 (#2007)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-11-13 12:14:14 +01:00
renovate[bot]
7f8b0a7e21
Update dependency com.github.TownyAdvanced:Towny to v0.98.4.0 (#2008)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-11-13 11:59:17 +01:00
Pierre Maurice Schwang
4c2119e404
Fix error on latest paper while copying entities (#2006) 2022-11-10 17:45:35 +00:00
renovate[bot]
1aa213fb4c
Update dependency com.github.TownyAdvanced:Towny to v0.98.3.19 (#2003)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-11-06 11:15:01 +01:00
Alexander Brandes
983e4407b5
Back to snapshot for development 2022-11-02 09:52:28 +01:00
Alexander Brandes
0ee18597ae
Release 2.4.9 2022-11-02 09:45:48 +01:00
Pierre Maurice Schwang
2fe54a04b5
Adjust platform specific code to recent changes (#1997)
* chore: remove usage of MCUtil in StarlightRelighter

* chore: cleanup of unused imports

* hacky shit-fuckery for papers new chunksystem und refactor

* chore: address review comments

* Update dependency io.papermc.paperweight.userdev:io.papermc.paperweight.userdev.gradle.plugin to v1.3.9 (#2001)

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>

* fix: suppress exceptions for field retrieval, cache fields / methods

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-11-02 09:41:20 +01:00
Hannes Greule
bbc1db9bd2
Read minecraft version from paper if available (#2002)
* read version from paper if available

* fix for versions without release information
2022-11-01 23:39:42 +01:00
renovate[bot]
e305c5d5ab
Update dependency io.papermc.paperweight.userdev:io.papermc.paperweight.userdev.gradle.plugin to v1.3.9 (#2001)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-11-01 22:45:58 +01:00
renovate[bot]
8127d57158
Update dependency com.github.TownyAdvanced:Towny to v0.98.3.15 (#1993)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-10-25 23:58:53 +02:00
Jordan
0d112b2913
fix: move main-thread call to be implementation from WorldWrapper (#1991)
- Fixes #1990
2022-10-23 21:22:53 +02:00
Jordan
bf28ab47b8
fix: bring default min/max y in line with upstream in AbstractRegion (#1992)
- Fixes #1987
2022-10-23 21:22:43 +02:00
renovate[bot]
e36b838227
Update dependency org.mockito:mockito-core to v4.8.1 (#1988)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-10-22 10:25:54 +02:00
Alexander Brandes
4f74cc671f
Back to snapshot for development 2022-10-18 23:25:52 +02:00
Alexander Brandes
dce86ec046
Release 2.4.8 2022-10-18 23:23:35 +02:00
Jordan
2082df4141
fix: Add blocked blocks to the correct set (#1975)
* fix: Add blocked blocks to the correct set

* Address comment
2022-10-13 19:21:25 +02:00
Jordan
8971d7064c
feat: Reduce any spam caused by exceptions thrown when writing history (#1976)
- Closes #1960
2022-10-13 19:21:02 +02:00
Jordan
ccb31c0ecc
fix: Do not cast y to byte in history database (#1978)
- y is/was already stored as an int
 - Fixes #1931
2022-10-13 19:20:17 +02:00
Hannes Greule
13eb1f815f
Fix mappings issue with biome-based regen on 1.18.2 (#1982)
access correct fields
2022-10-13 19:20:01 +02:00
Jordan
878509406b
fix: Add items to a player's inventory on the main thread (#1977)
- Fixes #1954
2022-10-12 20:48:56 +02:00
Alexander Brandes
33be942176
[ci skip] Rewrite README for modrinth (#1979)
docs: Rewrite README for modrinth
2022-10-09 16:41:22 +02:00
Alexander Brandes
f356f64c3d
[ci skip] chore: Announce releases on discord (#1980) 2022-10-09 16:40:04 +02:00
Pierre Maurice Schwang
598cd6ba19
Don't error when NPC-annotated "entity" leaves the server (#1969)
fix: no need to remove never-added attachment
2022-10-08 13:34:50 +02:00
Alexander Brandes
292d9f2439
chore: Re-enable CodeQL (#1973) 2022-10-08 13:34:25 +02:00
Alexander Brandes
a62b3158a7
Back to snapshot for development 2022-10-04 14:21:55 +02:00
Alexander Brandes
18bf911fdc
Release 2.4.7 2022-10-04 14:05:36 +02:00
Alexander Brandes
ad38d88642
[ci skip] Link to GH releases (#1970)
chore: Link to GH releases
2022-10-04 13:28:10 +02:00
Aurélien
2e386ea391
Fix region restrictions with methods non-overriden (#1948)
Fix region registrictions with methods non-overriden
See https://github.com/IntellectualSites/fastasyncvoxelsniper/issues/195 for context
2022-10-03 11:20:53 +02:00
Alexander Brandes
a32d8dcbdb
Release to Modrinth (#1968)
* feat: Release to Modrinth

* chore: List-ify gameVersions
2022-10-02 21:50:16 +02:00
Alexander Brandes
87f680683d
Update Upstream
0ef38b5 Use SnakeYaml 1.32+, set loader code point limit. (2194)

Defaults to 64MB, can be set via -Dworldedit.yaml.codePointLimit sysprop.
2022-09-26 23:45:06 +02:00
942570c754 Merge pull request 'Move Clipboards to /tmp + Update upstream' (#3) from upstream into main
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
Reviewed-on: #3
Reviewed-by: YoyoNow <jwsteam@nidido.de>
2022-09-24 19:48:09 +02:00
ae66ccfa8f Fix ci
Einige Prüfungen sind fehlgeschlagen
SteamWarCI Build failed
2022-09-24 19:32:14 +02:00
c0a135acc9 Merge remote-tracking branch 'upstream/main' into upstream 2022-09-24 19:28:53 +02:00
Alexander Brandes
10b852d416
Back to snapshot for development 2022-09-21 16:45:40 +02:00
Alexander Brandes
4f26561cc1
Release 2.4.6 2022-09-21 16:41:07 +02:00
Pierre Maurice Schwang
ab55d07ffd
Fix #saturate-Pattern (#1944)
* fix: block type access + resources in #saturate pattern

* chore: no need to download jar file in loadModTextures
2022-09-21 16:17:41 +02:00
Alexander Brandes
1706d64ddf
Retrieve the latest asset release version automatically (#1947)
* feat: retrieve the latest release version automatically

(cherry picked from commit a8885a349a567849f6db29565cc65b14e3dab155)

* feat/fix: validate hash of downloaded asset file

* chore: address review comments
Usage of nio Path instead of direct File access
Usage of HexFormat instead of custom implementation
No need for usage of channels

* chore: simplified sha-1 calculation logic

Co-authored-by: Pierre Maurice Schwang <mail@pschwang.eu>
2022-09-15 21:19:31 +02:00
renovate[bot]
c819031d1f
[ci skip] Update dependency com.github.TownyAdvanced:Towny to v0.98.3.8 (#1936)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-09-12 11:18:46 +02:00
renovate[bot]
2547fd590d
Update dependency org.mockito:mockito-core to v4.8.0 (#1940)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-09-12 11:16:14 +02:00
dd8ed8d5c6 Move clipboards to temp
Einige Prüfungen sind fehlgeschlagen
SteamWarCI Build failed
2022-09-06 21:34:13 +02:00
2553f169aa Merge pull request 'main' (#2) from Mirrors/FastAsyncWorldEdit:main into upstream
Einige Prüfungen sind fehlgeschlagen
SteamWarCI Build failed
Reviewed-on: #2
2022-09-06 21:32:29 +02:00
Alexander Brandes
673b467ad9
Back to snapshot for development
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
2022-09-05 11:29:51 +02:00
Alexander Brandes
122b32b9f0
Release 2.4.5 2022-09-05 11:26:31 +02:00
Hannes Greule
5da558e24c
feature: support paper chunk system (#1884)
* avoid usage of ticking chunk future on paper

* fix entity handling

* fix entity handling but on spigot

* seems like no one uses spigot

Co-authored-by: Alexander Brandes <mc.cache@web.de>
2022-09-04 23:30:32 +02:00
Alexander Brandes
3b109ba3ff
Upload files to curseforge on release (#1929)
* chore: Upload files to curseforge on release

* chore: Use direct artifact path
2022-09-04 23:30:02 +02:00
renovate[bot]
8233f132d4
Update dependency com.github.TownyAdvanced:Towny to v0.98.3.6 (#1926)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-08-29 21:31:06 +02:00
Alexander Brandes
aa216a990a
Update upstream
7e61ff1 Work around invalid legacy values in schematics (2171)
2022-08-29 17:21:21 +02:00
Hannes Greule
a51863c6f0
fix: use proper level data for regen (#1921) 2022-08-27 15:49:01 +01:00
Hannes Greule
a6a0b5eb66
fix: avoid recursive LegacyMapper initialization (#1922) 2022-08-27 15:48:54 +01:00
d5722fe9a5 Fix ci
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
2022-08-27 11:44:59 +02:00
c3b43e13e3 Improve initialisation performance
Einige Prüfungen sind fehlgeschlagen
SteamWarCI Build failed
2022-08-27 11:35:56 +02:00
8348c0bf19 Merge remote-tracking branch 'upstream/main' 2022-08-27 11:34:50 +02:00
Alexander Brandes
dc2db5f07f
Back to snapshot for development 2022-08-24 10:07:22 +02:00
Alexander Brandes
37bbebcc9d
Release 2.4.4 2022-08-24 10:06:31 +02:00
Alexander Brandes
d5acb4ec51
fix: Lazy fix macro stacktrace (#1911) 2022-08-24 10:02:25 +02:00
e5833aff58 Merge remote-tracking branch 'origin/main'
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
2022-08-21 17:58:20 +02:00
113c02ec3f Fix demon 2022-08-21 17:57:41 +02:00
0f74e2a0bb Merge pull request 'Remove Schematic Command' (#1) from remove_schematic_command into main
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
Reviewed-on: #1
Reviewed-by: Lixfel <lixfel@steamwar.de>
2022-08-21 17:50:28 +02:00
Chaoscaot
d4c8bd084e Remove Schematic Command
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
2022-08-21 17:40:19 +02:00
d67ec4fd63 Add CI
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful
2022-08-21 17:31:44 +02:00
Alexander Brandes
60ad2b51e8
[ci skip] chore: Add renovate schema URL 2022-08-20 15:31:42 +02:00
Hannes Greule
ab659eadde
fix: upstream missing Region#getBoundingBox() (#1908)
Use block change limit for //copy and //cut

(cherry picked from commit fd8dbdd7b7b8b561db98a45b4eae3810dedb1551)
2022-08-19 13:41:24 +02:00
renovate[bot]
cc1b466a04
build: Update dependency com.github.TownyAdvanced:Towny to v0.98.3.5 (#1906)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-08-15 23:49:00 +02:00
renovate[bot]
26bd9ec5ee
build: Update dependency org.mockito:mockito-core to v4.7.0 (#1904)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-08-13 17:16:52 +02:00
Alexander Brandes
5c2679f95d
Update Upstream
55e2d3d Catch InvalidPathException in safeFile handler (2167)

Closes #1872
2022-08-10 09:47:53 +02:00
Alexander Brandes
129f4f37a3
chore: Update assets to 1.19.2 (#1900) 2022-08-07 11:44:40 +02:00
Alexander Brandes
c520e1a686
Update upstream
54ed9e8 Add support for Y-offsets with back direction (2164)
2022-08-07 09:13:09 +02:00
Alexander Brandes
e78277e158
build: Update paperweight (#1901) 2022-08-06 22:41:03 +02:00
Alexander Brandes
86a9866455
build: Back to snapshot for development 2022-08-06 16:21:56 +02:00
Alexander Brandes
2a55bb5cfc
build: Release 2.4.3 2022-08-06 16:19:53 +02:00
renovate[bot]
8c8d5d5064
[ci skip] build: Update dependency com.github.TownyAdvanced:Towny to v0.98.3.4 (#1897)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-08-06 13:54:03 +02:00
Alexander Brandes
a91519e09d
Update bug_report.yml 2022-08-06 13:48:49 +02:00
renovate[bot]
a0b35c9cda
build: Update dependency gradle to v7.5.1 (#1899)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-08-06 13:48:24 +02:00
Alexander Brandes
a414fd308e
Add 1.19.2 (#1898)
feat: Add 1.19.2
2022-08-05 17:05:15 +02:00
Aurélien
e942175559
Improve `MainUtil#copyFile` (#1888) 2022-08-02 11:25:56 +02:00
Alexander Brandes
7a498497c5
chore: Use 1.19.1 asset URL (#1889) 2022-08-01 09:50:27 +02:00
Alexander Brandes
8b95c25194
Update bug_report.yml 2022-07-29 19:01:55 +02:00
Alexander Brandes
8d57c0b888
build: Back to snapshot for development 2022-07-28 10:32:10 +02:00
Alexander Brandes
8414e64bab
build: Release 2.4.2 2022-07-28 10:29:59 +02:00
Alexander Brandes
50ee45fedd
feat: Add support for 1.19.1 (#1887) 2022-07-28 10:26:43 +02:00
Alexander Brandes
e10774598e
chore: Reword light command messages (#1885) 2022-07-25 18:49:18 +02:00
peaches
77a929f6a1
fix: use servers removeGameEventListener instead of reimpl (#1881)
* fix: use servers removeGameEventListener instead of reimpl

* fix: 1.18.2 impl
2022-07-25 18:49:10 +02:00
dordsor21
a1babd5ec9
biomes is now an two-dimensional array in CharSetBlocks
- Fixes #1878
2022-07-17 17:33:51 +01:00
renovate[bot]
72f9b34f15
[ci skip] build: Update dependency com.github.TownyAdvanced:Towny to v0.98.3.2 (#1877)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-07-17 16:38:51 +02:00
Alexander Brandes
4fc2a25a9a
Update Upstream
d7b3c4c Clone the returned getRegion on BlockArrayClipboard (2144)
2022-07-16 11:08:42 +02:00
renovate[bot]
7a1a33aff0
build: Update dependency gradle to v7.5 (#1875)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-07-14 17:02:10 +02:00
Alexander Brandes
282e47dd19
build: Return to snapshot for development 2022-07-12 22:30:40 +02:00
Alexander Brandes
4aa84776ba
build: Release 2.4.1 2022-07-12 22:29:45 +02:00
renovate[bot]
4013eceb8e
[ci skip] build: Update dependency com.github.TownyAdvanced:Towny to v0.98.3.1 (#1860)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-07-12 22:22:50 +02:00
Alexander Brandes
42956839ee
[ci skip] chore: Update renovate excludes
Closes #1870
2022-07-03 13:52:33 +02:00
Aeliios
92518f71be
Correct return type for CuboidRegion#getFaces() upstream compatibility (#1866) 2022-07-03 12:43:13 +01:00
Aeliios
902f153929
Getting correct String from CompoundTag (#1867) 2022-07-03 12:43:03 +01:00
Alexander Brandes
def84a80c6
docs: Use rootProject.name over project.name for javadocs title (#1859)
* docs: Use rootProject.name over project.name for javadocs title

* docs: Add module name as well
2022-06-29 23:18:39 +02:00
Alexander Brandes
ffd98ad6d9
build: Update paperweight
Follow up to renovate PR
2022-06-28 17:38:46 +02:00
renovate[bot]
db37c28a2f
[ci skip] build: Update dependency io.papermc.paperweight.userdev:io.papermc.paperweight.userdev.gradle.plugin to v1.3.8 (#1855)
* build: build: Update dependency io.papermc.paperweight.userdev:io.papermc.paperweight.userdev.gradle.plugin to v1.3.8

* Update renovate.json

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Alexander Brandes <mc.cache@web.de>
2022-06-28 10:17:22 +02:00
Alexander Brandes
1400ce9958
[ci skip] chore: Exclude unused modules from renovate 2022-06-27 18:54:15 +02:00
Alexander Brandes
dbfb521795
build: Update bom to 1.9 2022-06-27 16:52:27 +02:00
dordsor21
3212dddb2d
Fix BlendBall for no mask 2022-06-27 13:38:22 +01:00
Alexander Brandes
041f4505a3
build: Back to snapshot for development 2022-06-27 13:57:35 +02:00
Alexander Brandes
f812fc14ab
build: Release 2.4.0 2022-06-27 13:52:50 +02:00
renovate[bot]
edfc5a7a01
[ci skip] build: build: Update dependency com.github.TownyAdvanced:Towny to v0.98.2.6 (#1843)
build: Update dependency com.github.TownyAdvanced:Towny to v0.98.2.6

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-06-27 09:51:50 +02:00
Jordan
34ea713d29
Fix walls command on 1D/2D selection (#1821) 2022-06-24 15:04:11 +01:00
dordsor21
38d1a64bf5
Correctly recycle CharSetBlocks 2022-06-24 15:03:48 +01:00
dordsor21
9762e4e220
Add Object2ObjectArrayMap to "DoNotMinimiseThese" class
- Fixes #1839
2022-06-24 10:43:21 +01:00
Jordan
8094b68967
Actually implement ChunkHolder/ChunkSet pools (#1840) 2022-06-24 10:13:58 +01:00
Jordan
800988aae7
Assume a file not being in a subdirectory of root means a symlink is used (#1838) 2022-06-23 17:32:21 +01:00
dordsor21
010611c4ac
Don't hide ChunkHolder generic "T" type paramter 2022-06-23 16:10:30 +01:00
Jordan
704f87da23
Re-implement incremental schematic names in a folder (#1833)
* Re-implement incremental schematic names in a folder
 - Fixes #1545

* Move fawe end comment

* Slight cleanup
2022-06-23 10:23:22 +02:00
Jordan
100288ada5
Implement a "sensitivity" setting, a mask, and an option to only distinguish air vs blocks to blendball (#1832) 2022-06-22 12:50:22 +01:00
Jordan
d498996cbd
Use Material rather than legacy int/data when specifying block break effect type (#1829) 2022-06-22 12:50:09 +01:00
NotMyFault
e3f2d5f737
[ci skip] docs: Add JB to Readme 2022-06-21 21:30:14 +02:00
Jordan
968799503f
Re-implement full Entity support in history, entity removal, entity creation, etc. (#1812)
Co-authored-by: Alexander Brandes <mc.cache@web.de>
2022-06-21 14:52:02 +01:00
dordsor21
d62c88a2ca
Remove unused import 2022-06-21 13:00:19 +01:00
dordsor21
8b05738929
Remove P2 apidescription annotation 2022-06-21 12:58:21 +01:00
Jordan
c5073d79e7
Account for use of MutableBlockVector3 in Spline Brush (#1831) 2022-06-21 12:56:02 +01:00
Jordan
3f103eea9b
Set the correct delegate to the ChunkHolder when using get or set in NULL delegate (#1830) 2022-06-21 12:55:51 +01:00
renovate[bot]
fe90142f1f
[ci skip] build: Update dependency com.github.TownyAdvanced:Towny to v0.98.2.5 (#1834)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-06-21 10:12:19 +02:00
Alexander Brandes
2ecf32b37c
chore: Add runServer task (#1835) 2022-06-20 17:56:51 +02:00
Jordan
dacb89a480
Bring stack in line with upstream using offset rather than direction (#1822)
Co-authored-by: Alexander Brandes <mc.cache@web.de>
2022-06-20 10:46:19 +02:00
Jordan
396faf6732
Support using //distr on console properly (#1827) 2022-06-19 22:35:36 +01:00
Jordan
dac3610bcf
Implement generation of biome decorations to //regen <biome> and add option for a random seed to be used (#1819) 2022-06-19 22:33:16 +01:00
Jordan
692a010c39
Actually apply source mask when using //paste -m <mask> (#1810) 2022-06-19 22:33:01 +01:00
Jordan
84f6039f41
Fix #fullcopy -r (#1816) 2022-06-19 00:59:11 +01:00
Jordan
aadd35c0c4
Don't limit split size for extra block data (signs, spawner, etc.) (#1818) 2022-06-19 00:58:59 +01:00
Jordan
8e5204c311
Allow editing solely of tiles/entities/heightmaps (#1817) 2022-06-19 00:58:54 +01:00
Jordan
003cec30be
Fix saving entities in DiskOptimizedClipboard when no tiles are present (#1815) 2022-06-19 00:58:47 +01:00
Jordan
907ad8528e
Don't do the unbelievable bad use of a MutableBlockVector2 in the creation of a set (#1825)
* Don't do the unbelievable bad use of a MutableBlockVector2 in the creation of a set
 - Fixes IntellectualSites/PlotSquared#3683

* Clean up remnants of the use of MutableBlockVector2
2022-06-17 23:41:25 +02:00
Jordan
d2b4154cc0
Properly support extended world heights (y > 255) in tripleBlockCoord (#1805) 2022-06-17 15:39:27 +01:00
Alexander Brandes
5b72f396bb
docs: Publish javadocs to GH pages (#1824)
* docs: Publish javadocs to GH pages

* chore: Use up to date URLs

* chore: Update README url
2022-06-17 15:09:32 +02:00
Jordan
fd00635533
Fixes to BlockMask and "char" masks (#1787)
* If a char mask  is successfully created from the full input, return it

* Don't double-up adding a block to a BlockMaskBuilder (if adding by regex is successful)
 - InputParseException is thrown if unsuccessful

* Fix optimisation of BlockMask for negation of a single block type
 - Fixes #1755

* Allow early returning of an optimized MaskIntersection to avoid unnecessary work

* Actually allow underscore in isAlphanumericUnd
 - Fixes #1626

* Replace a few more hard-coded air internal IDs

* Don't fail silently if BlockMaskBuilder#addRegex doesn't work when testing all block types

* Remove unused import
2022-06-16 16:24:48 +02:00
Jordan
f2bab901f4
The extent minY check in clipboard paste is un-needed as it is handled gracefully by FAWE (#1806)
- Fixes #1771
2022-06-16 16:24:00 +02:00
Jordan
1da987d594
Fix PNGWriter exporting blank PNGs (#1807)
* Fix horrendous variable assignment in PNGWriter
 - Fixes #1679

* More detailed information on PNG format

* Avoid a larger number of blocks that do nto have a color assigned in TextureUtil

* Don't error in PNGWriter if biomes aren't saved to clipboard and grass is present
2022-06-16 16:23:52 +02:00
Jordan
ac11da855a
Processor should be added to queue, not extent (#1809)
- Fixes #1559 root cause
2022-06-16 16:23:45 +02:00
Jordan
9395b3c575
Prevent unhinged tree generation by doing a sanity check on the block below/block of the tree placement (#1811) 2022-06-16 16:23:37 +02:00
dordsor21
462bba4f87
Fix biome history on 1.19 2022-06-15 18:52:49 +01:00
Jordan
cb6e200ca6
Use the correct CuboidRegion constructor to prevent clipboard height being limited when loading schematics (#1798)
Use the correct CuboidRegion constructor to prevent clipboard height being limited when loading schematicsd
 - Fixes #1757
2022-06-15 13:37:32 +02:00
Jordan
ea434163c4
Only create entities during a restore if they are contained by the region and the editsession's mask (#1800) 2022-06-15 13:37:20 +02:00
Alexander Brandes
5b2f8502fb
fix: Run GriefPrevention region check in sync (#1804)
* fix: Run GP check in sync

Fixes #1692

* refactor: Sync on last condition only
2022-06-15 13:37:08 +02:00
Alexander Brandes
1a3b0dc133
chore: Rename legacy adapters artifact to improve matching with FAWE (#1813)
chore: Rename adapters artifact
2022-06-14 23:59:53 +02:00
dordsor21
111d604075
Follow up to 39e1a811f7 to fix DOC loading 2022-06-14 17:20:59 +01:00
Alexander Brandes
aae696686d
fix: Don't export Paster transitively on the core module (#1808) 2022-06-14 17:02:11 +02:00
Alexander Brandes
8a85225523
fix: Suppress Tuinity light exception on 1.16 (#1801)
* fix: Suppress Tuinity light exception on 1.16

Fixes #1591

* chore: mv'd to the right directory
2022-06-14 09:21:31 +02:00
Owen
39e1a811f7
Don't apply offset to SimpleClipboard (#1751)
* Fix offset

* Don't apply offset in SimpleClipboard

Co-authored-by: Alexander Brandes <mc.cache@web.de>
2022-06-13 23:42:50 +02:00
Jordan
b797655d0c
Only implement cache to MaskingExtent when off main thread (#1789)
* Only implement cache to MaskingExtent when off main thread
 - It's possible for a [Chunk/Char]FilterBlock to be used multiple times in the same "tree" of method calls meaning the mutable paramets (particularly index) get increased within a loop, causing AIOOBs and other issues
 - This is only possible on the main thread due to the handling of submissions in SingleThreadQueueExtent, as it ensures all operation remains on the main thread to prevent deadlocks
 - Therefore safe usage of FilterBlocks requires that main-threaded operation create a new [Chunk/Char]FilterBlock instance each time
 - Further fixes #1681

* Fix typos

* Switch to LongFunction
2022-06-13 23:42:40 +02:00
Jordan
97ab47c90b
Command block messages should be sent on the main thread as it causes a block update (#1796)
- Fixes #1786
2022-06-13 23:42:26 +02:00
dordsor21
f8583fb7cb
Remove erroneous world height 256 limit 2022-06-13 15:11:39 +01:00
Alexander Brandes
a6b1b411d5
chore: Update upstream
3433e40 Fix CB watchdog, fail early if it breaks
2022-06-13 15:09:24 +02:00
Alexander Brandes
99a57f31b2
[ci skip] chore: Exclude doctools dependencies
Closes #1795
2022-06-13 09:07:47 +02:00
Jordan
63f031b01a
Only synchronise tree generation at the very lowest level (#1788)
* Only synchronise tree generation at the very lowest level
 - Fixes #1681

* Perform the generate inside try-finally and actually use the resultant copied map to place blocks to the editsession

* Check result of generateTree and return null if failed
2022-06-13 09:05:18 +02:00
Jordan
02a6bb9b27
Implement limits to image size and load times (#1790)
* Implement limits to image size and load times
 - Prevents issues caused by users attempting to load large images
 - Implements #1729

* Check dimensions given before attempting to load image
2022-06-13 09:04:59 +02:00
renovate[bot]
8377b0987c
[ci skip] build: Update dependency com.github.TownyAdvanced:Towny to v0.98.2.3 (#1791)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-06-13 09:04:30 +02:00
renovate[bot]
ab4f779445
[ci skip] build: Update dependency io.papermc.paperweight.userdev:io.papermc.paperweight.userdev.gradle.plugin to v1.3.7 (#1792)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-06-13 09:04:13 +02:00
Alexander Brandes
ccc936534b
[ci skip] chore: Update renovate ignores
Closes #1794
2022-06-13 09:03:17 +02:00
renovate[bot]
c3cb2c5ed7
[ci skip] build: Update dependency net.minecrell.plugin-yml.bukkit to v0.5.2 (#1793)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-06-13 09:01:54 +02:00
Alexander Brandes
c62f0c197f
build: Back to snapshot for development 2022-06-10 23:45:42 +02:00
Alexander Brandes
e54cae33f1
build: Release 2.3.0 2022-06-10 23:34:05 +02:00
Alexander Brandes
aa94612b70
feat: Add support for 1.19 (#1783)
* feat: Add support for 1.19

* build: Update paperweight version

* fix: obfuscated names, invalid method signatures

* avoid NPE on config access

* build: Update paperweight

* implement no-op light engine to avoid stalled tasks that never complete

* Apply DelegateSemaphore fixes to 1.19 (#1782)

* Apply DelegateSemaphore fixes to 1.19

* Fixes

* Avoid using PalettedContainerRO#recreate as much as possible. Show an error or warning when we're forced to use it to help fix (#1784)

Co-authored-by: Pierre Maurice Schwang <mail@pschwang.eu>
Co-authored-by: SirYwell <hannesgreule@outlook.de>
Co-authored-by: Jordan <dordsor21@gmail.com>
2022-06-10 23:22:06 +02:00
Jordan
da3fc2e6ea
Fix DelegateSemaphore synchronisation issues on Spigot (#1781)
* Fix DelegateSemaphore synchronisation issues on Spigot
 - Also effectively nullify it on paper - the synchronisation on the object is enough

* Remove unneeded imports
2022-06-10 19:50:16 +02:00
Alexander Brandes
7f8ce69563
[ci skip] docs: Add 1.19 to the issue template
Touches #1780
2022-06-10 15:39:00 +02:00
Alexander Brandes
3ec17f3507
chore: Drop WEManager#cancelEditSafe() logger (#1779) 2022-06-10 01:26:59 +02:00
Alexander Brandes
c5a50179f2
[ci skip] build: Switch to bom (#1778)
* build: Switch to bom

* chore: Use javax over checkerframework
2022-06-10 01:26:48 +02:00
Alexander Brandes
d7d43869e6
chore: Update upstream
31e5298 Fixed //stack erroring when given a count of 0 (2108)
2022-06-10 01:05:51 +02:00
Alexander Brandes
9b3608aada
chore: Update upstream
c515eb5 Cache properties to reduce startup memory (2103)
2022-06-10 01:02:03 +02:00
Jordan
0b33fa8757
Allow NBT stored in DiskOptimizedClipboards to be written to disk as a compressed byte array at the end of the file (#1745)
* Allow NBT stored in DiskOptimizedClipboards to be written to disk as a compressed byte array at the end of the file

* Add some deprecations/javadocs and provide the expected clipboard version on error

* Javadoc since tags and add location of clipboard folder to error

* Refactor load-from-file method into DOC class

* Refactor nbt loading code into separate method in DOC
2022-06-09 12:48:35 +02:00
Owen
af234b284b
Add block break effect to area pickaxe (#1770)
* Add block break effect to area pickaxe

* Create pos lower

* Check before queueing block effect

* comment
2022-06-09 12:48:24 +02:00
Owen
a16074cbe4
Fix //snowsmooth not working below Y0 (#1769)
* Use min y instead of 0 for SnowHeightMap

* Correctly handle rounding for height

* Revert old fix

* Use y instead of newHeight

* Remove line diff
2022-06-07 12:06:03 +02:00
renovate[bot]
d5a84d6e44
build: Update dependency org.mockito:mockito-core to v4.6.1 (#1773)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-06-06 09:49:00 +02:00
Jordan
32231b48fe
Avoid int overflow when using fillr in negative coords (#1711)
Fix int overflow when using fill and fillr in negative y-coordinates
2022-06-05 20:52:36 +02:00
Jordan
198c6b7800
Some fixes and improvements to internal queuing (#1715)
* the set array given in NMSAdapter should have get data written to it
 - Fixes #1664
 - May fix #1700

* Having target size >= 2* parallel threads allows for adjacent chunks to be loaded with issues

* "empty" chunk section doesn't need to be localised to the chunk and may be static

* Switch to slightly more performant stream method for testing for non-empty sections

* Implement lock into ChunkHolder preventing any modification to occur whilst the edit is being applied to the world
 (when ChunkHolder is called)

* Add config note about target-size

* set ordinal equal to air if both set and get are `__reserved__`

* Add note to checkAndWaitOnCalledLock method of its use

* Don't print exception and throw

* Switch to a wrapped StampedLock allowing reentrant behaviour
 - StampedLock is not reentrent
 - Allow unlock from a different thread only if it provides the correct stamp
 - This stamp can only be retrieved by the thread owning the lock

* Avoid some "doubling-up" of using checkAndWaitOnCalledLock

* Unbloat `checkAndWaitOnCalledLock`

* Add since tags
2022-06-05 20:52:28 +02:00
Jordan
8228b798e5
Implement biomes to filter blocks and use in Clipboard pasting (#1743)
- Fixes #1741
2022-06-05 20:52:14 +02:00
renovate[bot]
02eea35c3f
[ci skip] build: Update dependency com.github.TownyAdvanced:Towny to v0.98.2.2 (#1766)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-05-31 18:13:02 +02:00
Alexander Brandes
9804158865
[ci skip] chore: Update renovate schedule 2022-05-31 00:28:11 +02:00
renovate[bot]
69eae2e4bd
[ci skip] build: Update dependency org.mockito:mockito-core to v4.6.0 (#1765)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-05-30 13:59:56 +02:00
renovate[bot]
f9c56d94c5
[ci skip] build: Update dependency com.github.TownyAdvanced:Towny to v0.98.2.1 (#1764)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-05-30 13:58:43 +02:00
Alexander Brandes
a43fa912d6
[ci skip] build: Update renovate schedule 2022-05-30 13:57:26 +02:00
Alexander Brandes
8f01a5e4be
[ci skip] feat: Update Readme SVG (#1763) 2022-05-30 13:47:36 +02:00
renovate[bot]
6bb58dc113
[ci skip] build: Update dependency com.github.TownyAdvanced:Towny to v0.98.1.13 (#1759)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-05-23 13:10:57 +02:00
BlockyTheDev
d1f3ac8f76
chore: Update PaperMC repository URL (#1756)
* Migrate PaperMC Repository Endpoints

* Migrate PaperMC JavaDocs endpoints
2022-05-21 12:08:10 +02:00
Alexander Brandes
14811169e3
[ci skip] Attach assets to GH releases (#1754)
* ci: Upload release assets

* chore: Update workflow name
2022-05-19 16:17:45 +02:00
Alexander Brandes
ace325a90e
build: Back to snapshot for development 2022-05-18 21:58:07 +02:00
Alexander Brandes
3a65c64977
chore: Use correct since annoation dates 2022-05-18 21:50:20 +02:00
Alexander Brandes
3c4695bb73
build: Release 2.2.0 2022-05-18 21:46:22 +02:00
renovate[bot]
0d2ed796d8
build: Update release-drafter/release-drafter action to v5.20.0 (#1748)
* build: Update release-drafter/release-drafter action to v5.20.0

* Update release-drafter.yml

Co-authored-by: Renovate Bot <bot@renovateapp.com>
Co-authored-by: Alexander Brandes <mc.cache@web.de>
2022-05-18 17:21:27 +02:00
Jordan
84f975559c
[ci skip] Add jenkins to downloads list (#1750) 2022-05-18 17:20:41 +02:00
Pierre Maurice Schwang
39d77091d9
Don't error when loading a schematic fails (#1744)
fix: Throwable#getMessage may be null
2022-05-16 13:23:21 +01:00
Alexander Brandes
2c1ffd4ef4
Ignore .DS_Store files (#1746)
chore: Ignore ds store files
2022-05-15 12:30:39 +02:00
Jordan
deaf5ad2d6
Respect clipboard settings (disk vs memory) when loading a schematic (#1742) 2022-05-14 21:10:13 +01:00
Jordan
1c7643bb58
Allow use of BlockVectorSet for large //line selections instead of LocalBlockVectorSet (#1713) 2022-05-11 13:22:10 +01:00
dordsor21
059c5f046d
"Empty" side effects is default, and default does "apply" side effects 2022-05-10 17:28:09 +01:00
Jordan
b237ddf076
Cherry pick upstream commits to fix SideEffectSet (#1737)
* Fix SideEffectSet.none() being the default set (#1620)

* Fix SideEffectSet.none() being the default set

* Remove the unnecessary private empty constructor for SideEffectSet

* Back to ImmutableMap.of

* Speed up Fast Reorder Mode and make it default (#1653)

* Speed up Fast Reorder Mode and make it default

* Make non-exposed side effects internal

* Docs on isExposed

Co-authored-by: Matthew Miller <mnmiller1@me.com>
2022-05-10 10:11:12 +02:00
Jordan
d7543884a5
Check cached bukkit player is the same as the current player online (#1732)
* Check cached bukkit player is the same as the current player online
 - If plugins do silly things like teleport, deop (anything that requires a perm-recheck) (anything that ultimately requires a BukkitPlayer at some point) then the retention of metadata by the server (as it's stored based on a string value indescriminate of player a player relogging) means that a BukkitPlayer caching an old player object will be kept, cached and retrieved by FAWE. Adding a simple memory-based equality check when the player rejoins, and then "invaliding" (redoing) the cache if the players are not equal, fixes this.
 - Fixes #1730

* Address comments

* Add comment explaining reference equality check to code
2022-05-10 10:10:59 +02:00
renovate[bot]
ec97fca440
build: Update dependency org.mozilla:rhino-runtime to v1.7.14 (#1733)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-05-09 18:55:39 +02:00
renovate[bot]
ffeb940aff
build: Update plotsquared to v6.7.0 (#1739)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-05-09 16:20:59 +02:00
renovate[bot]
776dc3b69d
build: Update dependency com.github.TownyAdvanced:Towny to v0.98.1.12 (#1735)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-05-09 16:18:32 +02:00
Jordan
267dc153f0
Don't initialise a DiskOptimisedClipboard before checking for an existing one in the LocalSession when using loadClipboardFromDisk (#1731) 2022-05-09 12:50:19 +01:00
Alexander Brandes
b85888806a
[ci skip] chore: Update my name 2022-05-07 16:14:40 +02:00
Jordan
210ee9f2ef
Implement getNameUnsafe method to allow an unloaded world's name to be accessed (#1712)
* Implement getNameUnsafe method to allow an unloaded world's name to be accessed
 - Fixes #1671 and #504

* Add javadoc since tag

Co-authored-by: Alexander Brandes <mc.cache@web.de>

Co-authored-by: Alexander Brandes <mc.cache@web.de>
2022-05-05 21:39:45 +02:00
renovate[bot]
c1b5f8c84a
[ci skip] build: Update org.antlr to v4.10.1 (#1699)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
Co-authored-by: Alexander Brandes <mc.cache@web.de>
2022-05-03 10:06:46 +02:00
renovate[bot]
a51bc6eab3
build: Update dependency org.checkerframework:checker-qual to v3.22.0 (#1728) 2022-05-03 09:59:19 +02:00
renovate[bot]
091d64f723
[ci skip] build: Update dependency com.github.TownyAdvanced:Towny to v0.98.1.11 (#1727)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-05-02 12:40:48 +02:00
renovate[bot]
546e42aab5
[ci skip] build: Update dependency com.github.TownyAdvanced:Towny to v0.98.1.10 (#1723)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-04-30 14:14:29 +02:00
renovate[bot]
617b0ac95c
[ci skip] build: Update dependency io.papermc.paperweight.userdev:io.papermc.paperweight.userdev.gradle.plugin to v1.3.6 (#1720)
* build: Update dependency io.papermc.paperweight.userdev:io.papermc.paperweight.userdev.gradle.plugin to v1.3.6

* build: Update paperweight

Co-authored-by: Renovate Bot <bot@renovateapp.com>
Co-authored-by: NotMyFault <mc.cache@web.de>
2022-04-25 17:17:23 +02:00
renovate[bot]
a227e2618f
[ci skip] build: Update dependency com.github.TownyAdvanced:Towny to v0.98.1.9 (#1719)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-04-25 16:55:20 +02:00
renovate[bot]
3a22389d35
[ci skip] build: Update dependency org.mockito:mockito-core to v4.5.1 (#1721)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-04-25 16:23:27 +02:00
Jordan
e294245ec4
Fix some horrendous code where methods supposed to return a boolean only ever return true (#1718) 2022-04-24 18:03:40 +02:00
dordsor21
82ba96bf71
Add constraints to //asc and //desc 2022-04-24 00:11:57 +01:00
Octavia Togami
f2df511263
Bump paperdev 1.17.1 version (fixes yarn dependency resolution) 2022-04-23 14:39:26 +01:00
Alexander Brandes
3f970cdaef
Rename codeql.yml to codeql.yml.disabled 2022-04-21 13:11:39 +02:00
Jordan
65349392a6
Set empty block count when using fastmode on 1.17 (#1710)
* Set empty block count when using fastmode on 1.17
Fixes #1666

* Update legacy adapters
2022-04-21 13:11:23 +02:00
dordsor21
f5ef0cadb6
Clean up remaining byte casts from 39081e62c9 2022-04-20 23:47:09 +01:00
NotMyFault
c94cbf25a6
build: Back to snapshot for development 2022-04-19 09:14:45 +02:00
NotMyFault
9fdce09a4c
build: Release 2.1.2 2022-04-19 09:04:35 +02:00
Orlaando
3610af15e8
Show number of affected blocks in //set command (#1703)
* Show # of blocks affected in //set

* Fix typo

* fix: Add amount of blocks affected to strings.json

Co-authored-by: NotMyFault <mc.cache@web.de>
2022-04-19 08:55:19 +02:00
Alexander Brandes
27ee46047e
style: Emphasize project icon in idea selection (#1708) 2022-04-19 00:49:39 +02:00
renovate[bot]
ebf84c523c
[ci skip] build: Update dependency com.github.TownyAdvanced:Towny to v0.98.1.8 (#1707)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-04-18 21:58:46 +02:00
Pierre Maurice Schwang
bb71a18c8c
fix: update adapters (FastAsyncWorldEdit-Adapters#67) (#1706) 2022-04-18 21:58:02 +02:00
renovate[bot]
4fd676b931
build: Update dependency com.github.TownyAdvanced:Towny to v0.98.1.7 (#1705)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-04-18 09:19:05 +02:00
Pierre Maurice Schwang
6e26741fdc
fix: respect block categories in RichMaskParser (#1694) 2022-04-11 13:59:54 +02:00
Hannes Greule
8f1ca48bfc
lock is in PalettedContainer in 1.17 (#1697) 2022-04-11 13:59:37 +02:00
renovate[bot]
a9e43a6d78
[ci skip] build: Update dependency com.github.TownyAdvanced:Towny to v0.98.1.6 (#1698)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-04-11 13:59:21 +02:00
Pierre Maurice Schwang
2483eacff5
Fix memory leak by Citizen NPCs (#1693)
* fix: ignore uuid v2 for BukkitPermissionAttachmentManager

Fixes a memory leak that attaches and caches PermissionAttachments to NPCs. Citiziens uses version 2 UUIDs, which are not used for regular player uuids. Those v2 uuids are now excluded.

* fix: create Permission when required

* fix: use citizens documented way to check for NPCs
2022-04-06 16:22:53 +02:00
renovate[bot]
ed9317b4d6
build: Update dependency org.checkerframework:checker-qual to v3.21.4 (#1689)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-04-04 19:38:43 +02:00
renovate[bot]
9d56275247
[ci skip] build: Update actions/setup-java action to v3.1.0 (#1690)
* build: Update actions/setup-java action to v3.1.0

* Update build.yml

Co-authored-by: Renovate Bot <bot@renovateapp.com>
Co-authored-by: Alexander Brandes <mc.cache@web.de>
2022-04-04 15:17:09 +02:00
renovate[bot]
ffea228b52
build: Update dependency gradle to v7.4.2 (#1688)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-04-04 15:14:43 +02:00
renovate[bot]
569f3dc504
build: Update com.plotsquared to v6.6.2 (#1687)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-04-04 14:53:55 +02:00
NotMyFault
d26e15b6da
build: Back to snapshot for development 2022-04-04 13:53:15 +02:00
Alexander Brandes
90e77e5074
Update bug_report.yml 2022-04-04 13:20:08 +02:00
NotMyFault
93846fabaf
build: Release 2.1.1 2022-04-04 13:15:56 +02:00
Kekschen
f477120661
Remove unused 'listeningImages' variable. (#1684) 2022-04-02 22:00:57 +02:00
Hannes Greule
a240b002de
simplify biome id logic (#1677)
Co-authored-by: Alex <mc.cache@web.de>
2022-04-01 19:25:48 +02:00
NotMyFault
4970db0405
chore: Use assets for 1.18.2 2022-03-29 12:53:19 +02:00
Pierre Maurice Schwang
2276d82d2c
//regen creates vanilla decorations without error (#1650)
* fix: Feature placement on regen should create chunk

* feat: update adapter jar

* fix: update adapter jar
2022-03-28 21:06:26 +02:00
Hannes Greule
c45b14a52d
Avoid Unsafe on paper (#1678) 2022-03-27 23:56:59 +02:00
Pierre Maurice Schwang
d1588f9207
Fix tabcomplete for random pattern / multiple pattern (#1675)
* Merge RandomPatternParser#getSuggestions with upstream

* fix: don't throw AIIBE if patterns are empty

shouldn't be the case in the first place
2022-03-27 09:46:36 +02:00
Jordan
465c81d193
Remove hardcoding of heightmap compressed long size (#1668) 2022-03-18 21:28:25 +00:00
Alex
05f80f23b9
refactor!: Don't bundle 1.15.2 adapters anymore (#1656) 2022-03-17 09:41:50 +01:00
renovate[bot]
fbb25f289b
[ci skip] build: Update actions/checkout action to v3 (#1663)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-03-14 18:52:53 +01:00
NotMyFault
07bc33b52b
[ci skip] build: Ignore kyori updates until P2 supports 4.10 2022-03-14 16:20:31 +01:00
renovate[bot]
c672d7a0b3
build: Update dependency net.kyori:adventure-nbt to v4.9.3 (#1658)
* build: Update dependency net.kyori:adventure-nbt to v4.10.1

* build: Provide proper adventure version

Co-authored-by: Renovate Bot <bot@renovateapp.com>
Co-authored-by: NotMyFault <mc.cache@web.de>
2022-03-14 16:14:10 +01:00
renovate[bot]
6435fd3bea
build: Update dependency gradle to v7.4.1 (#1657)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-03-14 14:32:52 +01:00
renovate[bot]
8afde807b6
build: Drop ProtocolLib dependency (#1659)
* build: Update dependency com.comphenix.protocol:ProtocolLib to v4.8.0

* build: Drop ProtocolLib dependency

Co-authored-by: Renovate Bot <bot@renovateapp.com>
Co-authored-by: NotMyFault <mc.cache@web.de>
2022-03-14 14:32:27 +01:00
renovate[bot]
ebd7c136fd
build: Update dependency org.mockito:mockito-core to v4.4.0 (#1660)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-03-14 14:23:29 +01:00
Jordan
1708584e8d
Don't call ticking_list on Spigot (#1655)
* ticking_list is paper only

* Update adapters
2022-03-14 11:08:10 +01:00
NotMyFault
d400a470a1
Update upstream
5843aa5 Change vector command converter wording. (2059)
2022-03-13 19:19:59 +01:00
Jordan
5a97b23347
Don't error when adding processors to NullExtent, simply do nothing (#1654) 2022-03-13 18:35:27 +01:00
dordsor21
d8c0f8e3b1
Make sure thread-cached arrays are reset 2022-03-13 01:44:59 +00:00
NotMyFault
7ba185c4ac
build: Back to snapshot for development 2022-03-10 23:16:30 +01:00
NotMyFault
95512a4c0b
build: Release 2.1.0 2022-03-10 22:57:23 +01:00
NotMyFault
c3cdde9d2e
build: Update paperweight 2022-03-10 22:43:33 +01:00
Jordan
e9db749e2f
Add fluid ticking and refactor post-processing a bit (#1554)
* Make postProcessSet a default method and change to void

* Throwable#getMessage is nullable

* Move (re-)ticking to a post-processor per "platform"
 - Add fluid ticking

* chore: Ignore (for us) irrelevant rules

* chore: Fix correct toml syntax?

* Re-add removed method for API-compliance and refactor it to have a use

* Switch to javax annotations

* Switch to recalcBlockCounts for ticking blocks.

* No need to set air count anymore either

* We can still "not tick" in fast mode in 1.17.2

* update adapters

* Let paper create the chunk section if biomes are null

* Adjust notes to settings

* 1.17.2 didn't exist

* Add 1.18.2

* Don't attempt to cache plains biome ID

* Use correct annotation

Co-authored-by: NotMyFault <mc.cache@web.de>
2022-03-10 15:27:25 +01:00
Alex
5d18e15128
Replace JB occurrences with JSR 305 (for now) (#1651)
* refactor: Replace JB occurrences with JSR 305 (for now)

* chore: Update adapter jar
2022-03-10 14:24:44 +01:00
Jordan
f59353006a
Update to P2 extended heights (#1581) 2022-03-09 14:21:58 +01:00
NotMyFault
3ee9797408
build: Misc dependency updates 2022-03-08 20:51:17 +01:00
Pierre Maurice Schwang
49bc675f51
Fix //regen -b on 1.18.2 (#1647)
* fix: adapt correct biome type

* fix: PaperweightPlatformAdapter#adapt should return BiomeType
2022-03-08 18:55:52 +01:00
NotMyFault
fb66ba6adf
build: Update paperweight
Closes #1649
2022-03-07 21:20:25 +01:00
renovate[bot]
5e4143c1dc
[ci skip] build: Update dependency com.sk89q.worldguard:worldguard-bukkit to v7.0.7 (#1648)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-03-07 21:18:21 +01:00
Alex
345785a25e
feat: Support for 1.18.2 (#1641)
* feat: Preliminary work for 1.18.2

* Update SpigotNames to 1.18.2 (#1642)

* 1.18.2 / Biome-Holders, regeneration (#1645)

* 1.18.2 / Biome-Holders, regeneration

* fix: reuse old structure sets

* build: Update dev bundles

* fix: Don't log regen world generation

* fix: Run DataConverter with CBT

* fix: Override `#toNativeBinary`

* fix: Exception on regen

Co-Authored-By: Pierre Maurice Schwang <mail@pschwang.eu>

* refactor: Minor cleanup

Co-authored-by: Aurora <21148213+aurorasmiles@users.noreply.github.com>
Co-authored-by: Pierre Maurice Schwang <mail@pschwang.eu>
2022-03-07 15:20:05 +01:00
Pierre Maurice Schwang
668227ee6c
Update Upstream (#1643)
44863cf Don't access PluginClassLoader directly (#2045)
2022-03-05 18:19:58 +01:00
Alex
44078d1820
[ci skip] Update issue templates for 1.18.2 2022-03-04 13:25:42 +01:00
renovate[bot]
4ffea67514
build: Update dependency net.kyori:adventure-nbt to v4.10.0 (#1638)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-03-04 00:22:01 +01:00
NotMyFault
dafcd16a14
Update Upstream
eac5b51 Play dirty because bukkit classloading is bad. (2043)
2022-03-02 20:48:49 +01:00
NotMyFault
a23785632a
build: Address Gradle 7.4 deprecations 2022-02-28 15:44:05 +01:00
NotMyFault
7db06061f0
Update upstream
e2ab12c Change the class source validator to use classloaders for detection. (2039)
2022-02-28 15:42:03 +01:00
Alex
340f8dded3
tests: Remove stub server (#1629) 2022-02-28 13:53:08 +01:00
renovate[bot]
c5d70f0da1
build: Update dependency com.github.TechFortress:GriefPrevention to v16.18 (#1635)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-02-28 12:43:25 +01:00
renovate[bot]
be83c6ec70
build: Update com.plotsquared to v6.5.1 (#1633)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-02-28 10:56:22 +01:00
Jordan
dec0373081
Fix 1.17 snapshot restoration (#1632) 2022-02-27 21:20:16 +00:00
Alex
081d8ddb50
ci: Bump actions/setup-java to 3.0.0 (#1631) 2022-02-25 22:53:39 +01:00
Jordan
b8ab2a5204
Don't allow heightmap-based brushes to edit the entire world "depth" (#1617)
Fixes #1614

Co-authored-by: Alex <mc.cache@web.de>
2022-02-24 10:33:37 +01:00
Jordan
fc2662e51e
Fix //snapshot in 1.18 and re-implement biome/entity restoration (#1620)
* Re-add "//snap" and "//snapshot"

* Place code in correct method

* Use CompoundBinaryTags in AnvilChunk18 and implement biome/entity restoration

* Address comments

* Fix biome reading

* Fix retrieval of entities from zipped snapshot world

Co-authored-by: Alex <mc.cache@web.de>
2022-02-24 10:33:25 +01:00
Jordan
49d5183685
Load legacy config file before firing PlatformsRegisteredEvent (#1623)
Fixes #1622

Co-authored-by: Alex <mc.cache@web.de>
2022-02-24 10:33:06 +01:00
Jordan
28a0239437
Fix clipboards to allow proper heights by allowing extended CuboidRegion heights (#1624)
* Fix clipboards to allow proper heights by allowing extended CuboidRegion heights
Fixes #1534

* Add @since

* Fix javadoc comment

Co-authored-by: Alex <mc.cache@web.de>
2022-02-24 10:32:45 +01:00
NotMyFault
0a04b0b4cd
tests: Fix StubServer 2022-02-23 11:25:10 +01:00
NotMyFault
77b41e052a
Revert "build: Update dependency org.ajoberstar.grgit:grgit-gradle to v5 (#1611)"
This reverts commit cf0a21d

Apparently that doesn't integrate that seamless in all environments.
2022-02-23 11:15:01 +01:00
Alex
23b5f0cb4a
[ci skip] GitHub does now allow you to rebase PRs straight away 2022-02-21 00:52:22 +01:00
NotMyFault
f8e6feb1f2
Update upstream
17b9f00 Move tinyurls to ehub.to (2033)
76ec878 Allow biome commands to be used from non-player actors (2034)
2022-02-20 14:18:58 +01:00
Jordan
39081e62c9
byte cannot be used to represent height anymore (#1618)
Fixes #1593
2022-02-17 19:34:25 +01:00
Jordan
f7a0c14a1b
Correctly use getNearestSurfaceTerrainBlock in SurfaceSpline and SchemGen (#1616)
Fixes #1609
2022-02-17 19:34:07 +01:00
dordsor21
3f28a5759d
Make slope method slightly more readable in AngleMask 2022-02-16 18:18:58 +00:00
dordsor21
a40d1ccf51
Better naming for min position in HeightMap 2022-02-16 18:13:04 +00:00
dordsor21
fbe0c08c26
FAWE HeightMap constructor shouldn't be deprecated 2022-02-16 18:02:20 +00:00
dordsor21
05bd84b504
Don't crazily initialise HeightMapFilter...?? 2022-02-16 17:47:43 +00:00
dordsor21
3e85369765
Make angle pattern slope a little more readable 2022-02-16 17:42:22 +00:00
renovate[bot]
cf0a21d312
build: Update dependency org.ajoberstar.grgit:grgit-gradle to v5 (#1611)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-02-14 13:12:46 +01:00
renovate[bot]
b1a93766d3
build: Update com.plotsquared to v6.5.0 (#1610)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-02-14 12:00:32 +01:00
Pierre Maurice Schwang
f657a80dc6
fix: set size of MappedByteBuffer accordingly (#1608) 2022-02-13 13:57:19 +01:00
dordsor21
de4f73997e
Implement missing methods in tests 2022-02-12 13:38:04 +00:00
Pierre Maurice Schwang
646a683f22
fix: add coordinates to tile-entity nbt component (#1607) 2022-02-12 13:38:37 +01:00
NotMyFault
7da993d3f1
build: Update gradle 2022-02-09 23:35:13 +01:00
renovate[bot]
7e17a5cbd1
[ci skip] build: Update release-drafter/release-drafter action to v5.18.1 (#1603)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-02-07 10:34:27 +01:00
renovate[bot]
cf1e61c153
build: Update dependency org.checkerframework:checker-qual to v3.21.2 (#1602)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-02-07 10:34:13 +01:00
NotMyFault
15b9b8332c
fix: Make it build again 2022-02-04 11:24:11 +01:00
NotMyFault
d80bfc7495
docs: Update wiki link 2022-02-04 11:16:23 +01:00
NotMyFault
2bb72ebfea
[ci skip] ci: Don't run actions twice 2022-01-31 21:13:44 +01:00
renovate[bot]
faa2477305
build: Update org.bstats to v3 (#1589)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-01-31 13:00:09 +01:00
renovate[bot]
186386ce4a
build: Update dependency org.mockito:mockito-core to v4.3.1 (#1587)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-01-31 10:29:09 +01:00
renovate[bot]
d3f8a3beb3
build: Update dependency io.papermc.paperweight.userdev:io.papermc.paperweight.userdev.gradle.plugin to v1.3.4 (#1586)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-01-31 10:28:05 +01:00
NotMyFault
f0136460ba
Update upstream
ab31481 Use Chunk#getNoiseBiome instead of biome container (2025)
2022-01-30 21:18:40 +01:00
NotMyFault
38b0dcf7e4
Update upstream
e485433 Fix legacy error message output for WorldGuard commands (2023)
2022-01-30 19:54:50 +01:00
Jordan
178604bbb7
Only call org.bukkit.World height methods if they're present (1.17+) (#1551)
* Only call org.bukkit.World height methods if they're present (1.17+)

* Switch to WorldEdit get height methods in GPFeature
2022-01-29 13:12:16 +01:00
Alex
4610688fcb
fix: Debugpaste on 1.17 and lower due GSON incompatibility (#1583) 2022-01-28 22:15:24 +01:00
NotMyFault
15076f3d93
[ci skip] docs: Update documentation for Java 17 2022-01-27 21:04:22 +01:00
NotMyFault
272920fb25
build: Back to snapshot for development 2022-01-27 16:06:40 +01:00
NotMyFault
a0b61512fb
build: Release 2.0.1 2022-01-27 15:52:23 +01:00
NotMyFault
e309cf8f3c
build: Update PlotSquared 2022-01-27 15:30:18 +01:00
renovate[bot]
0f524e665b
[ci skip] build: Update dependency org.mockito:mockito-core to v4.3.0 (#1563)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-01-24 16:14:07 +01:00
Alex
e8f72d6521
fix: Deduplicate error messages (#1557)
Fixes https://github.com/IntellectualSites/FastAsyncWorldEdit/issues/1535
2022-01-24 12:52:33 +01:00
renovate[bot]
c461674402
build: Update release-drafter/release-drafter action to v5.17.6 (#1562)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-01-24 11:05:47 +01:00
ahdg
806ca62485
fix: GriefDefender filter (#1546)
* Fix: GriefDefender filter

* Update libs.versions.toml

* Now it only work with 2.1.0.
2022-01-23 18:29:01 +01:00
Alex
016b4ba81d
fix: Unify superpickaxe behavior (#1553)
Fixes https://github.com/IntellectualSites/FastAsyncWorldEdit/issues/1547
2022-01-21 14:41:24 +01:00
NotMyFault
d17e3a6555
chore: Add missing Fawe annotations to //regen command 2022-01-19 13:58:52 +01:00
NotMyFault
4d2a34fd21
refactor: Update upstream
0ad3ab1 Remove extra label from bukkit command usage string.
2022-01-17 13:20:16 +01:00
renovate[bot]
96805b85b5
build: Update release-drafter/release-drafter action to v5.17.5 (#1549)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-01-17 11:02:21 +01:00
dordsor21
d3696f91d4
Synchronise access to the PriorityQueue used for effect queuing in AbstractWorld
- Makes it thread-safe
2022-01-15 17:09:49 +00:00
NotMyFault
0ccae19ded
refactor: Update javaodc url 2022-01-14 15:34:04 +01:00
NotMyFault
f077ec9163
build: Back to snapshot for development 2022-01-14 14:54:37 +01:00
NotMyFault
2c4453b68f
build: Release 2.0.0 2022-01-14 13:53:59 +01:00
Jordan
6a972e7b99
Heightmaps used for brushes etc. should be normalised to zero. (#1522)
* Heightmaps used for brushes etc. should be normalised to zero.
Fixes #1508

* chars are unsigned

* Add scale paramer to javadoc
2022-01-14 10:49:23 +01:00
Alex
9e40b972b1
refactor: Put Fawe version information at debugpaste to (#1533) 2022-01-12 01:22:24 +01:00
Alex
6b857b0f58
ci: Cleanup maven repositories (#1526) 2022-01-12 01:21:27 +01:00
renovate[bot]
5fc0de0b82
build: Update actions/setup-java action to v2.5.0 (#1530)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-01-10 11:30:26 +01:00
renovate[bot]
4e2a1c393d
build: Update dependency org.checkerframework:checker-qual to v3.21.1 (#1528)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-01-10 11:27:07 +01:00
NotMyFault
f0f201002a
Update adapters 2022-01-09 11:22:00 +01:00
Alex
9ba90d8c83
refactor: Drop custom snakeyaml implementation (#1523)
* refactor: Drop custom snakeyaml implementation

* Merge branch 'main' into chore/main/remove-snakeyaml-wannabe-abstraction
2022-01-09 10:55:16 +01:00
dordsor21
c2f3c13a09
Fix #1510 2022-01-08 18:10:14 +00:00
dordsor21
4754f660c7
Fix #1524
Also brings in line with upstream
2022-01-08 17:46:28 +00:00
Alex
64442a8051
refactor: Tackle a few Semgrep and ErrorProne violations (#1520)
* refactor: Tackle a few Semgrep and ErrorProne violations

* Address comments
2022-01-07 12:45:53 +01:00
Alex
f27959e49a
[ci skip] Don't run build twice 2022-01-07 10:42:57 +01:00
dordsor21
59d4247ddb
Update legacy adapters 2022-01-05 23:53:02 +00:00
dordsor21
867d4c05cb
Merge branch 'main' of github.com:IntellectualSites/FastAsyncWorldEdit into main 2022-01-05 23:43:31 +00:00
dordsor21
d6695d23f0
Replace remaining instances of worldeditregentempworld 2022-01-05 23:42:57 +00:00
Alex
fe1a77a593
ci: Let release drafter listen to forks too 2022-01-05 23:49:36 +01:00
dordsor21
722c411219
Add workaround for when expressions are parsed in masks/patterns where '&&' is used
Fixes #1517
2022-01-05 17:46:18 +00:00
renovate[bot]
0408cd0575
build: Update dependency gradle.plugin.com.github.johnrengelman:shadow to v7.1.2 (#1513)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-01-05 17:11:06 +01:00
renovate[bot]
318b1ef690
Merge pull request #1512 from IntellectualSites/renovate/com.plotsquared
build: Update com.plotsquared to v6.2.2
2022-01-05 17:10:55 +01:00
NotMyFault
3a78abe273
ci: Change GH action branch 2022-01-05 17:00:42 +01:00
Alex
8b973da7ee
feat!: Update for 1.18 (#1482)
* ci: Switch deployment to gh actions and use semver & java 17

* build: Update core dependencies

- Drop paranamer, you can access parameter names at runtime with Java 8+ natively

* ci: Snapshot builds are the default

* ci: Cleanup and finish transition

* ci: Trigger initial sync with the OSSRH

* revert: OSSRH snapshot deployment was successful, returning to baseline

This reverts commit 3a189f65f2.

* ci: Register javadoc jar for lib artifacts

* ci: Sign artifacts

* build: Set kotlin jvm toolchain

* style: Use minimized `version` output

* feat: Setup project structure for 1.18

* Exclude 1.17

* Port initial paperweight classes to 1.18 folder structure

* Move to Paper 1.18

* Update templates, address JEP deprecations and place a few TODOs

* Drop Guava 21 enforcement

* Make 1.18 to be effectively in a usable state (#1452)

* Update swathes of easy-to-update-sort-of-code.
 - Untested
 - Should compile but NMF broken something
 - Several todos:
  - biome history//better support (move to biome sections in core)
  - regen (haha lol no thanks, someone else can do that)
  - probably actually do the palette stuff that probably won't work in PaperweightPlatformAdapter

* ci: Provide basic Jenkinsfile for ghprb pipeline

* build: Update paperweight

* upstream: Update Upstream

de6fa17 Add getBrush helper for use with instanceof pattern matching (1926)

* FAWE will now load on startup

* it....works?

* Begin to allow biome edits (and fix biomes reverting to plains upon editing blocks)

* Add new blocks/block properties

* Only create biome palette if supplies is null

* Fix biome operations

* Finally get removing BlockID done (major version change allows it)

* refactor!: Drop PlotSquared v4

Fawe 2.0.0 and newer requires Java 17, PlotSquared v4 supports 1.13 and 1.14, Fawe wont work on these versions nevertheless and refuses to load due Java version incompatiblities with older versions. Newer versions can use PlotSquared v6.

* docs: Update readme

* Added and removed some comments

* Added and removed some comments

* refactor: Rename worldedit configuration

* build: Re-add 1.17 module

This the a very nasty commit

* chore: Implement missing methods

* build: Update paperweight

* upstream: Update upstream

6df194e Remove finalize, use a Cleaner instead (1943)
9843a4f Fix snapshots in 1.18 (1959)

* ci: Escape workflows

* build: Update paperweight to 1.18.1

* build: Update Paster

* Fix compilation

* Bump to 1.18.1

* Do both 1.18 and 1.18.1

Co-authored-by: Alex <mc.cache@web.de>

* Fix single-block lookups

* Reserve ordinals 0 through 3 for air/"reserved"

* Create block palette data with values

* Fix classpath for testing for starlight

* Correctly use block rather than sky light layer [not used in paper]

Co-authored-by: NotMyFault <mc.cache@web.de>
Co-authored-by: Matt <4009945+MattBDev@users.noreply.github.com>

* Update version (checking) for semver

* build: Fix release drafter base branch

* Trigger GHPRB

* tests: Add resource pack methods

* build: Update paperweight and add 1.17 again

* chore: Lazily change build delimiter

* build: Deploy API snapshots for 2.0.0

* Update adapters jar

* More verbosely get block data and ensure biome layer isn't null

* refactor: Address a few `TODO 1.18`'s

(cherry picked from commit 0b77932b6e46c825d78b8c7ccae2a68ad890564e)

* fix: Fix `/fawe debugpaste`

* refactor! Remove deprecations marked for removal that are not present in upstream (#1483)

* Reverse a "debug" change to BukkitImplLoader

* Fix parsing of build in FaweVersion

* refactor: Do prepared statements properly

- Update TextureUtil client jar to 1.18.1
- Limit the update checker to our domain

* Add classes with the correct minor version to the start of the adapter candidates list

* refactor: Deprecate `IMP` initializors in favor of builders

* Fix WEManager (#1487)

* Fix WeManager?

* Fix WeManager?

* Also register WEManager if not available, like TaskManager.

* refactor: Also deprecated `IMP` for DBHandler

* feat: Add a bunch of new types to the flora generator

* use spigot-compatible palette constructor

* use spigot-compatible packet constructor

* implement 1.18 regen

* return air instead of reserved on get blocks

* refactor: Shift `FileAlreadyExistsException` catch to a higher level

* read the actual block from ZeroBitStorage

* Add get default version min/max world height to platform
 - Fixes #1500

* Add methods to CLIPlatform

* Fix #1490

* Fix tests

* Don't force tick limiter enable/disable

* Use Math.floor instead of int cast 757bef1f7d2b16317ab3d18427ad22183344e28d

* More precise method names in MinecraftVersion
 - Also ensure correct comparisons are made in FaweBukkit and BukkitServerInterface
 - Fixes #1504

* Add back statically-set reserved IDs for air blocks only, make it clear they're "reserved" (#1502)

* Add back statically-set reserved IDs for air blocks only, make it clear they're "reserved"
Also:
 - Ensure that reserved is never returned in GET block operations
 - "empty" thus doesn't exist in the GET update methods; remove the needless checks
 - Allow GET/SET chunks to determine their own default values for non-present blocks/sections

* Add comments

* Remove mentions of NMS from compilation instruction

* Update log4j version, update jd links to use "latest"

* Move to BinaryTags where appropriate in adapters

* Add comments to changed code

* Rename worldedit to fawe where appropriate

* Use new language features

* chore: Format our loggers properly

* Remove unneeded comments

* Replace CachedChange class with record

* Remove/add some more comments

* Remove remaining keywords frm CachedChanged. IJ doesn't warn?

* Compress switch statements a bit using enhanced

* More enhanced switches

* Refactor: getVersionMin/MaxY -> versionMin/MaxY

* Throw, catch, and rethrow our own exception to make sure we're finding the culprit to a possible shaded-FAWE.

* Don't wrap Exception thrown upon invalid schematic path inside a RuntimeException
Fixes #1506

* docs: Put `since` annotation on newly introduced API

* docs: Drop clarified todos

* Warn user if using small-edit history setting with extended world heights

* Refactor: add javadoc to Clipboard#create and improve variables when delegating to another paste method

* Fix issue with offset/origin when pasting a clipboard via API without wrapping into a BlockArrayClipboard

* build: Remove drop our maven repository

* docs: Fix deprecation tag

* Fix incorrect toNative method in 1.17 adapter

* refactor: Deprecate tick limiter API for public use

* ci: dordsor does love rebasing here too

* docs: Document annotations

* Update upstream

fb5ec19 Fix error for snapshot restore missing chunk

* docs: Document a few undocumented annotations

* feat: Add worldedit.schematic.list.other permission and functionality (#1507)

* Add worldedit.schematic.list.other permission and functionality

* Implement StringMan#containsUuid

* Javadocs

* chore: Add since annotation

Co-authored-by: NotMyFault <mc.cache@web.de>

Co-authored-by: NotMyFault <mc.cache@web.de>
Co-authored-by: Matt <4009945+MattBDev@users.noreply.github.com>
Co-authored-by: Aurélien <43724816+Aurelien30000@users.noreply.github.com>
Co-authored-by: SirYwell <hannesgreule@outlook.de>
Co-authored-by: JOO200 <github@joo200.de>
Co-authored-by: Owen1212055 <23108066+Owen1212055@users.noreply.github.com>
2022-01-05 16:58:30 +01:00
Owen1212055
c27a34ce40
feat: Add worldedit.schematic.list.other permission and functionality (#1507)
* Add worldedit.schematic.list.other permission and functionality

* Implement StringMan#containsUuid

* Javadocs

* chore: Add since annotation

Co-authored-by: NotMyFault <mc.cache@web.de>
2022-01-05 16:21:44 +01:00
NotMyFault
f4658cc668
docs: Document a few undocumented annotations 2022-01-04 21:15:45 +01:00
NotMyFault
ef686af8dd
Update upstream
fb5ec19 Fix error for snapshot restore missing chunk
2022-01-04 21:01:49 +01:00
NotMyFault
631fd3c7f5
docs: Document annotations 2022-01-04 20:57:23 +01:00
NotMyFault
30c2597aad
ci: dordsor does love rebasing here too 2022-01-04 20:33:43 +01:00
NotMyFault
b8399abfe1
refactor: Deprecate tick limiter API for public use 2022-01-04 20:33:05 +01:00
dordsor21
42dacfc7ef
Fix incorrect toNative method in 1.17 adapter 2022-01-04 13:28:29 +00:00
NotMyFault
7e96853b89
docs: Fix deprecation tag 2022-01-01 18:46:28 +01:00
NotMyFault
42d6466a4c
build: Remove drop our maven repository 2021-12-31 17:26:15 +01:00
dordsor21
0994ea1e67
Fix issue with offset/origin when pasting a clipboard via API without wrapping into a BlockArrayClipboard 2021-12-30 16:05:16 +00:00
dordsor21
f30ea96268
Refactor: add javadoc to Clipboard#create and improve variables when delegating to another paste method 2021-12-30 16:04:38 +00:00
dordsor21
9faacb38ef
Warn user if using small-edit history setting with extended world heights 2021-12-30 16:01:23 +00:00
NotMyFault
aaad86cf1d
docs: Drop clarified todos 2021-12-29 18:16:19 +01:00
NotMyFault
122cba677a
docs: Put since annotation on newly introduced API 2021-12-29 18:14:18 +01:00
dordsor21
235d0360da
Don't wrap Exception thrown upon invalid schematic path inside a RuntimeException
Fixes #1506
2021-12-29 16:55:32 +00:00
dordsor21
52fa44516e
Throw, catch, and rethrow our own exception to make sure we're finding the culprit to a possible shaded-FAWE. 2021-12-29 16:47:34 +00:00
dordsor21
9e8f0e7325
Refactor: getVersionMin/MaxY -> versionMin/MaxY 2021-12-29 16:44:41 +00:00
dordsor21
f505828af1
More enhanced switches 2021-12-29 16:44:18 +00:00
dordsor21
8d565b93f7
Compress switch statements a bit using enhanced 2021-12-29 16:39:44 +00:00
dordsor21
867b28d439
Remove remaining keywords frm CachedChanged. IJ doesn't warn? 2021-12-29 16:37:21 +00:00
dordsor21
fd3619f7b5
Merge branch 'major/2.0.0/1.18' of github.com:IntellectualSites/FastAsyncWorldEdit into major/2.0.0/1.18 2021-12-29 16:30:12 +00:00
dordsor21
3a3143065d
Remove/add some more comments 2021-12-29 16:29:55 +00:00
dordsor21
ca5640e89e
Replace CachedChange class with record 2021-12-29 16:16:23 +00:00
dordsor21
e5cbdec67e
Remove unneeded comments 2021-12-29 16:14:13 +00:00
NotMyFault
19de815ab4
chore: Format our loggers properly 2021-12-29 17:13:20 +01:00
dordsor21
e2a1721a5c
Use new language features 2021-12-29 16:12:43 +00:00
dordsor21
0d79d084a5
Rename worldedit to fawe where appropriate 2021-12-29 16:12:16 +00:00
dordsor21
3c2394afa4
Add comments to changed code 2021-12-29 16:06:49 +00:00
dordsor21
f38859237a
Move to BinaryTags where appropriate in adapters 2021-12-29 16:00:49 +00:00
dordsor21
48e2953910
Update log4j version, update jd links to use "latest" 2021-12-29 15:30:25 +00:00
dordsor21
1a281badc2
Remove mentions of NMS from compilation instruction 2021-12-29 15:30:12 +00:00
Jordan
177d731957
Add back statically-set reserved IDs for air blocks only, make it clear they're "reserved" (#1502)
* Add back statically-set reserved IDs for air blocks only, make it clear they're "reserved"
Also:
 - Ensure that reserved is never returned in GET block operations
 - "empty" thus doesn't exist in the GET update methods; remove the needless checks
 - Allow GET/SET chunks to determine their own default values for non-present blocks/sections

* Add comments
2021-12-29 16:17:20 +01:00
dordsor21
bca3a1b04d
More precise method names in MinecraftVersion
- Also ensure correct comparisons are made in FaweBukkit and BukkitServerInterface
 - Fixes #1504
2021-12-29 14:46:30 +00:00
557 geänderte Dateien mit 46038 neuen und 8052 gelöschten Zeilen

Datei anzeigen

@ -7,8 +7,8 @@ body:
attributes: attributes:
value: | value: |
Thanks for taking the time to fill out this bug report for FastAsyncWorldEdit! Fill out the following form to your best ability to help us fix the problem. Thanks for taking the time to fill out this bug report for FastAsyncWorldEdit! Fill out the following form to your best ability to help us fix the problem.
Only use this if you're absolutely sure that you found a bug and can reproduce it. For anything else, use: [our Discord server](https://discord.gg/intellectualsites) or [the wiki](https://github.com/IntellectualSites/FastAsyncWorldEdit-Documentation/wiki). Only use this if you're absolutely sure that you found a bug and can reproduce it. For anything else, use: [our Discord server](https://discord.gg/intellectualsites) or [the wiki](https://intellectualsites.github.io/fastasyncworldedit-documentation/).
Do NOT use the public issue tracker to report security vulnerabilities! They are disclosed using [this](https://forms.gle/btgdRn9yhGtzEiGW8) form! Do NOT use the public issue tracker to report security vulnerabilities! They are disclosed using [this](https://github.com/IntellectualSites/FastAsyncWorldEdit/security/policy) GitHub form!
- type: dropdown - type: dropdown
attributes: attributes:
@ -18,8 +18,6 @@ body:
options: options:
- Paper - Paper
- Spigot - Spigot
- Tuinity
- Purpur
validations: validations:
required: true required: true
@ -29,10 +27,11 @@ body:
description: Which server version version you using? If your server version is not listed, it is not supported. Update to a supported version first. description: Which server version version you using? If your server version is not listed, it is not supported. Update to a supported version first.
multiple: false multiple: false
options: options:
- '1.18.1' - '1.20.1'
- '1.20'
- '1.19.4'
- '1.18.2'
- '1.17.1' - '1.17.1'
- '1.16.5'
- '1.15.2'
validations: validations:
required: true required: true

Datei anzeigen

@ -4,5 +4,5 @@ contact_links:
url: https://discord.gg/intellectualsites url: https://discord.gg/intellectualsites
about: Our support Discord, please ask questions and seek support here. about: Our support Discord, please ask questions and seek support here.
- name: FastAsyncWorldEdit Wiki - name: FastAsyncWorldEdit Wiki
url: https://github.com/IntellectualSites/FastAsyncWorldEdit-Documentation/wiki url: https://intellectualsites.github.io/fastasyncworldedit-documentation/
about: Look at the wiki page for answers for setup instructions command syntax and more. about: Look at the wiki page for answers for setup instructions command syntax and more.

Datei anzeigen

@ -7,7 +7,7 @@ body:
attributes: attributes:
value: | value: |
Thanks for taking the time to fill out this feature request for FastAsyncWorldEdit! Fill out the following form to your best ability to help us understand your feature request and greately improve the change of it getting added. Thanks for taking the time to fill out this feature request for FastAsyncWorldEdit! Fill out the following form to your best ability to help us understand your feature request and greately improve the change of it getting added.
For anything else than a feature request, use: [our Discord server](https://discord.gg/intellectualsites) or [the wiki](https://github.com/IntellectualSites/FastAsyncWorldEdit-Documentation/wiki). For anything else than a feature request, use: [our Discord server](https://discord.gg/intellectualsites) or [the wiki](https://intellectualsites.github.io/fastasyncworldedit-documentation/).
- type: textarea - type: textarea
attributes: attributes:

35
.github/renovate.json vendored Normale Datei
Datei anzeigen

@ -0,0 +1,35 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:base",
":semanticCommitsDisabled"
],
"automerge": true,
"ignoreDeps": [
"guava",
"com.google.guava:guava",
"rhino-runtime",
"org.antlr",
"antlr4-runtime",
"fastutil",
"it.unimi.dsi:fastutil",
"auto-value-annotations",
"auto-value",
"com.google.code.gson:gson",
"net.fabricmc:fabric-loader",
"net.fabricmc.fabric-api:fabric-api",
"com.github.luben:zstd-jni",
"org.jetbrains.kotlin.jvm",
"log4j",
"org.apache.logging.log4j:log4j-api",
"org.apache.logging.log4j:log4j-bom",
"org.apache.logging.log4j:log4j-slf4j-impl",
"org.apache.logging.log4j:log4j-core",
"org.bstats:bstats-sponge",
"org.spongepowered:spongeapi",
"org.yaml:snakeyaml"
],
"labels": ["Renovate"],
"rebaseWhen": "conflicted",
"schedule": ["on the first day of the month"]
}

Datei anzeigen

@ -0,0 +1,28 @@
name: Announce release on discord
#on:
# workflow_run:
# workflows: ["Upload release assets"]
# types:
# - completed
jobs:
send_announcement:
runs-on: ubuntu-latest
steps:
- name: send custom message with args
env:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
DISCORD_USERNAME: FastAsyncWorldEdit Release
DISCORD_AVATAR: https://raw.githubusercontent.com/IntellectualSites/Assets/main/plugins/FastAsyncWorldEdit/FastAsyncWorldEdit.png
uses: Ilshidur/action-discord@0.3.2
with:
args: |
"<@&525015715300900875> <@&706463154804097105> <@&671372968462516240>"
""
"<:fawe:730750370984493106> **FastAsyncWorldEdit ${{ github.event.release.tag_name }} has been released!**"
""
"Click here to view changelog: https://github.com/IntellectualSites/FastAsyncWorldEdit/releases/tag/${{ github.event.release.tag_name }}"
""
"The download is available at:"
"- Spigot: <https://www.spigotmc.org/resources/13932/>"
"- Modrinth: <https://modrinth.com/plugin/fastasyncworldedit/version/${{ github.event.release.tag_name }}>"
"- CurseForge: <https://www.curseforge.com/minecraft/bukkit-plugins/fawe>"

27
.github/workflows/build-pr.yml vendored Normale Datei
Datei anzeigen

@ -0,0 +1,27 @@
name: Build PR
on: [pull_request]
jobs:
build_pr:
if: github.repository_owner == 'IntellectualSites'
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Validate Gradle Wrapper
uses: gradle/wrapper-validation-action@v1
- name: Setup Java
uses: actions/setup-java@v3
with:
distribution: temurin
cache: gradle
java-version: 17
- name: Build on ${{ matrix.os }}
run: ./gradlew build -s
- name: Archive artifacts
uses: actions/upload-artifact@v3
with:
name: FastAsyncWorldEdit-SNAPSHOT
path: worldedit-bukkit/build/libs/FastAsyncWorldEdit-Bukkit-*.jar

Datei anzeigen

@ -1,17 +1,19 @@
name: build name: Build
on:
on: [pull_request, push] push:
branches:
- main
jobs: jobs:
build: build:
if: github.repository_owner == 'IntellectualSites'
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout Repository - name: Checkout Repository
uses: actions/checkout@v2.4.0 uses: actions/checkout@v3
- name: Validate Gradle Wrapper - name: Validate Gradle Wrapper
uses : gradle/wrapper-validation-action@v1.0.4 uses: gradle/wrapper-validation-action@v1
- name: Setup Java - name: Setup Java
uses: actions/setup-java@v2.4.0 uses: actions/setup-java@v3
with: with:
distribution: temurin distribution: temurin
cache: gradle cache: gradle
@ -27,21 +29,50 @@ jobs:
echo "STATUS=release" >> $GITHUB_ENV echo "STATUS=release" >> $GITHUB_ENV
fi fi
- name: Publish Release - name: Publish Release
if: ${{ runner.os == 'Linux' && env.STATUS == 'release' && github.event_name == 'push' && github.ref == 'refs/heads/major/2.0.0/1.18'}} if: ${{ runner.os == 'Linux' && env.STATUS == 'release' && github.event_name == 'push' && github.ref == 'refs/heads/main'}}
run: ./gradlew publishToSonatype closeSonatypeStagingRepository run: ./gradlew publishToSonatype closeAndReleaseSonatypeStagingRepository
env: env:
ORG_GRADLE_PROJECT_sonatypeUsername: ${{ secrets.SONATYPE_USERNAME }} ORG_GRADLE_PROJECT_sonatypeUsername: ${{ secrets.SONATYPE_USERNAME }}
ORG_GRADLE_PROJECT_sonatypePassword: ${{ secrets.SONATYPE_PASSWORD }} ORG_GRADLE_PROJECT_sonatypePassword: ${{ secrets.SONATYPE_PASSWORD }}
ORG_GRADLE_PROJECT_signingKey: ${{ secrets.SIGNING_KEY }} ORG_GRADLE_PROJECT_signingKey: ${{ secrets.SIGNING_KEY }}
ORG_GRADLE_PROJECT_signingPassword: ${{ secrets.SIGNING_PASSWORD }} ORG_GRADLE_PROJECT_signingPassword: ${{ secrets.SIGNING_PASSWORD }}
- name: Publish Snapshot - name: Publish Snapshot
if: ${{ runner.os == 'Linux' && env.STATUS != 'release' && github.event_name == 'push' && github.ref == 'refs/heads/major/2.0.0/1.18' }} if: ${{ runner.os == 'Linux' && env.STATUS != 'release' && github.event_name == 'push' && github.ref == 'refs/heads/main' }}
run: ./gradlew publishToSonatype run: ./gradlew publishToSonatype
env: env:
ORG_GRADLE_PROJECT_sonatypeUsername: ${{ secrets.SONATYPE_USERNAME }} ORG_GRADLE_PROJECT_sonatypeUsername: ${{ secrets.SONATYPE_USERNAME }}
ORG_GRADLE_PROJECT_sonatypePassword: ${{ secrets.SONATYPE_PASSWORD }} ORG_GRADLE_PROJECT_sonatypePassword: ${{ secrets.SONATYPE_PASSWORD }}
- name: Publish core javadoc
if: ${{ runner.os == 'Linux' && env.STATUS == 'release' && github.event_name == 'push' && github.ref == 'refs/heads/main'}}
uses: cpina/github-action-push-to-another-repository@main
env:
SSH_DEPLOY_KEY: ${{ secrets.SSH_DEPLOY_KEY }}
with:
source-directory: 'worldedit-core/build/docs/javadoc'
destination-github-username: 'IntellectualSites'
destination-repository-name: 'fastasyncworldedit-javadocs'
user-email: ${{ secrets.USER_EMAIL }}
target-branch: main
target-directory: worldedit-core
- name: Publish bukkit javadoc
if: ${{ runner.os == 'Linux' && env.STATUS == 'release' && github.event_name == 'push' && github.ref == 'refs/heads/main'}}
uses: cpina/github-action-push-to-another-repository@main
env:
SSH_DEPLOY_KEY: ${{ secrets.SSH_DEPLOY_KEY }}
with:
source-directory: 'worldedit-bukkit/build/docs/javadoc'
destination-github-username: 'IntellectualSites'
destination-repository-name: 'fastasyncworldedit-javadocs'
user-email: ${{ secrets.USER_EMAIL }}
target-branch: main
target-directory: worldedit-bukkit
- name: Archive Artifacts - name: Archive Artifacts
uses: actions/upload-artifact@v2.3.1 uses: actions/upload-artifact@v3
with: with:
name: FastAsyncWorldEdit-Bukkit-SNAPSHOT name: FastAsyncWorldEdit-Bukkit-SNAPSHOT
path: worldedit-bukkit/build/libs/FastAsyncWorldEdit-Bukkit-*.jar path: worldedit-bukkit/build/libs/FastAsyncWorldEdit-Bukkit-*.jar
- name: Publish to Modrinth
if: ${{ runner.os == 'Linux' && env.STATUS == 'release' && github.event_name == 'push' && github.ref == 'refs/heads/main'}}
run: ./gradlew modrinth
env:
MODRINTH_TOKEN: ${{ secrets.MODRINTH_TOKEN }}

36
.github/workflows/codeql.yml vendored Normale Datei
Datei anzeigen

@ -0,0 +1,36 @@
name: "CodeQL"
on:
push:
branches: [main]
pull_request:
# The branches below must be a subset of the branches above
branches: [main]
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: ['java']
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Setup Java
uses: actions/setup-java@v3
with:
distribution: temurin
cache: gradle
java-version: 17
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
- name: Autobuild
uses: github/codeql-action/autobuild@v2
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2

Datei anzeigen

@ -1,14 +1,17 @@
name: draft release name: draft release
on: on:
push: push:
branches: branches:
- main - main
pull_request:
types: [opened, reopened, synchronize]
pull_request_target:
types: [opened, reopened, synchronize]
jobs: jobs:
update_release_draft: update_release_draft:
if: ${{ github.event_name != 'pull_request' || github.repository != github.event.pull_request.head.repo.full_name }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: release-drafter/release-drafter@v5.15.0 - uses: release-drafter/release-drafter@v5
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Datei anzeigen

@ -0,0 +1,26 @@
name: Upload release assets
on:
release:
types: [published]
jobs:
upload_asset:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Validate Gradle Wrapper
uses: gradle/wrapper-validation-action@v1
- name: Setup Java
uses: actions/setup-java@v3
with:
distribution: temurin
cache: gradle
java-version: 17
- name: Clean Build
run: ./gradlew clean build --no-daemon
- name: Upload Release Assets
uses: AButler/upload-release-assets@v2.0
with:
files: 'worldedit-bukkit/build/libs/FastAsyncWorldEdit-Bukkit-*.jar'
repo-token: ${{ secrets.GITHUB_TOKEN }}
release-tag: ${{ github.event.release.tag_name }}

8
.gitignore vendored
Datei anzeigen

@ -2,7 +2,8 @@
.project .project
.settings .settings
eclipse eclipse
.idea /.idea/*
!/.idea/icon.svg
*.iml *.iml
*.ipr *.ipr
*.iws *.iws
@ -23,7 +24,6 @@ logs/
worldedit-bukkit/src/main/java/ignore/* worldedit-bukkit/src/main/java/ignore/*
todo.txt todo.txt
mvn/* mvn/*
docs/
*.sh *.sh
# i18n # i18n
worldedit-core/src/main/resources/lang/* worldedit-core/src/main/resources/lang/*
@ -31,3 +31,7 @@ worldedit-core/src/main/resources/lang/*
**/*.eml **/*.eml
/worldedit-core/FastAsyncWorldEdit.worldedit-core.eml /worldedit-core/FastAsyncWorldEdit.worldedit-core.eml
/worldedit-core/.factorypath /worldedit-core/.factorypath
.DS_Store
### Run server ignore
run-*

112
.idea/icon.svg Normale Datei
Datei anzeigen

@ -0,0 +1,112 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
version="1.1"
id="svg2"
xml:space="preserve"
width="512"
height="512"
viewBox="0 0 512 512.00001"
sodipodi:docname="icon.svg"
inkscape:version="1.1.2 (b8e25be8, 2022-02-05)"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/">
<metadata
id="metadata8">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
</cc:Work>
</rdf:RDF>
</metadata>
<defs
id="defs6">
<clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath18">
<path
d="M 0,2500 H 3000 V 0 H 0 Z"
id="path16" />
</clipPath>
<clipPath
clipPathUnits="userSpaceOnUse"
id="clipPath18-2"><path
d="M 0,2500 H 3000 V 0 H 0 Z"
id="path16-1" /></clipPath></defs>
<sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="1440"
inkscape:window-height="872"
id="namedview4"
inkscape:pagecheckerboard="0"
showgrid="false"
width="512px"
inkscape:snap-others="false"
inkscape:zoom="0.2263301"
inkscape:cx="797.50773"
inkscape:cy="547.87234"
inkscape:window-x="0"
inkscape:window-y="28"
inkscape:window-maximized="0"
inkscape:current-layer="g10" />
<g
id="g10"
inkscape:groupmode="layer"
inkscape:label="FastAsyncWorldEdit"
transform="matrix(1.3333333,0,0,-1.3333333,0,3333.3333)">
<g
id="g12"
transform="matrix(0.17875858,0,0,0.17875858,-78.817913,2093.6589)"><g
id="g14"
clip-path="url(#clipPath18-2)"><g
id="g20"
transform="translate(1643.0798,2025.9724)"><path
d="m 0,0 c 34.839,11.026 70.869,18.313 107.28,21.408 18.861,-48.96 46.604,-93.992 77.514,-136.19 49.794,-66.487 110.495,-124.616 178.34,-172.506 78.156,-55.366 165.481,-97.254 256.496,-126.783 83.229,-27.124 169.601,-44.008 256.592,-53.295 -1.047,-153.146 -64.344,-303.076 -167.124,-415.762 -47.77,-52.914 -103.208,-99.136 -164.838,-135.047 -91.873,-53.843 -197.557,-83.896 -304.076,-85.705 -10.764,101.16 -31.91,201.534 -67.273,297.051 -28.243,76.537 -65.678,149.835 -112.853,216.465 -47.865,67.583 -105.685,128.332 -172.125,177.888 -42.102,31.22 -87.348,58.939 -136.404,77.823 3.834,48.628 15.479,96.636 33.625,141.906 19.169,46.769 46.96,90.968 85.752,123.926 C -91.706,-36.816 -46.722,-14.717 0,0"
style="fill:#4c8fcc;fill-opacity:1;fill-rule:nonzero;stroke:none"
id="path22" /></g><g
id="g24"
transform="translate(1887.3362,1969.7008)"><path
d="m 0,0 c 20.837,19.313 56.319,19.718 77.228,0.333 32.243,-32.053 64.272,-64.296 96.492,-96.373 17.313,-17.384 20.766,-46.27 8.93,-67.631 -9.073,-15.431 -23.813,-26.314 -35.744,-39.388 -37.339,25.29 -72.917,53.105 -106.637,83.015 -17.122,17.074 -36.316,32.076 -51.771,50.794 -8.525,10.74 -20.432,18.813 -26.457,31.458 C -25.242,-25.242 -12.788,-12.431 0,0"
style="fill:#062f4c;fill-opacity:1;fill-rule:nonzero;stroke:none"
id="path26" /></g><g
id="g28"
transform="translate(1463.3822,1497.8577)"><path
d="m 0,0 c -4.644,-0.786 -9.097,-2.786 -12.383,-6.168 -292.384,-292.645 -585.053,-585.029 -877.484,-877.627 -6.74,-6.382 -14.741,-13.145 -14.717,-23.337 -1.262,-12.383 8.668,-21.242 17.384,-28.291 9.882,-6.882 24.552,-4.215 32.481,4.525 293.718,293.693 587.411,587.387 881.104,881.104 10.74,9.049 12.241,27.219 1.929,37.101 C 21.48,-4.406 11.264,2.715 0,0 M -994.266,-946.234 C -647.088,-599.055 -299.885,-251.901 47.27,95.326 84.134,65.44 116.592,30.505 147.502,-5.382 c 23.266,-26.814 43.579,-55.986 64.749,-84.419 -346.679,-346.584 -693.215,-693.286 -1039.941,-1039.822 -20.623,-21.98 -58.439,-23.599 -80.514,-2.953 -32.172,32.149 -64.321,64.345 -96.493,96.493 -16.503,16.741 -19.932,44.007 -9.882,64.963 4.572,9.907 12.692,17.384 20.313,24.886"
style="fill:#062f4c;fill-opacity:1;fill-rule:nonzero;stroke:none"
id="path30" /></g><g
id="g32"
transform="translate(1827.8735,1911.1907)"><path
d="M 0,0 C 7.859,6.168 14.288,13.883 21.504,20.718 27.529,8.073 39.435,0 47.961,-10.74 c 15.455,-18.717 34.648,-33.72 51.77,-50.794 33.721,-29.91 69.298,-57.725 106.638,-83.015 -9.383,-9.263 -18.67,-18.67 -28.029,-27.957 C 110.495,-124.617 49.794,-66.488 0,0"
style="fill:#081d2d;fill-opacity:1;fill-rule:nonzero;stroke:none"
id="path34" /></g><g
id="g36"
transform="translate(1531.0129,1613.4966)"><path
d="m 0,0 c 66.44,-49.556 124.26,-110.305 172.125,-177.888 -9.145,-9.192 -18.36,-18.336 -27.505,-27.552 -21.17,28.433 -41.483,57.605 -64.749,84.419 C 48.961,-85.134 16.503,-50.199 -20.361,-20.313 -13.574,-13.55 -6.811,-6.763 0,0"
style="fill:#081d2d;fill-opacity:1;fill-rule:nonzero;stroke:none"
id="path38" /></g><g
id="g40"
transform="translate(2519.302,1558.6062)"><path
d="M 0,0 C 21.408,-2.334 42.865,-3.763 64.321,-5.596 73.179,-84.086 63.178,-164.123 40.126,-239.47 3.072,-360.657 -72.393,-468.319 -168.696,-549.976 c -101.446,-87.038 -230.349,-142.429 -363.943,-152.121 -32.72,-2.548 -65.726,-2.453 -98.279,1.786 -0.857,21.313 -3.072,42.555 -5.12,63.797 106.518,1.81 212.203,31.862 304.076,85.705 61.63,35.911 117.068,82.133 164.838,135.047 C -64.344,-303.076 -1.048,-153.145 0,0"
style="fill:#6fc4ee;fill-opacity:1;fill-rule:nonzero;stroke:none"
id="path42" /></g><g
id="g44"
transform="translate(1463.3822,1497.8577)"><path
d="m 0,0 c 11.264,2.715 21.48,-4.406 28.314,-12.693 10.312,-9.882 8.811,-28.052 -1.929,-37.101 -293.693,-293.717 -587.386,-587.411 -881.104,-881.104 -7.929,-8.74 -22.599,-11.407 -32.481,-4.525 -8.716,7.049 -18.646,15.908 -17.384,28.291 -0.024,10.192 7.977,16.955 14.717,23.337 292.431,292.598 585.1,584.982 877.484,877.627 C -9.097,-2.786 -4.644,-0.786 0,0"
style="fill:#105677;fill-opacity:1;fill-rule:nonzero;stroke:none"
id="path46" /></g></g></g></g>
</svg>

Nachher

Breite:  |  Höhe:  |  Größe: 6.3 KiB

Datei anzeigen

@ -1,13 +0,0 @@
{
"scanSettings": {
"baseBranches": ["main"]
},
"checkRunSettings": {
"vulnerableCheckRunConclusionLevel": "failure",
"displayMode": "diff"
},
"issueSettings": {
"minSeverityLevel": "LOW"
},
"enableRenovate": "true"
}

54
Annotation-Explanation.adoc Normale Datei
Datei anzeigen

@ -0,0 +1,54 @@
:toc:
:toclevels: 2
= Fawe annotations explained
If we have modified parts of the WorldEdit codebase, we considered annotating it with different styles of comments, which
are explained in this document.
== In-line annotations
[source,java]
-----------------
public static Player adapt(com.sk89q.worldedit.entity.Player player) {
//FAWE start - Get player from PlayerProxy instead of BukkitPlayer if null
player = PlayerProxy.unwrap(player);
return player == null ? null : ((BukkitPlayer) player).getPlayer();
//FAWE end
}
-----------------
The `-sources` jar retains comments, if you add the FAWE API to your maven or gradle project, you can view differences between the projects with ease.
Behind the `//FAWE start - ` you can find a comment what has been changed and why it has been changed.
== Block annotations
[source,java]
-----------------
//FAWE start
@Override
public void setPermission(String permission, boolean value) {
}
//FAWE end
-----------------
Annotations can cover whole methods or go beyond the method and wrap around several added methods.
== Package annotations
Class additions are added under the `com.fastasyncworldedit` namespace, but sometimes classes need to be added in package private.
If that is done, you can find a `package-info.java` file within the package affected that outlines FAWE added classes:
[source,java]
-----------------
/**
* The following classes are FAWE additions:
*
* @see com.sk89q.worldedit.world.block.BlockTypesCache
*/
package com.sk89q.worldedit.world.block;
-----------------
== Undocumented annotations
Specific changes are not annotated:
* `com.fastasyncworldedit.core.configuration.Caption` in `com.sk89q.worldedit` packages have been changed from
`com.sk89q.worldedit.util.formatting.text.Text` to allow the usage of color codes for messages.
* Certain Log4J loggers have been adjusted to use the proper format of placeholders.

Datei anzeigen

@ -1,12 +1,14 @@
Compiling :toc:
========= :toclevels: 2
= Compiling
You can compile FastAsyncWorldEdit as long as you have some version of Java greater than or equal to 17 installed. Gradle will download JDK 17 specifically if needed, You can compile FastAsyncWorldEdit as long as you have some version of Java greater than or equal to 17 installed. Gradle will download JDK 17 specifically if needed,
but it needs some version of Java to bootstrap from. but it needs some version of Java to bootstrap from.
Note that if you have JRE 8 installed, Gradle will currently attempt to use that to compile, which will not work. It is easiest to uninstall JRE 8 and replace it with JDK 16. Note that if you have JRE 8 installed, Gradle will currently attempt to use that to compile, which will not work. It is easiest to uninstall JRE 8 and replace it with JDK 17.
You can get the JDK 17 [here](https://adoptium.net/). You can get the JDK 17 link:https://adoptium.net/[here] from Adoptium.
The build process uses Gradle, which you do *not* need to download. FastAsyncWorldEdit is a multi-module project with three active modules: The build process uses Gradle, which you do *not* need to download. FastAsyncWorldEdit is a multi-module project with three active modules:
@ -14,23 +16,19 @@ The build process uses Gradle, which you do *not* need to download. FastAsyncWor
* `worldedit-bukkit` is the Bukkit plugin * `worldedit-bukkit` is the Bukkit plugin
* `worldedit-cli` is the command line interface * `worldedit-cli` is the command line interface
## To compile... == To compile...
### NMS === On Windows
FastAsyncWorldEdit uses NMS (net.minecraft.server) code in a variety of spots. NMS is not distributed via maven and therefore FastAsyncWorldEdit may not build without errors if you didn't install it into your local repository beforehand.
You can do that by either running Spigot's [BuildTools](https://www.spigotmc.org/wiki/buildtools/) targeting the versions needed or using Paper's [paperclip](https://papermc.io/downloads) with `java -Dpaperclip.install=true -jar paperclip.jar`.
### On Windows
1. Shift + right-click the folder with FastAsyncWorldEdit's files and click "Open command prompt". 1. Shift + right-click the folder with FastAsyncWorldEdit's files and click "Open command prompt".
2. `gradlew clean build` 2. `gradlew clean build`
### On Linux, BSD, or Mac OS X === On Linux, BSD, or Mac OS X
1. In your terminal, navigate to the folder with FastAsyncWorldEdit's files (`cd /folder/of/fawe/files`) 1. In your terminal, navigate to the folder with FastAsyncWorldEdit's files (`cd /folder/of/fawe/files`)
2. `./gradlew clean build` 2. `./gradlew clean build`
## Then you will find... == Then you will find...
You will find: You will find:
@ -42,10 +40,10 @@ If you want to use FastAsyncWorldEdit, use the `FastAsyncWorldEdit-<identifier>`
(The `-#` version includes FastAsyncWorldEdit + necessary libraries.) (The `-#` version includes FastAsyncWorldEdit + necessary libraries.)
## Other commands == Other commands
* `gradlew idea` will generate an [IntelliJ IDEA](https://www.jetbrains.com/idea/) module for each folder. * `gradlew idea` will generate an link:https://www.jetbrains.com/idea/[IntelliJ IDEA] module for each folder.
_Possibly broken_: _Possibly broken_:
* `gradlew eclipse` will generate an [Eclipse](https://www.eclipse.org/downloads/) project for each folder. * `gradlew eclipse` will generate an link:https://www.eclipse.org/downloads/[Eclipse] project for each folder.

36
Jenkinsfile vendored Normale Datei
Datei anzeigen

@ -0,0 +1,36 @@
pipeline {
agent any
options {
disableConcurrentBuilds()
}
stages {
stage('Build') {
steps {
withEnv([
"PATH+JAVA=${tool 'Temurin-17.0.7_7'}/bin"
]) {
sh './gradlew clean build'
}
}
}
stage('Archive artifacts') {
steps {
sh 'rm -rf artifacts'
sh 'mkdir artifacts'
sh 'cp worldedit-bukkit/build/libs/FastAsyncWorldEdit*.jar artifacts/'
sh 'cp worldedit-cli/build/libs/FastAsyncWorldEdit*.jar artifacts/'
archiveArtifacts artifacts: 'artifacts/*.jar', followSymlinks: false
}
}
stage('Fingerprint artifacts') {
steps {
fingerprint 'worldedit-bukkit/build/libs/FastAsyncWorldEdit*.jar'
}
}
stage('Publish JUnit test results') {
steps {
junit 'worldedit-core/build/test-results/test/*.xml,worldedit-bukkit/build/test-results/test/*.xml'
}
}
}
}

109
README.md
Datei anzeigen

@ -1,48 +1,95 @@
<p align="center"> # FastAsyncWorldEdit
<img src="fawe-logo.png" width="150"> [![Join us on Discord](https://img.shields.io/discord/268444645527126017.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/intellectualsites)
</p> [![bStats Servers](https://img.shields.io/bstats/servers/1403)](https://bstats.org/plugin/bukkit/FastAsyncWorldEdit/1403)
[![Crowdin](https://badges.crowdin.net/e/4a5819fae3fd88234a8ea13bfbb072bb/localized.svg)](https://intellectualsites.crowdin.com/fastasyncworldedit)
--- ## What is FAWE and why should I use it?
FastAsyncWorldEdit is a fork of WorldEdit that has huge speed and memory improvements and considerably more features FAWE is designed for efficient world editing.
* Simple to set up and use
* Extremely configurable
* Uses minimal CPU/Memory
* Safe for many players to use
* Insanely fast, when using the slowest mode
**A Minecraft Map Editor... that runs in-game!** FastAsyncWorldEdit is a fork of WorldEdit that has huge speed and memory improvements and considerably more features.
If you use other plugins which depend on WorldEdit, simply having FAWE installed will boost their performance.
* With selections, schematics, copy and paste, brushes, and scripting! ## Downloads
* Use it in creative, survival in single player or on your server.
* Use it on your Minecraft server to fix grieving and mistakes.
Java Edition required. FastAsyncWorldEdit is compatible with Bukkit, Spigot and Paper. Downloads are available either on SpigotMC, Modrinth or on CurseForge.
- [SpigotMC](https://www.spigotmc.org/resources/13932/)
- [Modrinth](https://modrinth.com/plugin/fastasyncworldedit/)
- [CurseForge](https://dev.bukkit.org/projects/fawe)
## Download FastAsyncWorldEdit Snapshots are available on [Jenkins](https://ci.athion.net/job/FastAsyncWorldEdit/).
* Spigot: https://www.spigotmc.org/resources/fast-async-worldedit.13932/
* Older, unsupported, versions: https://intellectualsites.github.io/download/fawe.html
## Links ## Features
* [Discord](https://discord.gg/intellectualsites) * Over 200 Commands
* [Wiki](https://github.com/IntellectualSites/FastAsyncWorldEdit-Documentation/wiki) * Style and translate messages and commands
* [Report Issue](https://github.com/IntellectualSites/FastAsyncWorldEdit/issues) * (No setup required) Clipboard web integration (Clipboard)
* [Crowdin (Translations)](https://intellectualsites.crowdin.com/fastasyncworldedit) * Unlimited //undo, per world history, instant lookups/rollback and cross server clipboards
* [JavaDocs for the -bukkit module](https://javadoc.io/doc/com.fastasyncworldedit/FastAsyncWorldEdit-Bukkit/latest/index.html) * Advanced per player limits (entity, tiles, memory, changes, iterations, regions, inventory)
* [JavaDocs for the -core module](https://javadoc.io/doc/com.fastasyncworldedit/FastAsyncWorldEdit-Core/latest/index.html) * Visualization, targeting modes/masks and scroll actions
* Adds lots of powerful new //brushes and //tools.
* Adds a lot more mask functionality. (new mask syntax, patterns, expressions, source masks)
* Adds a lot more pattern functionality. (a lot of new pattern syntax and patterns)
* Adds edit transforms (apply transforms to a source, e.g. on //paste)
* Adds support for new formats (e.g. Structure Blocks)
* Instant copying of arbitrary size with `//lazycopy`
* Auto repair partially corrupt schematic files
* Biome mixing, in-game world painting, dynamic view distance, vanilla cui, off axis rotation, image importing, cave generation,
multi-clipboards, interactive messages, schematic visualization, lag prevention, persistent brushes + A LOT MORE
## Edit The Code ### Performance
There are several placement modes, each supporting higher throughput than the previous. All editing is processed
asynchronously, with
certain tasks being broken up on the main thread. The default mode is chunk placement.
* Blocks (Bukkit-API) - Only used if chunk placement isn't supported. Still faster than any other plugin on spigot.
* Chunks (NMS) - Places entire chunk sections
* World (CFI) - Used to generate new worlds / regions
### Protection Plugins
The following plugins are supported with Bukkit:
* [WorldGuard](https://dev.bukkit.org/projects/worldguard)
* [PlotSquared](https://www.spigotmc.org/resources/77506/)
### Logging and Rollback
By default you can use `//inspect` and `//history rollback` to search and restore changes. To reduce disk usage, increase the
compression level and buffer size. To bypass logging use `//fast`.
### Developer API
FAWE maintains API compatibility with WorldEdit, so you can use the normal WorldEdit API asynchronously.
FAWE also has some asynchronously wrappers for the Bukkit API.
The wiki has examples for various things like reading NBT, modifying world files, pasting schematics, splitting up tasks, lighting etc.
If you need help with anything, hop on discord (link on the left bar).
## Documentation
* [Wiki](https://intellectualsites.github.io/fastasyncworldedit-documentation/)
* [Javadocs](https://intellectualsites.github.io/fastasyncworldedit-javadocs/)
## Contributing
Want to add new features to FastAsyncWorldEdit or fix bugs yourself? You can get the game running, with FastAsyncWorldEdit, from the code here: Want to add new features to FastAsyncWorldEdit or fix bugs yourself? You can get the game running, with FastAsyncWorldEdit, from the code here:
For additional information about compiling FastAsyncWorldEdit, see [COMPILING.md](COMPILING.md). For additional information about compiling FastAsyncWorldEdit, read the [compiling documentation](https://github.com/IntellectualSites/FastAsyncWorldEdit/blob/main/COMPILING.adoc).
## Submitting Your Changes ## Special thanks
FastAsyncWorldEdit is open source (specifically licensed under GPL v3), so note that your contributions will also be open source. The best way to submit a change is to create a fork on GitHub, put your changes there, and then create a "pull request" on our FastAsyncWorldEdit repository.
Please read [CONTRIBUTING.md](https://github.com/IntellectualSites/.github/blob/main/CONTRIBUTING.md) for important guidelines to follow. <a href="https://jb.gg/OpenSourceSupport"><img src="https://resources.jetbrains.com/storage/products/company/brand/logos/jb_beam.svg" width="150">
## YourKit
<a href="https://www.yourkit.com">
<img src="https://www.yourkit.com/images/yklogo.png">
</a> </a>
</br>
[JetBrains](https://jb.gg/OpenSourceSupport), creators of the IntelliJ IDEA, supports us with their Open Source Licenses.
<a href="https://yourkit.com/"><img src="https://www.yourkit.com/images/yklogo.png" width="200">
</a>
Thank you to YourKit for supporting our product by providing us with their innovative and intelligent tools Thank you to YourKit for supporting our product by providing us with their innovative and intelligent tools
for monitoring and profiling Java and .NET applications. for monitoring and profiling Java and .NET applications.
YourKit is the creator of <a href="https://www.yourkit.com/java/profiler/">YourKit Java Profiler</a>, <a href="https://www.yourkit.com/.net/profiler/">YourKit .NET Profiler</a>, and <a href="https://www.yourkit.com/youmonitor/">YourKit YouMonitor</a> YourKit is the creator of [YourKit Java Profiler](https://www.yourkit.com/java/profiler/), [YourKit .NET Profiler](https://www.yourkit.com/.net/profiler/), and [YourKit YouMonitor](https://www.yourkit.com/youmonitor/).

Datei anzeigen

@ -1,11 +1,23 @@
import org.ajoberstar.grgit.Grgit import org.ajoberstar.grgit.Grgit
import java.time.format.DateTimeFormatter
import org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL import org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL
import org.gradle.api.tasks.testing.logging.TestLogEvent.FAILED import org.gradle.api.tasks.testing.logging.TestLogEvent.FAILED
import java.net.URI import java.net.URI
import java.time.format.DateTimeFormatter
import xyz.jpenilla.runpaper.task.RunServer
plugins { plugins {
id("io.github.gradle-nexus.publish-plugin") version "1.1.0" id("io.github.gradle-nexus.publish-plugin") version "1.3.0"
id("xyz.jpenilla.run-paper") version "2.1.0"
}
if (!File("$rootDir/.git").exists()) {
logger.lifecycle("""
**************************************************************************************
You need to fork and clone this repository! Don't download a .zip file.
If you need assistance, consult the GitHub docs: https://docs.github.com/get-started/quickstart/fork-a-repo
**************************************************************************************
""".trimIndent()
).also { kotlin.system.exitProcess(1) }
} }
logger.lifecycle(""" logger.lifecycle("""
@ -13,7 +25,7 @@ logger.lifecycle("""
You are building FastAsyncWorldEdit! You are building FastAsyncWorldEdit!
If you encounter trouble: If you encounter trouble:
1) Read COMPILING.md if you haven't yet 1) Read COMPILING.adoc if you haven't yet
2) Try running 'build' in a separate Gradle run 2) Try running 'build' in a separate Gradle run
3) Use gradlew and not gradle 3) Use gradlew and not gradle
4) If you still need help, ask on Discord! https://discord.gg/intellectualsites 4) If you still need help, ask on Discord! https://discord.gg/intellectualsites
@ -22,7 +34,7 @@ logger.lifecycle("""
******************************************* *******************************************
""") """)
var rootVersion by extra("2.0.0") var rootVersion by extra("2.7.1")
var snapshot by extra("SNAPSHOT") var snapshot by extra("SNAPSHOT")
var revision: String by extra("") var revision: String by extra("")
var buildNumber by extra("") var buildNumber by extra("")
@ -71,9 +83,29 @@ allprojects {
} }
applyCommonConfiguration() applyCommonConfiguration()
val supportedVersions = listOf("1.16.5", "1.17", "1.17.1", "1.18.2", "1.19", "1.19.1", "1.19.2", "1.19.3", "1.19.4", "1.20", "1.20.1")
tasks {
supportedVersions.forEach {
register<RunServer>("runServer-$it") {
minecraftVersion(it)
pluginJars(*project(":worldedit-bukkit").getTasksByName("shadowJar", false).map { (it as Jar).archiveFile }
.toTypedArray())
jvmArgs("-DPaper.IgnoreJavaVersion=true", "-Dcom.mojang.eula.agree=true")
group = "run paper"
runDirectory.set(file("run-$it"))
}
}
runServer {
minecraftVersion("1.20.1")
pluginJars(*project(":worldedit-bukkit").getTasksByName("shadowJar", false).map { (it as Jar).archiveFile }
.toTypedArray())
}
}
nexusPublishing { nexusPublishing {
repositories { this.repositories {
sonatype { sonatype {
nexusUrl.set(URI.create("https://s01.oss.sonatype.org/service/local/")) nexusUrl.set(URI.create("https://s01.oss.sonatype.org/service/local/"))
snapshotRepositoryUrl.set(URI.create("https://s01.oss.sonatype.org/content/repositories/snapshots/")) snapshotRepositoryUrl.set(URI.create("https://s01.oss.sonatype.org/content/repositories/snapshots/"))

Datei anzeigen

@ -12,13 +12,6 @@ repositories {
name = "EngineHub" name = "EngineHub"
url = uri("https://maven.enginehub.org/repo/") url = uri("https://maven.enginehub.org/repo/")
} }
maven {
name = "PaperMC"
url = uri("https://papermc.io/repo/repository/maven-public/")
content {
includeGroupByRegex("io\\.papermc\\..*")
}
}
} }
val properties = Properties().also { props -> val properties = Properties().also { props ->
@ -29,9 +22,9 @@ val properties = Properties().also { props ->
dependencies { dependencies {
implementation(gradleApi()) implementation(gradleApi())
implementation("org.ajoberstar.grgit:grgit-gradle:4.1.1") implementation("org.ajoberstar.grgit:grgit-gradle:5.2.0")
implementation("gradle.plugin.com.github.johnrengelman:shadow:7.1.1") implementation("com.github.johnrengelman:shadow:8.1.1")
implementation("io.papermc.paperweight.userdev:io.papermc.paperweight.userdev.gradle.plugin:1.3.3") implementation("io.papermc.paperweight.userdev:io.papermc.paperweight.userdev.gradle.plugin:1.5.5")
} }
kotlin { kotlin {

Datei anzeigen

@ -1,4 +1,3 @@
import io.papermc.paperweight.userdev.attribute.Obfuscation
import org.gradle.api.Project import org.gradle.api.Project
import org.gradle.kotlin.dsl.apply import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.dependencies import org.gradle.kotlin.dsl.dependencies

Datei anzeigen

@ -10,12 +10,7 @@ fun Project.applyCommonConfiguration() {
version = rootProject.version version = rootProject.version
repositories { repositories {
mavenLocal()
mavenCentral() mavenCentral()
maven {
name = "IntellectualSites"
url = uri("https://mvn.intellectualsites.com/content/groups/public/")
}
maven { maven {
name = "EngineHub" name = "EngineHub"
url = uri("https://maven.enginehub.org/repo/") url = uri("https://maven.enginehub.org/repo/")
@ -24,10 +19,6 @@ fun Project.applyCommonConfiguration() {
name = "OSS Sonatype Snapshots" name = "OSS Sonatype Snapshots"
url = uri("https://oss.sonatype.org/content/repositories/snapshots/") url = uri("https://oss.sonatype.org/content/repositories/snapshots/")
} }
maven {
name = "OSS Sonatype Releases"
url = uri("https://oss.sonatype.org/content/repositories/releases/")
}
maven { maven {
name = "Athion" name = "Athion"
url = uri("https://ci.athion.net/plugin/repository/tools/") url = uri("https://ci.athion.net/plugin/repository/tools/")
@ -54,15 +45,15 @@ fun Project.applyCommonConfiguration() {
continue continue
} }
add(conf.name, "com.google.guava:guava") { add(conf.name, "com.google.guava:guava") {
version { require("31.0.1-jre") } version { require("31.1-jre") }
because("Mojang provides Guava") because("Mojang provides Guava")
} }
add(conf.name, "com.google.code.gson:gson") { add(conf.name, "com.google.code.gson:gson") {
version { require("2.8.8") } version { require("2.10") }
because("Mojang provides Gson") because("Mojang provides Gson")
} }
add(conf.name, "it.unimi.dsi:fastutil") { add(conf.name, "it.unimi.dsi:fastutil") {
version { require("8.5.6") } version { require("8.5.9") }
because("Mojang provides FastUtil") because("Mojang provides FastUtil")
} }
} }

Datei anzeigen

@ -1,7 +1,6 @@
import org.gradle.api.Project import org.gradle.api.Project
import org.gradle.api.attributes.java.TargetJvmVersion import org.gradle.api.attributes.java.TargetJvmVersion
import org.gradle.api.plugins.JavaPluginExtension import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.plugins.quality.CheckstyleExtension
import org.gradle.api.tasks.compile.JavaCompile import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.api.tasks.javadoc.Javadoc import org.gradle.api.tasks.javadoc.Javadoc
import org.gradle.api.tasks.testing.Test import org.gradle.api.tasks.testing.Test
@ -41,11 +40,11 @@ fun Project.applyCommonJavaConfiguration(sourcesJar: Boolean, banSlf4j: Boolean
dependencies { dependencies {
"compileOnly"("com.google.code.findbugs:jsr305:3.0.2") "compileOnly"("com.google.code.findbugs:jsr305:3.0.2")
"testImplementation"("org.junit.jupiter:junit-jupiter-api:5.8.1") "testImplementation"("org.junit.jupiter:junit-jupiter-api:5.10.0")
"testImplementation"("org.junit.jupiter:junit-jupiter-params:5.8.1") "testImplementation"("org.junit.jupiter:junit-jupiter-params:5.10.0")
"testImplementation"("org.mockito:mockito-core:3.12.4") "testImplementation"("org.mockito:mockito-core:5.4.0")
"testImplementation"("org.mockito:mockito-junit-jupiter:3.12.4") "testImplementation"("org.mockito:mockito-junit-jupiter:5.4.0")
"testRuntimeOnly"("org.junit.jupiter:junit-jupiter-engine:5.8.1") "testRuntimeOnly"("org.junit.jupiter:junit-jupiter-engine:5.10.0")
} }
// Java 8 turns on doclint which we fail // Java 8 turns on doclint which we fail
@ -59,15 +58,15 @@ fun Project.applyCommonJavaConfiguration(sourcesJar: Boolean, banSlf4j: Boolean
) )
options.encoding = "UTF-8" options.encoding = "UTF-8"
links( links(
"https://javadoc.io/doc/com.google.code.findbugs/jsr305/3.0.2/", "https://jd.advntr.dev/api/latest/",
"https://jd.adventure.kyori.net/api/4.9.3/", "https://logging.apache.org/log4j/2.x/log4j-api/apidocs/",
"https://javadoc.io/doc/org.apache.logging.log4j/log4j-api/2.14.1/",
"https://www.antlr.org/api/Java/", "https://www.antlr.org/api/Java/",
"https://docs.enginehub.org/javadoc/org.enginehub.piston/core/0.5.7/", "https://docs.enginehub.org/javadoc/org.enginehub.piston/core/0.5.7/",
"https://docs.enginehub.org/javadoc/org.enginehub.piston/default-impl/0.5.7/", "https://docs.enginehub.org/javadoc/org.enginehub.piston/default-impl/0.5.7/",
"https://papermc.io/javadocs/paper/1.18/", "https://jd.papermc.io/paper/1.20/",
"https://ci.athion.net/job/FastAsyncWorldEdit-1.17-Core-Javadocs/javadoc/" // needed for other module linking "https://intellectualsites.github.io/fastasyncworldedit-javadocs/worldedit-core/"
) )
docTitle = "${rootProject.name}-${project.description}" + " " + "${rootProject.version}"
} }
} }

Datei anzeigen

@ -204,7 +204,7 @@ fun Project.applyLibrariesConfiguration() {
from(libsComponent) from(libsComponent)
group = "com.fastasyncworldedit" group = "com.fastasyncworldedit"
artifactId = "FastAsyncWorldEdit-Libs-${project.name.capitalize()}" artifactId = "FastAsyncWorldEdit-Libs-${project.name.replaceFirstChar(Char::titlecase)}"
version = version version = version
pom { pom {
@ -223,8 +223,8 @@ fun Project.applyLibrariesConfiguration() {
developers { developers {
developer { developer {
id.set("NotMyFault") id.set("NotMyFault")
name.set("NotMyFault") name.set("Alexander Brandes")
email.set("contact@notmyfault.dev") email.set("contact(at)notmyfault.dev")
organization.set("IntellectualSites") organization.set("IntellectualSites")
} }
developer { developer {

Datei anzeigen

@ -84,8 +84,8 @@ fun Project.applyPlatformAndCoreConfiguration() {
developers { developers {
developer { developer {
id.set("NotMyFault") id.set("NotMyFault")
name.set("NotMyFault") name.set("Alexander Brandes")
email.set("contact@notmyfault.dev") email.set("contact(at)notmyfault.dev")
organization.set("IntellectualSites") organization.set("IntellectualSites")
} }
developer { developer {

Binäre Datei nicht angezeigt.

Vorher

Breite:  |  Höhe:  |  Größe: 17 KiB

Datei anzeigen

@ -1,96 +1,83 @@
[versions] [versions]
# Minecraft expectations # Minecraft expectations
fastutil = "8.5.6" paper = "1.20.1-R0.1-SNAPSHOT"
log4j = "2.17.0" fastutil = "8.5.9"
guava = "31.0.1-jre" guava = "31.1-jre"
gson = "2.8.9" log4j = "2.19.0"
gson = "2.10"
# Platform expectations snakeyaml = "2.0"
paper = "1.18.1-R0.1-SNAPSHOT"
# Plugins # Plugins
vault = "1.7.1"
dummypermscompat = "1.10" dummypermscompat = "1.10"
worldguard-bukkit = "7.0.6" worldguard-bukkit = "7.0.9"
mapmanager = "1.8.0-SNAPSHOT" mapmanager = "1.8.0-SNAPSHOT"
griefprevention = "16.17.1" griefprevention = "16.18.1"
griefdefender = "920a610" griefdefender = "2.1.0-SNAPSHOT"
mcore = "7.0.1"
residence = "4.5._13.1" residence = "4.5._13.1"
towny = "0.97.5.0" towny = "0.99.5.10"
protocollib = "4.7.0" plotsquared = "7.0.0-rc.4"
plotsquaredV6 = "6.2.0"
redprotect = "1.9.6"
# Third party # Third party
flow-math = "1.0.3" bstats = "3.0.2"
paperlib = "1.0.8-SNAPSHOT"
bstats = "2.2.1"
serverlib = "2.3.1"
paster = "1.1.3"
sparsebitset = "1.2" sparsebitset = "1.2"
parallelgzip = "1.0.5" parallelgzip = "1.0.5"
adventure = "4.9.3" adventure = "4.14.0"
adventure-bukkit = "4.3.0"
checkerqual = "3.37.0"
truezip = "6.8.4" truezip = "6.8.4"
auto-value = "1.9" auto-value = "1.10.2"
findbugs = "3.0.2" findbugs = "3.0.2"
rhino-runtime = "1.7.13" rhino-runtime = "1.7.14"
zstd-jni = "1.4.8-1" # Not latest as it can be difficult to obtain latest ZSTD libs zstd-jni = "1.4.8-1" # Not latest as it can be difficult to obtain latest ZSTD libs
antlr4 = "4.9.3" antlr4 = "4.13.0"
json-simple = "1.1.1" json-simple = "1.1.1"
jlibnoise = "1.0.0" jlibnoise = "1.0.0"
jchronic = "0.2.4a" jchronic = "0.2.4a"
lz4-java = "1.8.0" lz4-java = "1.8.0"
lz4-stream = "1.0.0" lz4-stream = "1.0.0"
commons-cli = "1.5.0"
paperlib = "1.0.8"
paster = "1.1.5"
vault = "1.7.1"
serverlib = "2.3.1"
## Internal ## Internal
adventure-text-minimessage = "4.2.0-SNAPSHOT"
text-adapter = "3.0.6" text-adapter = "3.0.6"
text = "3.0.4" text = "3.0.4"
piston = "0.5.7" piston = "0.5.7"
# Tests # Tests
mockito = "4.2.0" mockito = "5.4.0"
checker-qual = "3.21.0"
# Gradle plugins # Gradle plugins
pluginyml = "0.5.1" pluginyml = "0.6.0"
minotaur = "2.8.3"
[libraries] [libraries]
# Minecraft expectations # Minecraft expectations
paper = { group = "io.papermc.paper", name = "paper-api", version.ref = "paper" }
fastutil = { group = "it.unimi.dsi", name = "fastutil", version.ref = "fastutil" } fastutil = { group = "it.unimi.dsi", name = "fastutil", version.ref = "fastutil" }
log4j = { group = "org.apache.logging.log4j", name = "log4j-api", version.ref = "log4j" }
log4jBom = { group = "org.apache.logging.log4j", name = "log4j-bom", version.ref = "log4j" } log4jBom = { group = "org.apache.logging.log4j", name = "log4j-bom", version.ref = "log4j" }
log4jApi = { group = "org.apache.logging.log4j", name = "log4j-api", version.ref = "log4j" }
guava = { group = "com.google.guava", name = "guava", version.ref = "guava" } guava = { group = "com.google.guava", name = "guava", version.ref = "guava" }
gson = { group = "com.google.code.gson", name = "gson", version.ref = "gson" } gson = { group = "com.google.code.gson", name = "gson", version.ref = "gson" }
snakeyaml = { group = "org.yaml", name = "snakeyaml", version.ref = "snakeyaml" }
#Platform expectations
paper = { group = "io.papermc.paper", name = "paper-api", version.ref = "paper" }
# Plugins # Plugins
vault = { group = "com.github.MilkBowl", name = "VaultAPI", version.ref = "vault" }
dummypermscompat = { group = "com.sk89q", name = "dummypermscompat", version.ref = "dummypermscompat" } dummypermscompat = { group = "com.sk89q", name = "dummypermscompat", version.ref = "dummypermscompat" }
worldguard = { group = "com.sk89q.worldguard", name = "worldguard-bukkit", version.ref = "worldguard-bukkit" } worldguard = { group = "com.sk89q.worldguard", name = "worldguard-bukkit", version.ref = "worldguard-bukkit" }
mapmanager = { group = "com.github.InventivetalentDev", name = "MapManager", version.ref = "mapmanager" } mapmanager = { group = "com.github.InventivetalentDev", name = "MapManager", version.ref = "mapmanager" }
griefprevention = { group = "com.github.TechFortress", name = "GriefPrevention", version.ref = "griefprevention" } griefprevention = { group = "com.github.TechFortress", name = "GriefPrevention", version.ref = "griefprevention" }
griefdefender = { group = "com.github.bloodmc", name = "GriefDefenderApi", version.ref = "griefdefender" } griefdefender = { group = "com.griefdefender", name = "api", version.ref = "griefdefender" }
mcore = { group = "com.massivecraft", name = "mcore", version.ref = "mcore" }
residence = { group = "com.bekvon.bukkit.residence", name = "Residence", version.ref = "residence" } residence = { group = "com.bekvon.bukkit.residence", name = "Residence", version.ref = "residence" }
towny = { group = "com.github.TownyAdvanced", name = "Towny", version.ref = "towny" } towny = { group = "com.palmergames.bukkit.towny", name = "towny", version.ref = "towny" }
protocollib = { group = "com.comphenix.protocol", name = "ProtocolLib", version.ref = "protocollib" } plotSquaredCore = { group = "com.intellectualsites.plotsquared", name = "plotsquared-core", version.ref = "plotsquared" }
plotsquaredV6Bukkit = { group = "com.plotsquared", name = "PlotSquared-Bukkit", version.ref = "plotsquaredV6" } plotSquaredBukkit = { group = "com.intellectualsites.plotsquared", name = "plotsquared-bukkit", version.ref = "plotsquared" }
plotsquaredV6Core = { group = "com.plotsquared", name = "PlotSquared-Core", version.ref = "plotsquaredV6" }
redprotect = { group = "net.fabiozumbi12", name = "redprotect", version.ref = "redprotect" }
# Third Party # Third Party
flowmath = { group = "com.flowpowered", name = "flow-math", version.ref = "flow-math" }
paperlib = { group = "io.papermc", name = "paperlib", version.ref = "paperlib" }
bstatsBukkit = { group = "org.bstats", name = "bstats-bukkit", version.ref = "bstats" }
bstatsBase = { group = "org.bstats", name = "bstats-base", version.ref = "bstats" } bstatsBase = { group = "org.bstats", name = "bstats-base", version.ref = "bstats" }
serverlib = { group = "dev.notmyfault.serverlib", name = "ServerLib", version.ref = "serverlib" } bstatsBukkit = { group = "org.bstats", name = "bstats-bukkit", version.ref = "bstats" }
paster = { group = "com.intellectualsites.paster", name = "Paster", version.ref = "paster" }
sparsebitset = { group = "com.zaxxer", name = "SparseBitSet", version.ref = "sparsebitset" } sparsebitset = { group = "com.zaxxer", name = "SparseBitSet", version.ref = "sparsebitset" }
parallelgzip = { group = "org.anarres", name = "parallelgzip", version.ref = "parallelgzip" } parallelgzip = { group = "org.anarres", name = "parallelgzip", version.ref = "parallelgzip" }
adventure = { group = "net.kyori", name = "adventure-api", version.ref = "adventure" }
adventureNbt = { group = "net.kyori", name = "adventure-nbt", version.ref = "adventure" } adventureNbt = { group = "net.kyori", name = "adventure-nbt", version.ref = "adventure" }
truezip = { group = "de.schlichtherle", name = "truezip", version.ref = "truezip" } truezip = { group = "de.schlichtherle", name = "truezip", version.ref = "truezip" }
autoValueAnnotations = { group = "com.google.auto.value", name = "auto-value-annotations", version.ref = "auto-value" } autoValueAnnotations = { group = "com.google.auto.value", name = "auto-value-annotations", version.ref = "auto-value" }
@ -105,11 +92,19 @@ jlibnoise = { group = "com.sk89q.lib", name = "jlibnoise", version.ref = "jlibno
jchronic = { group = "com.sk89q", name = "jchronic", version.ref = "jchronic" } jchronic = { group = "com.sk89q", name = "jchronic", version.ref = "jchronic" }
lz4Java = { group = "org.lz4", name = "lz4-java", version.ref = "lz4-java" } lz4Java = { group = "org.lz4", name = "lz4-java", version.ref = "lz4-java" }
lz4JavaStream = { group = "net.jpountz", name = "lz4-java-stream", version.ref = "lz4-stream" } lz4JavaStream = { group = "net.jpountz", name = "lz4-java-stream", version.ref = "lz4-stream" }
commonsCli = { group = "commons-cli", name = "commons-cli", version.ref = "commons-cli" }
paperlib = { group = "io.papermc", name = "paperlib", version.ref = "paperlib" }
adventureApi = { group = "net.kyori", name = "adventure-api", version.ref = "adventure" }
adventureMiniMessage = { group = "net.kyori", name = "adventure-text-minimessage", version.ref = "adventure" }
adventureBukkit = { group = "net.kyori", name = "adventure-platform-bukkit", version.ref = "adventure-bukkit" }
paster = { group = "com.intellectualsites.paster", name = "Paster", version.ref = "paster" }
vault = { group = "com.github.MilkBowl", name = "VaultAPI", version.ref = "vault" }
serverlib = { group = "dev.notmyfault.serverlib", name = "ServerLib", version.ref = "serverlib" }
checkerqual = { group = "org.checkerframework", name = "checker-qual", version.ref = "checkerqual" }
# Internal # Internal
## Text ## Text
adventureTextAdapterBukkit = { group = "net.kyori", name = "text-adapter-bukkit", version.ref = "text-adapter" } adventureTextAdapterBukkit = { group = "net.kyori", name = "text-adapter-bukkit", version.ref = "text-adapter" }
adventureTextMiniMessage = { group = "net.kyori", name = "adventure-text-minimessage", version.ref = "adventure-text-minimessage" }
adventureTextApi = { group = "net.kyori", name = "text-api", version.ref = "text" } adventureTextApi = { group = "net.kyori", name = "text-api", version.ref = "text" }
adventureTextSerializerGson = { group = "net.kyori", name = "text-serializer-gson", version.ref = "text" } adventureTextSerializerGson = { group = "net.kyori", name = "text-serializer-gson", version.ref = "text" }
adventureTextSerializerLegacy = { group = "net.kyori", name = "text-serializer-legacy", version.ref = "text" } adventureTextSerializerLegacy = { group = "net.kyori", name = "text-serializer-legacy", version.ref = "text" }
@ -123,8 +118,8 @@ pistonRuntime = { group = "org.enginehub.piston.core-ap", name = "runtime", vers
# Tests # Tests
mockito = { group = "org.mockito", name = "mockito-core", version.ref = "mockito" } mockito = { group = "org.mockito", name = "mockito-core", version.ref = "mockito" }
checkerqual = { group = "org.checkerframework", name = "checker-qual", version.ref = "checker-qual" }
log4jCore = { group = "org.apache.logging.log4j", name = "log4j-core", version.ref = "log4j" } log4jCore = { group = "org.apache.logging.log4j", name = "log4j-core", version.ref = "log4j" }
[plugins] [plugins]
pluginyml = { id = "net.minecrell.plugin-yml.bukkit", version.ref = "pluginyml" } pluginyml = { id = "net.minecrell.plugin-yml.bukkit", version.ref = "pluginyml" }
minotaur = { id = "com.modrinth.minotaur", version.ref = "minotaur" }

Binäre Datei nicht angezeigt.

Datei anzeigen

@ -1,5 +1,7 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.2-all.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists

30
gradlew vendored
Datei anzeigen

@ -55,7 +55,7 @@
# Darwin, MinGW, and NonStop. # Darwin, MinGW, and NonStop.
# #
# (3) This script is generated from the Groovy template # (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project. # within the Gradle project.
# #
# You can find Gradle at https://github.com/gradle/gradle/. # You can find Gradle at https://github.com/gradle/gradle/.
@ -80,13 +80,10 @@ do
esac esac
done done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # This is normally unused
# shellcheck disable=SC2034
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/} APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD=maximum
@ -133,22 +130,29 @@ location of your Java installation."
fi fi
else else
JAVACMD=java JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi fi
fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #( case $MAX_FD in #(
max*) max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) || MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit" warn "Could not query maximum file descriptor limit"
esac esac
case $MAX_FD in #( case $MAX_FD in #(
'' | soft) :;; #( '' | soft) :;; #(
*) *)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" || ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD" warn "Could not set maximum file descriptor limit to $MAX_FD"
esac esac
@ -193,6 +197,10 @@ if "$cygwin" || "$msys" ; then
done done
fi fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command; # Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in # shell script including quotes and variable substitutions, so put them in
@ -205,6 +213,12 @@ set -- \
org.gradle.wrapper.GradleWrapperMain \ org.gradle.wrapper.GradleWrapperMain \
"$@" "$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args. # Use "xargs" to parse quoted args.
# #
# With -n1 it outputs one arg per line, with the quotes and backslashes removed. # With -n1 it outputs one arg per line, with the quotes and backslashes removed.

11
gradlew.bat vendored
Datei anzeigen

@ -26,6 +26,7 @@ if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=. if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% set APP_HOME=%DIRNAME%
@ -40,7 +41,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute if %ERRORLEVEL% equ 0 goto execute
echo. echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
@ -75,13 +76,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd if %ERRORLEVEL% equ 0 goto mainEnd
:fail :fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code! rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 set EXIT_CODE=%ERRORLEVEL%
exit /b 1 if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd :mainEnd
if "%OS%"=="Windows_NT" endlocal if "%OS%"=="Windows_NT" endlocal

Datei anzeigen

@ -1,29 +0,0 @@
{
"extends": [
"config:base",
":disableDependencyDashboard"
],
"ignoreDeps": [
"guava",
"com.google.guava:guava",
"rhino-runtime",
"mockito-core",
"org.antlr",
"antlr4-runtime",
"fastutil",
"it.unimi.dsi:fastutil",
"auto-value-annotations",
"auto-value",
"com.google.code.gson:gson",
"net.fabricmc:fabric-loader",
"net.fabricmc.fabric-api:fabric-api",
"com.github.luben:zstd-jni"
],
"timezone": "Europe/Berlin",
"schedule": [
"on monday after 9am"
],
"labels": ["Renovate"],
"commitMessagePrefix": "build: ",
"rebaseWhen": "conflicted"
}

Datei anzeigen

@ -2,15 +2,14 @@ rootProject.name = "FastAsyncWorldEdit"
include("worldedit-libs") include("worldedit-libs")
include("worldedit-bukkit:adapters:adapter-legacy") listOf("legacy", "1_17_1", "1_18_2", "1_19", "1_19_3","1_19_4", "1_20").forEach {
include("worldedit-bukkit:adapters:adapter-1_17_1") include("worldedit-bukkit:adapters:adapter-$it")
include("worldedit-bukkit:adapters:adapter-1_18") }
listOf("bukkit", "core", "cli").forEach { listOf("bukkit", "core", "cli").forEach {
include("worldedit-libs:$it") include("worldedit-libs:$it")
include("worldedit-$it") include("worldedit-$it")
} }
// include("worldedit-mod")
include("worldedit-libs:core:ap") include("worldedit-libs:core:ap")
dependencyResolutionManagement { dependencyResolutionManagement {
@ -23,5 +22,4 @@ dependencyResolutionManagement {
} }
} }
enableFeaturePreview("VERSION_CATALOGS")
enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS") enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS")

9
steamwarci.yml Normale Datei
Datei anzeigen

@ -0,0 +1,9 @@
build:
- "JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64 ./gradlew build"
- "JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64 ./gradlew --stop"
artifacts:
"/binarys/FastAsyncWorldEdit-1.18.jar": "worldedit-bukkit/build/libs/FastAsyncWorldEdit-Bukkit-2.7.1-SNAPSHOT.jar"
release:
- "mvn deploy:deploy-file -DgroupId=de.steamwar -DartifactId=fastasyncworldedit -Dversion=1.18 -Dpackaging=jar -Dfile=/binarys/FastAsyncWorldEdit-1.18.jar -Durl=file:///var/www/html/maven/"

Datei anzeigen

@ -1,3 +1,5 @@
import io.papermc.paperweight.userdev.PaperweightUserDependenciesExtension
applyPaperweightAdapterConfiguration() applyPaperweightAdapterConfiguration()
plugins { plugins {
@ -6,10 +8,7 @@ plugins {
repositories { repositories {
mavenCentral() mavenCentral()
maven { gradlePluginPortal()
name = "PaperMC"
url = uri("https://papermc.io/repo/repository/maven-public/")
}
} }
java { java {
@ -22,6 +21,6 @@ configurations.all {
dependencies { dependencies {
paperDevBundle("1.17.1-R0.1-20211219.175449-201") the<PaperweightUserDependenciesExtension>().paperDevBundle("1.17.1-R0.1-20220414.034903-210")
compileOnly(libs.paperlib) compileOnly(libs.paperlib)
} }

Datei anzeigen

@ -28,8 +28,6 @@ import com.google.common.collect.Maps;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.Futures;
import com.mojang.datafixers.util.Either; import com.mojang.datafixers.util.Either;
import com.mojang.serialization.Codec;
import com.mojang.serialization.Dynamic;
import com.mojang.serialization.Lifecycle; import com.mojang.serialization.Lifecycle;
import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
@ -56,6 +54,7 @@ import com.sk89q.worldedit.registry.state.IntegerProperty;
import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.registry.state.Property;
import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.util.Direction;
import com.sk89q.worldedit.util.SideEffect; import com.sk89q.worldedit.util.SideEffect;
import com.sk89q.worldedit.util.concurrency.LazyReference;
import com.sk89q.worldedit.util.formatting.text.Component; import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.util.formatting.text.TranslatableComponent; import com.sk89q.worldedit.util.formatting.text.TranslatableComponent;
import com.sk89q.worldedit.util.io.file.SafeFiles; import com.sk89q.worldedit.util.io.file.SafeFiles;
@ -86,10 +85,7 @@ import com.sk89q.worldedit.world.item.ItemType;
import net.minecraft.Util; import net.minecraft.Util;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.nbt.NbtOps;
import net.minecraft.network.protocol.game.ClientboundEntityEventPacket; import net.minecraft.network.protocol.game.ClientboundEntityEventPacket;
import net.minecraft.resources.RegistryReadOps;
import net.minecraft.resources.RegistryWriteOps;
import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
@ -152,13 +148,14 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.OptionalInt; import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.Set; import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinPool;
@ -171,11 +168,11 @@ import static com.google.common.base.Preconditions.checkState;
public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft.nbt.Tag> { public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft.nbt.Tag> {
private final Logger logger = Logger.getLogger(getClass().getCanonicalName()); private final Logger LOGGER = Logger.getLogger(getClass().getCanonicalName());
private final Field serverWorldsField; private final Field worldsField;
private final Method getChunkFutureMethod; private final Method getChunkFutureMainThreadMethod;
private final Field chunkProviderExecutorField; private final Field mainThreadProcessorField;
private final Watchdog watchdog; private final Watchdog watchdog;
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
@ -191,18 +188,18 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
throw new UnsupportedClassVersionError("Not 1.17.1!"); throw new UnsupportedClassVersionError("Not 1.17.1!");
} }
serverWorldsField = CraftServer.class.getDeclaredField("worlds"); worldsField = CraftServer.class.getDeclaredField("worlds");
serverWorldsField.setAccessible(true); worldsField.setAccessible(true);
getChunkFutureMethod = ServerChunkCache.class.getDeclaredMethod("getChunkFutureMainThread", getChunkFutureMainThreadMethod = ServerChunkCache.class.getDeclaredMethod("getChunkFutureMainThread",
int.class, int.class, ChunkStatus.class, boolean.class int.class, int.class, ChunkStatus.class, boolean.class
); );
getChunkFutureMethod.setAccessible(true); getChunkFutureMainThreadMethod.setAccessible(true);
chunkProviderExecutorField = ServerChunkCache.class.getDeclaredField( mainThreadProcessorField = ServerChunkCache.class.getDeclaredField(
Refraction.pickName("mainThreadProcessor", "h") Refraction.pickName("mainThreadProcessor", "h")
); );
chunkProviderExecutorField.setAccessible(true); mainThreadProcessorField.setAccessible(true);
new PaperweightDataConverters(CraftMagicNumbers.INSTANCE.getDataVersion(), this).build(ForkJoinPool.commonPool()); new PaperweightDataConverters(CraftMagicNumbers.INSTANCE.getDataVersion(), this).build(ForkJoinPool.commonPool());
@ -221,7 +218,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
try { try {
Class.forName("org.spigotmc.SpigotConfig"); Class.forName("org.spigotmc.SpigotConfig");
SpigotConfig.config.set("world-settings.worldeditregentempworld.verbose", false); SpigotConfig.config.set("world-settings.faweregentempworld.verbose", false);
} catch (ClassNotFoundException ignored) { } catch (ClassNotFoundException ignored) {
} }
} }
@ -435,7 +432,12 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
net.minecraft.nbt.CompoundTag tag = new net.minecraft.nbt.CompoundTag(); net.minecraft.nbt.CompoundTag tag = new net.minecraft.nbt.CompoundTag();
readEntityIntoTag(mcEntity, tag); readEntityIntoTag(mcEntity, tag);
return new BaseEntity(com.sk89q.worldedit.world.entity.EntityTypes.get(id), (CompoundTag) toNative(tag)); //FAWE start - BinaryTag
return new BaseEntity(
com.sk89q.worldedit.world.entity.EntityTypes.get(id),
LazyReference.from(() -> (CompoundBinaryTag) toNativeBinary(tag))
);
//FAWE end
} }
@Nullable @Nullable
@ -484,42 +486,34 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
} }
@SuppressWarnings({"unchecked", "rawtypes"}) @SuppressWarnings({"unchecked", "rawtypes"})
private static final LoadingCache<net.minecraft.world.level.block.state.properties.Property, Property<?>> PROPERTY_CACHE = CacheBuilder.newBuilder().build(new CacheLoader<net.minecraft.world.level.block.state.properties.Property, Property<?>>() {
@Override
public Property<?> load(net.minecraft.world.level.block.state.properties.Property state) throws Exception {
if (state instanceof net.minecraft.world.level.block.state.properties.BooleanProperty) {
return new BooleanProperty(state.getName(), ImmutableList.copyOf(state.getPossibleValues()));
} else if (state instanceof DirectionProperty) {
return new DirectionalProperty(state.getName(),
(List<Direction>) state.getPossibleValues().stream().map(e -> Direction.valueOf(((StringRepresentable) e).getSerializedName().toUpperCase(Locale.ROOT))).collect(Collectors.toList()));
} else if (state instanceof net.minecraft.world.level.block.state.properties.EnumProperty) {
return new EnumProperty(state.getName(),
(List<String>) state.getPossibleValues().stream().map(e -> ((StringRepresentable) e).getSerializedName()).collect(Collectors.toList()));
} else if (state instanceof net.minecraft.world.level.block.state.properties.IntegerProperty) {
return new IntegerProperty(state.getName(), ImmutableList.copyOf(state.getPossibleValues()));
} else {
throw new IllegalArgumentException("FastAsyncWorldEdit needs an update to support " + state.getClass().getSimpleName());
}
}
});
@SuppressWarnings({ "rawtypes" })
@Override @Override
public Map<String, ? extends Property<?>> getProperties(BlockType blockType) { public Map<String, ? extends Property<?>> getProperties(BlockType blockType) {
Map<String, Property<?>> properties = Maps.newTreeMap(String::compareTo); Map<String, Property<?>> properties = new TreeMap<>();
Block block = getBlockFromType(blockType); Block block = getBlockFromType(blockType);
StateDefinition<Block, net.minecraft.world.level.block.state.BlockState> blockStateList = StateDefinition<Block, net.minecraft.world.level.block.state.BlockState> blockStateList =
block.getStateDefinition(); block.getStateDefinition();
for (net.minecraft.world.level.block.state.properties.Property state : blockStateList.getProperties()) { for (net.minecraft.world.level.block.state.properties.Property state : blockStateList.getProperties()) {
Property property; Property<?> property = PROPERTY_CACHE.getUnchecked(state);
if (state instanceof net.minecraft.world.level.block.state.properties.BooleanProperty) {
property = new BooleanProperty(state.getName(), ImmutableList.copyOf(state.getPossibleValues()));
} else if (state instanceof DirectionProperty) {
property = new DirectionalProperty(
state.getName(),
(List<Direction>) state
.getPossibleValues()
.stream()
.map(e -> Direction.valueOf(((StringRepresentable) e)
.getSerializedName()
.toUpperCase(Locale.ROOT)))
.collect(Collectors.toList())
);
} else if (state instanceof net.minecraft.world.level.block.state.properties.EnumProperty) {
property = new EnumProperty(
state.getName(),
(List<String>) state
.getPossibleValues()
.stream()
.map(e -> ((StringRepresentable) e).getSerializedName())
.collect(Collectors.toList())
);
} else if (state instanceof net.minecraft.world.level.block.state.properties.IntegerProperty) {
property = new IntegerProperty(state.getName(), ImmutableList.copyOf(state.getPossibleValues()));
} else {
throw new IllegalArgumentException("WorldEdit needs an update to support " + state.getClass().getSimpleName());
}
properties.put(property.getName(), property); properties.put(property.getName(), property);
} }
return properties; return properties;
@ -622,7 +616,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
Path tempDir = Files.createTempDirectory("FastAsyncWorldEditWorldGen"); Path tempDir = Files.createTempDirectory("FastAsyncWorldEditWorldGen");
LevelStorageSource levelStorage = LevelStorageSource.createDefault(tempDir); LevelStorageSource levelStorage = LevelStorageSource.createDefault(tempDir);
ResourceKey<LevelStem> worldDimKey = getWorldDimKey(env); ResourceKey<LevelStem> worldDimKey = getWorldDimKey(env);
try (LevelStorageSource.LevelStorageAccess session = levelStorage.createAccess("worldeditregentempworld", worldDimKey)) { try (LevelStorageSource.LevelStorageAccess session = levelStorage.createAccess("faweregentempworld", worldDimKey)) {
ServerLevel originalWorld = ((CraftWorld) bukkitWorld).getHandle(); ServerLevel originalWorld = ((CraftWorld) bukkitWorld).getHandle();
PrimaryLevelData levelProperties = (PrimaryLevelData) originalWorld.getServer() PrimaryLevelData levelProperties = (PrimaryLevelData) originalWorld.getServer()
.getWorldData().overworldData(); .getWorldData().overworldData();
@ -630,11 +624,11 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
long seed = options.getSeed().orElse(originalWorld.getSeed()); long seed = options.getSeed().orElse(originalWorld.getSeed());
WorldGenSettings newOpts = options.getSeed().isPresent() WorldGenSettings newOpts = options.getSeed().isPresent()
? replaceSeed(originalWorld, seed, originalOpts) ? originalOpts.withSeed(levelProperties.isHardcore(), OptionalLong.of(seed))
: originalOpts; : originalOpts;
LevelSettings newWorldSettings = new LevelSettings( LevelSettings newWorldSettings = new LevelSettings(
"worldeditregentempworld", "faweregentempworld",
levelProperties.settings.gameType(), levelProperties.settings.gameType(),
levelProperties.settings.hardcore(), levelProperties.settings.hardcore(),
levelProperties.settings.difficulty(), levelProperties.settings.difficulty(),
@ -667,65 +661,14 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
} finally { } finally {
try { try {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<String, org.bukkit.World> map = (Map<String, org.bukkit.World>) serverWorldsField.get(Bukkit.getServer()); Map<String, org.bukkit.World> map = (Map<String, org.bukkit.World>) worldsField.get(Bukkit.getServer());
map.remove("worldeditregentempworld"); map.remove("faweregentempworld");
} catch (IllegalAccessException ignored) { } catch (IllegalAccessException ignored) {
} }
SafeFiles.tryHardToDeleteDir(tempDir); SafeFiles.tryHardToDeleteDir(tempDir);
} }
} }
// FAWE start - private -> public static
public static WorldGenSettings replaceSeed(ServerLevel originalWorld, long seed, WorldGenSettings originalOpts) {
// FAWE end
RegistryWriteOps<net.minecraft.nbt.Tag> nbtReadRegOps = RegistryWriteOps.create(
NbtOps.INSTANCE,
originalWorld.getServer().registryAccess()
);
RegistryReadOps<net.minecraft.nbt.Tag> nbtRegOps = RegistryReadOps.createAndLoad(
NbtOps.INSTANCE,
originalWorld.getServer().getResourceManager(),
originalWorld.getServer().registryAccess()
);
Codec<WorldGenSettings> dimCodec = WorldGenSettings.CODEC;
return dimCodec
.encodeStart(nbtReadRegOps, originalOpts)
.flatMap(tag ->
dimCodec.parse(
recursivelySetSeed(new Dynamic<>(nbtRegOps, tag), seed, new HashSet<>())
)
)
.get()
.map(
l -> l,
error -> {
throw new IllegalStateException("Unable to map GeneratorOptions: " + error.message());
}
);
}
// FAWE start - private -> private static
@SuppressWarnings("unchecked")
private static Dynamic<net.minecraft.nbt.Tag> recursivelySetSeed(
// FAWE end
Dynamic<net.minecraft.nbt.Tag> dynamic,
long seed,
Set<Dynamic<net.minecraft.nbt.Tag>> seen
) {
if (!seen.add(dynamic)) {
return dynamic;
}
return dynamic.updateMapValues(pair -> {
if (pair.getFirst().asString("").equals("seed")) {
return pair.mapSecond(v -> v.createLong(seed));
}
if (pair.getSecond().getValue() instanceof net.minecraft.nbt.CompoundTag) {
return pair.mapSecond(v -> recursivelySetSeed((Dynamic<net.minecraft.nbt.Tag>) v, seed, seen));
}
return pair;
});
}
private BiomeType adapt(ServerLevel serverWorld, Biome origBiome) { private BiomeType adapt(ServerLevel serverWorld, Biome origBiome) {
ResourceLocation key = serverWorld.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).getKey(origBiome); ResourceLocation key = serverWorld.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).getKey(origBiome);
if (key == null) { if (key == null) {
@ -740,7 +683,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
List<CompletableFuture<ChunkAccess>> chunkLoadings = submitChunkLoadTasks(region, serverWorld); List<CompletableFuture<ChunkAccess>> chunkLoadings = submitChunkLoadTasks(region, serverWorld);
BlockableEventLoop<Runnable> executor; BlockableEventLoop<Runnable> executor;
try { try {
executor = (BlockableEventLoop<Runnable>) chunkProviderExecutorField.get(serverWorld.getChunkSource()); executor = (BlockableEventLoop<Runnable>) mainThreadProcessorField.get(serverWorld.getChunkSource());
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
throw new IllegalStateException("Couldn't get executor for chunk loading.", e); throw new IllegalStateException("Couldn't get executor for chunk loading.", e);
} }
@ -798,10 +741,9 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
// Pre-gen all the chunks // Pre-gen all the chunks
for (BlockVector2 chunk : region.getChunks()) { for (BlockVector2 chunk : region.getChunks()) {
try { try {
//noinspection unchecked
chunkLoadings.add( chunkLoadings.add(
((CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>>) ((CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>>)
getChunkFutureMethod.invoke(chunkManager, chunk.getX(), chunk.getZ(), ChunkStatus.FEATURES, true)) getChunkFutureMainThreadMethod.invoke(chunkManager, chunk.getX(), chunk.getZ(), ChunkStatus.FEATURES, true))
.thenApply(either -> either.left().orElse(null)) .thenApply(either -> either.left().orElse(null))
); );
} catch (IllegalAccessException | InvocationTargetException e) { } catch (IllegalAccessException | InvocationTargetException e) {
@ -893,7 +835,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
try { try {
return toNativeList((net.minecraft.nbt.ListTag) foreign); return toNativeList((net.minecraft.nbt.ListTag) foreign);
} catch (Throwable e) { } catch (Throwable e) {
logger.log(Level.WARNING, "Failed to convert net.minecraft.nbt.ListTag", e); LOGGER.log(Level.WARNING, "Failed to convert net.minecraft.nbt.ListTag", e);
return ListBinaryTag.empty(); return ListBinaryTag.empty();
} }
} else if (foreign instanceof net.minecraft.nbt.LongTag) { } else if (foreign instanceof net.minecraft.nbt.LongTag) {
@ -918,7 +860,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
* @throws IllegalArgumentException on error * @throws IllegalArgumentException on error
*/ */
private ListBinaryTag toNativeList(net.minecraft.nbt.ListTag foreign) throws SecurityException, IllegalArgumentException { private ListBinaryTag toNativeList(net.minecraft.nbt.ListTag foreign) throws SecurityException, IllegalArgumentException {
ListBinaryTag.Builder values = ListBinaryTag.builder(); ListBinaryTag.Builder<BinaryTag> values = ListBinaryTag.builder();
for (net.minecraft.nbt.Tag tag : foreign) { for (net.minecraft.nbt.Tag tag : foreign) {
values.add(toNativeBinary(tag)); values.add(toNativeBinary(tag));
@ -958,9 +900,8 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
return new net.minecraft.nbt.IntArrayTag(((IntArrayBinaryTag) foreign).value()); return new net.minecraft.nbt.IntArrayTag(((IntArrayBinaryTag) foreign).value());
} else if (foreign instanceof LongArrayBinaryTag) { } else if (foreign instanceof LongArrayBinaryTag) {
return new net.minecraft.nbt.LongArrayTag(((LongArrayBinaryTag) foreign).value()); return new net.minecraft.nbt.LongArrayTag(((LongArrayBinaryTag) foreign).value());
} else if (foreign instanceof ListBinaryTag) { } else if (foreign instanceof ListBinaryTag foreignList) {
net.minecraft.nbt.ListTag tag = new net.minecraft.nbt.ListTag(); net.minecraft.nbt.ListTag tag = new net.minecraft.nbt.ListTag();
ListBinaryTag foreignList = (ListBinaryTag) foreign;
for (BinaryTag t : foreignList) { for (BinaryTag t : foreignList) {
tag.add(fromNativeBinary(t)); tag.add(fromNativeBinary(t));
} }
@ -1012,7 +953,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
WatchdogThread.tick(); WatchdogThread.tick();
} }
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
logger.log(Level.WARNING, "Failed to tick watchdog", e); LOGGER.log(Level.WARNING, "Failed to tick watchdog", e);
} }
} }
@ -1049,7 +990,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
} }
@Override @Override
public void onStatusChange(ChunkPos pos, @org.jetbrains.annotations.Nullable ChunkStatus status) { public void onStatusChange(ChunkPos pos, @Nullable ChunkStatus status) {
} }
@Override @Override

Datei anzeigen

@ -6,13 +6,14 @@ import com.fastasyncworldedit.bukkit.adapter.NMSRelighterFactory;
import com.fastasyncworldedit.core.FaweCache; import com.fastasyncworldedit.core.FaweCache;
import com.fastasyncworldedit.core.entity.LazyBaseEntity; import com.fastasyncworldedit.core.entity.LazyBaseEntity;
import com.fastasyncworldedit.core.extent.processor.lighting.RelighterFactory; import com.fastasyncworldedit.core.extent.processor.lighting.RelighterFactory;
import com.fastasyncworldedit.core.queue.IBatchProcessor;
import com.fastasyncworldedit.core.queue.IChunkGet; import com.fastasyncworldedit.core.queue.IChunkGet;
import com.fastasyncworldedit.core.queue.implementation.packet.ChunkPacket; import com.fastasyncworldedit.core.queue.implementation.packet.ChunkPacket;
import com.fastasyncworldedit.core.util.NbtUtils;
import com.fastasyncworldedit.core.util.TaskManager;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.StringTag;
import com.sk89q.jnbt.Tag; import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.blocks.BaseItemStack;
@ -40,6 +41,9 @@ import com.sk89q.worldedit.util.SideEffect;
import com.sk89q.worldedit.util.SideEffectSet; import com.sk89q.worldedit.util.SideEffectSet;
import com.sk89q.worldedit.util.TreeGenerator; import com.sk89q.worldedit.util.TreeGenerator;
import com.sk89q.worldedit.util.formatting.text.Component; import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.util.nbt.BinaryTag;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.util.nbt.StringBinaryTag;
import com.sk89q.worldedit.world.RegenOptions; import com.sk89q.worldedit.world.RegenOptions;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BaseBlock;
@ -82,7 +86,6 @@ import org.bukkit.block.data.BlockData;
import org.bukkit.craftbukkit.v1_17_R1.CraftChunk; import org.bukkit.craftbukkit.v1_17_R1.CraftChunk;
import org.bukkit.craftbukkit.v1_17_R1.CraftServer; import org.bukkit.craftbukkit.v1_17_R1.CraftServer;
import org.bukkit.craftbukkit.v1_17_R1.CraftWorld; import org.bukkit.craftbukkit.v1_17_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_17_R1.block.CraftBlock;
import org.bukkit.craftbukkit.v1_17_R1.block.CraftBlockState; import org.bukkit.craftbukkit.v1_17_R1.block.CraftBlockState;
import org.bukkit.craftbukkit.v1_17_R1.block.data.CraftBlockData; import org.bukkit.craftbukkit.v1_17_R1.block.data.CraftBlockData;
import org.bukkit.craftbukkit.v1_17_R1.entity.CraftEntity; import org.bukkit.craftbukkit.v1_17_R1.entity.CraftEntity;
@ -100,6 +103,7 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.OptionalInt; import java.util.OptionalInt;
import java.util.Set; import java.util.Set;
import java.util.function.Supplier; import java.util.function.Supplier;
@ -140,6 +144,7 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
return parent; return parent;
} }
@SuppressWarnings("unchecked")
private synchronized boolean init() { private synchronized boolean init() {
if (ibdToStateOrdinal != null && ibdToStateOrdinal[1] != 0) { if (ibdToStateOrdinal != null && ibdToStateOrdinal[1] != 0) {
return false; return false;
@ -158,10 +163,9 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
try { try {
for (Field field : BlockStateProperties.class.getDeclaredFields()) { for (Field field : BlockStateProperties.class.getDeclaredFields()) {
Object obj = field.get(null); Object obj = field.get(null);
if (!(obj instanceof net.minecraft.world.level.block.state.properties.Property)) { if (!(obj instanceof net.minecraft.world.level.block.state.properties.Property<?> state)) {
continue; continue;
} }
net.minecraft.world.level.block.state.properties.Property<?> state = (net.minecraft.world.level.block.state.properties.Property<?>) obj;
Property<?> property; Property<?> property;
if (state instanceof net.minecraft.world.level.block.state.properties.BooleanProperty) { if (state instanceof net.minecraft.world.level.block.state.properties.BooleanProperty) {
property = new BooleanProperty( property = new BooleanProperty(
@ -274,9 +278,8 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
// Read the NBT data // Read the NBT data
BlockEntity blockEntity = chunk.getBlockEntity(blockPos, LevelChunk.EntityCreationType.CHECK); BlockEntity blockEntity = chunk.getBlockEntity(blockPos, LevelChunk.EntityCreationType.CHECK);
if (blockEntity != null) { if (blockEntity != null) {
//TODO 1.18 recheck logic, I may skipped loading - NMF
net.minecraft.nbt.CompoundTag tag = blockEntity.save(new net.minecraft.nbt.CompoundTag()); net.minecraft.nbt.CompoundTag tag = blockEntity.save(new net.minecraft.nbt.CompoundTag());
return state.toBaseBlock((CompoundTag) toNative(tag)); return state.toBaseBlock((CompoundBinaryTag) toNativeBinary(tag));
} }
} }
@ -288,6 +291,7 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
return SideEffectSet.defaults().getSideEffectsToApply(); return SideEffectSet.defaults().getSideEffectsToApply();
} }
@SuppressWarnings("rawtypes")
public boolean setBlock(org.bukkit.Chunk chunk, int x, int y, int z, BlockStateHolder state, boolean update) { public boolean setBlock(org.bukkit.Chunk chunk, int x, int y, int z, BlockStateHolder state, boolean update) {
CraftChunk craftChunk = (CraftChunk) chunk; CraftChunk craftChunk = (CraftChunk) chunk;
LevelChunk levelChunk = craftChunk.getHandle(); LevelChunk levelChunk = craftChunk.getHandle();
@ -308,7 +312,7 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
levelChunk.removeBlockEntity(blockPos); // Force delete the old tile entity levelChunk.removeBlockEntity(blockPos); // Force delete the old tile entity
CompoundTag compoundTag = state instanceof BaseBlock ? state.getNbtData() : null; CompoundBinaryTag compoundTag = state instanceof BaseBlock ? state.getNbt() : null;
if (compoundTag != null || existing instanceof TileEntityBlock) { if (compoundTag != null || existing instanceof TileEntityBlock) {
level.setBlock(blockPos, blockState, 0); level.setBlock(blockPos, blockState, 0);
// remove tile // remove tile
@ -317,7 +321,7 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
// though we do not do this on the Forge version // though we do not do this on the Forge version
BlockEntity blockEntity = level.getBlockEntity(blockPos); BlockEntity blockEntity = level.getBlockEntity(blockPos);
if (blockEntity != null) { if (blockEntity != null) {
net.minecraft.nbt.CompoundTag tag = (net.minecraft.nbt.CompoundTag) fromNative(compoundTag); net.minecraft.nbt.CompoundTag tag = (net.minecraft.nbt.CompoundTag) fromNativeBinary(compoundTag);
tag.put("x", IntTag.valueOf(x)); tag.put("x", IntTag.valueOf(x));
tag.put("y", IntTag.valueOf(y)); tag.put("y", IntTag.valueOf(y));
tag.put("z", IntTag.valueOf(z)); tag.put("z", IntTag.valueOf(z));
@ -361,14 +365,14 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
if (id != null) { if (id != null) {
EntityType type = com.sk89q.worldedit.world.entity.EntityTypes.get(id); EntityType type = com.sk89q.worldedit.world.entity.EntityTypes.get(id);
Supplier<CompoundTag> saveTag = () -> { Supplier<CompoundBinaryTag> saveTag = () -> {
final net.minecraft.nbt.CompoundTag minecraftTag = new net.minecraft.nbt.CompoundTag(); final net.minecraft.nbt.CompoundTag minecraftTag = new net.minecraft.nbt.CompoundTag();
readEntityIntoTag(mcEntity, minecraftTag); readEntityIntoTag(mcEntity, minecraftTag);
//add Id for AbstractChangeSet to work //add Id for AbstractChangeSet to work
final CompoundTag tag = (CompoundTag) toNative(minecraftTag); final CompoundBinaryTag tag = (CompoundBinaryTag) toNativeBinary(minecraftTag);
final Map<String, Tag> tags = new HashMap<>(tag.getValue()); final Map<String, BinaryTag> tags = NbtUtils.getCompoundBinaryTagValues(tag);
tags.put("Id", new StringTag(id)); tags.put("Id", StringBinaryTag.of(id));
return new CompoundTag(tags); return CompoundBinaryTag.from(tags);
}; };
return new LazyBaseEntity(type, saveTag); return new LazyBaseEntity(type, saveTag);
} else { } else {
@ -425,7 +429,7 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
LOGGER.error("Attempted to convert {} with ID {} to char. ibdToStateOrdinal length: {}. Defaulting to air!", LOGGER.error("Attempted to convert {} with ID {} to char. ibdToStateOrdinal length: {}. Defaulting to air!",
blockState.getBlock(), Block.BLOCK_STATE_REGISTRY.getId(blockState), ibdToStateOrdinal.length, e1 blockState.getBlock(), Block.BLOCK_STATE_REGISTRY.getId(blockState), ibdToStateOrdinal.length, e1
); );
return 0; return BlockTypesCache.ReservedIDs.AIR;
} }
} }
} }
@ -541,7 +545,7 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
Registry.ITEM.get(ResourceLocation.tryParse(baseItemStack.getType().getId())), Registry.ITEM.get(ResourceLocation.tryParse(baseItemStack.getType().getId())),
baseItemStack.getAmount() baseItemStack.getAmount()
); );
stack.setTag(((net.minecraft.nbt.CompoundTag) fromNative(baseItemStack.getNbtData()))); stack.setTag(((net.minecraft.nbt.CompoundTag) fromNativeBinary(baseItemStack.getNbt())));
return CraftItemStack.asCraftMirror(stack); return CraftItemStack.asCraftMirror(stack);
} }
@ -559,16 +563,26 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
); // bukkit skips the feature gen which does this offset normally, so we have to add it back ); // bukkit skips the feature gen which does this offset normally, so we have to add it back
} }
ServerLevel serverLevel = ((CraftWorld) bukkitWorld).getHandle(); ServerLevel serverLevel = ((CraftWorld) bukkitWorld).getHandle();
final BlockVector3 finalBlockVector = blockVector3;
// Sync to main thread to ensure no clashes occur
Map<BlockPos, CraftBlockState> placed = TaskManager.taskManager().sync(() -> {
serverLevel.captureTreeGeneration = true; serverLevel.captureTreeGeneration = true;
serverLevel.captureBlockStates = true; serverLevel.captureBlockStates = true;
boolean grownTree = bukkitWorld.generateTree(BukkitAdapter.adapt(bukkitWorld, blockVector3), bukkitType); try {
if (!bukkitWorld.generateTree(BukkitAdapter.adapt(bukkitWorld, finalBlockVector), bukkitType)) {
return null;
}
return ImmutableMap.copyOf(serverLevel.capturedBlockStates);
} finally {
serverLevel.captureBlockStates = false; serverLevel.captureBlockStates = false;
serverLevel.captureTreeGeneration = false; serverLevel.captureTreeGeneration = false;
if (!grownTree) {
serverLevel.capturedBlockStates.clear(); serverLevel.capturedBlockStates.clear();
}
});
if (placed == null || placed.isEmpty()) {
return false; return false;
} else { }
for (CraftBlockState craftBlockState : serverLevel.capturedBlockStates.values()) { for (CraftBlockState craftBlockState : placed.values()) {
if (craftBlockState == null || craftBlockState.getType() == Material.AIR) { if (craftBlockState == null || craftBlockState.getType() == Material.AIR) {
continue; continue;
} }
@ -576,11 +590,8 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
BukkitAdapter.adapt(((org.bukkit.block.BlockState) craftBlockState).getBlockData()) BukkitAdapter.adapt(((org.bukkit.block.BlockState) craftBlockState).getBlockData())
); );
} }
serverLevel.capturedBlockStates.clear();
return true; return true;
} }
}
@Override @Override
public List<org.bukkit.entity.Entity> getEntities(org.bukkit.World world) { public List<org.bukkit.entity.Entity> getEntities(org.bukkit.World world) {
@ -603,7 +614,7 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
public BaseItemStack adapt(org.bukkit.inventory.ItemStack itemStack) { public BaseItemStack adapt(org.bukkit.inventory.ItemStack itemStack) {
final ItemStack nmsStack = CraftItemStack.asNMSCopy(itemStack); final ItemStack nmsStack = CraftItemStack.asNMSCopy(itemStack);
final BaseItemStack weStack = new BaseItemStack(BukkitAdapter.asItemType(itemStack.getType()), itemStack.getAmount()); final BaseItemStack weStack = new BaseItemStack(BukkitAdapter.asItemType(itemStack.getType()), itemStack.getAmount());
weStack.setNbtData(((CompoundTag) toNative(nmsStack.getTag()))); weStack.setNbt(((CompoundBinaryTag) toNativeBinary(nmsStack.getTag())));
return weStack; return weStack;
} }
@ -632,22 +643,13 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
@Override @Override
public int getInternalBiomeId(BiomeType biomeType) { public int getInternalBiomeId(BiomeType biomeType) {
if (biomeType.getId().startsWith("minecraft:")) { final Registry<Biome> registry = MinecraftServer
Biome biomeBase = CraftBlock.biomeToBiomeBase( .getServer()
MinecraftServer.getServer().registryAccess().ownedRegistryOrThrow(Registry.BIOME_REGISTRY), .registryAccess()
BukkitAdapter.adapt(biomeType)
);
return MinecraftServer.getServer().registryAccess().ownedRegistryOrThrow(Registry.BIOME_REGISTRY).getId(biomeBase);
} else {
WritableRegistry<Biome> biomeRegistry = MinecraftServer.getServer().registryAccess()
.ownedRegistryOrThrow(Registry.BIOME_REGISTRY); .ownedRegistryOrThrow(Registry.BIOME_REGISTRY);
ResourceLocation resourceLocation = ResourceLocation.tryParse(biomeType.getId());
ResourceLocation resourceLocation = biomeRegistry.keySet().stream() Biome biome = registry.get(resourceLocation);
.filter(resource -> resource.toString().equals(biomeType.getId())) return registry.getId(biome);
.findAny().orElse(null);
return biomeRegistry.getId(biomeRegistry.get(resourceLocation));
}
} }
@Override @Override
@ -657,10 +659,17 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
.registryAccess() .registryAccess()
.ownedRegistryOrThrow( .ownedRegistryOrThrow(
Registry.BIOME_REGISTRY); Registry.BIOME_REGISTRY);
return biomeRegistry.stream() List<ResourceLocation> keys = biomeRegistry.stream()
.map(biomeRegistry::getKey) .map(biomeRegistry::getKey).filter(Objects::nonNull).toList();
.map(CraftNamespacedKey::fromMinecraft) List<NamespacedKey> namespacedKeys = new ArrayList<>();
.collect(Collectors.toList()); for (ResourceLocation key : keys) {
try {
namespacedKeys.add(CraftNamespacedKey.fromMinecraft(key));
} catch (IllegalArgumentException e) {
LOGGER.error("Error converting biome key {}", key.toString(), e);
}
}
return namespacedKeys;
} }
@Override @Override
@ -692,4 +701,9 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
} }
} }
@Override
public IBatchProcessor getTickingPostProcessor() {
return new PaperweightPostProcessor();
}
} }

Datei anzeigen

@ -246,7 +246,7 @@ public class PaperweightFaweWorldNativeAccess implements WorldNativeAccess<Level
return; return;
} }
for (IntPair chunk : toSend) { for (IntPair chunk : toSend) {
PaperweightPlatformAdapter.sendChunk(getLevel().getWorld().getHandle(), chunk.x, chunk.z, false); PaperweightPlatformAdapter.sendChunk(getLevel().getWorld().getHandle(), chunk.x(), chunk.z(), false);
} }
} }
}; };
@ -262,7 +262,7 @@ public class PaperweightFaweWorldNativeAccess implements WorldNativeAccess<Level
sideEffectSet != null && sideEffectSet.shouldApply(SideEffect.UPDATE) sideEffectSet != null && sideEffectSet.shouldApply(SideEffect.UPDATE)
)); ));
for (IntPair chunk : cachedChunksToSend) { for (IntPair chunk : cachedChunksToSend) {
PaperweightPlatformAdapter.sendChunk(getLevel().getWorld().getHandle(), chunk.x, chunk.z, false); PaperweightPlatformAdapter.sendChunk(getLevel().getWorld().getHandle(), chunk.x(), chunk.z(), false);
} }
} }
}; };
@ -275,21 +275,11 @@ public class PaperweightFaweWorldNativeAccess implements WorldNativeAccess<Level
cachedChunksToSend.clear(); cachedChunksToSend.clear();
} }
private static final class CachedChange { private record CachedChange(
private final LevelChunk levelChunk;
private final BlockPos blockPos;
private final net.minecraft.world.level.block.state.BlockState blockState;
private CachedChange(
LevelChunk levelChunk, LevelChunk levelChunk,
BlockPos blockPos, BlockPos blockPos,
net.minecraft.world.level.block.state.BlockState blockState net.minecraft.world.level.block.state.BlockState blockState
) { ) {
this.levelChunk = levelChunk;
this.blockPos = blockPos;
this.blockState = blockState;
}
} }

Datei anzeigen

@ -11,9 +11,9 @@ import com.fastasyncworldedit.core.queue.IChunkGet;
import com.fastasyncworldedit.core.queue.IChunkSet; import com.fastasyncworldedit.core.queue.IChunkSet;
import com.fastasyncworldedit.core.queue.implementation.QueueHandler; import com.fastasyncworldedit.core.queue.implementation.QueueHandler;
import com.fastasyncworldedit.core.queue.implementation.blocks.CharGetBlocks; import com.fastasyncworldedit.core.queue.implementation.blocks.CharGetBlocks;
import com.fastasyncworldedit.core.util.MathMan;
import com.fastasyncworldedit.core.util.collection.AdaptedMap; import com.fastasyncworldedit.core.util.collection.AdaptedMap;
import com.google.common.base.Suppliers; import com.google.common.base.Suppliers;
import com.google.common.collect.Iterables;
import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.ListTag; import com.sk89q.jnbt.ListTag;
import com.sk89q.jnbt.StringTag; import com.sk89q.jnbt.StringTag;
@ -25,6 +25,7 @@ import com.sk89q.worldedit.internal.Constants;
import com.sk89q.worldedit.internal.util.LogManagerCompat; import com.sk89q.worldedit.internal.util.LogManagerCompat;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BlockTypesCache;
import io.papermc.lib.PaperLib; import io.papermc.lib.PaperLib;
import io.papermc.paper.event.block.BeaconDeactivatedEvent; import io.papermc.paper.event.block.BeaconDeactivatedEvent;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
@ -57,15 +58,14 @@ import org.bukkit.World;
import org.bukkit.craftbukkit.v1_17_R1.CraftWorld; import org.bukkit.craftbukkit.v1_17_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_17_R1.block.CraftBlock; import org.bukkit.craftbukkit.v1_17_R1.block.CraftBlock;
import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.CreatureSpawnEvent;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nullable; import javax.annotation.Nonnull;
import java.util.AbstractSet; import java.util.AbstractSet;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -73,9 +73,11 @@ import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors;
public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBlocks { public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBlocks {
@ -171,7 +173,8 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
@Override @Override
public void setHeightmapToGet(HeightMapType type, int[] data) { public void setHeightmapToGet(HeightMapType type, int[] data) {
BitArrayUnstretched bitArray = new BitArrayUnstretched(9, 256); // height + 1 to match server internal
BitArrayUnstretched bitArray = new BitArrayUnstretched(MathMan.log2nlz(getChunk().getHeight() + 1), 256);
bitArray.fromRaw(data); bitArray.fromRaw(data);
Heightmap.Types nativeType = Heightmap.Types.valueOf(type.name()); Heightmap.Types nativeType = Heightmap.Types.valueOf(type.name());
Heightmap heightMap = getChunk().heightmaps.get(nativeType); Heightmap heightMap = getChunk().heightmaps.get(nativeType);
@ -325,14 +328,9 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
org.bukkit.entity.Entity bukkitEnt = entity.getBukkitEntity(); org.bukkit.entity.Entity bukkitEnt = entity.getBukkitEntity();
return BukkitAdapter.adapt(bukkitEnt).getState().getNbtData(); return BukkitAdapter.adapt(bukkitEnt).getState().getNbtData();
} }
for (List<Entity> entry : /*getChunk().getEntitySlices()*/ new List[0]) { for (CompoundTag tag : getEntities()) {
if (entry != null) { if (uuid.equals(tag.getUUID())) {
for (Entity ent : entry) { return tag;
if (uuid.equals(ent.getUUID())) {
org.bukkit.entity.Entity bukkitEnt = ent.getBukkitEntity();
return BukkitAdapter.adapt(bukkitEnt).getState().getNbtData();
}
}
} }
} }
return null; return null;
@ -340,21 +338,15 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
@Override @Override
public Set<CompoundTag> getEntities() { public Set<CompoundTag> getEntities() {
List<Entity>[] slices = /*getChunk().getEntitySlices()*/ new List[0]; List<Entity> entities = PaperweightPlatformAdapter.getEntities(getChunk());
int size = 0; if (entities.isEmpty()) {
for (List<Entity> slice : slices) {
if (slice != null) {
size += slice.size();
}
}
if (slices.length == 0) {
return Collections.emptySet(); return Collections.emptySet();
} }
int finalSize = size; int size = entities.size();
return new AbstractSet<CompoundTag>() { return new AbstractSet<>() {
@Override @Override
public int size() { public int size() {
return finalSize; return size;
} }
@Override @Override
@ -364,40 +356,27 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
@Override @Override
public boolean contains(Object get) { public boolean contains(Object get) {
if (!(get instanceof CompoundTag)) { if (!(get instanceof CompoundTag getTag)) {
return false; return false;
} }
CompoundTag getTag = (CompoundTag) get; UUID getUUID = getTag.getUUID();
Map<String, Tag> value = getTag.getValue(); for (Entity entity : entities) {
CompoundTag getParts = (CompoundTag) value.get("UUID");
UUID getUUID = new UUID(getParts.getLong("Most"), getParts.getLong("Least"));
for (List<Entity> slice : slices) {
if (slice != null) {
for (Entity entity : slice) {
UUID uuid = entity.getUUID(); UUID uuid = entity.getUUID();
if (uuid.equals(getUUID)) { if (uuid.equals(getUUID)) {
return true; return true;
} }
} }
}
}
return false; return false;
} }
@NotNull @Nonnull
@Override @Override
public Iterator<CompoundTag> iterator() { public Iterator<CompoundTag> iterator() {
Iterable<CompoundTag> result = Iterables.transform( Iterable<CompoundTag> result = entities.stream().map(input -> {
Iterables.concat(slices),
new com.google.common.base.Function<Entity, CompoundTag>() {
@Nullable
@Override
public CompoundTag apply(@Nullable Entity input) {
net.minecraft.nbt.CompoundTag tag = new net.minecraft.nbt.CompoundTag(); net.minecraft.nbt.CompoundTag tag = new net.minecraft.nbt.CompoundTag();
return (CompoundTag) adapter.toNative(input.saveWithoutId(tag)); input.save(tag);
} return (CompoundTag) adapter.toNative(tag);
} }).collect(Collectors.toList());
);
return result.iterator(); return result.iterator();
} }
}; };
@ -412,9 +391,10 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} }
@Override @Override
@SuppressWarnings("rawtypes")
public synchronized <T extends Future<T>> T call(IChunkSet set, Runnable finalizer) { public synchronized <T extends Future<T>> T call(IChunkSet set, Runnable finalizer) {
forceLoadSections = false; forceLoadSections = false;
copy = createCopy ? new PaperweightGetBlocks_Copy(serverLevel) : null; copy = createCopy ? new PaperweightGetBlocks_Copy(levelChunk) : null;
try { try {
ServerLevel nmsWorld = serverLevel; ServerLevel nmsWorld = serverLevel;
LevelChunk nmsChunk = ensureLoaded(nmsWorld, chunkX, chunkZ); LevelChunk nmsChunk = ensureLoaded(nmsWorld, chunkX, chunkZ);
@ -435,7 +415,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} }
int ordinal = set.getBlock(lx, ly, lz).getOrdinal(); int ordinal = set.getBlock(lx, ly, lz).getOrdinal();
if (ordinal != 0) { if (ordinal != BlockTypesCache.ReservedIDs.__RESERVED__) {
BlockEntity tile = entry.getValue(); BlockEntity tile = entry.getValue();
if (PaperLib.isPaper() && tile instanceof BeaconBlockEntity) { if (PaperLib.isPaper() && tile instanceof BeaconBlockEntity) {
if (beacons == null) { if (beacons == null) {
@ -465,9 +445,11 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
bitMask |= 1 << layer; bitMask |= 1 << layer;
// setArr is modified by PaperweightPlatformAdapter#newChunkSection. This is in order to write changes to
// this chunk GET when #updateGet is called. Future dords, please listen this time.
char[] tmp = set.load(layerNo); char[] tmp = set.load(layerNo);
char[] setArr = new char[4096]; char[] setArr = new char[tmp.length];
System.arraycopy(tmp, 0, setArr, 0, 4096); System.arraycopy(tmp, 0, setArr, 0, tmp.length);
// synchronise on internal section to avoid circular locking with a continuing edit if the chunk was // synchronise on internal section to avoid circular locking with a continuing edit if the chunk was
// submitted to keep loaded internal chunks to queue target size. // submitted to keep loaded internal chunks to queue target size.
@ -481,6 +463,14 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
LevelChunkSection newSection; LevelChunkSection newSection;
LevelChunkSection existingSection = levelChunkSections[layer]; LevelChunkSection existingSection = levelChunkSections[layer];
// Don't attempt to tick section whilst we're editing
if (existingSection != null) {
PaperweightPlatformAdapter.clearCounts(existingSection);
if (PaperLib.isPaper()) {
existingSection.tickingList.clear();
}
}
if (existingSection == null) { if (existingSection == null) {
newSection = PaperweightPlatformAdapter.newChunkSection(layerNo, setArr, fastmode, adapter); newSection = PaperweightPlatformAdapter.newChunkSection(layerNo, setArr, fastmode, adapter);
if (PaperweightPlatformAdapter.setSectionAtomic(levelChunkSections, null, newSection, layer)) { if (PaperweightPlatformAdapter.setSectionAtomic(levelChunkSections, null, newSection, layer)) {
@ -496,13 +486,18 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} }
} }
} }
PaperweightPlatformAdapter.fieldTickingBlockCount.set(existingSection, (short) 0);
//ensure that the server doesn't try to tick the chunksection while we're editing it. //ensure that the server doesn't try to tick the chunksection while we're editing it (again).
PaperweightPlatformAdapter.clearCounts(existingSection);
if (PaperLib.isPaper()) {
existingSection.tickingList.clear();
}
DelegateSemaphore lock = PaperweightPlatformAdapter.applyLock(existingSection); DelegateSemaphore lock = PaperweightPlatformAdapter.applyLock(existingSection);
// Synchronize to prevent further acquisitions
synchronized (lock) { synchronized (lock) {
// lock.acquire(); lock.acquire(); // Wait until we have the lock
lock.release();
try { try {
sectionLock.writeLock().lock(); sectionLock.writeLock().lock();
if (this.getChunk() != nmsChunk) { if (this.getChunk() != nmsChunk) {
@ -617,23 +612,31 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} }
syncTasks[2] = () -> { syncTasks[2] = () -> {
final List<Entity>[] entities = /*nmsChunk.e()*/ new List[0]; Set<UUID> entitiesRemoved = new HashSet<>();
final List<Entity> entities = PaperweightPlatformAdapter.getEntities(nmsChunk);
for (final Collection<Entity> ents : entities) { for (Entity entity : entities) {
if (!ents.isEmpty()) { UUID uuid = entity.getUUID();
final Iterator<Entity> iter = ents.iterator(); if (entityRemoves.contains(uuid)) {
while (iter.hasNext()) {
final Entity entity = iter.next();
if (entityRemoves.contains(entity.getUUID())) {
if (createCopy) { if (createCopy) {
copy.storeEntity(entity); copy.storeEntity(entity);
} }
iter.remove(); removeEntity(entity);
entitiesRemoved.add(uuid);
entityRemoves.remove(uuid);
}
}
if (Settings.settings().EXPERIMENTAL.REMOVE_ENTITY_FROM_WORLD_ON_CHUNK_FAIL) {
for (UUID uuid : entityRemoves) {
Entity entity = nmsWorld.entityManager.getEntityGetter().get(uuid);
if (entity != null) {
removeEntity(entity); removeEntity(entity);
} }
} }
} }
} // Only save entities that were actually removed to history
set.getEntityRemoves().clear();
set.getEntityRemoves().addAll(entitiesRemoved);
}; };
} }
@ -644,7 +647,9 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} }
syncTasks[1] = () -> { syncTasks[1] = () -> {
for (final CompoundTag nativeTag : entities) { Iterator<CompoundTag> iterator = entities.iterator();
while (iterator.hasNext()) {
final CompoundTag nativeTag = iterator.next();
final Map<String, Tag> entityTagMap = nativeTag.getValue(); final Map<String, Tag> entityTagMap = nativeTag.getValue();
final StringTag idTag = (StringTag) entityTagMap.get("Id"); final StringTag idTag = (StringTag) entityTagMap.get("Id");
final ListTag posTag = (ListTag) entityTagMap.get("Pos"); final ListTag posTag = (ListTag) entityTagMap.get("Pos");
@ -671,12 +676,23 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} }
entity.load(tag); entity.load(tag);
entity.absMoveTo(x, y, z, yaw, pitch); entity.absMoveTo(x, y, z, yaw, pitch);
nmsWorld.addEntity(entity, CreatureSpawnEvent.SpawnReason.CUSTOM); entity.setUUID(nativeTag.getUUID());
if (!nmsWorld.addEntity(entity, CreatureSpawnEvent.SpawnReason.CUSTOM)) {
LOGGER.warn(
"Error creating entity of type `{}` in world `{}` at location `{},{},{}`",
id,
nmsWorld.getWorld().getName(),
x,
y,
z
);
// Unsuccessful create should not be saved to history
iterator.remove();
}
} }
} }
} }
}; };
} }
// set tiles // set tiles
@ -760,6 +776,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
throw e; throw e;
} }
}; };
//noinspection unchecked - required at compile time
return (T) (Future) queueHandler.sync(chain); return (T) (Future) queueHandler.sync(chain);
} else { } else {
if (callback == null) { if (callback == null) {
@ -839,23 +856,24 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
* @return the given array to be filled with data, or a new array if null is given. * @return the given array to be filled with data, or a new array if null is given.
*/ */
@Override @Override
@SuppressWarnings("unchecked")
public char[] update(int layer, char[] data, boolean aggressive) { public char[] update(int layer, char[] data, boolean aggressive) {
LevelChunkSection section = getSections(aggressive)[layer]; LevelChunkSection section = getSections(aggressive)[layer];
// Section is null, return empty array // Section is null, return empty array
if (section == null) { if (section == null) {
data = new char[4096]; data = new char[4096];
Arrays.fill(data, (char) 1); Arrays.fill(data, (char) BlockTypesCache.ReservedIDs.AIR);
return data; return data;
} }
if (data != null && data.length != 4096) { if (data != null && data.length != 4096) {
data = new char[4096]; data = new char[4096];
Arrays.fill(data, (char) 1); Arrays.fill(data, (char) BlockTypesCache.ReservedIDs.AIR);
} }
if (data == null || data == FaweCache.INSTANCE.EMPTY_CHAR_4096) { if (data == null || data == FaweCache.INSTANCE.EMPTY_CHAR_4096) {
data = new char[4096]; data = new char[4096];
Arrays.fill(data, (char) 1); Arrays.fill(data, (char) BlockTypesCache.ReservedIDs.AIR);
} }
DelegateSemaphore lock = PaperweightPlatformAdapter.applyLock(section); Semaphore lock = PaperweightPlatformAdapter.applyLock(section);
synchronized (lock) { synchronized (lock) {
// Efficiently convert ChunkSection to raw data // Efficiently convert ChunkSection to raw data
try { try {
@ -878,8 +896,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
for (int i = 0; i < 4096; i++) { for (int i = 0; i < 4096; i++) {
char paletteVal = data[i]; char paletteVal = data[i];
char ordinal = adapter.ibdIDToOrdinal(paletteVal); char ordinal = adapter.ibdIDToOrdinal(paletteVal);
// Don't read "empty". data[i] = ordinal;
data[i] = ordinal == 0 ? 1 : ordinal;
} }
return data; return data;
} }
@ -898,18 +915,10 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
val = ordinal(palette.valueFor(i), adapter); val = ordinal(palette.valueFor(i), adapter);
paletteToOrdinal[i] = val; paletteToOrdinal[i] = val;
} }
// Don't read "empty".
if (val == 0) {
val = 1;
}
data[i] = val; data[i] = val;
} }
} else { } else {
char ordinal = ordinal(palette.valueFor(0), adapter); char ordinal = ordinal(palette.valueFor(0), adapter);
// Don't read "empty".
if (ordinal == 0) {
ordinal = 1;
}
Arrays.fill(data, ordinal); Arrays.fill(data, ordinal);
} }
} finally { } finally {
@ -929,7 +938,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
private char ordinal(net.minecraft.world.level.block.state.BlockState ibd, PaperweightFaweAdapter adapter) { private char ordinal(net.minecraft.world.level.block.state.BlockState ibd, PaperweightFaweAdapter adapter) {
if (ibd == null) { if (ibd == null) {
return 1; return BlockTypesCache.ReservedIDs.AIR;
} else { } else {
return adapter.adaptToChar(ibd); return adapter.adaptToChar(ibd);
} }
@ -1011,6 +1020,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} }
@Override @Override
@SuppressWarnings("unchecked")
public synchronized boolean trim(boolean aggressive) { public synchronized boolean trim(boolean aggressive) {
skyLight = new DataLayer[getSectionCount()]; skyLight = new DataLayer[getSectionCount()];
blockLight = new DataLayer[getSectionCount()]; blockLight = new DataLayer[getSectionCount()];

Datei anzeigen

@ -19,6 +19,7 @@ import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.chunk.ChunkBiomeContainer; import net.minecraft.world.level.chunk.ChunkBiomeContainer;
import net.minecraft.world.level.chunk.LevelChunk;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.HashMap; import java.util.HashMap;
@ -35,13 +36,15 @@ public class PaperweightGetBlocks_Copy implements IChunkGet {
private final char[][] blocks; private final char[][] blocks;
private final int minHeight; private final int minHeight;
private final int maxHeight; private final int maxHeight;
private final ServerLevel serverLevel; final ServerLevel serverLevel;
final LevelChunk levelChunk;
private ChunkBiomeContainer chunkBiomeContainer; private ChunkBiomeContainer chunkBiomeContainer;
protected PaperweightGetBlocks_Copy(ServerLevel world) { protected PaperweightGetBlocks_Copy(LevelChunk levelChunk) {
this.serverLevel = world; this.levelChunk = levelChunk;
this.minHeight = world.getMinBuildHeight(); this.serverLevel = levelChunk.level;
this.maxHeight = world.getMaxBuildHeight() - 1; // Minecraft max limit is exclusive. this.minHeight = serverLevel.getMinBuildHeight();
this.maxHeight = serverLevel.getMaxBuildHeight() - 1; // Minecraft max limit is exclusive.
this.blocks = new char[getSectionCount()][]; this.blocks = new char[getSectionCount()][];
} }
@ -67,10 +70,12 @@ public class PaperweightGetBlocks_Copy implements IChunkGet {
return tiles.get(BlockVector3.at(x, y, z)); return tiles.get(BlockVector3.at(x, y, z));
} }
@SuppressWarnings({"unchecked", "rawtypes"})
protected void storeEntity(Entity entity) { protected void storeEntity(Entity entity) {
BukkitImplAdapter adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter(); BukkitImplAdapter adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter();
net.minecraft.nbt.CompoundTag compoundTag = new net.minecraft.nbt.CompoundTag(); net.minecraft.nbt.CompoundTag compoundTag = new net.minecraft.nbt.CompoundTag();
entities.add((CompoundTag) adapter.toNative(entity.save(compoundTag))); entity.save(compoundTag);
entities.add((CompoundTag) adapter.toNative(compoundTag));
} }
@Override @Override
@ -81,18 +86,7 @@ public class PaperweightGetBlocks_Copy implements IChunkGet {
@Override @Override
public CompoundTag getEntity(UUID uuid) { public CompoundTag getEntity(UUID uuid) {
for (CompoundTag tag : entities) { for (CompoundTag tag : entities) {
UUID tagUUID; if (uuid.equals(tag.getUUID())) {
if (tag.containsKey("UUID")) {
int[] arr = tag.getIntArray("UUID");
tagUUID = new UUID((long) arr[0] << 32 | (arr[1] & 0xFFFFFFFFL), (long) arr[2] << 32 | (arr[3] & 0xFFFFFFFFL));
} else if (tag.containsKey("UUIDMost")) {
tagUUID = new UUID(tag.getLong("UUIDMost"), tag.getLong("UUIDLeast"));
} else if (tag.containsKey("PersistentIDMSB")) {
tagUUID = new UUID(tag.getLong("PersistentIDMSB"), tag.getLong("PersistentIDLSB"));
} else {
return null;
}
if (uuid.equals(tagUUID)) {
return tag; return tag;
} }
} }

Datei anzeigen

@ -12,7 +12,7 @@ import com.fastasyncworldedit.core.util.ReflectionUtils;
import com.fastasyncworldedit.core.util.TaskManager; import com.fastasyncworldedit.core.util.TaskManager;
import com.mojang.datafixers.util.Either; import com.mojang.datafixers.util.Either;
import com.sk89q.worldedit.bukkit.adapter.Refraction; import com.sk89q.worldedit.bukkit.adapter.Refraction;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.internal.util.LogManagerCompat;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes; import com.sk89q.worldedit.world.biome.BiomeTypes;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockState;
@ -30,7 +30,10 @@ import net.minecraft.server.level.ChunkHolder;
import net.minecraft.server.level.ChunkMap; import net.minecraft.server.level.ChunkMap;
import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.level.TicketType;
import net.minecraft.util.BitStorage; import net.minecraft.util.BitStorage;
import net.minecraft.util.Unit;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome;
@ -46,6 +49,8 @@ import net.minecraft.world.level.chunk.Palette;
import net.minecraft.world.level.chunk.PalettedContainer; import net.minecraft.world.level.chunk.PalettedContainer;
import net.minecraft.world.level.gameevent.GameEventDispatcher; import net.minecraft.world.level.gameevent.GameEventDispatcher;
import net.minecraft.world.level.gameevent.GameEventListener; import net.minecraft.world.level.gameevent.GameEventListener;
import org.apache.logging.log4j.Logger;
import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_17_R1.CraftChunk; import org.bukkit.craftbukkit.v1_17_R1.CraftChunk;
import sun.misc.Unsafe; import sun.misc.Unsafe;
@ -54,12 +59,13 @@ import java.lang.invoke.MethodHandles;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Semaphore; import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -71,9 +77,9 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
public static final Field fieldBitsPerEntry; public static final Field fieldBitsPerEntry;
public static final Field fieldTickingFluidContent; private static final Field fieldTickingFluidContent;
public static final Field fieldTickingBlockCount; private static final Field fieldTickingBlockCount;
public static final Field fieldNonEmptyBlockCount; private static final Field fieldNonEmptyBlockCount;
private static final Field fieldBiomes; private static final Field fieldBiomes;
@ -86,10 +92,12 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
private static final long fieldLockOffset; private static final long fieldLockOffset;
private static final Field fieldGameEventDispatcherSections; private static final Field fieldGameEventDispatcherSections;
private static final MethodHandle methodremoveTickingBlockEntity; private static final MethodHandle methodremoveBlockEntityTicker;
private static final Field fieldRemove; private static final Field fieldRemove;
private static final Logger LOGGER = LogManagerCompat.getLogger();
static { static {
try { try {
fieldBits = PalettedContainer.class.getDeclaredField(Refraction.pickName("bits", "l")); fieldBits = PalettedContainer.class.getDeclaredField(Refraction.pickName("bits", "l"));
@ -120,8 +128,15 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
methodGetVisibleChunk = MethodHandles.lookup().unreflect(getVisibleChunkIfPresent); methodGetVisibleChunk = MethodHandles.lookup().unreflect(getVisibleChunkIfPresent);
Unsafe unsafe = ReflectionUtils.getUnsafe(); Unsafe unsafe = ReflectionUtils.getUnsafe();
if (!PaperLib.isPaper()) {
fieldLock = PalettedContainer.class.getDeclaredField(Refraction.pickName("lock", "m")); fieldLock = PalettedContainer.class.getDeclaredField(Refraction.pickName("lock", "m"));
fieldLockOffset = unsafe.objectFieldOffset(fieldLock); fieldLockOffset = unsafe.objectFieldOffset(fieldLock);
} else {
// in paper, the used methods are synchronized properly
fieldLock = null;
fieldLockOffset = -1;
}
fieldGameEventDispatcherSections = LevelChunk.class.getDeclaredField(Refraction.pickName( fieldGameEventDispatcherSections = LevelChunk.class.getDeclaredField(Refraction.pickName(
"gameEventDispatcherSections", "x")); "gameEventDispatcherSections", "x"));
@ -133,7 +148,7 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
), BlockPos.class ), BlockPos.class
); );
removeBlockEntityTicker.setAccessible(true); removeBlockEntityTicker.setAccessible(true);
methodremoveTickingBlockEntity = MethodHandles.lookup().unreflect(removeBlockEntityTicker); methodremoveBlockEntityTicker = MethodHandles.lookup().unreflect(removeBlockEntityTicker);
fieldRemove = BlockEntity.class.getDeclaredField(Refraction.pickName("remove", "p")); fieldRemove = BlockEntity.class.getDeclaredField(Refraction.pickName("remove", "p"));
fieldRemove.setAccessible(true); fieldRemove.setAccessible(true);
@ -165,15 +180,21 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
return false; return false;
} }
// There is no point in having a functional semaphore for paper servers.
private static final ThreadLocal<DelegateSemaphore> SEMAPHORE_THREAD_LOCAL =
ThreadLocal.withInitial(() -> new DelegateSemaphore(1, null));
static DelegateSemaphore applyLock(LevelChunkSection section) { static DelegateSemaphore applyLock(LevelChunkSection section) {
//todo there has to be a better way to do this. Maybe using a() in DataPaletteBlock which acquires the lock in NMS? if (PaperLib.isPaper()) {
return SEMAPHORE_THREAD_LOCAL.get();
}
try { try {
synchronized (section) { synchronized (section) {
Unsafe unsafe = ReflectionUtils.getUnsafe(); Unsafe unsafe = ReflectionUtils.getUnsafe();
PalettedContainer<net.minecraft.world.level.block.state.BlockState> blocks = section.getStates(); PalettedContainer<net.minecraft.world.level.block.state.BlockState> blocks = section.getStates();
Semaphore currentLock = (Semaphore) unsafe.getObject(blocks, fieldLockOffset); Semaphore currentLock = (Semaphore) unsafe.getObject(blocks, fieldLockOffset);
if (currentLock instanceof DelegateSemaphore) { if (currentLock instanceof DelegateSemaphore delegateSemaphore) {
return (DelegateSemaphore) currentLock; return delegateSemaphore;
} }
DelegateSemaphore newLock = new DelegateSemaphore(1, currentLock); DelegateSemaphore newLock = new DelegateSemaphore(1, currentLock);
unsafe.putObject(blocks, fieldLockOffset, newLock); unsafe.putObject(blocks, fieldLockOffset, newLock);
@ -197,10 +218,12 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
} else { } else {
LevelChunk nmsChunk = serverLevel.getChunkSource().getChunkAtIfCachedImmediately(chunkX, chunkZ); LevelChunk nmsChunk = serverLevel.getChunkSource().getChunkAtIfCachedImmediately(chunkX, chunkZ);
if (nmsChunk != null) { if (nmsChunk != null) {
addTicket(serverLevel, chunkX, chunkZ);
return nmsChunk; return nmsChunk;
} }
nmsChunk = serverLevel.getChunkSource().getChunkAtIfLoadedImmediately(chunkX, chunkZ); nmsChunk = serverLevel.getChunkSource().getChunkAtIfLoadedImmediately(chunkX, chunkZ);
if (nmsChunk != null) { if (nmsChunk != null) {
addTicket(serverLevel, chunkX, chunkZ);
return nmsChunk; return nmsChunk;
} }
// Avoid "async" methods from the main thread. // Avoid "async" methods from the main thread.
@ -209,7 +232,21 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
} }
CompletableFuture<org.bukkit.Chunk> future = serverLevel.getWorld().getChunkAtAsync(chunkX, chunkZ, true, true); CompletableFuture<org.bukkit.Chunk> future = serverLevel.getWorld().getChunkAtAsync(chunkX, chunkZ, true, true);
try { try {
CraftChunk chunk = (CraftChunk) future.get(); CraftChunk chunk;
try {
chunk = (CraftChunk) future.get(10, TimeUnit.SECONDS);
} catch (TimeoutException e) {
String world = serverLevel.getWorld().getName();
// We've already taken 10 seconds we can afford to wait a little here.
boolean loaded = TaskManager.taskManager().sync(() -> Bukkit.getWorld(world) != null);
if (loaded) {
LOGGER.warn("Chunk {},{} failed to load in 10 seconds in world {}. Retrying...", chunkX, chunkZ, world);
// Retry chunk load
chunk = (CraftChunk) serverLevel.getWorld().getChunkAtAsync(chunkX, chunkZ, true, true).get();
} else {
throw new UnsupportedOperationException("Cannot load chunk from unloaded world " + world + "!");
}
}
return chunk.getHandle(); return chunk.getHandle();
} catch (Throwable e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
@ -218,6 +255,13 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
return TaskManager.taskManager().sync(() -> serverLevel.getChunk(chunkX, chunkZ)); return TaskManager.taskManager().sync(() -> serverLevel.getChunk(chunkX, chunkZ));
} }
private static void addTicket(ServerLevel serverLevel, int chunkX, int chunkZ) {
// Ensure chunk is definitely loaded before applying a ticket
net.minecraft.server.MCUtil.MAIN_EXECUTOR.execute(() -> serverLevel
.getChunkSource()
.addRegionTicket(TicketType.PLUGIN, new ChunkPos(chunkX, chunkZ), 0, Unit.INSTANCE));
}
public static ChunkHolder getPlayerChunk(ServerLevel nmsWorld, final int chunkX, final int chunkZ) { public static ChunkHolder getPlayerChunk(ServerLevel nmsWorld, final int chunkX, final int chunkZ) {
ChunkMap chunkMap = nmsWorld.getChunkSource().chunkMap; ChunkMap chunkMap = nmsWorld.getChunkSource().chunkMap;
try { try {
@ -227,6 +271,7 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
} }
} }
@SuppressWarnings("unchecked")
public static void sendChunk(ServerLevel nmsWorld, int chunkX, int chunkZ, boolean lighting) { public static void sendChunk(ServerLevel nmsWorld, int chunkX, int chunkZ, boolean lighting) {
ChunkHolder chunkHolder = getPlayerChunk(nmsWorld, chunkX, chunkZ); ChunkHolder chunkHolder = getPlayerChunk(nmsWorld, chunkX, chunkZ);
if (chunkHolder == null) { if (chunkHolder == null) {
@ -270,15 +315,20 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
NMS conversion NMS conversion
*/ */
public static LevelChunkSection newChunkSection( public static LevelChunkSection newChunkSection(
final int layer, final char[] blocks, boolean fastmode, final int layer,
final char[] blocks,
boolean fastMode,
CachedBukkitAdapter adapter CachedBukkitAdapter adapter
) { ) {
return newChunkSection(layer, null, blocks, fastmode, adapter); return newChunkSection(layer, null, blocks, fastMode, adapter);
} }
public static LevelChunkSection newChunkSection( public static LevelChunkSection newChunkSection(
final int layer, final Function<Integer, char[]> get, char[] set, final int layer,
boolean fastmode, CachedBukkitAdapter adapter final Function<Integer, char[]> get,
char[] set,
boolean fastMode,
CachedBukkitAdapter adapter
) { ) {
if (set == null) { if (set == null) {
return newChunkSection(layer); return newChunkSection(layer);
@ -288,19 +338,22 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
final long[] blockStates = FaweCache.INSTANCE.BLOCK_STATES.get(); final long[] blockStates = FaweCache.INSTANCE.BLOCK_STATES.get();
final int[] blocksCopy = FaweCache.INSTANCE.SECTION_BLOCKS.get(); final int[] blocksCopy = FaweCache.INSTANCE.SECTION_BLOCKS.get();
try { try {
int[] num_palette_buffer = new int[1]; int num_palette;
Map<BlockVector3, Integer> ticking_blocks = new HashMap<>(); final short[] nonEmptyBlockCount = fastMode ? new short[1] : null;
int air;
if (get == null) { if (get == null) {
air = createPalette(blockToPalette, paletteToBlock, blocksCopy, num_palette_buffer, num_palette = createPalette(blockToPalette, paletteToBlock, blocksCopy, set, adapter, nonEmptyBlockCount);
set, ticking_blocks, fastmode, adapter
);
} else { } else {
air = createPalette(layer, blockToPalette, paletteToBlock, blocksCopy, num_palette = createPalette(
num_palette_buffer, get, set, ticking_blocks, fastmode, adapter layer,
blockToPalette,
paletteToBlock,
blocksCopy,
get,
set,
adapter,
nonEmptyBlockCount
); );
} }
int num_palette = num_palette_buffer[0];
// BlockStates // BlockStates
int bitsPerEntry = MathMan.log2nlz(num_palette - 1); int bitsPerEntry = MathMan.log2nlz(num_palette - 1);
if (Settings.settings().PROTOCOL_SUPPORT_FIX || num_palette != 1) { if (Settings.settings().PROTOCOL_SUPPORT_FIX || num_palette != 1) {
@ -363,21 +416,27 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
fieldStorage.set(dataPaletteBlocks, nmsBits); fieldStorage.set(dataPaletteBlocks, nmsBits);
fieldPalette.set(dataPaletteBlocks, blockStatePalettedContainer); fieldPalette.set(dataPaletteBlocks, blockStatePalettedContainer);
fieldBits.set(dataPaletteBlocks, bitsPerEntry); fieldBits.set(dataPaletteBlocks, bitsPerEntry);
setCount(ticking_blocks.size(), 4096 - air, levelChunkSection);
if (!fastmode) {
ticking_blocks.forEach((pos, ordinal) -> levelChunkSection
.setBlockState(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ(),
Block.stateById(ordinal)
));
}
} catch (final IllegalAccessException e) { } catch (final IllegalAccessException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
if (!fastMode) {
levelChunkSection.recalcBlockCounts();
} else {
try {
fieldNonEmptyBlockCount.set(levelChunkSection, nonEmptyBlockCount[0]);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
return levelChunkSection; return levelChunkSection;
} catch (final Throwable e) { } catch (final Throwable e) {
Arrays.fill(blockToPalette, Integer.MAX_VALUE);
throw e; throw e;
} finally {
Arrays.fill(blockToPalette, Integer.MAX_VALUE);
Arrays.fill(paletteToBlock, Integer.MAX_VALUE);
Arrays.fill(blockStates, 0);
Arrays.fill(blocksCopy, 0);
} }
} }
@ -385,11 +444,9 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
return new LevelChunkSection(layer); return new LevelChunkSection(layer);
} }
public static void setCount(final int tickingBlockCount, final int nonEmptyBlockCount, final LevelChunkSection section) throws public static void clearCounts(final LevelChunkSection section) throws IllegalAccessException {
IllegalAccessException { fieldTickingFluidContent.setShort(section, (short) 0);
fieldTickingFluidContent.setShort(section, (short) 0); // TODO FIXME fieldTickingBlockCount.setShort(section, (short) 0);
fieldTickingBlockCount.setShort(section, (short) tickingBlockCount);
fieldNonEmptyBlockCount.setShort(section, (short) nonEmptyBlockCount);
} }
public static Biome[] getBiomeArray(ChunkBiomeContainer chunkBiomeContainer) { public static Biome[] getBiomeArray(ChunkBiomeContainer chunkBiomeContainer) {
@ -412,6 +469,7 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
return BiomeTypes.get(resourceLocation.toString().toLowerCase(Locale.ROOT)); return BiomeTypes.get(resourceLocation.toString().toLowerCase(Locale.ROOT));
} }
@SuppressWarnings("unchecked")
static void removeBeacon(BlockEntity beacon, LevelChunk levelChunk) { static void removeBeacon(BlockEntity beacon, LevelChunk levelChunk) {
try { try {
// Do the method ourselves to avoid trying to reflect generic method parameters // Do the method ourselves to avoid trying to reflect generic method parameters
@ -440,10 +498,14 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
fieldRemove.set(beacon, true); fieldRemove.set(beacon, true);
} }
} }
methodremoveTickingBlockEntity.invoke(levelChunk, beacon.getBlockPos()); methodremoveBlockEntityTicker.invoke(levelChunk, beacon.getBlockPos());
} catch (Throwable throwable) { } catch (Throwable throwable) {
throwable.printStackTrace(); throwable.printStackTrace();
} }
} }
static List<Entity> getEntities(LevelChunk chunk) {
return chunk.level.entityManager.getEntities(chunk.getPos());
}
} }

Datei anzeigen

@ -0,0 +1,175 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_17_R1_2;
import com.fastasyncworldedit.core.configuration.Settings;
import com.fastasyncworldedit.core.extent.processor.ProcessorScope;
import com.fastasyncworldedit.core.queue.IBatchProcessor;
import com.fastasyncworldedit.core.queue.IChunk;
import com.fastasyncworldedit.core.queue.IChunkGet;
import com.fastasyncworldedit.core.queue.IChunkSet;
import com.fastasyncworldedit.core.registry.state.PropertyKey;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldedit.world.block.BlockTypesCache;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.Fluids;
import javax.annotation.Nullable;
public class PaperweightPostProcessor implements IBatchProcessor {
@Override
public IChunkSet processSet(final IChunk chunk, final IChunkGet get, final IChunkSet set) {
return set;
}
@SuppressWarnings("deprecation")
@Override
public void postProcess(final IChunk chunk, final IChunkGet iChunkGet, final IChunkSet iChunkSet) {
boolean tickFluid = Settings.settings().EXPERIMENTAL.ALLOW_TICK_FLUIDS;
// The PostProcessor shouldn't be added, but just in case
if (!tickFluid) {
return;
}
PaperweightGetBlocks_Copy getBlocks = (PaperweightGetBlocks_Copy) iChunkGet;
layer:
for (int layer = iChunkSet.getMinSectionPosition(); layer <= iChunkSet.getMaxSectionPosition(); layer++) {
char[] set = iChunkSet.loadIfPresent(layer);
if (set == null) {
// No edit means no need to process
continue;
}
char[] get = null;
for (int i = 0; i < 4096; i++) {
char ordinal = set[i];
char replacedOrdinal = BlockTypesCache.ReservedIDs.__RESERVED__;
boolean fromGet = false; // Used for liquids
if (ordinal == BlockTypesCache.ReservedIDs.__RESERVED__) {
if (get == null) {
get = getBlocks.load(layer);
}
// If this is null, then it's because we're loading a layer in the range of 0->15, but blocks aren't
// actually being set
if (get == null) {
continue layer;
}
fromGet = true;
ordinal = replacedOrdinal = get[i];
}
if (ordinal == BlockTypesCache.ReservedIDs.__RESERVED__) {
continue;
} else if (!fromGet) { // if fromGet, don't do the same again
if (get == null) {
get = getBlocks.load(layer);
}
replacedOrdinal = get[i];
}
boolean ticking = BlockTypesCache.ticking[ordinal];
boolean replacedWasTicking = BlockTypesCache.ticking[replacedOrdinal];
boolean replacedWasLiquid = false;
BlockState replacedState = null;
if (!ticking) {
// If the block being replaced was not ticking, it cannot be a liquid
if (!replacedWasTicking) {
continue;
}
// If the block being replaced is not fluid, we do not need to worry
if (!(replacedWasLiquid =
(replacedState = BlockState.getFromOrdinal(replacedOrdinal)).getMaterial().isLiquid())) {
continue;
}
}
BlockState state = BlockState.getFromOrdinal(ordinal);
boolean liquid = state.getMaterial().isLiquid();
int x = i & 15;
int y = (i >> 8) & 15;
int z = (i >> 4) & 15;
BlockPos position = new BlockPos((chunk.getX() << 4) + x, (layer << 4) + y, (chunk.getZ() << 4) + z);
if (liquid || replacedWasLiquid) {
if (liquid) {
addFluid(getBlocks.serverLevel, state, position);
continue;
}
// If the replaced fluid (is?) adjacent to water. Do not bother to check adjacent chunks(sections) as this
// may be time consuming. Chances are any fluid blocks in adjacent chunks are being replaced or will end up
// being ticked anyway. We only need it to be "hit" once.
if (!wasAdjacentToWater(get, set, i, x, y, z)) {
continue;
}
addFluid(getBlocks.serverLevel, replacedState, position);
}
}
}
}
@Nullable
@Override
public Extent construct(final Extent child) {
throw new UnsupportedOperationException("Processing only");
}
@Override
public ProcessorScope getScope() {
return ProcessorScope.READING_SET_BLOCKS;
}
private boolean wasAdjacentToWater(char[] get, char[] set, int i, int x, int y, int z) {
if (set == null || get == null) {
return false;
}
char ordinal;
char reserved = BlockTypesCache.ReservedIDs.__RESERVED__;
if (x > 0 && set[i - 1] != reserved) {
if (BlockTypesCache.ticking[(ordinal = get[i - 1])] && isFluid(ordinal)) {
return true;
}
}
if (x < 15 && set[i + 1] != reserved) {
if (BlockTypesCache.ticking[(ordinal = get[i + 1])] && isFluid(ordinal)) {
return true;
}
}
if (z > 0 && set[i - 16] != reserved) {
if (BlockTypesCache.ticking[(ordinal = get[i - 16])] && isFluid(ordinal)) {
return true;
}
}
if (z < 15 && set[i + 16] != reserved) {
if (BlockTypesCache.ticking[(ordinal = get[i + 16])] && isFluid(ordinal)) {
return true;
}
}
if (y > 0 && set[i - 256] != reserved) {
if (BlockTypesCache.ticking[(ordinal = get[i - 256])] && isFluid(ordinal)) {
return true;
}
}
if (y < 15 && set[i + 256] != reserved) {
return BlockTypesCache.ticking[(ordinal = get[i + 256])] && isFluid(ordinal);
}
return false;
}
@SuppressWarnings("deprecation")
private boolean isFluid(char ordinal) {
return BlockState.getFromOrdinal(ordinal).getMaterial().isLiquid();
}
@SuppressWarnings("deprecation")
private void addFluid(final ServerLevel serverLevel, final BlockState replacedState, final BlockPos position) {
Fluid type;
if (replacedState.getBlockType() == BlockTypes.LAVA) {
type = (int) replacedState.getState(PropertyKey.LEVEL) == 0 ? Fluids.LAVA : Fluids.FLOWING_LAVA;
} else {
type = (int) replacedState.getState(PropertyKey.LEVEL) == 0 ? Fluids.WATER : Fluids.FLOWING_WATER;
}
serverLevel.getLiquidTicks().scheduleTick(
position,
type,
type.getTickDelay(serverLevel)
);
}
}

Datei anzeigen

@ -70,6 +70,7 @@ public class PaperweightStarlightRelighter implements Relighter {
private final ReentrantLock areaLock = new ReentrantLock(); private final ReentrantLock areaLock = new ReentrantLock();
private final NMSRelighter delegate; private final NMSRelighter delegate;
@SuppressWarnings("rawtypes")
public PaperweightStarlightRelighter(ServerLevel serverLevel, IQueueExtent<IQueueChunk> queue) { public PaperweightStarlightRelighter(ServerLevel serverLevel, IQueueExtent<IQueueChunk> queue) {
this.serverLevel = serverLevel; this.serverLevel = serverLevel;
this.delegate = new NMSRelighter(queue); this.delegate = new NMSRelighter(queue);

Datei anzeigen

@ -16,6 +16,7 @@ public class PaperweightStarlightRelighterFactory implements RelighterFactory {
@Override @Override
public @Nonnull public @Nonnull
@SuppressWarnings("rawtypes")
Relighter createRelighter(RelightMode relightMode, World world, IQueueExtent<IQueueChunk> queue) { Relighter createRelighter(RelightMode relightMode, World world, IQueueExtent<IQueueChunk> queue) {
org.bukkit.World w = Bukkit.getWorld(world.getName()); org.bukkit.World w = Bukkit.getWorld(world.getName());
if (w == null) { if (w == null) {

Datei anzeigen

@ -35,6 +35,7 @@ public class PaperweightLazyCompoundTag extends LazyCompoundTag {
} }
@Override @Override
@SuppressWarnings("unchecked")
public Map<String, Tag> getValue() { public Map<String, Tag> getValue() {
if (compoundTag == null) { if (compoundTag == null) {
compoundTag = (CompoundTag) WorldEditPlugin.getInstance().getBukkitImplAdapter().toNative(compoundTagSupplier.get()); compoundTag = (CompoundTag) WorldEditPlugin.getInstance().getBukkitImplAdapter().toNative(compoundTagSupplier.get());
@ -66,8 +67,8 @@ public class PaperweightLazyCompoundTag extends LazyCompoundTag {
public double asDouble(String key) { public double asDouble(String key) {
net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key); net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key);
if (tag instanceof NumericTag) { if (tag instanceof NumericTag numTag) {
return ((NumericTag) tag).getAsDouble(); return numTag.getAsDouble();
} }
return 0; return 0;
} }
@ -86,20 +87,20 @@ public class PaperweightLazyCompoundTag extends LazyCompoundTag {
public int asInt(String key) { public int asInt(String key) {
net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key); net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key);
if (tag instanceof NumericTag) { if (tag instanceof NumericTag numTag) {
return ((NumericTag) tag).getAsInt(); return numTag.getAsInt();
} }
return 0; return 0;
} }
@SuppressWarnings("unchecked")
public List<Tag> getList(String key) { public List<Tag> getList(String key) {
net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key); net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key);
if (tag instanceof net.minecraft.nbt.ListTag) { if (tag instanceof net.minecraft.nbt.ListTag nbtList) {
ArrayList<Tag> list = new ArrayList<>(); ArrayList<Tag> list = new ArrayList<>();
net.minecraft.nbt.ListTag nbtList = (net.minecraft.nbt.ListTag) tag;
for (net.minecraft.nbt.Tag elem : nbtList) { for (net.minecraft.nbt.Tag elem : nbtList) {
if (elem instanceof net.minecraft.nbt.CompoundTag) { if (elem instanceof net.minecraft.nbt.CompoundTag compoundTag) {
list.add(new PaperweightLazyCompoundTag((net.minecraft.nbt.CompoundTag) elem)); list.add(new PaperweightLazyCompoundTag(compoundTag));
} else { } else {
list.add(WorldEditPlugin.getInstance().getBukkitImplAdapter().toNative(elem)); list.add(WorldEditPlugin.getInstance().getBukkitImplAdapter().toNative(elem));
} }
@ -109,6 +110,7 @@ public class PaperweightLazyCompoundTag extends LazyCompoundTag {
return Collections.emptyList(); return Collections.emptyList();
} }
@SuppressWarnings("unchecked")
public ListTag getListTag(String key) { public ListTag getListTag(String key) {
net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key); net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key);
if (tag instanceof net.minecraft.nbt.ListTag) { if (tag instanceof net.minecraft.nbt.ListTag) {
@ -137,8 +139,8 @@ public class PaperweightLazyCompoundTag extends LazyCompoundTag {
public long asLong(String key) { public long asLong(String key) {
net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key); net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key);
if (tag instanceof NumericTag) { if (tag instanceof NumericTag numTag) {
return ((NumericTag) tag).getAsLong(); return numTag.getAsLong();
} }
return 0; return 0;
} }

Datei anzeigen

@ -11,7 +11,6 @@ import com.mojang.datafixers.util.Either;
import com.mojang.serialization.Codec; import com.mojang.serialization.Codec;
import com.mojang.serialization.Lifecycle; import com.mojang.serialization.Lifecycle;
import com.sk89q.worldedit.bukkit.adapter.Refraction; import com.sk89q.worldedit.bukkit.adapter.Refraction;
import com.sk89q.worldedit.bukkit.adapter.ext.fawe.PaperweightAdapter;
import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_17_R1_2.PaperweightGetBlocks; import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_17_R1_2.PaperweightGetBlocks;
import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.internal.util.LogManagerCompat; import com.sk89q.worldedit.internal.util.LogManagerCompat;
@ -38,6 +37,7 @@ import net.minecraft.world.level.LevelHeightAccessor;
import net.minecraft.world.level.LevelSettings; import net.minecraft.world.level.LevelSettings;
import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeSource; import net.minecraft.world.level.biome.BiomeSource;
import net.minecraft.world.level.biome.FixedBiomeSource;
import net.minecraft.world.level.biome.OverworldBiomeSource; import net.minecraft.world.level.biome.OverworldBiomeSource;
import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.ChunkGenerator; import net.minecraft.world.level.chunk.ChunkGenerator;
@ -67,6 +67,7 @@ import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_17_R1.CraftServer; import org.bukkit.craftbukkit.v1_17_R1.CraftServer;
import org.bukkit.craftbukkit.v1_17_R1.CraftWorld; import org.bukkit.craftbukkit.v1_17_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_17_R1.generator.CustomChunkGenerator; import org.bukkit.craftbukkit.v1_17_R1.generator.CustomChunkGenerator;
import org.bukkit.generator.BiomeProvider;
import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.BlockPopulator;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -78,6 +79,7 @@ import java.util.Collections;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.OptionalLong;
import java.util.Random; import java.util.Random;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -90,13 +92,13 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
private static final Logger LOGGER = LogManagerCompat.getLogger(); private static final Logger LOGGER = LogManagerCompat.getLogger();
private static final Field serverWorldsField; private static final Field worldsField;
private static final Field worldPaperConfigField; private static final Field paperConfigField;
private static final Field flatBedrockField; private static final Field generateFlatBedrockField;
private static final Field generatorSettingFlatField; private static final Field generatorSettingFlatField;
private static final Field generatorSettingBaseSupplierField; private static final Field generatorSettingBaseSupplierField;
private static final Field delegateField; private static final Field delegateField;
private static final Field chunkProviderField; private static final Field chunkSourceField;
//list of chunk stati in correct order without FULL //list of chunk stati in correct order without FULL
private static final Map<ChunkStatus, Concurrency> chunkStati = new LinkedHashMap<>(); private static final Map<ChunkStatus, Concurrency> chunkStati = new LinkedHashMap<>();
@ -125,8 +127,8 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
chunkStati.put(ChunkStatus.HEIGHTMAPS, Concurrency.FULL); // heightmaps: radius 0 chunkStati.put(ChunkStatus.HEIGHTMAPS, Concurrency.FULL); // heightmaps: radius 0
try { try {
serverWorldsField = CraftServer.class.getDeclaredField("worlds"); worldsField = CraftServer.class.getDeclaredField("worlds");
serverWorldsField.setAccessible(true); worldsField.setAccessible(true);
Field tmpPaperConfigField; Field tmpPaperConfigField;
Field tmpFlatBedrockField; Field tmpFlatBedrockField;
@ -140,8 +142,8 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
tmpPaperConfigField = null; tmpPaperConfigField = null;
tmpFlatBedrockField = null; tmpFlatBedrockField = null;
} }
worldPaperConfigField = tmpPaperConfigField; paperConfigField = tmpPaperConfigField;
flatBedrockField = tmpFlatBedrockField; generateFlatBedrockField = tmpFlatBedrockField;
generatorSettingBaseSupplierField = NoiseBasedChunkGenerator.class.getDeclaredField(Refraction.pickName( generatorSettingBaseSupplierField = NoiseBasedChunkGenerator.class.getDeclaredField(Refraction.pickName(
"settings", "g")); "settings", "g"));
@ -153,8 +155,8 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
delegateField = CustomChunkGenerator.class.getDeclaredField("delegate"); delegateField = CustomChunkGenerator.class.getDeclaredField("delegate");
delegateField.setAccessible(true); delegateField.setAccessible(true);
chunkProviderField = ServerLevel.class.getDeclaredField(Refraction.pickName("chunkSource", "C")); chunkSourceField = ServerLevel.class.getDeclaredField(Refraction.pickName("chunkSource", "C"));
chunkProviderField.setAccessible(true); chunkSourceField.setAccessible(true);
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -187,9 +189,9 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
} }
//flat bedrock? (only on paper) //flat bedrock? (only on paper)
if (worldPaperConfigField != null) { if (paperConfigField != null) {
try { try {
generateFlatBedrock = flatBedrockField.getBoolean(worldPaperConfigField.get(originalServerWorld)); generateFlatBedrock = generateFlatBedrockField.getBoolean(paperConfigField.get(originalServerWorld));
} catch (Exception ignored) { } catch (Exception ignored) {
} }
} }
@ -210,18 +212,18 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
org.bukkit.generator.ChunkGenerator generator = originalBukkitWorld.getGenerator(); org.bukkit.generator.ChunkGenerator generator = originalBukkitWorld.getGenerator();
LevelStorageSource levelStorageSource = LevelStorageSource.createDefault(tempDir); LevelStorageSource levelStorageSource = LevelStorageSource.createDefault(tempDir);
ResourceKey<LevelStem> levelStemResourceKey = getWorldDimKey(environment); ResourceKey<LevelStem> levelStemResourceKey = getWorldDimKey(environment);
session = levelStorageSource.createAccess("worldeditregentempworld", levelStemResourceKey); session = levelStorageSource.createAccess("faweregentempworld", levelStemResourceKey);
PrimaryLevelData originalWorldData = originalServerWorld.serverLevelData; PrimaryLevelData originalWorldData = originalServerWorld.serverLevelData;
MinecraftServer server = originalServerWorld.getCraftServer().getServer(); BiomeProvider biomeProvider = getBiomeProvider();
PrimaryLevelData levelProperties = (PrimaryLevelData) server.getWorldData();
WorldGenSettings originalOpts = levelProperties.worldGenSettings();
MinecraftServer server = originalServerWorld.getCraftServer().getServer();
WorldGenSettings originalOpts = originalWorldData.worldGenSettings();
WorldGenSettings newOpts = options.getSeed().isPresent() WorldGenSettings newOpts = options.getSeed().isPresent()
? PaperweightAdapter.replaceSeed(originalServerWorld, seed, originalOpts) ? originalOpts.withSeed(originalWorldData.isHardcore(), OptionalLong.of(seed))
: originalOpts; : originalOpts;
LevelSettings newWorldSettings = new LevelSettings( LevelSettings newWorldSettings = new LevelSettings(
"worldeditregentempworld", "faweregentempworld",
originalWorldData.settings.gameType(), originalWorldData.settings.gameType(),
originalWorldData.settings.hardcore(), originalWorldData.settings.hardcore(),
originalWorldData.settings.difficulty(), originalWorldData.settings.difficulty(),
@ -248,7 +250,7 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
false, false,
environment, environment,
generator, generator,
originalBukkitWorld.getBiomeProvider() biomeProvider
) { ) {
private final Biome singleBiome = options.hasBiomeType() ? BuiltinRegistries.BIOME.get(ResourceLocation.tryParse( private final Biome singleBiome = options.hasBiomeType() ? BuiltinRegistries.BIOME.get(ResourceLocation.tryParse(
options options
@ -270,8 +272,8 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
freshWorld.noSave = true; freshWorld.noSave = true;
removeWorldFromWorldsMap(); removeWorldFromWorldsMap();
newWorldData.checkName(originalServerWorld.serverLevelData.getLevelName()); //rename to original world name newWorldData.checkName(originalServerWorld.serverLevelData.getLevelName()); //rename to original world name
if (worldPaperConfigField != null) { if (paperConfigField != null) {
worldPaperConfigField.set(freshWorld, originalServerWorld.paperConfig); paperConfigField.set(freshWorld, originalServerWorld.paperConfig);
} }
//generator //generator
@ -282,10 +284,17 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
} else if (originalChunkProvider.getGenerator() instanceof NoiseBasedChunkGenerator) { } else if (originalChunkProvider.getGenerator() instanceof NoiseBasedChunkGenerator) {
Supplier<NoiseGeneratorSettings> generatorSettingBaseSupplier = (Supplier<NoiseGeneratorSettings>) generatorSettingBaseSupplierField Supplier<NoiseGeneratorSettings> generatorSettingBaseSupplier = (Supplier<NoiseGeneratorSettings>) generatorSettingBaseSupplierField
.get(originalChunkProvider.getGenerator()); .get(originalChunkProvider.getGenerator());
BiomeSource biomeSource = originalChunkProvider.getGenerator().getBiomeSource(); BiomeSource biomeSource;
if (options.hasBiomeType()) {
biomeSource = new FixedBiomeSource(BuiltinRegistries.BIOME.get(ResourceLocation.tryParse(options
.getBiomeType()
.getId())));
} else {
biomeSource = originalChunkProvider.getGenerator().getBiomeSource();
if (biomeSource instanceof OverworldBiomeSource) { if (biomeSource instanceof OverworldBiomeSource) {
biomeSource = fastOverworldBiomeSource(biomeSource); biomeSource = fastOverworldBiomeSource(biomeSource);
} }
}
chunkGenerator = new NoiseBasedChunkGenerator(biomeSource, seed, generatorSettingBaseSupplier); chunkGenerator = new NoiseBasedChunkGenerator(biomeSource, seed, generatorSettingBaseSupplier);
} else if (originalChunkProvider.getGenerator() instanceof CustomChunkGenerator) { } else if (originalChunkProvider.getGenerator() instanceof CustomChunkGenerator) {
chunkGenerator = (ChunkGenerator) delegateField.get(originalChunkProvider.getGenerator()); chunkGenerator = (ChunkGenerator) delegateField.get(originalChunkProvider.getGenerator());
@ -314,12 +323,16 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
) { ) {
// redirect to LevelChunks created in #createChunks // redirect to LevelChunks created in #createChunks
@Override @Override
public ChunkAccess getChunk(int x, int z, ChunkStatus chunkstatus, boolean flag) { public ChunkAccess getChunk(int x, int z, ChunkStatus chunkstatus, boolean create) {
return getChunkAt(x, z); ChunkAccess chunkAccess = getChunkAt(x, z);
if (chunkAccess == null && create) {
chunkAccess = createChunk(getProtoChunkAt(x, z));
}
return chunkAccess;
} }
}; };
ReflectionUtils.unsafeSet(chunkProviderField, freshWorld, freshChunkProvider); ReflectionUtils.unsafeSet(chunkSourceField, freshWorld, freshChunkProvider);
//let's start then //let's start then
structureManager = server.getStructureManager(); structureManager = server.getStructureManager();
threadedLevelLightEngine = freshChunkProvider.getLightEngine(); threadedLevelLightEngine = freshChunkProvider.getLightEngine();
@ -402,11 +415,12 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
} }
//util //util
@SuppressWarnings("unchecked")
private void removeWorldFromWorldsMap() { private void removeWorldFromWorldsMap() {
Fawe.instance().getQueueHandler().sync(() -> { Fawe.instance().getQueueHandler().sync(() -> {
try { try {
Map<String, org.bukkit.World> map = (Map<String, org.bukkit.World>) serverWorldsField.get(Bukkit.getServer()); Map<String, org.bukkit.World> map = (Map<String, org.bukkit.World>) worldsField.get(Bukkit.getServer());
map.remove("worldeditregentempworld"); map.remove("faweregentempworld");
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -414,17 +428,14 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
} }
private ResourceKey<LevelStem> getWorldDimKey(org.bukkit.World.Environment env) { private ResourceKey<LevelStem> getWorldDimKey(org.bukkit.World.Environment env) {
switch (env) { return switch (env) {
case NETHER: case NETHER -> LevelStem.NETHER;
return LevelStem.NETHER; case THE_END -> LevelStem.END;
case THE_END: default -> LevelStem.OVERWORLD;
return LevelStem.END; };
case NORMAL:
default:
return LevelStem.OVERWORLD;
}
} }
@SuppressWarnings({"unchecked", "rawtypes"})
private BiomeSource fastOverworldBiomeSource(BiomeSource biomeSource) throws Exception { private BiomeSource fastOverworldBiomeSource(BiomeSource biomeSource) throws Exception {
Field legacyBiomeInitLayerField = OverworldBiomeSource.class.getDeclaredField( Field legacyBiomeInitLayerField = OverworldBiomeSource.class.getDeclaredField(
Refraction.pickName("legacyBiomeInitLayer", "i")); Refraction.pickName("legacyBiomeInitLayer", "i"));
@ -588,17 +599,7 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
} }
private static class FastAreaLazy implements Area { private record FastAreaLazy(ConcurrentHashMap<Long, Integer> sharedMap, PixelTransformer transformer) implements Area {
private final PixelTransformer transformer;
//ConcurrentHashMap is 50% faster that Long2IntLinkedOpenHashMap in a synchronized context
//using a map for each thread worsens the performance significantly due to cache misses (factor 5)
private final ConcurrentHashMap<Long, Integer> sharedMap;
public FastAreaLazy(ConcurrentHashMap<Long, Integer> sharedMap, PixelTransformer transformer) {
this.sharedMap = sharedMap;
this.transformer = transformer;
}
@Override @Override
public int get(int x, int z) { public int get(int x, int z) {

Datei anzeigen

@ -1,17 +0,0 @@
plugins {
java
}
applyPaperweightAdapterConfiguration()
repositories {
maven {
name = "PaperMC"
url = uri("https://papermc.io/repo/repository/maven-public/")
}
}
dependencies {
paperDevBundle("1.18.1-R0.1-20211221.093324-19")
compileOnly(libs.paperlib)
}

Datei anzeigen

@ -0,0 +1,17 @@
import io.papermc.paperweight.userdev.PaperweightUserDependenciesExtension
plugins {
java
}
applyPaperweightAdapterConfiguration()
repositories {
gradlePluginPortal()
}
dependencies {
// https://papermc.io/repo/service/rest/repository/browse/maven-public/io/papermc/paper/dev-bundle/
the<PaperweightUserDependenciesExtension>().paperDevBundle("1.18.2-R0.1-20220920.010157-167")
compileOnly(libs.paperlib)
}

Datei anzeigen

@ -17,7 +17,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.bukkit.adapter.ext.fawe.v1_18_R1; package com.sk89q.worldedit.bukkit.adapter.ext.fawe.v1_18_R2;
import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader; import com.google.common.cache.CacheLoader;
@ -27,18 +27,13 @@ import com.google.common.collect.Maps;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.Futures;
import com.mojang.datafixers.util.Either; import com.mojang.datafixers.util.Either;
import com.mojang.serialization.Codec;
import com.mojang.serialization.Dynamic;
import com.mojang.serialization.Lifecycle; import com.mojang.serialization.Lifecycle;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseItem; import com.sk89q.worldedit.blocks.BaseItem;
import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.blocks.BaseItemStack;
import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter; import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter;
import com.sk89q.worldedit.bukkit.adapter.Refraction; import com.sk89q.worldedit.bukkit.adapter.Refraction;
import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R1.PaperweightFaweAdapter;
import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.extension.platform.Watchdog; import com.sk89q.worldedit.extension.platform.Watchdog;
import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.Extent;
@ -55,6 +50,7 @@ import com.sk89q.worldedit.registry.state.IntegerProperty;
import com.sk89q.worldedit.registry.state.Property; import com.sk89q.worldedit.registry.state.Property;
import com.sk89q.worldedit.util.Direction; import com.sk89q.worldedit.util.Direction;
import com.sk89q.worldedit.util.SideEffect; import com.sk89q.worldedit.util.SideEffect;
import com.sk89q.worldedit.util.concurrency.LazyReference;
import com.sk89q.worldedit.util.formatting.text.Component; import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.util.formatting.text.TranslatableComponent; import com.sk89q.worldedit.util.formatting.text.TranslatableComponent;
import com.sk89q.worldedit.util.io.file.SafeFiles; import com.sk89q.worldedit.util.io.file.SafeFiles;
@ -85,11 +81,8 @@ import com.sk89q.worldedit.world.item.ItemType;
import net.minecraft.Util; import net.minecraft.Util;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.nbt.NbtOps;
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
import net.minecraft.network.protocol.game.ClientboundEntityEventPacket; import net.minecraft.network.protocol.game.ClientboundEntityEventPacket;
import net.minecraft.resources.RegistryReadOps;
import net.minecraft.resources.RegistryWriteOps;
import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
@ -120,7 +113,6 @@ import net.minecraft.world.level.block.state.properties.DirectionProperty;
import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.ChunkStatus; import net.minecraft.world.level.chunk.ChunkStatus;
import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.PalettedContainer;
import net.minecraft.world.level.dimension.LevelStem; import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.levelgen.WorldGenSettings; import net.minecraft.world.level.levelgen.WorldGenSettings;
import net.minecraft.world.level.storage.LevelStorageSource; import net.minecraft.world.level.storage.LevelStorageSource;
@ -131,20 +123,19 @@ import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World.Environment; import org.bukkit.World.Environment;
import org.bukkit.block.data.BlockData; import org.bukkit.block.data.BlockData;
import org.bukkit.craftbukkit.v1_18_R1.CraftServer; import org.bukkit.craftbukkit.v1_18_R2.CraftServer;
import org.bukkit.craftbukkit.v1_18_R1.CraftWorld; import org.bukkit.craftbukkit.v1_18_R2.CraftWorld;
import org.bukkit.craftbukkit.v1_18_R1.block.data.CraftBlockData; import org.bukkit.craftbukkit.v1_18_R2.block.data.CraftBlockData;
import org.bukkit.craftbukkit.v1_18_R1.entity.CraftEntity; import org.bukkit.craftbukkit.v1_18_R2.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_18_R1.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_18_R2.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_18_R1.inventory.CraftItemStack; import org.bukkit.craftbukkit.v1_18_R2.inventory.CraftItemStack;
import org.bukkit.craftbukkit.v1_18_R1.util.CraftMagicNumbers; import org.bukkit.craftbukkit.v1_18_R2.util.CraftMagicNumbers;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.generator.ChunkGenerator; import org.bukkit.generator.ChunkGenerator;
import org.spigotmc.SpigotConfig; import org.spigotmc.SpigotConfig;
import org.spigotmc.WatchdogThread; import org.spigotmc.WatchdogThread;
import javax.annotation.Nullable;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
@ -153,43 +144,54 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.OptionalInt; import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.Set; import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinPool;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft.nbt.Tag> { public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft.nbt.Tag> {
private final Logger logger = Logger.getLogger(getClass().getCanonicalName()); private static final Set<SideEffect> SUPPORTED_SIDE_EFFECTS = Sets.immutableEnumSet(
SideEffect.NEIGHBORS,
SideEffect.LIGHTING,
SideEffect.VALIDATION,
SideEffect.ENTITY_AI,
SideEffect.EVENTS,
SideEffect.UPDATE
);
private final Field serverWorldsField; private final Field serverWorldsField;
private final Method getChunkFutureMethod; private final Method getChunkFutureMethod;
private final Field chunkProviderExecutorField; private final Field chunkProviderExecutorField;
private final Watchdog watchdog; private final Logger LOGGER = Logger.getLogger(getClass().getCanonicalName());
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
// Code that may break between versions of Minecraft // Code that may break between versions of Minecraft
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------
private final Watchdog watchdog;
private final LoadingCache<ServerLevel, PaperweightFakePlayer> fakePlayers
= CacheBuilder.newBuilder().weakKeys().softValues().build(CacheLoader.from(PaperweightFakePlayer::new));
public PaperweightAdapter() throws NoSuchFieldException, NoSuchMethodException { public PaperweightAdapter() throws NoSuchFieldException, NoSuchMethodException {
// A simple test // A simple test
CraftServer.class.cast(Bukkit.getServer()); CraftServer.class.cast(Bukkit.getServer());
int dataVersion = CraftMagicNumbers.INSTANCE.getDataVersion(); int dataVersion = CraftMagicNumbers.INSTANCE.getDataVersion();
if (dataVersion != 2860 && dataVersion != 2865) { if (dataVersion != 2975) {
throw new UnsupportedClassVersionError("Not 1.18 or 1.18.1!"); throw new UnsupportedClassVersionError("Not 1.18.2!");
} }
serverWorldsField = CraftServer.class.getDeclaredField("worlds"); serverWorldsField = CraftServer.class.getDeclaredField("worlds");
@ -202,7 +204,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
getChunkFutureMethod.setAccessible(true); getChunkFutureMethod.setAccessible(true);
chunkProviderExecutorField = ServerChunkCache.class.getDeclaredField( chunkProviderExecutorField = ServerChunkCache.class.getDeclaredField(
Refraction.pickName("mainThreadProcessor", "h") Refraction.pickName("mainThreadProcessor", "g")
); );
chunkProviderExecutorField.setAccessible(true); chunkProviderExecutorField.setAccessible(true);
@ -223,16 +225,11 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
try { try {
Class.forName("org.spigotmc.SpigotConfig"); Class.forName("org.spigotmc.SpigotConfig");
SpigotConfig.config.set("world-settings.worldeditregentempworld.verbose", false); SpigotConfig.config.set("world-settings.faweregentempworld.verbose", false);
} catch (ClassNotFoundException ignored) { } catch (ClassNotFoundException ignored) {
} }
} }
@Override
public DataFixer getDataFixer() {
return PaperweightDataConverters.INSTANCE;
}
/** /**
* Read the given NBT data into the given tile entity. * Read the given NBT data into the given tile entity.
* *
@ -294,6 +291,29 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
return Registry.ITEM.get(ResourceLocation.tryParse(itemType.getId())); return Registry.ITEM.get(ResourceLocation.tryParse(itemType.getId()));
} }
private static net.minecraft.core.Direction adapt(Direction face) {
switch (face) {
case NORTH:
return net.minecraft.core.Direction.NORTH;
case SOUTH:
return net.minecraft.core.Direction.SOUTH;
case WEST:
return net.minecraft.core.Direction.WEST;
case EAST:
return net.minecraft.core.Direction.EAST;
case DOWN:
return net.minecraft.core.Direction.DOWN;
case UP:
default:
return net.minecraft.core.Direction.UP;
}
}
@Override
public DataFixer getDataFixer() {
return PaperweightDataConverters.INSTANCE;
}
@Override @Override
public OptionalInt getInternalBlockStateId(BlockData data) { public OptionalInt getInternalBlockStateId(BlockData data) {
net.minecraft.world.level.block.state.BlockState state = ((CraftBlockData) data).getState(); net.minecraft.world.level.block.state.BlockState state = ((CraftBlockData) data).getState();
@ -323,8 +343,9 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
final ServerLevel handle = craftWorld.getHandle(); final ServerLevel handle = craftWorld.getHandle();
LevelChunk chunk = handle.getChunk(x >> 4, z >> 4); LevelChunk chunk = handle.getChunk(x >> 4, z >> 4);
final BlockPos blockPos = new BlockPos(x, y, z); final BlockPos blockPos = new BlockPos(x, y, z);
final CraftBlockData blockData = chunk.getBlockState(blockPos).createCraftBlockData(); final net.minecraft.world.level.block.state.BlockState blockData = chunk.getBlockState(blockPos);
BlockState state = BukkitAdapter.adapt(blockData); int internalId = Block.getId(blockData);
BlockState state = BlockStateIdAccess.getBlockStateById(internalId);
if (state == null) { if (state == null) {
org.bukkit.block.Block bukkitBlock = location.getBlock(); org.bukkit.block.Block bukkitBlock = location.getBlock();
state = BukkitAdapter.adapt(bukkitBlock.getBlockData()); state = BukkitAdapter.adapt(bukkitBlock.getBlockData());
@ -366,24 +387,6 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
); );
} }
private static net.minecraft.core.Direction adapt(Direction face) {
switch (face) {
case NORTH:
return net.minecraft.core.Direction.NORTH;
case SOUTH:
return net.minecraft.core.Direction.SOUTH;
case WEST:
return net.minecraft.core.Direction.WEST;
case EAST:
return net.minecraft.core.Direction.EAST;
case DOWN:
return net.minecraft.core.Direction.DOWN;
case UP:
default:
return net.minecraft.core.Direction.UP;
}
}
@SuppressWarnings({"rawtypes", "unchecked"}) @SuppressWarnings({"rawtypes", "unchecked"})
private net.minecraft.world.level.block.state.BlockState applyProperties( private net.minecraft.world.level.block.state.BlockState applyProperties(
StateDefinition<Block, net.minecraft.world.level.block.state.BlockState> stateContainer, StateDefinition<Block, net.minecraft.world.level.block.state.BlockState> stateContainer,
@ -427,7 +430,12 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
net.minecraft.nbt.CompoundTag tag = new net.minecraft.nbt.CompoundTag(); net.minecraft.nbt.CompoundTag tag = new net.minecraft.nbt.CompoundTag();
readEntityIntoTag(mcEntity, tag); readEntityIntoTag(mcEntity, tag);
return new BaseEntity(com.sk89q.worldedit.world.entity.EntityTypes.get(id), (CompoundTag) toNative(tag)); //FAWE start - CompoundBinaryTag
return new BaseEntity(
com.sk89q.worldedit.world.entity.EntityTypes.get(id),
LazyReference.from(() -> (CompoundBinaryTag) toNativeBinary(tag))
);
//FAWE end
} }
@Nullable @Nullable
@ -442,9 +450,9 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
Entity createdEntity = createEntityFromId(state.getType().getId(), craftWorld.getHandle()); Entity createdEntity = createEntityFromId(state.getType().getId(), craftWorld.getHandle());
if (createdEntity != null) { if (createdEntity != null) {
CompoundTag nativeTag = state.getNbtData(); CompoundBinaryTag nativeTag = state.getNbt();
if (nativeTag != null) { if (nativeTag != null) {
net.minecraft.nbt.CompoundTag tag = (net.minecraft.nbt.CompoundTag) fromNative(nativeTag); net.minecraft.nbt.CompoundTag tag = (net.minecraft.nbt.CompoundTag) fromNativeBinary(nativeTag);
for (String name : Constants.NO_COPY_ENTITY_NBT_FIELDS) { for (String name : Constants.NO_COPY_ENTITY_NBT_FIELDS) {
tag.remove(name); tag.remove(name);
} }
@ -476,47 +484,40 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
} }
@SuppressWarnings({"unchecked", "rawtypes"}) @SuppressWarnings({"unchecked", "rawtypes"})
private static final LoadingCache<net.minecraft.world.level.block.state.properties.Property, Property<?>> PROPERTY_CACHE = CacheBuilder.newBuilder().build(new CacheLoader<net.minecraft.world.level.block.state.properties.Property, Property<?>>() {
@Override
public Property<?> load(net.minecraft.world.level.block.state.properties.Property state) throws Exception {
if (state instanceof net.minecraft.world.level.block.state.properties.BooleanProperty) {
return new BooleanProperty(state.getName(), ImmutableList.copyOf(state.getPossibleValues()));
} else if (state instanceof DirectionProperty) {
return new DirectionalProperty(state.getName(),
(List<Direction>) state.getPossibleValues().stream().map(e -> Direction.valueOf(((StringRepresentable) e).getSerializedName().toUpperCase(Locale.ROOT))).collect(Collectors.toList()));
} else if (state instanceof net.minecraft.world.level.block.state.properties.EnumProperty) {
return new EnumProperty(state.getName(),
(List<String>) state.getPossibleValues().stream().map(e -> ((StringRepresentable) e).getSerializedName()).collect(Collectors.toList()));
} else if (state instanceof net.minecraft.world.level.block.state.properties.IntegerProperty) {
return new IntegerProperty(state.getName(), ImmutableList.copyOf(state.getPossibleValues()));
} else {
throw new IllegalArgumentException("FastAsyncWorldEdit needs an update to support " + state.getClass().getSimpleName());
}
}
});
@SuppressWarnings({ "rawtypes" })
@Override @Override
public Map<String, ? extends Property<?>> getProperties(BlockType blockType) { public Map<String, ? extends Property<?>> getProperties(BlockType blockType) {
Map<String, Property<?>> properties = Maps.newTreeMap(String::compareTo); Map<String, Property<?>> properties = new TreeMap<>();
Block block = getBlockFromType(blockType); Block block = getBlockFromType(blockType);
StateDefinition<Block, net.minecraft.world.level.block.state.BlockState> blockStateList = StateDefinition<Block, net.minecraft.world.level.block.state.BlockState> blockStateList =
block.getStateDefinition(); block.getStateDefinition();
for (net.minecraft.world.level.block.state.properties.Property state : blockStateList.getProperties()) { for (net.minecraft.world.level.block.state.properties.Property state : blockStateList.getProperties()) {
Property property; Property<?> property = PROPERTY_CACHE.getUnchecked(state);
if (state instanceof net.minecraft.world.level.block.state.properties.BooleanProperty) {
property = new BooleanProperty(state.getName(), ImmutableList.copyOf(state.getPossibleValues()));
} else if (state instanceof DirectionProperty) {
property = new DirectionalProperty(
state.getName(),
(List<Direction>) state
.getPossibleValues()
.stream()
.map(e -> Direction.valueOf(((StringRepresentable) e)
.getSerializedName()
.toUpperCase(Locale.ROOT)))
.collect(Collectors.toList())
);
} else if (state instanceof net.minecraft.world.level.block.state.properties.EnumProperty) {
property = new EnumProperty(
state.getName(),
(List<String>) state
.getPossibleValues()
.stream()
.map(e -> ((StringRepresentable) e).getSerializedName())
.collect(Collectors.toList())
);
} else if (state instanceof net.minecraft.world.level.block.state.properties.IntegerProperty) {
property = new IntegerProperty(state.getName(), ImmutableList.copyOf(state.getPossibleValues()));
} else {
throw new IllegalArgumentException("WorldEdit needs an update to support " + state.getClass().getSimpleName());
}
properties.put(property.getName(), property); properties.put(property.getName(), property);
} }
return properties; return properties;
} }
//FAWE start - CompoundBinaryTag > CompoundTag
@Override @Override
public void sendFakeNBT(Player player, BlockVector3 pos, CompoundBinaryTag nbtData) { public void sendFakeNBT(Player player, BlockVector3 pos, CompoundBinaryTag nbtData) {
((CraftPlayer) player).getHandle().networkManager.send(ClientboundBlockEntityDataPacket.create( ((CraftPlayer) player).getHandle().networkManager.send(ClientboundBlockEntityDataPacket.create(
@ -527,6 +528,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
__ -> (net.minecraft.nbt.CompoundTag) fromNativeBinary(nbtData) __ -> (net.minecraft.nbt.CompoundTag) fromNativeBinary(nbtData)
)); ));
} }
//FAWE end
@Override @Override
public void sendFakeOP(Player player) { public void sendFakeOP(Player player) {
@ -546,13 +548,12 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
public BaseItemStack adapt(org.bukkit.inventory.ItemStack itemStack) { public BaseItemStack adapt(org.bukkit.inventory.ItemStack itemStack) {
final ItemStack nmsStack = CraftItemStack.asNMSCopy(itemStack); final ItemStack nmsStack = CraftItemStack.asNMSCopy(itemStack);
final BaseItemStack weStack = new BaseItemStack(BukkitAdapter.asItemType(itemStack.getType()), itemStack.getAmount()); final BaseItemStack weStack = new BaseItemStack(BukkitAdapter.asItemType(itemStack.getType()), itemStack.getAmount());
weStack.setNbtData(((CompoundTag) toNative(nmsStack.getTag()))); //FAWE start - CBT > CT
weStack.setNbt(((CompoundBinaryTag) toNativeBinary(nmsStack.getTag())));
//FAWE end
return weStack; return weStack;
} }
private final LoadingCache<ServerLevel, PaperweightFakePlayer> fakePlayers
= CacheBuilder.newBuilder().weakKeys().softValues().build(CacheLoader.from(PaperweightFakePlayer::new));
@Override @Override
public boolean simulateItemUse(org.bukkit.World world, BlockVector3 position, BaseItem item, Direction face) { public boolean simulateItemUse(org.bukkit.World world, BlockVector3 position, BaseItem item, Direction face) {
CraftWorld craftWorld = (CraftWorld) world; CraftWorld craftWorld = (CraftWorld) world;
@ -620,7 +621,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
Path tempDir = Files.createTempDirectory("FastAsyncWorldEditWorldGen"); Path tempDir = Files.createTempDirectory("FastAsyncWorldEditWorldGen");
LevelStorageSource levelStorage = LevelStorageSource.createDefault(tempDir); LevelStorageSource levelStorage = LevelStorageSource.createDefault(tempDir);
ResourceKey<LevelStem> worldDimKey = getWorldDimKey(env); ResourceKey<LevelStem> worldDimKey = getWorldDimKey(env);
try (LevelStorageSource.LevelStorageAccess session = levelStorage.createAccess("worldeditregentempworld", worldDimKey)) { try (LevelStorageSource.LevelStorageAccess session = levelStorage.createAccess("faweregentempworld", worldDimKey)) {
ServerLevel originalWorld = ((CraftWorld) bukkitWorld).getHandle(); ServerLevel originalWorld = ((CraftWorld) bukkitWorld).getHandle();
PrimaryLevelData levelProperties = (PrimaryLevelData) originalWorld.getServer() PrimaryLevelData levelProperties = (PrimaryLevelData) originalWorld.getServer()
.getWorldData().overworldData(); .getWorldData().overworldData();
@ -628,11 +629,11 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
long seed = options.getSeed().orElse(originalWorld.getSeed()); long seed = options.getSeed().orElse(originalWorld.getSeed());
WorldGenSettings newOpts = options.getSeed().isPresent() WorldGenSettings newOpts = options.getSeed().isPresent()
? replaceSeed(originalWorld, seed, originalOpts) ? originalOpts.withSeed(levelProperties.isHardcore(), OptionalLong.of(seed))
: originalOpts; : originalOpts;
LevelSettings newWorldSettings = new LevelSettings( LevelSettings newWorldSettings = new LevelSettings(
"worldeditregentempworld", "faweregentempworld",
levelProperties.settings.gameType(), levelProperties.settings.gameType(),
levelProperties.settings.hardcore(), levelProperties.settings.hardcore(),
levelProperties.settings.difficulty(), levelProperties.settings.difficulty(),
@ -647,7 +648,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
originalWorld.getServer().executor, originalWorld.getServer().executor,
session, newWorldData, session, newWorldData,
originalWorld.dimension(), originalWorld.dimension(),
originalWorld.dimensionType(), originalWorld.dimensionTypeRegistration(),
new NoOpWorldLoadListener(), new NoOpWorldLoadListener(),
newOpts.dimensions().get(worldDimKey).generator(), newOpts.dimensions().get(worldDimKey).generator(),
originalWorld.isDebug(), originalWorld.isDebug(),
@ -666,64 +667,13 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
try { try {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<String, org.bukkit.World> map = (Map<String, org.bukkit.World>) serverWorldsField.get(Bukkit.getServer()); Map<String, org.bukkit.World> map = (Map<String, org.bukkit.World>) serverWorldsField.get(Bukkit.getServer());
map.remove("worldeditregentempworld"); map.remove("faweregentempworld");
} catch (IllegalAccessException ignored) { } catch (IllegalAccessException ignored) {
} }
SafeFiles.tryHardToDeleteDir(tempDir); SafeFiles.tryHardToDeleteDir(tempDir);
} }
} }
// FAWE start - private -> public static
public static WorldGenSettings replaceSeed(ServerLevel originalWorld, long seed, WorldGenSettings originalOpts) {
// FAWE end
RegistryWriteOps<net.minecraft.nbt.Tag> nbtReadRegOps = RegistryWriteOps.create(
NbtOps.INSTANCE,
originalWorld.getServer().registryAccess()
);
RegistryReadOps<net.minecraft.nbt.Tag> nbtRegOps = RegistryReadOps.createAndLoad(
NbtOps.INSTANCE,
originalWorld.getServer().getResourceManager(),
originalWorld.getServer().registryAccess()
);
Codec<WorldGenSettings> dimCodec = WorldGenSettings.CODEC;
return dimCodec
.encodeStart(nbtReadRegOps, originalOpts)
.flatMap(tag ->
dimCodec.parse(
recursivelySetSeed(new Dynamic<>(nbtRegOps, tag), seed, new HashSet<>())
)
)
.get()
.map(
l -> l,
error -> {
throw new IllegalStateException("Unable to map GeneratorOptions: " + error.message());
}
);
}
// FAWE start - private -> private static
@SuppressWarnings("unchecked")
private static Dynamic<net.minecraft.nbt.Tag> recursivelySetSeed(
// FAWE end
Dynamic<net.minecraft.nbt.Tag> dynamic,
long seed,
Set<Dynamic<net.minecraft.nbt.Tag>> seen
) {
if (!seen.add(dynamic)) {
return dynamic;
}
return dynamic.updateMapValues(pair -> {
if (pair.getFirst().asString("").equals("seed")) {
return pair.mapSecond(v -> v.createLong(seed));
}
if (pair.getSecond().getValue() instanceof net.minecraft.nbt.CompoundTag) {
return pair.mapSecond(v -> recursivelySetSeed((Dynamic<net.minecraft.nbt.Tag>) v, seed, seen));
}
return pair;
});
}
private BiomeType adapt(ServerLevel serverWorld, Biome origBiome) { private BiomeType adapt(ServerLevel serverWorld, Biome origBiome) {
ResourceLocation key = serverWorld.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).getKey(origBiome); ResourceLocation key = serverWorld.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).getKey(origBiome);
if (key == null) { if (key == null) {
@ -763,9 +713,8 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
BlockPos pos = new BlockPos(vec.getBlockX(), vec.getBlockY(), vec.getBlockZ()); BlockPos pos = new BlockPos(vec.getBlockX(), vec.getBlockY(), vec.getBlockZ());
ChunkAccess chunk = chunks.get(new ChunkPos(pos)); ChunkAccess chunk = chunks.get(new ChunkPos(pos));
final net.minecraft.world.level.block.state.BlockState blockData = chunk.getBlockState(pos); final net.minecraft.world.level.block.state.BlockState blockData = chunk.getBlockState(pos);
BlockStateHolder<?> state = ((PaperweightFaweAdapter) WorldEditPlugin int internalId = Block.getId(blockData);
.getInstance() BlockStateHolder<?> state = BlockStateIdAccess.getBlockStateById(internalId);
.getBukkitImplAdapter()).adapt(blockData);
Objects.requireNonNull(state); Objects.requireNonNull(state);
BlockEntity blockEntity = chunk.getBlockEntity(pos); BlockEntity blockEntity = chunk.getBlockEntity(pos);
if (blockEntity != null) { if (blockEntity != null) {
@ -776,9 +725,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
} }
extent.setBlock(vec, state.toBaseBlock()); extent.setBlock(vec, state.toBaseBlock());
if (options.shouldRegenBiomes()) { if (options.shouldRegenBiomes()) {
PalettedContainer<Biome> biomeIndex = chunk.getSection(chunk.getSectionIndex(vec.getBlockY())) Biome origBiome = chunk.getNoiseBiome(vec.getX(), vec.getY(), vec.getZ()).value();
.getBiomes();
Biome origBiome = biomeIndex.get(vec.getBlockX(), vec.getBlockY(), vec.getBlockZ());
BiomeType adaptedBiome = adapt(serverWorld, origBiome); BiomeType adaptedBiome = adapt(serverWorld, origBiome);
if (adaptedBiome != null) { if (adaptedBiome != null) {
extent.setBiome(vec, adaptedBiome); extent.setBiome(vec, adaptedBiome);
@ -819,15 +766,6 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
} }
} }
private static final Set<SideEffect> SUPPORTED_SIDE_EFFECTS = Sets.immutableEnumSet(
SideEffect.NEIGHBORS,
SideEffect.LIGHTING,
SideEffect.VALIDATION,
SideEffect.ENTITY_AI,
SideEffect.EVENTS,
SideEffect.UPDATE
);
@Override @Override
public Set<SideEffect> getSupportedSideEffects() { public Set<SideEffect> getSupportedSideEffects() {
return SUPPORTED_SIDE_EFFECTS; return SUPPORTED_SIDE_EFFECTS;
@ -889,7 +827,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
try { try {
return toNativeList((net.minecraft.nbt.ListTag) foreign); return toNativeList((net.minecraft.nbt.ListTag) foreign);
} catch (Throwable e) { } catch (Throwable e) {
logger.log(Level.WARNING, "Failed to convert net.minecraft.nbt.ListTag", e); LOGGER.log(Level.WARNING, "Failed to convert net.minecraft.nbt.ListTag", e);
return ListBinaryTag.empty(); return ListBinaryTag.empty();
} }
} else if (foreign instanceof net.minecraft.nbt.LongTag) { } else if (foreign instanceof net.minecraft.nbt.LongTag) {
@ -914,7 +852,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
* @throws IllegalArgumentException on error * @throws IllegalArgumentException on error
*/ */
private ListBinaryTag toNativeList(net.minecraft.nbt.ListTag foreign) throws SecurityException, IllegalArgumentException { private ListBinaryTag toNativeList(net.minecraft.nbt.ListTag foreign) throws SecurityException, IllegalArgumentException {
ListBinaryTag.Builder values = ListBinaryTag.builder(); ListBinaryTag.Builder<BinaryTag> values = ListBinaryTag.builder();
for (net.minecraft.nbt.Tag tag : foreign) { for (net.minecraft.nbt.Tag tag : foreign) {
values.add(toNativeBinary(tag)); values.add(toNativeBinary(tag));
@ -954,9 +892,8 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
return new net.minecraft.nbt.IntArrayTag(((IntArrayBinaryTag) foreign).value()); return new net.minecraft.nbt.IntArrayTag(((IntArrayBinaryTag) foreign).value());
} else if (foreign instanceof LongArrayBinaryTag) { } else if (foreign instanceof LongArrayBinaryTag) {
return new net.minecraft.nbt.LongArrayTag(((LongArrayBinaryTag) foreign).value()); return new net.minecraft.nbt.LongArrayTag(((LongArrayBinaryTag) foreign).value());
} else if (foreign instanceof ListBinaryTag) { } else if (foreign instanceof ListBinaryTag foreignList) {
net.minecraft.nbt.ListTag tag = new net.minecraft.nbt.ListTag(); net.minecraft.nbt.ListTag tag = new net.minecraft.nbt.ListTag();
ListBinaryTag foreignList = (ListBinaryTag) foreign;
for (BinaryTag t : foreignList) { for (BinaryTag t : foreignList) {
tag.add(fromNativeBinary(t)); tag.add(fromNativeBinary(t));
} }
@ -985,35 +922,6 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
watchdog.tick(); watchdog.tick();
} }
private class SpigotWatchdog implements Watchdog {
private final Field instanceField;
private final Field lastTickField;
SpigotWatchdog() throws NoSuchFieldException {
Field instanceField = WatchdogThread.class.getDeclaredField("instance");
instanceField.setAccessible(true);
this.instanceField = instanceField;
Field lastTickField = WatchdogThread.class.getDeclaredField("lastTick");
lastTickField.setAccessible(true);
this.lastTickField = lastTickField;
}
@Override
public void tick() {
try {
WatchdogThread instance = (WatchdogThread) this.instanceField.get(null);
if ((long) lastTickField.get(instance) != 0) {
WatchdogThread.tick();
}
} catch (IllegalAccessException e) {
logger.log(Level.WARNING, "Failed to tick watchdog", e);
}
}
}
private static class MojangWatchdog implements Watchdog { private static class MojangWatchdog implements Watchdog {
private final DedicatedServer server; private final DedicatedServer server;
@ -1045,7 +953,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
} }
@Override @Override
public void onStatusChange(ChunkPos pos, @org.jetbrains.annotations.Nullable ChunkStatus status) { public void onStatusChange(ChunkPos pos, @Nullable ChunkStatus status) {
} }
@Override @Override
@ -1062,4 +970,33 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
} }
private class SpigotWatchdog implements Watchdog {
private final Field instanceField;
private final Field lastTickField;
SpigotWatchdog() throws NoSuchFieldException {
Field instanceField = WatchdogThread.class.getDeclaredField("instance");
instanceField.setAccessible(true);
this.instanceField = instanceField;
Field lastTickField = WatchdogThread.class.getDeclaredField("lastTick");
lastTickField.setAccessible(true);
this.lastTickField = lastTickField;
}
@Override
public void tick() {
try {
WatchdogThread instance = (WatchdogThread) this.instanceField.get(null);
if ((long) lastTickField.get(instance) != 0) {
WatchdogThread.tick();
}
} catch (IllegalAccessException e) {
LOGGER.log(Level.WARNING, "Failed to tick watchdog", e);
}
}
}
} }

Datei anzeigen

@ -17,7 +17,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.bukkit.adapter.ext.fawe.v1_18_R1; package com.sk89q.worldedit.bukkit.adapter.ext.fawe.v1_18_R2;
import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfile;
import net.minecraft.network.chat.ChatType; import net.minecraft.network.chat.ChatType;

Datei anzeigen

@ -17,7 +17,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.bukkit.adapter.ext.fawe.v1_18_R1; package com.sk89q.worldedit.bukkit.adapter.ext.fawe.v1_18_R2;
import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.internal.block.BlockStateIdAccess; import com.sk89q.worldedit.internal.block.BlockStateIdAccess;
@ -31,13 +31,13 @@ import net.minecraft.server.level.ChunkHolder;
import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.level.chunk.LevelChunk;
import org.bukkit.craftbukkit.v1_18_R1.CraftWorld; import org.bukkit.craftbukkit.v1_18_R2.CraftWorld;
import org.bukkit.craftbukkit.v1_18_R1.block.data.CraftBlockData; import org.bukkit.craftbukkit.v1_18_R2.block.data.CraftBlockData;
import org.bukkit.event.block.BlockPhysicsEvent; import org.bukkit.event.block.BlockPhysicsEvent;
import javax.annotation.Nullable;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.Objects; import java.util.Objects;
import javax.annotation.Nullable;
public class PaperweightWorldNativeAccess implements public class PaperweightWorldNativeAccess implements
WorldNativeAccess<LevelChunk, net.minecraft.world.level.block.state.BlockState, BlockPos> { WorldNativeAccess<LevelChunk, net.minecraft.world.level.block.state.BlockState, BlockPos> {
@ -201,9 +201,11 @@ public class PaperweightWorldNativeAccess implements
getWorld().onBlockStateChange(pos, oldState, newState); getWorld().onBlockStateChange(pos, oldState, newState);
} }
//FAWE start
@Override @Override
public void flush() { public void flush() {
} }
//FAWE end
} }

Datei anzeigen

@ -1,10 +1,10 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R1; package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R2;
import com.google.common.base.Suppliers; import com.google.common.base.Suppliers;
import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.CompoundTag;
import com.sk89q.util.ReflectionUtil; import com.sk89q.util.ReflectionUtil;
import com.sk89q.worldedit.bukkit.adapter.Refraction; import com.sk89q.worldedit.bukkit.adapter.Refraction;
import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R1.nbt.PaperweightLazyCompoundTag; import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R2.nbt.PaperweightLazyCompoundTag;
import com.sk89q.worldedit.world.registry.BlockMaterial; import com.sk89q.worldedit.world.registry.BlockMaterial;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.world.level.EmptyBlockGetter; import net.minecraft.world.level.EmptyBlockGetter;
@ -15,7 +15,7 @@ import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Material; import net.minecraft.world.level.material.Material;
import net.minecraft.world.level.material.PushReaction; import net.minecraft.world.level.material.PushReaction;
import org.bukkit.craftbukkit.v1_18_R1.block.data.CraftBlockData; import org.bukkit.craftbukkit.v1_18_R2.block.data.CraftBlockData;
public class PaperweightBlockMaterial implements BlockMaterial { public class PaperweightBlockMaterial implements BlockMaterial {
@ -26,7 +26,6 @@ public class PaperweightBlockMaterial implements BlockMaterial {
private final CraftBlockData craftBlockData; private final CraftBlockData craftBlockData;
private final org.bukkit.Material craftMaterial; private final org.bukkit.Material craftMaterial;
private final int opacity; private final int opacity;
//TODO 1.18 be a CompoundBinaryTag ?
private final CompoundTag tile; private final CompoundTag tile;
public PaperweightBlockMaterial(Block block) { public PaperweightBlockMaterial(Block block) {
@ -40,7 +39,7 @@ public class PaperweightBlockMaterial implements BlockMaterial {
this.craftBlockData = CraftBlockData.fromData(blockState); this.craftBlockData = CraftBlockData.fromData(blockState);
this.craftMaterial = craftBlockData.getMaterial(); this.craftMaterial = craftBlockData.getMaterial();
BlockBehaviour.Properties blockInfo = ReflectionUtil.getField(BlockBehaviour.class, block, Refraction.pickName( BlockBehaviour.Properties blockInfo = ReflectionUtil.getField(BlockBehaviour.class, block, Refraction.pickName(
"properties", "aP")); "properties", "aO"));
this.isTranslucent = !(boolean) ReflectionUtil.getField(BlockBehaviour.Properties.class, blockInfo, this.isTranslucent = !(boolean) ReflectionUtil.getField(BlockBehaviour.Properties.class, blockInfo,
Refraction.pickName("canOcclude", "n") Refraction.pickName("canOcclude", "n")
); );

Datei anzeigen

@ -1,19 +1,19 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R1; package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R2;
import ca.spottedleaf.starlight.common.light.StarLightEngine;
import com.fastasyncworldedit.bukkit.adapter.CachedBukkitAdapter; import com.fastasyncworldedit.bukkit.adapter.CachedBukkitAdapter;
import com.fastasyncworldedit.bukkit.adapter.IDelegateBukkitImplAdapter; import com.fastasyncworldedit.bukkit.adapter.IDelegateBukkitImplAdapter;
import com.fastasyncworldedit.bukkit.adapter.NMSRelighterFactory; import com.fastasyncworldedit.bukkit.adapter.NMSRelighterFactory;
import com.fastasyncworldedit.core.FaweCache; import com.fastasyncworldedit.core.FaweCache;
import com.fastasyncworldedit.core.entity.LazyBaseEntity; import com.fastasyncworldedit.core.entity.LazyBaseEntity;
import com.fastasyncworldedit.core.extent.processor.lighting.RelighterFactory; import com.fastasyncworldedit.core.extent.processor.lighting.RelighterFactory;
import com.fastasyncworldedit.core.queue.IBatchProcessor;
import com.fastasyncworldedit.core.queue.IChunkGet; import com.fastasyncworldedit.core.queue.IChunkGet;
import com.fastasyncworldedit.core.queue.implementation.packet.ChunkPacket; import com.fastasyncworldedit.core.queue.implementation.packet.ChunkPacket;
import com.fastasyncworldedit.core.util.NbtUtils;
import com.fastasyncworldedit.core.util.TaskManager;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.StringTag;
import com.sk89q.jnbt.Tag; import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.blocks.BaseItemStack; import com.sk89q.worldedit.blocks.BaseItemStack;
@ -21,9 +21,9 @@ import com.sk89q.worldedit.blocks.TileEntityBlock;
import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.bukkit.BukkitWorld; import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter; import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter;
import com.sk89q.worldedit.bukkit.adapter.ext.fawe.v1_18_R1.PaperweightAdapter; import com.sk89q.worldedit.bukkit.adapter.ext.fawe.v1_18_R2.PaperweightAdapter;
import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R1.nbt.PaperweightLazyCompoundTag; import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R2.nbt.PaperweightLazyCompoundTag;
import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R1.regen.PaperweightRegen; import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R2.regen.PaperweightRegen;
import com.sk89q.worldedit.entity.BaseEntity; import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.internal.block.BlockStateIdAccess; import com.sk89q.worldedit.internal.block.BlockStateIdAccess;
@ -41,6 +41,9 @@ import com.sk89q.worldedit.util.SideEffect;
import com.sk89q.worldedit.util.SideEffectSet; import com.sk89q.worldedit.util.SideEffectSet;
import com.sk89q.worldedit.util.TreeGenerator; import com.sk89q.worldedit.util.TreeGenerator;
import com.sk89q.worldedit.util.formatting.text.Component; import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.util.nbt.BinaryTag;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.util.nbt.StringBinaryTag;
import com.sk89q.worldedit.world.RegenOptions; import com.sk89q.worldedit.world.RegenOptions;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BaseBlock;
@ -52,6 +55,7 @@ import com.sk89q.worldedit.world.block.BlockTypesCache;
import com.sk89q.worldedit.world.entity.EntityType; import com.sk89q.worldedit.world.entity.EntityType;
import com.sk89q.worldedit.world.item.ItemType; import com.sk89q.worldedit.world.item.ItemType;
import com.sk89q.worldedit.world.registry.BlockMaterial; import com.sk89q.worldedit.world.registry.BlockMaterial;
import io.papermc.lib.PaperLib;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.core.WritableRegistry; import net.minecraft.core.WritableRegistry;
@ -80,16 +84,15 @@ import org.bukkit.Material;
import org.bukkit.NamespacedKey; import org.bukkit.NamespacedKey;
import org.bukkit.TreeType; import org.bukkit.TreeType;
import org.bukkit.block.data.BlockData; import org.bukkit.block.data.BlockData;
import org.bukkit.craftbukkit.v1_18_R1.CraftChunk; import org.bukkit.craftbukkit.v1_18_R2.CraftChunk;
import org.bukkit.craftbukkit.v1_18_R1.CraftServer; import org.bukkit.craftbukkit.v1_18_R2.CraftServer;
import org.bukkit.craftbukkit.v1_18_R1.CraftWorld; import org.bukkit.craftbukkit.v1_18_R2.CraftWorld;
import org.bukkit.craftbukkit.v1_18_R1.block.CraftBlock; import org.bukkit.craftbukkit.v1_18_R2.block.CraftBlockState;
import org.bukkit.craftbukkit.v1_18_R1.block.CraftBlockState; import org.bukkit.craftbukkit.v1_18_R2.block.data.CraftBlockData;
import org.bukkit.craftbukkit.v1_18_R1.block.data.CraftBlockData; import org.bukkit.craftbukkit.v1_18_R2.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_18_R1.entity.CraftEntity; import org.bukkit.craftbukkit.v1_18_R2.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_18_R1.entity.CraftPlayer; import org.bukkit.craftbukkit.v1_18_R2.inventory.CraftItemStack;
import org.bukkit.craftbukkit.v1_18_R1.inventory.CraftItemStack; import org.bukkit.craftbukkit.v1_18_R2.util.CraftNamespacedKey;
import org.bukkit.craftbukkit.v1_18_R1.util.CraftNamespacedKey;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -101,6 +104,7 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.OptionalInt; import java.util.OptionalInt;
import java.util.Set; import java.util.Set;
import java.util.function.Supplier; import java.util.function.Supplier;
@ -275,7 +279,7 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
BlockEntity blockEntity = chunk.getBlockEntity(blockPos, LevelChunk.EntityCreationType.CHECK); BlockEntity blockEntity = chunk.getBlockEntity(blockPos, LevelChunk.EntityCreationType.CHECK);
if (blockEntity != null) { if (blockEntity != null) {
net.minecraft.nbt.CompoundTag tag = blockEntity.saveWithId(); net.minecraft.nbt.CompoundTag tag = blockEntity.saveWithId();
return state.toBaseBlock((CompoundTag) toNative(tag)); return state.toBaseBlock((CompoundBinaryTag) toNativeBinary(tag));
} }
} }
@ -287,7 +291,6 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
return SideEffectSet.defaults().getSideEffectsToApply(); return SideEffectSet.defaults().getSideEffectsToApply();
} }
//TODO 1.18 address raw access of BlockStateHolder
public boolean setBlock(org.bukkit.Chunk chunk, int x, int y, int z, BlockStateHolder state, boolean update) { public boolean setBlock(org.bukkit.Chunk chunk, int x, int y, int z, BlockStateHolder state, boolean update) {
CraftChunk craftChunk = (CraftChunk) chunk; CraftChunk craftChunk = (CraftChunk) chunk;
LevelChunk levelChunk = craftChunk.getHandle(); LevelChunk levelChunk = craftChunk.getHandle();
@ -308,7 +311,7 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
levelChunk.removeBlockEntity(blockPos); // Force delete the old tile entity levelChunk.removeBlockEntity(blockPos); // Force delete the old tile entity
CompoundTag compoundTag = state instanceof BaseBlock ? state.getNbtData() : null; CompoundBinaryTag compoundTag = state instanceof BaseBlock ? state.getNbt() : null;
if (compoundTag != null || existing instanceof TileEntityBlock) { if (compoundTag != null || existing instanceof TileEntityBlock) {
level.setBlock(blockPos, blockState, 0); level.setBlock(blockPos, blockState, 0);
// remove tile // remove tile
@ -317,7 +320,7 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
// though we do not do this on the Forge version // though we do not do this on the Forge version
BlockEntity blockEntity = level.getBlockEntity(blockPos); BlockEntity blockEntity = level.getBlockEntity(blockPos);
if (blockEntity != null) { if (blockEntity != null) {
net.minecraft.nbt.CompoundTag tag = (net.minecraft.nbt.CompoundTag) fromNative(compoundTag); net.minecraft.nbt.CompoundTag tag = (net.minecraft.nbt.CompoundTag) fromNativeBinary(compoundTag);
tag.put("x", IntTag.valueOf(x)); tag.put("x", IntTag.valueOf(x));
tag.put("y", IntTag.valueOf(y)); tag.put("y", IntTag.valueOf(y));
tag.put("z", IntTag.valueOf(z)); tag.put("z", IntTag.valueOf(z));
@ -355,15 +358,14 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
if (id != null) { if (id != null) {
EntityType type = com.sk89q.worldedit.world.entity.EntityTypes.get(id); EntityType type = com.sk89q.worldedit.world.entity.EntityTypes.get(id);
//TODO 1.18 be a CBT ? Supplier<CompoundBinaryTag> saveTag = () -> {
Supplier<CompoundTag> saveTag = () -> {
final net.minecraft.nbt.CompoundTag minecraftTag = new net.minecraft.nbt.CompoundTag(); final net.minecraft.nbt.CompoundTag minecraftTag = new net.minecraft.nbt.CompoundTag();
readEntityIntoTag(mcEntity, minecraftTag); readEntityIntoTag(mcEntity, minecraftTag);
//add Id for AbstractChangeSet to work //add Id for AbstractChangeSet to work
final CompoundTag tag = (CompoundTag) toNative(minecraftTag); final CompoundBinaryTag tag = (CompoundBinaryTag) toNativeBinary(minecraftTag);
final Map<String, Tag> tags = new HashMap<>(tag.getValue()); final Map<String, BinaryTag> tags = NbtUtils.getCompoundBinaryTagValues(tag);
tags.put("Id", new StringTag(id)); tags.put("Id", StringBinaryTag.of(id));
return new CompoundTag(tags); return CompoundBinaryTag.from(tags);
}; };
return new LazyBaseEntity(type, saveTag); return new LazyBaseEntity(type, saveTag);
} else { } else {
@ -420,7 +422,7 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
LOGGER.error("Attempted to convert {} with ID {} to char. ibdToStateOrdinal length: {}. Defaulting to air!", LOGGER.error("Attempted to convert {} with ID {} to char. ibdToStateOrdinal length: {}. Defaulting to air!",
blockState.getBlock(), Block.BLOCK_STATE_REGISTRY.getId(blockState), ibdToStateOrdinal.length, e1 blockState.getBlock(), Block.BLOCK_STATE_REGISTRY.getId(blockState), ibdToStateOrdinal.length, e1
); );
return 0; return BlockTypesCache.ReservedIDs.AIR;
} }
} }
} }
@ -490,7 +492,6 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
ServerLevel nmsWorld = ((CraftWorld) world).getHandle(); ServerLevel nmsWorld = ((CraftWorld) world).getHandle();
ChunkHolder map = PaperweightPlatformAdapter.getPlayerChunk(nmsWorld, chunkPacket.getChunkX(), chunkPacket.getChunkZ()); ChunkHolder map = PaperweightPlatformAdapter.getPlayerChunk(nmsWorld, chunkPacket.getChunkX(), chunkPacket.getChunkZ());
if (map != null && map.wasAccessibleSinceLastSave()) { if (map != null && map.wasAccessibleSinceLastSave()) {
boolean flag = false;
// PlayerChunk.d players = map.players; // PlayerChunk.d players = map.players;
Stream<ServerPlayer> stream = /*players.a(new ChunkCoordIntPair(packet.getChunkX(), packet.getChunkZ()), flag) Stream<ServerPlayer> stream = /*players.a(new ChunkCoordIntPair(packet.getChunkX(), packet.getChunkZ()), flag)
*/ Stream.empty(); */ Stream.empty();
@ -554,16 +555,26 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
); // bukkit skips the feature gen which does this offset normally, so we have to add it back ); // bukkit skips the feature gen which does this offset normally, so we have to add it back
} }
ServerLevel serverLevel = ((CraftWorld) bukkitWorld).getHandle(); ServerLevel serverLevel = ((CraftWorld) bukkitWorld).getHandle();
final BlockVector3 finalBlockVector = blockVector3;
// Sync to main thread to ensure no clashes occur
Map<BlockPos, CraftBlockState> placed = TaskManager.taskManager().sync(() -> {
serverLevel.captureTreeGeneration = true; serverLevel.captureTreeGeneration = true;
serverLevel.captureBlockStates = true; serverLevel.captureBlockStates = true;
boolean grownTree = bukkitWorld.generateTree(BukkitAdapter.adapt(bukkitWorld, blockVector3), bukkitType); try {
if (!bukkitWorld.generateTree(BukkitAdapter.adapt(bukkitWorld, finalBlockVector), bukkitType)) {
return null;
}
return ImmutableMap.copyOf(serverLevel.capturedBlockStates);
} finally {
serverLevel.captureBlockStates = false; serverLevel.captureBlockStates = false;
serverLevel.captureTreeGeneration = false; serverLevel.captureTreeGeneration = false;
if (!grownTree) {
serverLevel.capturedBlockStates.clear(); serverLevel.capturedBlockStates.clear();
}
});
if (placed == null || placed.isEmpty()) {
return false; return false;
} else { }
for (CraftBlockState craftBlockState : serverLevel.capturedBlockStates.values()) { for (CraftBlockState craftBlockState : placed.values()) {
if (craftBlockState == null || craftBlockState.getType() == Material.AIR) { if (craftBlockState == null || craftBlockState.getType() == Material.AIR) {
continue; continue;
} }
@ -571,11 +582,8 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
BukkitAdapter.adapt(((org.bukkit.block.BlockState) craftBlockState).getBlockData()) BukkitAdapter.adapt(((org.bukkit.block.BlockState) craftBlockState).getBlockData())
); );
} }
serverLevel.capturedBlockStates.clear();
return true; return true;
} }
}
@Override @Override
public List<org.bukkit.entity.Entity> getEntities(org.bukkit.World world) { public List<org.bukkit.entity.Entity> getEntities(org.bukkit.World world) {
@ -598,7 +606,7 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
public BaseItemStack adapt(org.bukkit.inventory.ItemStack itemStack) { public BaseItemStack adapt(org.bukkit.inventory.ItemStack itemStack) {
final ItemStack nmsStack = CraftItemStack.asNMSCopy(itemStack); final ItemStack nmsStack = CraftItemStack.asNMSCopy(itemStack);
final BaseItemStack weStack = new BaseItemStack(BukkitAdapter.asItemType(itemStack.getType()), itemStack.getAmount()); final BaseItemStack weStack = new BaseItemStack(BukkitAdapter.asItemType(itemStack.getType()), itemStack.getAmount());
weStack.setNbtData(((CompoundTag) toNative(nmsStack.getTag()))); weStack.setNbt(((CompoundBinaryTag) toNativeBinary(nmsStack.getTag())));
return weStack; return weStack;
} }
@ -607,12 +615,17 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
return parent.toNative(foreign); return parent.toNative(foreign);
} }
@Override
public BinaryTag toNativeBinary(final net.minecraft.nbt.Tag foreign) {
return parent.toNativeBinary(foreign);
}
@Override @Override
public net.minecraft.nbt.Tag fromNative(Tag foreign) { public net.minecraft.nbt.Tag fromNative(Tag foreign) {
if (foreign instanceof PaperweightLazyCompoundTag) { if (foreign instanceof PaperweightLazyCompoundTag) {
return ((PaperweightLazyCompoundTag) foreign).get(); return ((PaperweightLazyCompoundTag) foreign).get();
} }
return parent.fromNative(foreign); return (net.minecraft.nbt.Tag) parent.fromNative(foreign);
} }
@Override @Override
@ -627,51 +640,43 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
@Override @Override
public int getInternalBiomeId(BiomeType biomeType) { public int getInternalBiomeId(BiomeType biomeType) {
if (biomeType.getId().startsWith("minecraft:")) { final Registry<Biome> registry = MinecraftServer
Biome biomeBase = CraftBlock.biomeToBiomeBase( .getServer()
MinecraftServer.getServer().registryAccess().ownedRegistryOrThrow(Registry.BIOME_REGISTRY), .registryAccess()
BukkitAdapter.adapt(biomeType)
);
return MinecraftServer.getServer().registryAccess().ownedRegistryOrThrow(Registry.BIOME_REGISTRY).getId(biomeBase);
} else {
WritableRegistry<Biome> biomeRegistry = MinecraftServer.getServer().registryAccess()
.ownedRegistryOrThrow(Registry.BIOME_REGISTRY); .ownedRegistryOrThrow(Registry.BIOME_REGISTRY);
ResourceLocation resourceLocation = ResourceLocation.tryParse(biomeType.getId());
ResourceLocation resourceLocation = biomeRegistry.keySet().stream() Biome biome = registry.get(resourceLocation);
.filter(resource -> resource.toString().equals(biomeType.getId())) return registry.getId(biome);
.findAny().orElse(null);
return biomeRegistry.getId(biomeRegistry.get(resourceLocation));
}
} }
@Override @Override
public Iterable<NamespacedKey> getRegisteredBiomes() { public Iterable<NamespacedKey> getRegisteredBiomes() {
WritableRegistry<Biome> biomeRegistry = ((CraftServer) Bukkit.getServer()) WritableRegistry<Biome> biomeRegistry = (WritableRegistry<Biome>) ((CraftServer) Bukkit.getServer())
.getServer() .getServer()
.registryAccess() .registryAccess()
.ownedRegistryOrThrow( .ownedRegistryOrThrow(
Registry.BIOME_REGISTRY); Registry.BIOME_REGISTRY);
return biomeRegistry.stream() List<ResourceLocation> keys = biomeRegistry.stream()
.map(biomeRegistry::getKey) .map(biomeRegistry::getKey).filter(Objects::nonNull).toList();
.map(CraftNamespacedKey::fromMinecraft) List<NamespacedKey> namespacedKeys = new ArrayList<>();
.collect(Collectors.toList()); for (ResourceLocation key : keys) {
try {
namespacedKeys.add(CraftNamespacedKey.fromMinecraft(key));
} catch (IllegalArgumentException e) {
LOGGER.error("Error converting biome key {}", key.toString(), e);
}
}
return namespacedKeys;
} }
@Override @Override
public RelighterFactory getRelighterFactory() { public RelighterFactory getRelighterFactory() {
try { if (PaperLib.isPaper()) {
Class.forName("ca.spottedleaf.starlight.common.light.StarLightEngine");
if (PaperweightStarlightRelighter.isUsable()) {
return new PaperweightStarlightRelighterFactory(); return new PaperweightStarlightRelighterFactory();
} } else {
} catch (ThreadDeath td) {
throw td;
} catch (Throwable ignored) {
}
return new NMSRelighterFactory(); return new NMSRelighterFactory();
} }
}
@Override @Override
public Map<String, List<Property<?>>> getAllProperties() { public Map<String, List<Property<?>>> getAllProperties() {
@ -687,4 +692,9 @@ public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
} }
} }
@Override
public IBatchProcessor getTickingPostProcessor() {
return new PaperweightPostProcessor();
}
} }

Datei anzeigen

@ -1,4 +1,4 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R1; package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R2;
import com.fastasyncworldedit.core.Fawe; import com.fastasyncworldedit.core.Fawe;
import com.fastasyncworldedit.core.math.IntPair; import com.fastasyncworldedit.core.math.IntPair;
@ -21,8 +21,8 @@ import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.chunk.LevelChunk; import net.minecraft.world.level.chunk.LevelChunk;
import org.bukkit.craftbukkit.v1_18_R1.CraftWorld; import org.bukkit.craftbukkit.v1_18_R2.CraftWorld;
import org.bukkit.craftbukkit.v1_18_R1.block.data.CraftBlockData; import org.bukkit.craftbukkit.v1_18_R2.block.data.CraftBlockData;
import org.bukkit.event.block.BlockPhysicsEvent; import org.bukkit.event.block.BlockPhysicsEvent;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -246,7 +246,7 @@ public class PaperweightFaweWorldNativeAccess implements WorldNativeAccess<Level
return; return;
} }
for (IntPair chunk : toSend) { for (IntPair chunk : toSend) {
PaperweightPlatformAdapter.sendChunk(getLevel().getWorld().getHandle(), chunk.x, chunk.z, false); PaperweightPlatformAdapter.sendChunk(getLevel().getWorld().getHandle(), chunk.x(), chunk.z(), false);
} }
} }
}; };
@ -262,7 +262,7 @@ public class PaperweightFaweWorldNativeAccess implements WorldNativeAccess<Level
sideEffectSet != null && sideEffectSet.shouldApply(SideEffect.UPDATE) sideEffectSet != null && sideEffectSet.shouldApply(SideEffect.UPDATE)
)); ));
for (IntPair chunk : cachedChunksToSend) { for (IntPair chunk : cachedChunksToSend) {
PaperweightPlatformAdapter.sendChunk(getLevel().getWorld().getHandle(), chunk.x, chunk.z, false); PaperweightPlatformAdapter.sendChunk(getLevel().getWorld().getHandle(), chunk.x(), chunk.z(), false);
} }
} }
}; };
@ -275,21 +275,11 @@ public class PaperweightFaweWorldNativeAccess implements WorldNativeAccess<Level
cachedChunksToSend.clear(); cachedChunksToSend.clear();
} }
private static final class CachedChange { private record CachedChange(
private final LevelChunk levelChunk;
private final BlockPos blockPos;
private final net.minecraft.world.level.block.state.BlockState blockState;
private CachedChange(
LevelChunk levelChunk, LevelChunk levelChunk,
BlockPos blockPos, BlockPos blockPos,
net.minecraft.world.level.block.state.BlockState blockState net.minecraft.world.level.block.state.BlockState blockState
) { ) {
this.levelChunk = levelChunk;
this.blockPos = blockPos;
this.blockState = blockState;
}
} }

Datei anzeigen

@ -1,4 +1,4 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R1; package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R2;
import com.fastasyncworldedit.bukkit.adapter.BukkitGetBlocks; import com.fastasyncworldedit.bukkit.adapter.BukkitGetBlocks;
import com.fastasyncworldedit.bukkit.adapter.DelegateSemaphore; import com.fastasyncworldedit.bukkit.adapter.DelegateSemaphore;
@ -11,6 +11,7 @@ import com.fastasyncworldedit.core.queue.IChunkGet;
import com.fastasyncworldedit.core.queue.IChunkSet; import com.fastasyncworldedit.core.queue.IChunkSet;
import com.fastasyncworldedit.core.queue.implementation.QueueHandler; import com.fastasyncworldedit.core.queue.implementation.QueueHandler;
import com.fastasyncworldedit.core.queue.implementation.blocks.CharGetBlocks; import com.fastasyncworldedit.core.queue.implementation.blocks.CharGetBlocks;
import com.fastasyncworldedit.core.util.MathMan;
import com.fastasyncworldedit.core.util.collection.AdaptedMap; import com.fastasyncworldedit.core.util.collection.AdaptedMap;
import com.google.common.base.Suppliers; import com.google.common.base.Suppliers;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
@ -20,18 +21,21 @@ import com.sk89q.jnbt.StringTag;
import com.sk89q.jnbt.Tag; import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.bukkit.WorldEditPlugin; import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R1.nbt.PaperweightLazyCompoundTag; import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R2.nbt.PaperweightLazyCompoundTag;
import com.sk89q.worldedit.internal.Constants; import com.sk89q.worldedit.internal.Constants;
import com.sk89q.worldedit.internal.util.LogManagerCompat; import com.sk89q.worldedit.internal.util.LogManagerCompat;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes;
import com.sk89q.worldedit.world.block.BlockTypesCache;
import io.papermc.lib.PaperLib; import io.papermc.lib.PaperLib;
import io.papermc.paper.event.block.BeaconDeactivatedEvent; import io.papermc.paper.event.block.BeaconDeactivatedEvent;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.IdMap;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.core.SectionPos; import net.minecraft.core.SectionPos;
import net.minecraft.nbt.IntTag; import net.minecraft.nbt.IntTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerLevel;
import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundEvents;
import net.minecraft.util.BitStorage; import net.minecraft.util.BitStorage;
@ -40,7 +44,6 @@ import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.EntityType;
import net.minecraft.world.level.LightLayer; import net.minecraft.world.level.LightLayer;
import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.Biomes;
import net.minecraft.world.level.block.entity.BeaconBlockEntity; import net.minecraft.world.level.block.entity.BeaconBlockEntity;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
@ -55,17 +58,18 @@ import net.minecraft.world.level.levelgen.Heightmap;
import net.minecraft.world.level.lighting.LevelLightEngine; import net.minecraft.world.level.lighting.LevelLightEngine;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.craftbukkit.v1_18_R1.CraftWorld; import org.bukkit.craftbukkit.v1_18_R2.CraftWorld;
import org.bukkit.craftbukkit.v1_18_R1.block.CraftBlock; import org.bukkit.craftbukkit.v1_18_R2.block.CraftBlock;
import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.CreatureSpawnEvent;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.AbstractSet; import java.util.AbstractSet;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -73,6 +77,7 @@ import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Function; import java.util.function.Function;
@ -98,6 +103,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
private final int minSectionPosition; private final int minSectionPosition;
private final int maxSectionPosition; private final int maxSectionPosition;
private final Registry<Biome> biomeRegistry; private final Registry<Biome> biomeRegistry;
private final IdMap<Holder<Biome>> biomeHolderIdMap;
private LevelChunkSection[] sections; private LevelChunkSection[] sections;
private LevelChunk levelChunk; private LevelChunk levelChunk;
private DataLayer[] blockLight; private DataLayer[] blockLight;
@ -123,6 +129,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
this.skyLight = new DataLayer[getSectionCount()]; this.skyLight = new DataLayer[getSectionCount()];
this.blockLight = new DataLayer[getSectionCount()]; this.blockLight = new DataLayer[getSectionCount()];
this.biomeRegistry = serverLevel.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY); this.biomeRegistry = serverLevel.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY);
this.biomeHolderIdMap = biomeRegistry.asHolderIdMap();
} }
public int getChunkX() { public int getChunkX() {
@ -174,7 +181,8 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
@Override @Override
public void setHeightmapToGet(HeightMapType type, int[] data) { public void setHeightmapToGet(HeightMapType type, int[] data) {
BitArrayUnstretched bitArray = new BitArrayUnstretched(9, 256); // height + 1 to match server internal
BitArrayUnstretched bitArray = new BitArrayUnstretched(MathMan.log2nlz(getChunk().getHeight() + 1), 256);
bitArray.fromRaw(data); bitArray.fromRaw(data);
Heightmap.Types nativeType = Heightmap.Types.valueOf(type.name()); Heightmap.Types nativeType = Heightmap.Types.valueOf(type.name());
Heightmap heightMap = getChunk().heightmaps.get(nativeType); Heightmap heightMap = getChunk().heightmaps.get(nativeType);
@ -194,7 +202,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
@Override @Override
public BiomeType getBiomeType(int x, int y, int z) { public BiomeType getBiomeType(int x, int y, int z) {
LevelChunkSection section = getSections(false)[(y >> 4) - getMinSectionPosition()]; LevelChunkSection section = getSections(false)[(y >> 4) - getMinSectionPosition()];
Biome biomes = section.getNoiseBiome(x >> 2, (y & 15) >> 2, z >> 2); Holder<Biome> biomes = section.getNoiseBiome(x >> 2, (y & 15) >> 2, z >> 2);
return PaperweightPlatformAdapter.adapt(biomes, serverLevel); return PaperweightPlatformAdapter.adapt(biomes, serverLevel);
} }
@ -228,7 +236,6 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} }
@Override @Override
//TODO 1.18 be CBT?
public CompoundTag getTile(int x, int y, int z) { public CompoundTag getTile(int x, int y, int z) {
BlockEntity blockEntity = getChunk().getBlockEntity(new BlockPos((x & 15) + ( BlockEntity blockEntity = getChunk().getBlockEntity(new BlockPos((x & 15) + (
chunkX << 4), y, (z & 15) + ( chunkX << 4), y, (z & 15) + (
@ -313,17 +320,11 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
Entity entity = serverLevel.getEntity(uuid); Entity entity = serverLevel.getEntity(uuid);
if (entity != null) { if (entity != null) {
org.bukkit.entity.Entity bukkitEnt = entity.getBukkitEntity(); org.bukkit.entity.Entity bukkitEnt = entity.getBukkitEntity();
//TODO 1.18 CBT & #getNbt?
return BukkitAdapter.adapt(bukkitEnt).getState().getNbtData(); return BukkitAdapter.adapt(bukkitEnt).getState().getNbtData();
} }
for (List<Entity> entry : /*getChunk().getEntitySlices()*/ new List[0]) { for (CompoundTag tag : getEntities()) {
if (entry != null) { if (uuid.equals(tag.getUUID())) {
for (Entity ent : entry) { return tag;
if (uuid.equals(ent.getUUID())) {
org.bukkit.entity.Entity bukkitEnt = ent.getBukkitEntity();
return BukkitAdapter.adapt(bukkitEnt).getState().getNbtData();
}
}
} }
} }
return null; return null;
@ -331,21 +332,15 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
@Override @Override
public Set<CompoundTag> getEntities() { public Set<CompoundTag> getEntities() {
List<Entity>[] slices = /*getChunk().getEntitySlices()*/ new List[0]; List<Entity> entities = PaperweightPlatformAdapter.getEntities(getChunk());
int size = 0; if (entities.isEmpty()) {
for (List<Entity> slice : slices) {
if (slice != null) {
size += slice.size();
}
}
if (slices.length == 0) {
return Collections.emptySet(); return Collections.emptySet();
} }
int finalSize = size; int size = entities.size();
return new AbstractSet<CompoundTag>() { return new AbstractSet<>() {
@Override @Override
public int size() { public int size() {
return finalSize; return size;
} }
@Override @Override
@ -358,28 +353,23 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
if (!(get instanceof CompoundTag getTag)) { if (!(get instanceof CompoundTag getTag)) {
return false; return false;
} }
Map<String, Tag> value = getTag.getValue(); UUID getUUID = getTag.getUUID();
CompoundTag getParts = (CompoundTag) value.get("UUID"); for (Entity entity : entities) {
UUID getUUID = new UUID(getParts.getLong("Most"), getParts.getLong("Least"));
for (List<Entity> slice : slices) {
if (slice != null) {
for (Entity entity : slice) {
UUID uuid = entity.getUUID(); UUID uuid = entity.getUUID();
if (uuid.equals(getUUID)) { if (uuid.equals(getUUID)) {
return true; return true;
} }
} }
}
}
return false; return false;
} }
@NotNull @Nonnull
@Override @Override
public Iterator<CompoundTag> iterator() { public Iterator<CompoundTag> iterator() {
Iterable<CompoundTag> result = StreamSupport.stream(Iterables.concat(slices).spliterator(), false).map(input -> { Iterable<CompoundTag> result = entities.stream().map(input -> {
net.minecraft.nbt.CompoundTag tag = new net.minecraft.nbt.CompoundTag(); net.minecraft.nbt.CompoundTag tag = new net.minecraft.nbt.CompoundTag();
return (CompoundTag) adapter.toNative(input.saveWithoutId(tag)); input.save(tag);
return (CompoundTag) adapter.toNative(tag);
}).collect(Collectors.toList()); }).collect(Collectors.toList());
return result.iterator(); return result.iterator();
} }
@ -395,13 +385,13 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} }
@Override @Override
@SuppressWarnings("rawtypes")
public synchronized <T extends Future<T>> T call(IChunkSet set, Runnable finalizer) { public synchronized <T extends Future<T>> T call(IChunkSet set, Runnable finalizer) {
forceLoadSections = false; forceLoadSections = false;
copy = createCopy ? new PaperweightGetBlocks_Copy(serverLevel) : null; copy = createCopy ? new PaperweightGetBlocks_Copy(levelChunk) : null;
try { try {
ServerLevel nmsWorld = serverLevel; ServerLevel nmsWorld = serverLevel;
LevelChunk nmsChunk = ensureLoaded(nmsWorld, chunkX, chunkZ); LevelChunk nmsChunk = ensureLoaded(nmsWorld, chunkX, chunkZ);
boolean fastmode = set.isFastMode() && Settings.settings().QUEUE.NO_TICK_FASTMODE;
// Remove existing tiles. Create a copy so that we can remove blocks // Remove existing tiles. Create a copy so that we can remove blocks
Map<BlockPos, BlockEntity> chunkTiles = new HashMap<>(nmsChunk.getBlockEntities()); Map<BlockPos, BlockEntity> chunkTiles = new HashMap<>(nmsChunk.getBlockEntities());
@ -418,7 +408,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} }
int ordinal = set.getBlock(lx, ly, lz).getOrdinal(); int ordinal = set.getBlock(lx, ly, lz).getOrdinal();
if (ordinal != 0) { if (ordinal != BlockTypesCache.ReservedIDs.__RESERVED__) {
BlockEntity tile = entry.getValue(); BlockEntity tile = entry.getValue();
if (PaperLib.isPaper() && tile instanceof BeaconBlockEntity) { if (PaperLib.isPaper() && tile instanceof BeaconBlockEntity) {
if (beacons == null) { if (beacons == null) {
@ -462,19 +452,23 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} }
if (existingSection == null) { if (existingSection == null) {
PalettedContainer<Biome> biomeData = PaperweightPlatformAdapter.getBiomePalettedContainer( PalettedContainer<Holder<Biome>> biomeData = PaperweightPlatformAdapter.getBiomePalettedContainer(
biomes[setSectionIndex], biomes[setSectionIndex],
biomeRegistry biomeHolderIdMap
); );
LevelChunkSection newSection = PaperweightPlatformAdapter.newChunkSection( LevelChunkSection newSection = PaperweightPlatformAdapter.newChunkSection(
layerNo, layerNo,
new char[4096], new char[4096],
fastmode,
adapter, adapter,
biomeRegistry, biomeRegistry,
biomeData biomeData
); );
if (PaperweightPlatformAdapter.setSectionAtomic(levelChunkSections, null, newSection, getSectionIndex)) { if (PaperweightPlatformAdapter.setSectionAtomic(
levelChunkSections,
null,
newSection,
getSectionIndex
)) {
updateGet(nmsChunk, levelChunkSections, newSection, new char[4096], getSectionIndex); updateGet(nmsChunk, levelChunkSections, newSection, new char[4096], getSectionIndex);
continue; continue;
} else { } else {
@ -487,7 +481,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} }
} }
} else { } else {
PalettedContainer<Biome> biomeData = existingSection.getBiomes(); PalettedContainer<Holder<Biome>> biomeData = existingSection.getBiomes();
setBiomesToPalettedContainer(biomes[setSectionIndex], biomeData); setBiomesToPalettedContainer(biomes[setSectionIndex], biomeData);
} }
} }
@ -497,9 +491,11 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
bitMask |= 1 << getSectionIndex; bitMask |= 1 << getSectionIndex;
// setArr is modified by PaperweightPlatformAdapter#newChunkSection. This is in order to write changes to
// this chunk GET when #updateGet is called. Future dords, please listen this time.
char[] tmp = set.load(layerNo); char[] tmp = set.load(layerNo);
char[] setArr = new char[4096]; char[] setArr = new char[tmp.length];
System.arraycopy(tmp, 0, setArr, 0, 4096); System.arraycopy(tmp, 0, setArr, 0, tmp.length);
// synchronise on internal section to avoid circular locking with a continuing edit if the chunk was // synchronise on internal section to avoid circular locking with a continuing edit if the chunk was
// submitted to keep loaded internal chunks to queue target size. // submitted to keep loaded internal chunks to queue target size.
@ -507,6 +503,13 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
LevelChunkSection newSection; LevelChunkSection newSection;
LevelChunkSection existingSection = levelChunkSections[getSectionIndex]; LevelChunkSection existingSection = levelChunkSections[getSectionIndex];
// Don't attempt to tick section whilst we're editing
if (existingSection != null) {
PaperweightPlatformAdapter.clearCounts(existingSection);
if (PaperLib.isPaper()) {
existingSection.tickingList.clear();
}
}
if (createCopy) { if (createCopy) {
char[] tmpLoad = loadPrivately(layerNo); char[] tmpLoad = loadPrivately(layerNo);
@ -519,21 +522,29 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} }
if (existingSection == null) { if (existingSection == null) {
PalettedContainer<Biome> biomeData = biomes == null ? new PalettedContainer<>( PalettedContainer<Holder<Biome>> biomeData = biomes == null ? new PalettedContainer<>(
biomeRegistry, biomeHolderIdMap,
biomeRegistry.getOrThrow(Biomes.PLAINS), biomeHolderIdMap.byIdOrThrow(WorldEditPlugin
.getInstance()
.getBukkitImplAdapter()
.getInternalBiomeId(
BiomeTypes.PLAINS)),
PalettedContainer.Strategy.SECTION_BIOMES, PalettedContainer.Strategy.SECTION_BIOMES,
null null
) : PaperweightPlatformAdapter.getBiomePalettedContainer(biomes[setSectionIndex], biomeRegistry); ) : PaperweightPlatformAdapter.getBiomePalettedContainer(biomes[setSectionIndex], biomeHolderIdMap);
newSection = PaperweightPlatformAdapter.newChunkSection( newSection = PaperweightPlatformAdapter.newChunkSection(
layerNo, layerNo,
setArr, setArr,
fastmode,
adapter, adapter,
biomeRegistry, biomeRegistry,
biomeData biomeData
); );
if (PaperweightPlatformAdapter.setSectionAtomic(levelChunkSections, null, newSection, getSectionIndex)) { if (PaperweightPlatformAdapter.setSectionAtomic(
levelChunkSections,
null,
newSection,
getSectionIndex
)) {
updateGet(nmsChunk, levelChunkSections, newSection, setArr, getSectionIndex); updateGet(nmsChunk, levelChunkSections, newSection, setArr, getSectionIndex);
continue; continue;
} else { } else {
@ -546,13 +557,18 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} }
} }
} }
PaperweightPlatformAdapter.fieldTickingBlockCount.set(existingSection, (short) 0);
//ensure that the server doesn't try to tick the chunksection while we're editing it. //ensure that the server doesn't try to tick the chunksection while we're editing it. (Again)
PaperweightPlatformAdapter.clearCounts(existingSection);
if (PaperLib.isPaper()) {
existingSection.tickingList.clear();
}
DelegateSemaphore lock = PaperweightPlatformAdapter.applyLock(existingSection); DelegateSemaphore lock = PaperweightPlatformAdapter.applyLock(existingSection);
// Synchronize to prevent further acquisitions
synchronized (lock) { synchronized (lock) {
// lock.acquire(); lock.acquire(); // Wait until we have the lock
lock.release();
try { try {
sectionLock.writeLock().lock(); sectionLock.writeLock().lock();
if (this.getChunk() != nmsChunk) { if (this.getChunk() != nmsChunk) {
@ -562,7 +578,10 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} else if (existingSection != getSections(false)[getSectionIndex]) { } else if (existingSection != getSections(false)[getSectionIndex]) {
this.sections[getSectionIndex] = existingSection; this.sections[getSectionIndex] = existingSection;
this.reset(); this.reset();
} else if (!Arrays.equals(update(getSectionIndex, new char[4096], true), loadPrivately(layerNo))) { } else if (!Arrays.equals(
update(getSectionIndex, new char[4096], true),
loadPrivately(layerNo)
)) {
this.reset(layerNo); this.reset(layerNo);
/*} else if (lock.isModified()) { /*} else if (lock.isModified()) {
this.reset(layerNo);*/ this.reset(layerNo);*/
@ -571,7 +590,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
sectionLock.writeLock().unlock(); sectionLock.writeLock().unlock();
} }
PalettedContainer<Biome> biomeData = existingSection.getBiomes(); PalettedContainer<Holder<Biome>> biomeData = existingSection.getBiomes();
if (biomes != null && biomes[setSectionIndex] != null) { if (biomes != null && biomes[setSectionIndex] != null) {
setBiomesToPalettedContainer(biomes[setSectionIndex], biomeData); setBiomesToPalettedContainer(biomes[setSectionIndex], biomeData);
@ -582,7 +601,6 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
layerNo, layerNo,
this::loadPrivately, this::loadPrivately,
setArr, setArr,
fastmode,
adapter, adapter,
biomeRegistry, biomeRegistry,
biomeData biomeData
@ -645,23 +663,31 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} }
syncTasks[2] = () -> { syncTasks[2] = () -> {
final List<Entity>[] entities = /*nmsChunk.e()*/ new List[0]; Set<UUID> entitiesRemoved = new HashSet<>();
final List<Entity> entities = PaperweightPlatformAdapter.getEntities(nmsChunk);
for (final Collection<Entity> ents : entities) { for (Entity entity : entities) {
if (!ents.isEmpty()) { UUID uuid = entity.getUUID();
final Iterator<Entity> iter = ents.iterator(); if (entityRemoves.contains(uuid)) {
while (iter.hasNext()) {
final Entity entity = iter.next();
if (entityRemoves.contains(entity.getUUID())) {
if (createCopy) { if (createCopy) {
copy.storeEntity(entity); copy.storeEntity(entity);
} }
iter.remove(); removeEntity(entity);
entitiesRemoved.add(uuid);
entityRemoves.remove(uuid);
}
}
if (Settings.settings().EXPERIMENTAL.REMOVE_ENTITY_FROM_WORLD_ON_CHUNK_FAIL) {
for (UUID uuid : entityRemoves) {
Entity entity = nmsWorld.entityManager.getEntityGetter().get(uuid);
if (entity != null) {
removeEntity(entity); removeEntity(entity);
} }
} }
} }
} // Only save entities that were actually removed to history
set.getEntityRemoves().clear();
set.getEntityRemoves().addAll(entitiesRemoved);
}; };
} }
@ -672,8 +698,9 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} }
syncTasks[1] = () -> { syncTasks[1] = () -> {
//TODO 1.18 be a CBT & ListBinaryTag ? Iterator<CompoundTag> iterator = entities.iterator();
for (final CompoundTag nativeTag : entities) { while (iterator.hasNext()) {
final CompoundTag nativeTag = iterator.next();
final Map<String, Tag> entityTagMap = nativeTag.getValue(); final Map<String, Tag> entityTagMap = nativeTag.getValue();
final StringTag idTag = (StringTag) entityTagMap.get("Id"); final StringTag idTag = (StringTag) entityTagMap.get("Id");
final ListTag posTag = (ListTag) entityTagMap.get("Pos"); final ListTag posTag = (ListTag) entityTagMap.get("Pos");
@ -700,12 +727,23 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} }
entity.load(tag); entity.load(tag);
entity.absMoveTo(x, y, z, yaw, pitch); entity.absMoveTo(x, y, z, yaw, pitch);
nmsWorld.addFreshEntity(entity, CreatureSpawnEvent.SpawnReason.CUSTOM); entity.setUUID(nativeTag.getUUID());
if (!nmsWorld.addFreshEntity(entity, CreatureSpawnEvent.SpawnReason.CUSTOM)) {
LOGGER.warn(
"Error creating entity of type `{}` in world `{}` at location `{},{},{}`",
id,
nmsWorld.getWorld().getName(),
x,
y,
z
);
// Unsuccessful create should not be saved to history
iterator.remove();
}
} }
} }
} }
}; };
} }
// set tiles // set tiles
@ -768,7 +806,6 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
Runnable[] finalSyncTasks = syncTasks; Runnable[] finalSyncTasks = syncTasks;
// Chain the sync tasks and the callback // Chain the sync tasks and the callback
//TODO 1.18 address raw access
Callable<Future> chain = () -> { Callable<Future> chain = () -> {
try { try {
// Run the sync tasks // Run the sync tasks
@ -790,6 +827,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
throw e; throw e;
} }
}; };
//noinspection unchecked - required at compile time
return (T) (Future) queueHandler.sync(chain); return (T) (Future) queueHandler.sync(chain);
} else { } else {
if (callback == null) { if (callback == null) {
@ -869,29 +907,30 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
* @return the given array to be filled with data, or a new array if null is given. * @return the given array to be filled with data, or a new array if null is given.
*/ */
@Override @Override
@SuppressWarnings("unchecked")
public char[] update(int layer, char[] data, boolean aggressive) { public char[] update(int layer, char[] data, boolean aggressive) {
LevelChunkSection section = getSections(aggressive)[layer]; LevelChunkSection section = getSections(aggressive)[layer];
// Section is null, return empty array // Section is null, return empty array
if (section == null) { if (section == null) {
data = new char[4096]; data = new char[4096];
Arrays.fill(data, (char) 1); Arrays.fill(data, (char) BlockTypesCache.ReservedIDs.AIR);
return data; return data;
} }
if (data != null && data.length != 4096) { if (data != null && data.length != 4096) {
data = new char[4096]; data = new char[4096];
Arrays.fill(data, (char) 1); Arrays.fill(data, (char) BlockTypesCache.ReservedIDs.AIR);
} }
if (data == null || data == FaweCache.INSTANCE.EMPTY_CHAR_4096) { if (data == null || data == FaweCache.INSTANCE.EMPTY_CHAR_4096) {
data = new char[4096]; data = new char[4096];
Arrays.fill(data, (char) 1); Arrays.fill(data, (char) BlockTypesCache.ReservedIDs.AIR);
} }
DelegateSemaphore lock = PaperweightPlatformAdapter.applyLock(section); Semaphore lock = PaperweightPlatformAdapter.applyLock(section);
synchronized (lock) { synchronized (lock) {
// Efficiently convert ChunkSection to raw data // Efficiently convert ChunkSection to raw data
try { try {
lock.acquire(); lock.acquire();
final PalettedContainer<net.minecraft.world.level.block.state.BlockState> blocks = section.getStates(); final PalettedContainer<BlockState> blocks = section.getStates();
final Object dataObject = PaperweightPlatformAdapter.fieldData.get(blocks); final Object dataObject = PaperweightPlatformAdapter.fieldData.get(blocks);
final BitStorage bits = (BitStorage) PaperweightPlatformAdapter.fieldStorage.get(dataObject); final BitStorage bits = (BitStorage) PaperweightPlatformAdapter.fieldStorage.get(dataObject);
@ -915,8 +954,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
for (int i = 0; i < 4096; i++) { for (int i = 0; i < 4096; i++) {
char paletteVal = data[i]; char paletteVal = data[i];
char ordinal = adapter.ibdIDToOrdinal(paletteVal); char ordinal = adapter.ibdIDToOrdinal(paletteVal);
// Don't read "empty". data[i] = ordinal;
data[i] = ordinal == 0 ? 1 : ordinal;
} }
return data; return data;
} }
@ -935,18 +973,10 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
val = ordinal(palette.valueFor(i), adapter); val = ordinal(palette.valueFor(i), adapter);
paletteToOrdinal[i] = val; paletteToOrdinal[i] = val;
} }
// Don't read "empty".
if (val == 0) {
val = 1;
}
data[i] = val; data[i] = val;
} }
} else { } else {
char ordinal = ordinal(palette.valueFor(0), adapter); char ordinal = ordinal(palette.valueFor(0), adapter);
// Don't read "empty".
if (ordinal == 0) {
ordinal = 1;
}
Arrays.fill(data, ordinal); Arrays.fill(data, ordinal);
} }
} finally { } finally {
@ -964,9 +994,9 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} }
} }
private char ordinal(net.minecraft.world.level.block.state.BlockState ibd, PaperweightFaweAdapter adapter) { private char ordinal(BlockState ibd, PaperweightFaweAdapter adapter) {
if (ibd == null) { if (ibd == null) {
return 1; return BlockTypesCache.ReservedIDs.AIR;
} else { } else {
return adapter.adaptToChar(ibd); return adapter.adaptToChar(ibd);
} }
@ -1043,7 +1073,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
private void setBiomesToPalettedContainer( private void setBiomesToPalettedContainer(
final BiomeType[] biomes, final BiomeType[] biomes,
PalettedContainer<Biome> data PalettedContainer<Holder<Biome>> data
) { ) {
int index = 0; int index = 0;
if (biomes == null) { if (biomes == null) {
@ -1060,7 +1090,10 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
x, x,
y, y,
z, z,
biomeRegistry.get(ResourceLocation.tryParse(biomeType.getId())) biomeHolderIdMap.byIdOrThrow(WorldEditPlugin
.getInstance()
.getBukkitImplAdapter()
.getInternalBiomeId(biomeType))
); );
} }
} }
@ -1074,6 +1107,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} }
@Override @Override
@SuppressWarnings("unchecked")
public synchronized boolean trim(boolean aggressive) { public synchronized boolean trim(boolean aggressive) {
skyLight = new DataLayer[getSectionCount()]; skyLight = new DataLayer[getSectionCount()];
blockLight = new DataLayer[getSectionCount()]; blockLight = new DataLayer[getSectionCount()];
@ -1094,10 +1128,9 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
} }
LevelChunkSection existing = getSections(true)[layer]; LevelChunkSection existing = getSections(true)[layer];
try { try {
final PalettedContainer<net.minecraft.world.level.block.state.BlockState> blocksExisting = existing.getStates(); final PalettedContainer<BlockState> blocksExisting = existing.getStates();
final Object dataObject = PaperweightPlatformAdapter.fieldData.get(blocksExisting); final Object dataObject = PaperweightPlatformAdapter.fieldData.get(blocksExisting);
//TODO this field doesn't exist in 1.18
final Palette<BlockState> palette = (Palette<BlockState>) PaperweightPlatformAdapter.fieldPalette.get( final Palette<BlockState> palette = (Palette<BlockState>) PaperweightPlatformAdapter.fieldPalette.get(
dataObject); dataObject);
int paletteSize; int paletteSize;

Datei anzeigen

@ -1,4 +1,4 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R1; package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R2;
import com.fastasyncworldedit.core.extent.processor.heightmap.HeightMapType; import com.fastasyncworldedit.core.extent.processor.heightmap.HeightMapType;
import com.fastasyncworldedit.core.queue.IBlocks; import com.fastasyncworldedit.core.queue.IBlocks;
@ -8,16 +8,19 @@ import com.google.common.base.Suppliers;
import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.bukkit.WorldEditPlugin; import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter; import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter;
import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R1.nbt.PaperweightLazyCompoundTag; import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R2.nbt.PaperweightLazyCompoundTag;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes;
import com.sk89q.worldedit.world.block.BaseBlock; import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypesCache; import com.sk89q.worldedit.world.block.BlockTypesCache;
import net.minecraft.core.Holder;
import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.PalettedContainer; import net.minecraft.world.level.chunk.PalettedContainer;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -35,13 +38,15 @@ public class PaperweightGetBlocks_Copy implements IChunkGet {
private final char[][] blocks; private final char[][] blocks;
private final int minHeight; private final int minHeight;
private final int maxHeight; private final int maxHeight;
private final ServerLevel serverLevel; final ServerLevel serverLevel;
private PalettedContainer<Biome>[] biomes = null; final LevelChunk levelChunk;
private PalettedContainer<Holder<Biome>>[] biomes = null;
protected PaperweightGetBlocks_Copy(ServerLevel world) { protected PaperweightGetBlocks_Copy(LevelChunk levelChunk) {
this.serverLevel = world; this.levelChunk = levelChunk;
this.minHeight = world.getMinBuildHeight(); this.serverLevel = levelChunk.level;
this.maxHeight = world.getMaxBuildHeight() - 1; // Minecraft max limit is exclusive. this.minHeight = serverLevel.getMinBuildHeight();
this.maxHeight = serverLevel.getMaxBuildHeight() - 1; // Minecraft max limit is exclusive.
this.blocks = new char[getSectionCount()][]; this.blocks = new char[getSectionCount()][];
} }
@ -67,11 +72,12 @@ public class PaperweightGetBlocks_Copy implements IChunkGet {
return tiles.get(BlockVector3.at(x, y, z)); return tiles.get(BlockVector3.at(x, y, z));
} }
@SuppressWarnings({"unchecked", "rawtypes"})
protected void storeEntity(Entity entity) { protected void storeEntity(Entity entity) {
//TODO 1.18 address raw access & possibly be a CBT ?
BukkitImplAdapter adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter(); BukkitImplAdapter adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter();
net.minecraft.nbt.CompoundTag compoundTag = new net.minecraft.nbt.CompoundTag(); net.minecraft.nbt.CompoundTag compoundTag = new net.minecraft.nbt.CompoundTag();
entities.add((CompoundTag) adapter.toNative(entity.save(compoundTag))); entity.save(compoundTag);
entities.add((CompoundTag) adapter.toNative(compoundTag));
} }
@Override @Override
@ -82,18 +88,7 @@ public class PaperweightGetBlocks_Copy implements IChunkGet {
@Override @Override
public CompoundTag getEntity(UUID uuid) { public CompoundTag getEntity(UUID uuid) {
for (CompoundTag tag : entities) { for (CompoundTag tag : entities) {
UUID tagUUID; if (uuid.equals(tag.getUUID())) {
if (tag.containsKey("UUID")) {
int[] arr = tag.getIntArray("UUID");
tagUUID = new UUID((long) arr[0] << 32 | (arr[1] & 0xFFFFFFFFL), (long) arr[2] << 32 | (arr[3] & 0xFFFFFFFFL));
} else if (tag.containsKey("UUIDMost")) {
tagUUID = new UUID(tag.getLong("UUIDMost"), tag.getLong("UUIDLeast"));
} else if (tag.containsKey("PersistentIDMSB")) {
tagUUID = new UUID(tag.getLong("PersistentIDMSB"), tag.getLong("PersistentIDLSB"));
} else {
return null;
}
if (uuid.equals(tagUUID)) {
return tag; return tag;
} }
} }
@ -143,8 +138,8 @@ public class PaperweightGetBlocks_Copy implements IChunkGet {
@Override @Override
public BiomeType getBiomeType(int x, int y, int z) { public BiomeType getBiomeType(int x, int y, int z) {
Biome biome = biomes[(y >> 4) - getMinSectionPosition()].get(x >> 2, (y & 15) >> 2, z >> 2); Holder<Biome> biome = biomes[(y >> 4) - getMinSectionPosition()].get(x >> 2, (y & 15) >> 2, z >> 2);
return biome != null ? PaperweightPlatformAdapter.adapt(biome, serverLevel) : null; return PaperweightPlatformAdapter.adapt(biome, serverLevel);
} }
@Override @Override
@ -170,7 +165,7 @@ public class PaperweightGetBlocks_Copy implements IChunkGet {
blocks[layer] = data; blocks[layer] = data;
} }
protected void storeBiomes(int layer, PalettedContainer<Biome> biomeData) { protected void storeBiomes(int layer, PalettedContainer<Holder<Biome>> biomeData) {
if (biomes == null) { if (biomes == null) {
biomes = new PalettedContainer[getSectionCount()]; biomes = new PalettedContainer[getSectionCount()];
} }

Datei anzeigen

@ -0,0 +1,34 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R2;
import com.fastasyncworldedit.bukkit.adapter.MapChunkUtil;
import com.sk89q.worldedit.bukkit.adapter.Refraction;
import net.minecraft.network.protocol.game.ClientboundLevelChunkPacketData;
import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket;
//TODO un-very-break-this
public class PaperweightMapChunkUtil extends MapChunkUtil<ClientboundLevelChunkWithLightPacket> {
public PaperweightMapChunkUtil() throws NoSuchFieldException {
fieldX = ClientboundLevelChunkPacketData.class.getDeclaredField(Refraction.pickName("TWO_MEGABYTES", "a"));
fieldZ = ClientboundLevelChunkWithLightPacket.class.getDeclaredField(Refraction.pickName("x", "a"));
fieldBitMask = ClientboundLevelChunkWithLightPacket.class.getDeclaredField(Refraction.pickName("z", "b"));
fieldHeightMap = ClientboundLevelChunkPacketData.class.getDeclaredField(Refraction.pickName("heightmaps", "b"));
fieldChunkData = ClientboundLevelChunkWithLightPacket.class.getDeclaredField(Refraction.pickName("chunkData", "c"));
fieldBlockEntities = ClientboundLevelChunkPacketData.class.getDeclaredField(Refraction.pickName("buffer", "c"));
fieldFull = ClientboundLevelChunkPacketData.class.getDeclaredField(Refraction.pickName("blockEntitiesData", "d"));
fieldX.setAccessible(true);
fieldZ.setAccessible(true);
fieldBitMask.setAccessible(true);
fieldHeightMap.setAccessible(true);
fieldChunkData.setAccessible(true);
fieldBlockEntities.setAccessible(true);
fieldFull.setAccessible(true);
}
@Override
public ClientboundLevelChunkWithLightPacket createPacket() {
// TODO ??? return new ClientboundLevelChunkPacket();
throw new UnsupportedOperationException();
}
}

Datei anzeigen

@ -1,4 +1,4 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R1; package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R2;
import com.fastasyncworldedit.bukkit.adapter.CachedBukkitAdapter; import com.fastasyncworldedit.bukkit.adapter.CachedBukkitAdapter;
import com.fastasyncworldedit.bukkit.adapter.DelegateSemaphore; import com.fastasyncworldedit.bukkit.adapter.DelegateSemaphore;
@ -10,35 +10,36 @@ import com.fastasyncworldedit.core.util.MathMan;
import com.fastasyncworldedit.core.util.ReflectionUtils; import com.fastasyncworldedit.core.util.ReflectionUtils;
import com.fastasyncworldedit.core.util.TaskManager; import com.fastasyncworldedit.core.util.TaskManager;
import com.mojang.datafixers.util.Either; import com.mojang.datafixers.util.Either;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter;
import com.sk89q.worldedit.bukkit.adapter.Refraction; import com.sk89q.worldedit.bukkit.adapter.Refraction;
import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.internal.util.LogManagerCompat;
import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes; import com.sk89q.worldedit.world.biome.BiomeTypes;
import com.sk89q.worldedit.world.block.BlockState; import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypesCache; import com.sk89q.worldedit.world.block.BlockTypesCache;
import io.papermc.lib.PaperLib; import io.papermc.lib.PaperLib;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.IdMap; import net.minecraft.core.IdMap;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.core.SectionPos;
import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket; import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ChunkHolder; import net.minecraft.server.level.ChunkHolder;
import net.minecraft.server.level.ChunkMap; import net.minecraft.server.level.ChunkMap;
import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.level.TicketType;
import net.minecraft.util.BitStorage; import net.minecraft.util.BitStorage;
import net.minecraft.util.SimpleBitStorage; import net.minecraft.util.SimpleBitStorage;
import net.minecraft.util.ThreadingDetector; import net.minecraft.util.ThreadingDetector;
import net.minecraft.util.Unit;
import net.minecraft.util.ZeroBitStorage; import net.minecraft.util.ZeroBitStorage;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.Biomes;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.EntityBlock;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.chunk.GlobalPalette; import net.minecraft.world.level.chunk.GlobalPalette;
import net.minecraft.world.level.chunk.HashMapPalette; import net.minecraft.world.level.chunk.HashMapPalette;
@ -48,13 +49,13 @@ import net.minecraft.world.level.chunk.LinearPalette;
import net.minecraft.world.level.chunk.Palette; import net.minecraft.world.level.chunk.Palette;
import net.minecraft.world.level.chunk.PalettedContainer; import net.minecraft.world.level.chunk.PalettedContainer;
import net.minecraft.world.level.chunk.SingleValuePalette; import net.minecraft.world.level.chunk.SingleValuePalette;
import net.minecraft.world.level.gameevent.GameEventDispatcher; import org.apache.logging.log4j.Logger;
import net.minecraft.world.level.gameevent.GameEventListener; import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_18_R1.CraftChunk; import org.bukkit.craftbukkit.v1_18_R2.CraftChunk;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import sun.misc.Unsafe; import sun.misc.Unsafe;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
@ -68,11 +69,12 @@ import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Semaphore; import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Function; import java.util.function.Function;
public final class PaperweightPlatformAdapter extends NMSAdapter { public final class PaperweightPlatformAdapter extends NMSAdapter {
@ -84,10 +86,9 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
public static final Field fieldStorage; public static final Field fieldStorage;
public static final Field fieldPalette; public static final Field fieldPalette;
private static final Field fieldTickingFluidCount;
public static final Field fieldTickingFluidContent; private static final Field fieldTickingBlockCount;
public static final Field fieldTickingBlockCount; private static final Field fieldNonEmptyBlockCount;
public static final Field fieldNonEmptyBlockCount;
private static final MethodHandle methodGetVisibleChunk; private static final MethodHandle methodGetVisibleChunk;
@ -100,11 +101,13 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
private static final Field fieldLock; private static final Field fieldLock;
private static final long fieldLockOffset; private static final long fieldLockOffset;
private static final Field fieldGameEventDispatcherSections; private static final MethodHandle methodRemoveGameEventListener;
private static final MethodHandle methodremoveTickingBlockEntity; private static final MethodHandle methodremoveTickingBlockEntity;
private static final Field fieldRemove; private static final Field fieldRemove;
private static final Logger LOGGER = LogManagerCompat.getLogger();
static { static {
try { try {
fieldData = PalettedContainer.class.getDeclaredField(Refraction.pickName("data", "d")); fieldData = PalettedContainer.class.getDeclaredField(Refraction.pickName("data", "d"));
@ -114,14 +117,13 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
dataConstructor = dataClazz.getDeclaredConstructors()[0]; dataConstructor = dataClazz.getDeclaredConstructors()[0];
dataConstructor.setAccessible(true); dataConstructor.setAccessible(true);
//TODO FIXME 1.18
fieldStorage = dataClazz.getDeclaredField(Refraction.pickName("storage", "b")); fieldStorage = dataClazz.getDeclaredField(Refraction.pickName("storage", "b"));
fieldStorage.setAccessible(true); fieldStorage.setAccessible(true);
fieldPalette = dataClazz.getDeclaredField(Refraction.pickName("palette", "c")); fieldPalette = dataClazz.getDeclaredField(Refraction.pickName("palette", "c"));
fieldPalette.setAccessible(true); fieldPalette.setAccessible(true);
fieldTickingFluidContent = LevelChunkSection.class.getDeclaredField(Refraction.pickName("tickingFluidCount", "h")); fieldTickingFluidCount = LevelChunkSection.class.getDeclaredField(Refraction.pickName("tickingFluidCount", "h"));
fieldTickingFluidContent.setAccessible(true); fieldTickingFluidCount.setAccessible(true);
fieldTickingBlockCount = LevelChunkSection.class.getDeclaredField(Refraction.pickName("tickingBlockCount", "g")); fieldTickingBlockCount = LevelChunkSection.class.getDeclaredField(Refraction.pickName("tickingBlockCount", "g"));
fieldTickingBlockCount.setAccessible(true); fieldTickingBlockCount.setAccessible(true);
fieldNonEmptyBlockCount = LevelChunkSection.class.getDeclaredField(Refraction.pickName("nonEmptyBlockCount", "f")); fieldNonEmptyBlockCount = LevelChunkSection.class.getDeclaredField(Refraction.pickName("nonEmptyBlockCount", "f"));
@ -135,19 +137,31 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
methodGetVisibleChunk = MethodHandles.lookup().unreflect(getVisibleChunkIfPresent); methodGetVisibleChunk = MethodHandles.lookup().unreflect(getVisibleChunkIfPresent);
Unsafe unsafe = ReflectionUtils.getUnsafe(); Unsafe unsafe = ReflectionUtils.getUnsafe();
if (!PaperLib.isPaper()) {
fieldThreadingDetector = PalettedContainer.class.getDeclaredField(Refraction.pickName("threadingDetector", "f")); fieldThreadingDetector = PalettedContainer.class.getDeclaredField(Refraction.pickName("threadingDetector", "f"));
fieldThreadingDetectorOffset = unsafe.objectFieldOffset(fieldThreadingDetector); fieldThreadingDetectorOffset = unsafe.objectFieldOffset(fieldThreadingDetector);
fieldLock = ThreadingDetector.class.getDeclaredField(Refraction.pickName("lock", "c")); fieldLock = ThreadingDetector.class.getDeclaredField(Refraction.pickName("lock", "c"));
fieldLockOffset = unsafe.objectFieldOffset(fieldLock); fieldLockOffset = unsafe.objectFieldOffset(fieldLock);
} else {
// in paper, the used methods are synchronized properly
fieldThreadingDetector = null;
fieldThreadingDetectorOffset = -1;
fieldGameEventDispatcherSections = LevelChunk.class.getDeclaredField(Refraction.pickName( fieldLock = null;
"gameEventDispatcherSections", "t")); fieldLockOffset = -1;
fieldGameEventDispatcherSections.setAccessible(true); }
Method removeGameEventListener = LevelChunk.class.getDeclaredMethod(
Refraction.pickName("removeGameEventListener", "d"),
BlockEntity.class
);
removeGameEventListener.setAccessible(true);
methodRemoveGameEventListener = MethodHandles.lookup().unreflect(removeGameEventListener);
Method removeBlockEntityTicker = LevelChunk.class.getDeclaredMethod( Method removeBlockEntityTicker = LevelChunk.class.getDeclaredMethod(
Refraction.pickName( Refraction.pickName(
"removeBlockEntityTicker", "removeBlockEntityTicker",
"m" "l"
), BlockPos.class ), BlockPos.class
); );
removeBlockEntityTicker.setAccessible(true); removeBlockEntityTicker.setAccessible(true);
@ -183,17 +197,26 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
return false; return false;
} }
// There is no point in having a functional semaphore for paper servers.
private static final ThreadLocal<DelegateSemaphore> SEMAPHORE_THREAD_LOCAL =
ThreadLocal.withInitial(() -> new DelegateSemaphore(1, null));
static DelegateSemaphore applyLock(LevelChunkSection section) { static DelegateSemaphore applyLock(LevelChunkSection section) {
if (PaperLib.isPaper()) {
return SEMAPHORE_THREAD_LOCAL.get();
}
try { try {
synchronized (section) { synchronized (section) {
Unsafe unsafe = ReflectionUtils.getUnsafe(); Unsafe unsafe = ReflectionUtils.getUnsafe();
PalettedContainer<net.minecraft.world.level.block.state.BlockState> blocks = section.getStates(); PalettedContainer<net.minecraft.world.level.block.state.BlockState> blocks = section.getStates();
ThreadingDetector currentThreadingDetector = (ThreadingDetector) unsafe.getObject(blocks, ThreadingDetector currentThreadingDetector = (ThreadingDetector) unsafe.getObject(
fieldThreadingDetectorOffset) ; blocks,
fieldThreadingDetectorOffset
);
synchronized (currentThreadingDetector) { synchronized (currentThreadingDetector) {
Semaphore currentLock = (Semaphore) unsafe.getObject(currentThreadingDetector, fieldLockOffset); Semaphore currentLock = (Semaphore) unsafe.getObject(currentThreadingDetector, fieldLockOffset);
if (currentLock instanceof DelegateSemaphore) { if (currentLock instanceof DelegateSemaphore delegateSemaphore) {
return (DelegateSemaphore) currentLock; return delegateSemaphore;
} }
DelegateSemaphore newLock = new DelegateSemaphore(1, currentLock); DelegateSemaphore newLock = new DelegateSemaphore(1, currentLock);
unsafe.putObject(currentThreadingDetector, fieldLockOffset, newLock); unsafe.putObject(currentThreadingDetector, fieldLockOffset, newLock);
@ -218,10 +241,12 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
} else { } else {
LevelChunk nmsChunk = serverLevel.getChunkSource().getChunkAtIfCachedImmediately(chunkX, chunkZ); LevelChunk nmsChunk = serverLevel.getChunkSource().getChunkAtIfCachedImmediately(chunkX, chunkZ);
if (nmsChunk != null) { if (nmsChunk != null) {
addTicket(serverLevel, chunkX, chunkZ);
return nmsChunk; return nmsChunk;
} }
nmsChunk = serverLevel.getChunkSource().getChunkAtIfLoadedImmediately(chunkX, chunkZ); nmsChunk = serverLevel.getChunkSource().getChunkAtIfLoadedImmediately(chunkX, chunkZ);
if (nmsChunk != null) { if (nmsChunk != null) {
addTicket(serverLevel, chunkX, chunkZ);
return nmsChunk; return nmsChunk;
} }
// Avoid "async" methods from the main thread. // Avoid "async" methods from the main thread.
@ -230,7 +255,21 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
} }
CompletableFuture<org.bukkit.Chunk> future = serverLevel.getWorld().getChunkAtAsync(chunkX, chunkZ, true, true); CompletableFuture<org.bukkit.Chunk> future = serverLevel.getWorld().getChunkAtAsync(chunkX, chunkZ, true, true);
try { try {
CraftChunk chunk = (CraftChunk) future.get(); CraftChunk chunk;
try {
chunk = (CraftChunk) future.get(10, TimeUnit.SECONDS);
} catch (TimeoutException e) {
String world = serverLevel.getWorld().getName();
// We've already taken 10 seconds we can afford to wait a little here.
boolean loaded = TaskManager.taskManager().sync(() -> Bukkit.getWorld(world) != null);
if (loaded) {
LOGGER.warn("Chunk {},{} failed to load in 10 seconds in world {}. Retrying...", chunkX, chunkZ, world);
// Retry chunk load
chunk = (CraftChunk) serverLevel.getWorld().getChunkAtAsync(chunkX, chunkZ, true, true).get();
} else {
throw new UnsupportedOperationException("Cannot load chunk from unloaded world " + world + "!");
}
}
return chunk.getHandle(); return chunk.getHandle();
} catch (Throwable e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
@ -239,6 +278,13 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
return TaskManager.taskManager().sync(() -> serverLevel.getChunk(chunkX, chunkZ)); return TaskManager.taskManager().sync(() -> serverLevel.getChunk(chunkX, chunkZ));
} }
private static void addTicket(ServerLevel serverLevel, int chunkX, int chunkZ) {
// Ensure chunk is definitely loaded before applying a ticket
net.minecraft.server.MCUtil.MAIN_EXECUTOR.execute(() -> serverLevel
.getChunkSource()
.addRegionTicket(TicketType.PLUGIN, new ChunkPos(chunkX, chunkZ), 0, Unit.INSTANCE));
}
public static ChunkHolder getPlayerChunk(ServerLevel nmsWorld, final int chunkX, final int chunkZ) { public static ChunkHolder getPlayerChunk(ServerLevel nmsWorld, final int chunkX, final int chunkZ) {
ChunkMap chunkMap = nmsWorld.getChunkSource().chunkMap; ChunkMap chunkMap = nmsWorld.getChunkSource().chunkMap;
try { try {
@ -248,6 +294,7 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
} }
} }
@SuppressWarnings("deprecation")
public static void sendChunk(ServerLevel nmsWorld, int chunkX, int chunkZ, boolean lighting) { public static void sendChunk(ServerLevel nmsWorld, int chunkX, int chunkZ, boolean lighting) {
ChunkHolder chunkHolder = getPlayerChunk(nmsWorld, chunkX, chunkZ); ChunkHolder chunkHolder = getPlayerChunk(nmsWorld, chunkX, chunkZ);
if (chunkHolder == null) { if (chunkHolder == null) {
@ -280,8 +327,7 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
false // last false is to not bother with x-ray false // last false is to not bother with x-ray
); );
} else { } else {
// deprecated on paper // deprecated on paper - deprecation suppressed
//noinspection deprecation
packet = new ClientboundLevelChunkWithLightPacket( packet = new ClientboundLevelChunkWithLightPacket(
levelChunk, levelChunk,
nmsWorld.getChunkSource().getLightEngine(), nmsWorld.getChunkSource().getLightEngine(),
@ -302,17 +348,22 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
NMS conversion NMS conversion
*/ */
public static LevelChunkSection newChunkSection( public static LevelChunkSection newChunkSection(
final int layer, final char[] blocks, boolean fastmode, final int layer,
CachedBukkitAdapter adapter, Registry<Biome> biomeRegistry, final char[] blocks,
@Nullable PalettedContainer<Biome> biomes CachedBukkitAdapter adapter,
Registry<Biome> biomeRegistry,
@Nullable PalettedContainer<Holder<Biome>> biomes
) { ) {
return newChunkSection(layer, null, blocks, fastmode, adapter, biomeRegistry, biomes); return newChunkSection(layer, null, blocks, adapter, biomeRegistry, biomes);
} }
public static LevelChunkSection newChunkSection( public static LevelChunkSection newChunkSection(
final int layer, final Function<Integer, char[]> get, char[] set, final int layer,
boolean fastmode, CachedBukkitAdapter adapter, Registry<Biome> biomeRegistry, final Function<Integer, char[]> get,
@Nullable PalettedContainer<Biome> biomes char[] set,
CachedBukkitAdapter adapter,
Registry<Biome> biomeRegistry,
@Nullable PalettedContainer<Holder<Biome>> biomes
) { ) {
if (set == null) { if (set == null) {
return newChunkSection(layer, biomeRegistry, biomes); return newChunkSection(layer, biomeRegistry, biomes);
@ -322,24 +373,14 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
final long[] blockStates = FaweCache.INSTANCE.BLOCK_STATES.get(); final long[] blockStates = FaweCache.INSTANCE.BLOCK_STATES.get();
final int[] blocksCopy = FaweCache.INSTANCE.SECTION_BLOCKS.get(); final int[] blocksCopy = FaweCache.INSTANCE.SECTION_BLOCKS.get();
try { try {
int[] num_palette_buffer = new int[1]; int num_palette;
Map<BlockVector3, Integer> ticking_blocks = new HashMap<>();
int air;
if (get == null) { if (get == null) {
air = createPalette(blockToPalette, paletteToBlock, blocksCopy, num_palette_buffer, num_palette = createPalette(blockToPalette, paletteToBlock, blocksCopy, set, adapter, null);
set, ticking_blocks, fastmode, adapter
);
} else { } else {
air = createPalette(layer, blockToPalette, paletteToBlock, blocksCopy, num_palette = createPalette(layer, blockToPalette, paletteToBlock, blocksCopy, get, set, adapter, null);
num_palette_buffer, get, set, ticking_blocks, fastmode, adapter
);
} }
int num_palette = num_palette_buffer[0];
// BlockStates
int bitsPerEntry = MathMan.log2nlz(num_palette - 1); int bitsPerEntry = MathMan.log2nlz(num_palette - 1);
Object configuration =
PalettedContainer.Strategy.SECTION_STATES.getConfiguration(new FakeIdMapBlock(num_palette), bitsPerEntry);
if (bitsPerEntry > 0 && bitsPerEntry < 5) { if (bitsPerEntry > 0 && bitsPerEntry < 5) {
bitsPerEntry = 4; bitsPerEntry = 4;
} else if (bitsPerEntry > 8) { } else if (bitsPerEntry > 8) {
@ -366,7 +407,6 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
} else { } else {
nmsBits = new SimpleBitStorage(bitsPerEntry, 4096, bits); nmsBits = new SimpleBitStorage(bitsPerEntry, 4096, bits);
} }
final Palette<net.minecraft.world.level.block.state.BlockState> blockStatePalette;
List<net.minecraft.world.level.block.state.BlockState> palette; List<net.minecraft.world.level.block.state.BlockState> palette;
if (bitsPerEntry < 9) { if (bitsPerEntry < 9) {
palette = new ArrayList<>(); palette = new ArrayList<>();
@ -390,73 +430,68 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
nmsBits, nmsBits,
palette palette
); );
LevelChunkSection levelChunkSection;
try {
//fieldStorage.set(dataPaletteBlocks, nmsBits);
//fieldPalette.set(dataPaletteBlocks, blockStatePalettedContainer);
if (biomes == null) { if (biomes == null) {
IdMap<Holder<Biome>> biomeHolderIdMap = biomeRegistry.asHolderIdMap();
biomes = new PalettedContainer<>( biomes = new PalettedContainer<>(
biomeRegistry, biomeHolderIdMap,
biomeRegistry.getOrThrow(Biomes.PLAINS), biomeHolderIdMap.byIdOrThrow(WorldEditPlugin
.getInstance()
.getBukkitImplAdapter()
.getInternalBiomeId(
BiomeTypes.PLAINS)),
PalettedContainer.Strategy.SECTION_BIOMES, PalettedContainer.Strategy.SECTION_BIOMES,
null null
); );
} }
levelChunkSection = new LevelChunkSection(layer, blockStatePalettedContainer, biomes);
setCount(ticking_blocks.size(), 4096 - air, levelChunkSection);
if (!fastmode) {
ticking_blocks.forEach((pos, ordinal) -> levelChunkSection.setBlockState(
pos.getBlockX(),
pos.getBlockY(),
pos.getBlockZ(),
Block.stateById(ordinal)
));
}
} catch (final IllegalAccessException e) {
throw new RuntimeException(e);
}
return levelChunkSection; return new LevelChunkSection(layer, blockStatePalettedContainer, biomes);
} catch (final Throwable e) { } catch (final Throwable e) {
Arrays.fill(blockToPalette, Integer.MAX_VALUE);
throw e; throw e;
} finally {
Arrays.fill(blockToPalette, Integer.MAX_VALUE);
Arrays.fill(paletteToBlock, Integer.MAX_VALUE);
Arrays.fill(blockStates, 0);
Arrays.fill(blocksCopy, 0);
} }
} }
@SuppressWarnings("deprecation") // Only deprecated in paper
private static LevelChunkSection newChunkSection( private static LevelChunkSection newChunkSection(
int layer, Registry<Biome> biomeRegistry, int layer,
@Nullable PalettedContainer<Biome> biomes Registry<Biome> biomeRegistry,
@Nullable PalettedContainer<Holder<Biome>> biomes
) { ) {
if (biomes == null) {
return new LevelChunkSection(layer, biomeRegistry);
}
PalettedContainer<net.minecraft.world.level.block.state.BlockState> dataPaletteBlocks = new PalettedContainer<>( PalettedContainer<net.minecraft.world.level.block.state.BlockState> dataPaletteBlocks = new PalettedContainer<>(
Block.BLOCK_STATE_REGISTRY, Block.BLOCK_STATE_REGISTRY,
Blocks.AIR.defaultBlockState(), Blocks.AIR.defaultBlockState(),
PalettedContainer.Strategy.SECTION_STATES, PalettedContainer.Strategy.SECTION_STATES,
null null
); );
PalettedContainer<Biome> biomesPalette = biomes != null ? biomes : new PalettedContainer<>( return new LevelChunkSection(layer, dataPaletteBlocks, biomes);
biomeRegistry,
biomeRegistry.getOrThrow(Biomes.PLAINS),
PalettedContainer.Strategy.SECTION_BIOMES,
null
);
return new LevelChunkSection(layer, dataPaletteBlocks, biomesPalette);
} }
/** /**
* Create a new {@link PalettedContainer<Biome>}. Should only be used if no biome container existed beforehand. * Create a new {@link PalettedContainer<Biome>}. Should only be used if no biome container existed beforehand.
*/ */
public static PalettedContainer<Biome> getBiomePalettedContainer(BiomeType[] biomes, Registry<Biome> biomeRegistry) { public static PalettedContainer<Holder<Biome>> getBiomePalettedContainer(
BiomeType[] biomes,
IdMap<Holder<Biome>> biomeRegistry
) {
if (biomes == null) { if (biomes == null) {
return null; return null;
} }
BukkitImplAdapter<?> adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter();
// Don't stream this as typically will see 1-4 biomes; stream overhead is large for the small length // Don't stream this as typically will see 1-4 biomes; stream overhead is large for the small length
Map<BiomeType, Biome> palette = new HashMap<>(); Map<BiomeType, Holder<Biome>> palette = new HashMap<>();
for (BiomeType biomeType : new LinkedList<>(Arrays.asList(biomes))) { for (BiomeType biomeType : new LinkedList<>(Arrays.asList(biomes))) {
Biome biome; Holder<Biome> biome;
if (biomeType == null) { if (biomeType == null) {
biome = biomeRegistry.getOrThrow(Biomes.PLAINS); biome = biomeRegistry.byId(adapter.getInternalBiomeId(BiomeTypes.PLAINS));
} else { } else {
biome = biomeRegistry.get(ResourceLocation.tryParse(biomeType.getId())); biome = biomeRegistry.byId(adapter.getInternalBiomeId(biomeType));
} }
palette.put(biomeType, biome); palette.put(biomeType, biome);
} }
@ -469,14 +504,14 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
if (bitsPerEntry > 3) { if (bitsPerEntry > 3) {
bitsPerEntry = MathMan.log2nlz(biomeRegistry.size() - 1); bitsPerEntry = MathMan.log2nlz(biomeRegistry.size() - 1);
} }
PalettedContainer<Biome> biomePalettedContainer = new PalettedContainer<>( PalettedContainer<Holder<Biome>> biomePalettedContainer = new PalettedContainer<>(
biomeRegistry, biomeRegistry,
biomeRegistry.getOrThrow(Biomes.PLAINS), biomeRegistry.byIdOrThrow(adapter.getInternalBiomeId(BiomeTypes.PLAINS)),
PalettedContainer.Strategy.SECTION_BIOMES, PalettedContainer.Strategy.SECTION_BIOMES,
null null
); );
final Palette<Biome> biomePalette; final Palette<Holder<Biome>> biomePalette;
if (bitsPerEntry == 0) { if (bitsPerEntry == 0) {
biomePalette = new SingleValuePalette<>( biomePalette = new SingleValuePalette<>(
biomePalettedContainer.registry, biomePalettedContainer.registry,
@ -528,7 +563,10 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
if (biomeType == null) { if (biomeType == null) {
continue; continue;
} }
Biome biome = biomeRegistry.get(ResourceLocation.tryParse(biomeType.getId())); Holder<Biome> biome = biomeRegistry.byId(WorldEditPlugin
.getInstance()
.getBukkitImplAdapter()
.getInternalBiomeId(biomeType));
if (biome == null) { if (biome == null) {
continue; continue;
} }
@ -542,24 +580,21 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
return biomePalettedContainer; return biomePalettedContainer;
} }
public static void setCount(final int tickingBlockCount, final int nonEmptyBlockCount, final LevelChunkSection section) throws public static void clearCounts(final LevelChunkSection section) throws IllegalAccessException {
IllegalAccessException { fieldTickingFluidCount.setShort(section, (short) 0);
fieldTickingFluidContent.setShort(section, (short) 0); // TODO FIXME fieldTickingBlockCount.setShort(section, (short) 0);
fieldTickingBlockCount.setShort(section, (short) tickingBlockCount);
fieldNonEmptyBlockCount.setShort(section, (short) nonEmptyBlockCount);
} }
public static BiomeType adapt(Biome biome, LevelAccessor levelAccessor) { public static BiomeType adapt(Holder<Biome> biome, LevelAccessor levelAccessor) {
ResourceLocation resourceLocation = levelAccessor.registryAccess().ownedRegistryOrThrow(Registry.BIOME_REGISTRY).getKey( final Registry<Biome> biomeRegistry = levelAccessor.registryAccess().ownedRegistryOrThrow(Registry.BIOME_REGISTRY);
biome); if (biomeRegistry.getKey(biome.value()) == null) {
if (resourceLocation == null) { return biomeRegistry.asHolderIdMap().getId(biome) == -1 ? BiomeTypes.OCEAN
return levelAccessor.registryAccess().ownedRegistryOrThrow(Registry.BIOME_REGISTRY).getId(biome) == -1
? BiomeTypes.OCEAN
: null; : null;
} }
return BiomeTypes.get(resourceLocation.toString().toLowerCase(Locale.ROOT)); return BiomeTypes.get(biome.unwrapKey().orElseThrow().location().toString());
} }
@SuppressWarnings("unchecked")
static void removeBeacon(BlockEntity beacon, LevelChunk levelChunk) { static void removeBeacon(BlockEntity beacon, LevelChunk levelChunk) {
try { try {
// Do the method ourselves to avoid trying to reflect generic method parameters // Do the method ourselves to avoid trying to reflect generic method parameters
@ -568,23 +603,7 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
BlockEntity blockEntity = levelChunk.blockEntities.remove(beacon.getBlockPos()); BlockEntity blockEntity = levelChunk.blockEntities.remove(beacon.getBlockPos());
if (blockEntity != null) { if (blockEntity != null) {
if (!levelChunk.level.isClientSide) { if (!levelChunk.level.isClientSide) {
Block block = beacon.getBlockState().getBlock(); methodRemoveGameEventListener.invoke(levelChunk, beacon);
if (block instanceof EntityBlock) {
GameEventListener gameEventListener = ((EntityBlock) block).getListener(levelChunk.level, beacon);
if (gameEventListener != null) {
int i = SectionPos.blockToSectionCoord(beacon.getBlockPos().getY());
GameEventDispatcher gameEventDispatcher = levelChunk.getEventDispatcher(i);
gameEventDispatcher.unregister(gameEventListener);
if (gameEventDispatcher.isEmpty()) {
try {
((Int2ObjectMap<GameEventDispatcher>) fieldGameEventDispatcherSections.get(levelChunk))
.remove(i);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
} }
fieldRemove.set(beacon, true); fieldRemove.set(beacon, true);
} }
@ -595,14 +614,12 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
} }
} }
static class FakeIdMapBlock implements IdMap<net.minecraft.world.level.block.state.BlockState> { static List<Entity> getEntities(LevelChunk chunk) {
return chunk.level.entityManager.getEntities(chunk.getPos());
private final int size;
FakeIdMapBlock(int size) {
this.size = size;
} }
record FakeIdMapBlock(int size) implements IdMap<net.minecraft.world.level.block.state.BlockState> {
@Override @Override
public int getId(final net.minecraft.world.level.block.state.BlockState entry) { public int getId(final net.minecraft.world.level.block.state.BlockState entry) {
return 0; return 0;
@ -614,12 +631,7 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
return null; return null;
} }
@Override @Nonnull
public int size() {
return size;
}
@NotNull
@Override @Override
public Iterator<net.minecraft.world.level.block.state.BlockState> iterator() { public Iterator<net.minecraft.world.level.block.state.BlockState> iterator() {
return Collections.emptyIterator(); return Collections.emptyIterator();
@ -627,13 +639,7 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
} }
static class FakeIdMapBiome implements IdMap<Biome> { record FakeIdMapBiome(int size) implements IdMap<Biome> {
private final int size;
FakeIdMapBiome(int size) {
this.size = size;
}
@Override @Override
public int getId(final Biome entry) { public int getId(final Biome entry) {
@ -646,12 +652,7 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
return null; return null;
} }
@Override @Nonnull
public int size() {
return size;
}
@NotNull
@Override @Override
public Iterator<Biome> iterator() { public Iterator<Biome> iterator() {
return Collections.emptyIterator(); return Collections.emptyIterator();

Datei anzeigen

@ -0,0 +1,175 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R2;
import com.fastasyncworldedit.core.configuration.Settings;
import com.fastasyncworldedit.core.extent.processor.ProcessorScope;
import com.fastasyncworldedit.core.queue.IBatchProcessor;
import com.fastasyncworldedit.core.queue.IChunk;
import com.fastasyncworldedit.core.queue.IChunkGet;
import com.fastasyncworldedit.core.queue.IChunkSet;
import com.fastasyncworldedit.core.registry.state.PropertyKey;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldedit.world.block.BlockTypesCache;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.Fluids;
import javax.annotation.Nullable;
public class PaperweightPostProcessor implements IBatchProcessor {
@Override
public IChunkSet processSet(final IChunk chunk, final IChunkGet get, final IChunkSet set) {
return set;
}
@SuppressWarnings("deprecation")
@Override
public void postProcess(final IChunk chunk, final IChunkGet iChunkGet, final IChunkSet iChunkSet) {
boolean tickFluid = Settings.settings().EXPERIMENTAL.ALLOW_TICK_FLUIDS;
// The PostProcessor shouldn't be added, but just in case
if (!tickFluid) {
return;
}
PaperweightGetBlocks_Copy getBlocks = (PaperweightGetBlocks_Copy) iChunkGet;
layer:
for (int layer = iChunkSet.getMinSectionPosition(); layer <= iChunkSet.getMaxSectionPosition(); layer++) {
char[] set = iChunkSet.loadIfPresent(layer);
if (set == null) {
// No edit means no need to process
continue;
}
char[] get = null;
for (int i = 0; i < 4096; i++) {
char ordinal = set[i];
char replacedOrdinal = BlockTypesCache.ReservedIDs.__RESERVED__;
boolean fromGet = false; // Used for liquids
if (ordinal == BlockTypesCache.ReservedIDs.__RESERVED__) {
if (get == null) {
get = getBlocks.load(layer);
}
// If this is null, then it's because we're loading a layer in the range of 0->15, but blocks aren't
// actually being set
if (get == null) {
continue layer;
}
fromGet = true;
ordinal = replacedOrdinal = get[i];
}
if (ordinal == BlockTypesCache.ReservedIDs.__RESERVED__) {
continue;
} else if (!fromGet) { // if fromGet, don't do the same again
if (get == null) {
get = getBlocks.load(layer);
}
replacedOrdinal = get[i];
}
boolean ticking = BlockTypesCache.ticking[ordinal];
boolean replacedWasTicking = BlockTypesCache.ticking[replacedOrdinal];
boolean replacedWasLiquid = false;
BlockState replacedState = null;
if (!ticking) {
// If the block being replaced was not ticking, it cannot be a liquid
if (!replacedWasTicking) {
continue;
}
// If the block being replaced is not fluid, we do not need to worry
if (!(replacedWasLiquid =
(replacedState = BlockState.getFromOrdinal(replacedOrdinal)).getMaterial().isLiquid())) {
continue;
}
}
BlockState state = BlockState.getFromOrdinal(ordinal);
boolean liquid = state.getMaterial().isLiquid();
int x = i & 15;
int y = (i >> 8) & 15;
int z = (i >> 4) & 15;
BlockPos position = new BlockPos((chunk.getX() << 4) + x, (layer << 4) + y, (chunk.getZ() << 4) + z);
if (liquid || replacedWasLiquid) {
if (liquid) {
addFluid(getBlocks.serverLevel, state, position);
continue;
}
// If the replaced fluid (is?) adjacent to water. Do not bother to check adjacent chunks(sections) as this
// may be time consuming. Chances are any fluid blocks in adjacent chunks are being replaced or will end up
// being ticked anyway. We only need it to be "hit" once.
if (!wasAdjacentToWater(get, set, i, x, y, z)) {
continue;
}
addFluid(getBlocks.serverLevel, replacedState, position);
}
}
}
}
@Nullable
@Override
public Extent construct(final Extent child) {
throw new UnsupportedOperationException("Processing only");
}
@Override
public ProcessorScope getScope() {
return ProcessorScope.READING_SET_BLOCKS;
}
private boolean wasAdjacentToWater(char[] get, char[] set, int i, int x, int y, int z) {
if (set == null || get == null) {
return false;
}
char ordinal;
char reserved = BlockTypesCache.ReservedIDs.__RESERVED__;
if (x > 0 && set[i - 1] != reserved) {
if (BlockTypesCache.ticking[(ordinal = get[i - 1])] && isFluid(ordinal)) {
return true;
}
}
if (x < 15 && set[i + 1] != reserved) {
if (BlockTypesCache.ticking[(ordinal = get[i + 1])] && isFluid(ordinal)) {
return true;
}
}
if (z > 0 && set[i - 16] != reserved) {
if (BlockTypesCache.ticking[(ordinal = get[i - 16])] && isFluid(ordinal)) {
return true;
}
}
if (z < 15 && set[i + 16] != reserved) {
if (BlockTypesCache.ticking[(ordinal = get[i + 16])] && isFluid(ordinal)) {
return true;
}
}
if (y > 0 && set[i - 256] != reserved) {
if (BlockTypesCache.ticking[(ordinal = get[i - 256])] && isFluid(ordinal)) {
return true;
}
}
if (y < 15 && set[i + 256] != reserved) {
return BlockTypesCache.ticking[(ordinal = get[i + 256])] && isFluid(ordinal);
}
return false;
}
@SuppressWarnings("deprecation")
private boolean isFluid(char ordinal) {
return BlockState.getFromOrdinal(ordinal).getMaterial().isLiquid();
}
@SuppressWarnings("deprecation")
private void addFluid(final ServerLevel serverLevel, final BlockState replacedState, final BlockPos position) {
Fluid type;
if (replacedState.getBlockType() == BlockTypes.LAVA) {
type = (int) replacedState.getState(PropertyKey.LEVEL) == 0 ? Fluids.LAVA : Fluids.FLOWING_LAVA;
} else {
type = (int) replacedState.getState(PropertyKey.LEVEL) == 0 ? Fluids.WATER : Fluids.FLOWING_WATER;
}
serverLevel.scheduleTick(
position,
type,
type.getTickDelay(serverLevel)
);
}
}

Datei anzeigen

@ -1,4 +1,4 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R1; package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R2;
import com.fastasyncworldedit.core.configuration.Settings; import com.fastasyncworldedit.core.configuration.Settings;
import com.fastasyncworldedit.core.extent.processor.lighting.NMSRelighter; import com.fastasyncworldedit.core.extent.processor.lighting.NMSRelighter;
@ -14,16 +14,12 @@ import it.unimi.dsi.fastutil.longs.LongIterator;
import it.unimi.dsi.fastutil.longs.LongSet; import it.unimi.dsi.fastutil.longs.LongSet;
import net.minecraft.server.MCUtil; import net.minecraft.server.MCUtil;
import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ThreadedLevelLightEngine;
import net.minecraft.server.level.TicketType; import net.minecraft.server.level.TicketType;
import net.minecraft.util.Unit; import net.minecraft.util.Unit;
import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.chunk.ChunkStatus; import net.minecraft.world.level.chunk.ChunkStatus;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
@ -35,7 +31,6 @@ import java.util.function.IntConsumer;
public class PaperweightStarlightRelighter implements Relighter { public class PaperweightStarlightRelighter implements Relighter {
public static final MethodHandle RELIGHT;
private static final Logger LOGGER = LogManagerCompat.getLogger(); private static final Logger LOGGER = LogManagerCompat.getLogger();
private static final int CHUNKS_PER_BATCH = 1024; // 32 * 32 private static final int CHUNKS_PER_BATCH = 1024; // 32 * 32
private static final int CHUNKS_PER_BATCH_SQRT_LOG2 = 5; // for shifting private static final int CHUNKS_PER_BATCH_SQRT_LOG2 = 5; // for shifting
@ -43,26 +38,6 @@ public class PaperweightStarlightRelighter implements Relighter {
private static final TicketType<Unit> FAWE_TICKET = TicketType.create("fawe_ticket", (a, b) -> 0); private static final TicketType<Unit> FAWE_TICKET = TicketType.create("fawe_ticket", (a, b) -> 0);
private static final int LIGHT_LEVEL = MCUtil.getTicketLevelFor(ChunkStatus.LIGHT); private static final int LIGHT_LEVEL = MCUtil.getTicketLevelFor(ChunkStatus.LIGHT);
static {
MethodHandle tmp = null;
try {
MethodHandles.Lookup lookup = MethodHandles.lookup();
tmp = lookup.findVirtual(
ThreadedLevelLightEngine.class,
"relight",
MethodType.methodType(
int.class, // return type
// params
Set.class,
Consumer.class,
IntConsumer.class
)
);
} catch (NoSuchMethodException | IllegalAccessException e) {
LOGGER.error("Failed to locate 'relight' method in ThreadedLevelLightEngine. Is everything up to date?", e);
}
RELIGHT = tmp;
}
private final ServerLevel serverLevel; private final ServerLevel serverLevel;
private final ReentrantLock lock = new ReentrantLock(); private final ReentrantLock lock = new ReentrantLock();
@ -70,16 +45,12 @@ public class PaperweightStarlightRelighter implements Relighter {
private final ReentrantLock areaLock = new ReentrantLock(); private final ReentrantLock areaLock = new ReentrantLock();
private final NMSRelighter delegate; private final NMSRelighter delegate;
//TODO 1.18 address raw access of IQueueChunk @SuppressWarnings("rawtypes")
public PaperweightStarlightRelighter(ServerLevel serverLevel, IQueueExtent<IQueueChunk> queue) { public PaperweightStarlightRelighter(ServerLevel serverLevel, IQueueExtent<IQueueChunk> queue) {
this.serverLevel = serverLevel; this.serverLevel = serverLevel;
this.delegate = new NMSRelighter(queue); this.delegate = new NMSRelighter(queue);
} }
public static boolean isUsable() {
return RELIGHT != null;
}
@Override @Override
public boolean addChunk(int cx, int cz, byte[] skipReason, int bitmask) { public boolean addChunk(int cx, int cz, byte[] skipReason, int bitmask) {
areaLock.lock(); areaLock.lock();
@ -169,14 +140,9 @@ public class PaperweightStarlightRelighter implements Relighter {
IntConsumer processCallback IntConsumer processCallback
) { ) {
try { try {
int unused = (int) RELIGHT.invokeExact( serverLevel.getChunkSource().getLightEngine().relight(coords, chunkCallback, processCallback);
serverLevel.getChunkSource().getLightEngine(), } catch (Exception e) {
coords, LOGGER.error("Error occurred on relighting", e);
chunkCallback, // callback per chunk
processCallback // callback for all chunks
);
} catch (Throwable throwable) {
LOGGER.error("Error occurred on relighting", throwable);
} }
} }

Datei anzeigen

@ -1,4 +1,4 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R1; package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R2;
import com.fastasyncworldedit.core.extent.processor.lighting.NullRelighter; import com.fastasyncworldedit.core.extent.processor.lighting.NullRelighter;
import com.fastasyncworldedit.core.extent.processor.lighting.RelightMode; import com.fastasyncworldedit.core.extent.processor.lighting.RelightMode;
@ -8,7 +8,7 @@ import com.fastasyncworldedit.core.queue.IQueueChunk;
import com.fastasyncworldedit.core.queue.IQueueExtent; import com.fastasyncworldedit.core.queue.IQueueExtent;
import com.sk89q.worldedit.world.World; import com.sk89q.worldedit.world.World;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_18_R1.CraftWorld; import org.bukkit.craftbukkit.v1_18_R2.CraftWorld;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
@ -16,7 +16,7 @@ public class PaperweightStarlightRelighterFactory implements RelighterFactory {
@Override @Override
public @Nonnull public @Nonnull
//TODO 1.18 address raw access of IQueueChunk @SuppressWarnings("rawtypes")
Relighter createRelighter(RelightMode relightMode, World world, IQueueExtent<IQueueChunk> queue) { Relighter createRelighter(RelightMode relightMode, World world, IQueueExtent<IQueueChunk> queue) {
org.bukkit.World w = Bukkit.getWorld(world.getName()); org.bukkit.World w = Bukkit.getWorld(world.getName());
if (w == null) { if (w == null) {

Datei anzeigen

@ -1,4 +1,4 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R1.nbt; package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R2.nbt;
import com.sk89q.jnbt.CompoundTag; import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.LazyCompoundTag; import com.sk89q.jnbt.LazyCompoundTag;
@ -35,6 +35,7 @@ public class PaperweightLazyCompoundTag extends LazyCompoundTag {
} }
@Override @Override
@SuppressWarnings("unchecked")
public Map<String, Tag> getValue() { public Map<String, Tag> getValue() {
if (compoundTag == null) { if (compoundTag == null) {
compoundTag = (CompoundTag) WorldEditPlugin.getInstance().getBukkitImplAdapter().toNative(compoundTagSupplier.get()); compoundTag = (CompoundTag) WorldEditPlugin.getInstance().getBukkitImplAdapter().toNative(compoundTagSupplier.get());
@ -66,8 +67,8 @@ public class PaperweightLazyCompoundTag extends LazyCompoundTag {
public double asDouble(String key) { public double asDouble(String key) {
net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key); net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key);
if (tag instanceof NumericTag) { if (tag instanceof NumericTag numTag) {
return ((NumericTag) tag).getAsDouble(); return numTag.getAsDouble();
} }
return 0; return 0;
} }
@ -86,20 +87,20 @@ public class PaperweightLazyCompoundTag extends LazyCompoundTag {
public int asInt(String key) { public int asInt(String key) {
net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key); net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key);
if (tag instanceof NumericTag) { if (tag instanceof NumericTag numTag) {
return ((NumericTag) tag).getAsInt(); return numTag.getAsInt();
} }
return 0; return 0;
} }
@SuppressWarnings("unchecked")
public List<Tag> getList(String key) { public List<Tag> getList(String key) {
net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key); net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key);
if (tag instanceof net.minecraft.nbt.ListTag) { if (tag instanceof net.minecraft.nbt.ListTag nbtList) {
ArrayList<Tag> list = new ArrayList<>(); ArrayList<Tag> list = new ArrayList<>();
net.minecraft.nbt.ListTag nbtList = (net.minecraft.nbt.ListTag) tag;
for (net.minecraft.nbt.Tag elem : nbtList) { for (net.minecraft.nbt.Tag elem : nbtList) {
if (elem instanceof net.minecraft.nbt.CompoundTag) { if (elem instanceof net.minecraft.nbt.CompoundTag compoundTag) {
list.add(new PaperweightLazyCompoundTag((net.minecraft.nbt.CompoundTag) elem)); list.add(new PaperweightLazyCompoundTag(compoundTag));
} else { } else {
list.add(WorldEditPlugin.getInstance().getBukkitImplAdapter().toNative(elem)); list.add(WorldEditPlugin.getInstance().getBukkitImplAdapter().toNative(elem));
} }
@ -109,7 +110,7 @@ public class PaperweightLazyCompoundTag extends LazyCompoundTag {
return Collections.emptyList(); return Collections.emptyList();
} }
//TODO 1.18 be a ListBinaryTag ? @SuppressWarnings("unchecked")
public ListTag getListTag(String key) { public ListTag getListTag(String key) {
net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key); net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key);
if (tag instanceof net.minecraft.nbt.ListTag) { if (tag instanceof net.minecraft.nbt.ListTag) {
@ -138,8 +139,8 @@ public class PaperweightLazyCompoundTag extends LazyCompoundTag {
public long asLong(String key) { public long asLong(String key) {
net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key); net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key);
if (tag instanceof NumericTag) { if (tag instanceof NumericTag numTag) {
return ((NumericTag) tag).getAsLong(); return numTag.getAsLong();
} }
return 0; return 0;
} }

Datei anzeigen

@ -1,4 +1,4 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R1.regen; package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R2.regen;
import com.fastasyncworldedit.bukkit.adapter.Regenerator; import com.fastasyncworldedit.bukkit.adapter.Regenerator;
import com.fastasyncworldedit.core.Fawe; import com.fastasyncworldedit.core.Fawe;
@ -9,19 +9,20 @@ import com.fastasyncworldedit.core.util.TaskManager;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.mojang.datafixers.util.Either; import com.mojang.datafixers.util.Either;
import com.mojang.serialization.Lifecycle; import com.mojang.serialization.Lifecycle;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.adapter.Refraction; import com.sk89q.worldedit.bukkit.adapter.Refraction;
import com.sk89q.worldedit.bukkit.adapter.ext.fawe.v1_18_R1.PaperweightAdapter; import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R2.PaperweightGetBlocks;
import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R1.PaperweightGetBlocks;
import com.sk89q.worldedit.extent.Extent; import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.internal.util.LogManagerCompat; import com.sk89q.worldedit.internal.util.LogManagerCompat;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.io.file.SafeFiles; import com.sk89q.worldedit.util.io.file.SafeFiles;
import com.sk89q.worldedit.world.RegenOptions; import com.sk89q.worldedit.world.RegenOptions;
import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry; import net.minecraft.core.Registry;
import net.minecraft.data.BuiltinRegistries; import net.minecraft.data.BuiltinRegistries;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerChunkCache; import net.minecraft.server.level.ServerChunkCache;
import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerLevel;
@ -33,6 +34,7 @@ import net.minecraft.world.level.LevelHeightAccessor;
import net.minecraft.world.level.LevelSettings; import net.minecraft.world.level.LevelSettings;
import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeSource; import net.minecraft.world.level.biome.BiomeSource;
import net.minecraft.world.level.biome.FixedBiomeSource;
import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.ChunkGenerator; import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.chunk.ChunkStatus; import net.minecraft.world.level.chunk.ChunkStatus;
@ -46,14 +48,16 @@ import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import net.minecraft.world.level.levelgen.WorldGenSettings; import net.minecraft.world.level.levelgen.WorldGenSettings;
import net.minecraft.world.level.levelgen.blending.BlendingData; import net.minecraft.world.level.levelgen.blending.BlendingData;
import net.minecraft.world.level.levelgen.flat.FlatLevelGeneratorSettings; import net.minecraft.world.level.levelgen.flat.FlatLevelGeneratorSettings;
import net.minecraft.world.level.levelgen.structure.placement.ConcentricRingsStructurePlacement;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureManager; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureManager;
import net.minecraft.world.level.storage.LevelStorageSource; import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.PrimaryLevelData; import net.minecraft.world.level.storage.PrimaryLevelData;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_18_R1.CraftServer; import org.bukkit.craftbukkit.v1_18_R2.CraftServer;
import org.bukkit.craftbukkit.v1_18_R1.CraftWorld; import org.bukkit.craftbukkit.v1_18_R2.CraftWorld;
import org.bukkit.craftbukkit.v1_18_R1.generator.CustomChunkGenerator; import org.bukkit.craftbukkit.v1_18_R2.generator.CustomChunkGenerator;
import org.bukkit.generator.BiomeProvider;
import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.BlockPopulator;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -64,6 +68,7 @@ import java.util.Collections;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.OptionalLong;
import java.util.Random; import java.util.Random;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.function.BooleanSupplier; import java.util.function.BooleanSupplier;
@ -74,12 +79,14 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
private static final Logger LOGGER = LogManagerCompat.getLogger(); private static final Logger LOGGER = LogManagerCompat.getLogger();
private static final Field serverWorldsField; private static final Field serverWorldsField;
private static final Field worldPaperConfigField; private static final Field paperConfigField;
private static final Field flatBedrockField; private static final Field flatBedrockField;
private static final Field generatorSettingFlatField; private static final Field generatorSettingFlatField;
private static final Field generatorSettingBaseSupplierField; private static final Field generatorSettingBaseSupplierField;
private static final Field delegateField; private static final Field delegateField;
private static final Field chunkProviderField; private static final Field chunkSourceField;
private static final Field ringPositionsField;
private static final Field hasGeneratedPositionsField;
//list of chunk stati in correct order without FULL //list of chunk stati in correct order without FULL
private static final Map<ChunkStatus, Concurrency> chunkStati = new LinkedHashMap<>(); private static final Map<ChunkStatus, Concurrency> chunkStati = new LinkedHashMap<>();
@ -123,21 +130,27 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
tmpPaperConfigField = null; tmpPaperConfigField = null;
tmpFlatBedrockField = null; tmpFlatBedrockField = null;
} }
worldPaperConfigField = tmpPaperConfigField; paperConfigField = tmpPaperConfigField;
flatBedrockField = tmpFlatBedrockField; flatBedrockField = tmpFlatBedrockField;
generatorSettingBaseSupplierField = NoiseBasedChunkGenerator.class.getDeclaredField(Refraction.pickName( generatorSettingBaseSupplierField = NoiseBasedChunkGenerator.class.getDeclaredField(Refraction.pickName(
"settings", "f")); "settings", "h"));
generatorSettingBaseSupplierField.setAccessible(true); generatorSettingBaseSupplierField.setAccessible(true);
generatorSettingFlatField = FlatLevelSource.class.getDeclaredField(Refraction.pickName("settings", "e")); generatorSettingFlatField = FlatLevelSource.class.getDeclaredField(Refraction.pickName("settings", "g"));
generatorSettingFlatField.setAccessible(true); generatorSettingFlatField.setAccessible(true);
delegateField = CustomChunkGenerator.class.getDeclaredField("delegate"); delegateField = CustomChunkGenerator.class.getDeclaredField("delegate");
delegateField.setAccessible(true); delegateField.setAccessible(true);
chunkProviderField = ServerLevel.class.getDeclaredField(Refraction.pickName("chunkSource", "L")); chunkSourceField = ServerLevel.class.getDeclaredField(Refraction.pickName("chunkSource", "K"));
chunkProviderField.setAccessible(true); chunkSourceField.setAccessible(true);
ringPositionsField = ChunkGenerator.class.getDeclaredField(Refraction.pickName("ringPositions", "h"));
ringPositionsField.setAccessible(true);
hasGeneratedPositionsField = ChunkGenerator.class.getDeclaredField(Refraction.pickName("hasGeneratedPositions", "i"));
hasGeneratedPositionsField.setAccessible(true);
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -170,9 +183,9 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
} }
//flat bedrock? (only on paper) //flat bedrock? (only on paper)
if (worldPaperConfigField != null) { if (paperConfigField != null) {
try { try {
generateFlatBedrock = flatBedrockField.getBoolean(worldPaperConfigField.get(originalServerWorld)); generateFlatBedrock = flatBedrockField.getBoolean(paperConfigField.get(originalServerWorld));
} catch (Exception ignored) { } catch (Exception ignored) {
} }
} }
@ -184,6 +197,7 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
} }
@Override @Override
@SuppressWarnings("unchecked")
protected boolean initNewWorld() throws Exception { protected boolean initNewWorld() throws Exception {
//world folder //world folder
tempDir = java.nio.file.Files.createTempDirectory("FastAsyncWorldEditWorldGen"); tempDir = java.nio.file.Files.createTempDirectory("FastAsyncWorldEditWorldGen");
@ -193,17 +207,18 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
org.bukkit.generator.ChunkGenerator generator = originalBukkitWorld.getGenerator(); org.bukkit.generator.ChunkGenerator generator = originalBukkitWorld.getGenerator();
LevelStorageSource levelStorageSource = LevelStorageSource.createDefault(tempDir); LevelStorageSource levelStorageSource = LevelStorageSource.createDefault(tempDir);
ResourceKey<LevelStem> levelStemResourceKey = getWorldDimKey(environment); ResourceKey<LevelStem> levelStemResourceKey = getWorldDimKey(environment);
session = levelStorageSource.createAccess("worldeditregentempworld", levelStemResourceKey); session = levelStorageSource.createAccess("faweregentempworld", levelStemResourceKey);
PrimaryLevelData originalWorldData = originalServerWorld.serverLevelData; PrimaryLevelData originalWorldData = originalServerWorld.serverLevelData;
BiomeProvider biomeProvider = getBiomeProvider();
MinecraftServer server = originalServerWorld.getCraftServer().getServer(); MinecraftServer server = originalServerWorld.getCraftServer().getServer();
PrimaryLevelData levelProperties = (PrimaryLevelData) server.getWorldData(); WorldGenSettings originalOpts = originalWorldData.worldGenSettings();
WorldGenSettings originalOpts = levelProperties.worldGenSettings();
WorldGenSettings newOpts = options.getSeed().isPresent() WorldGenSettings newOpts = options.getSeed().isPresent()
? PaperweightAdapter.replaceSeed(originalServerWorld, seed, originalOpts) ? originalOpts.withSeed(originalWorldData.isHardcore(), OptionalLong.of(seed))
: originalOpts; : originalOpts;
LevelSettings newWorldSettings = new LevelSettings( LevelSettings newWorldSettings = new LevelSettings(
"worldeditregentempworld", "faweregentempworld",
originalWorldData.settings.gameType(), originalWorldData.settings.gameType(),
originalWorldData.settings.hardcore(), originalWorldData.settings.hardcore(),
originalWorldData.settings.difficulty(), originalWorldData.settings.difficulty(),
@ -220,29 +235,28 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
session, session,
newWorldData, newWorldData,
originalServerWorld.dimension(), originalServerWorld.dimension(),
originalServerWorld.dimensionType(), originalServerWorld.dimensionTypeRegistration(),
new RegenNoOpWorldLoadListener(), new RegenNoOpWorldLoadListener(),
// placeholder. Required for new ChunkProviderServer, but we create and then set it later // placeholder. Required for new ChunkProviderServer, but we create and then set it later
newOpts.dimensions().get(levelStemResourceKey).generator(), newOpts.dimensions().getOrThrow(levelStemResourceKey).generator(),
originalServerWorld.isDebug(), originalServerWorld.isDebug(),
seed, seed,
ImmutableList.of(), ImmutableList.of(),
false, false,
environment, environment,
generator, generator,
originalBukkitWorld.getBiomeProvider() biomeProvider
) { ) {
private final Biome singleBiome = options.hasBiomeType() ? BuiltinRegistries.BIOME.get(ResourceLocation.tryParse( private final Holder<Biome> singleBiome = options.hasBiomeType() ? BuiltinRegistries.BIOME.asHolderIdMap().byId(
options WorldEditPlugin.getInstance().getBukkitImplAdapter().getInternalBiomeId(options.getBiomeType())
.getBiomeType() ) : null;
.getId())) : null;
@Override @Override
public void tick(BooleanSupplier shouldKeepTicking) { //no ticking public void tick(BooleanSupplier shouldKeepTicking) { //no ticking
} }
@Override @Override
public Biome getUncachedNoiseBiome(int biomeX, int biomeY, int biomeZ) { public Holder<Biome> getUncachedNoiseBiome(int biomeX, int biomeY, int biomeZ) {
if (options.hasBiomeType()) { if (options.hasBiomeType()) {
return singleBiome; return singleBiome;
} }
@ -254,25 +268,35 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
freshWorld.noSave = true; freshWorld.noSave = true;
removeWorldFromWorldsMap(); removeWorldFromWorldsMap();
newWorldData.checkName(originalServerWorld.serverLevelData.getLevelName()); //rename to original world name newWorldData.checkName(originalServerWorld.serverLevelData.getLevelName()); //rename to original world name
if (worldPaperConfigField != null) { if (paperConfigField != null) {
worldPaperConfigField.set(freshWorld, originalServerWorld.paperConfig); paperConfigField.set(freshWorld, originalServerWorld.paperConfig);
} }
//generator //generator
if (originalChunkProvider.getGenerator() instanceof FlatLevelSource flatLevelSource) { ChunkGenerator originalGenerator = originalChunkProvider.getGenerator();
if (originalGenerator instanceof FlatLevelSource flatLevelSource) {
FlatLevelGeneratorSettings generatorSettingFlat = flatLevelSource.settings(); FlatLevelGeneratorSettings generatorSettingFlat = flatLevelSource.settings();
chunkGenerator = new FlatLevelSource(generatorSettingFlat); chunkGenerator = new FlatLevelSource(originalGenerator.structureSets, generatorSettingFlat);
} else if (originalChunkProvider.getGenerator() instanceof NoiseBasedChunkGenerator noiseBasedChunkGenerator) { } else if (originalGenerator instanceof NoiseBasedChunkGenerator noiseBasedChunkGenerator) {
Supplier<NoiseGeneratorSettings> generatorSettingBaseSupplier = (Supplier<NoiseGeneratorSettings>) generatorSettingBaseSupplierField Holder<NoiseGeneratorSettings> generatorSettingBaseSupplier =
.get(originalChunkProvider.getGenerator()); (Holder<NoiseGeneratorSettings>) generatorSettingBaseSupplierField
BiomeSource biomeSource = originalChunkProvider.getGenerator().getBiomeSource(); .get(originalGenerator);
chunkGenerator = new NoiseBasedChunkGenerator(noiseBasedChunkGenerator.noises, biomeSource, seed, BiomeSource biomeSource;
if (options.hasBiomeType()) {
biomeSource = new FixedBiomeSource(BuiltinRegistries.BIOME
.asHolderIdMap()
.byId(WorldEditPlugin.getInstance().getBukkitImplAdapter().getInternalBiomeId(options.getBiomeType())));
} else {
biomeSource = originalGenerator.getBiomeSource();
}
chunkGenerator = new NoiseBasedChunkGenerator(originalGenerator.structureSets, noiseBasedChunkGenerator.noises,
biomeSource, seed,
generatorSettingBaseSupplier generatorSettingBaseSupplier
); );
} else if (originalChunkProvider.getGenerator() instanceof CustomChunkGenerator customChunkGenerator) { } else if (originalGenerator instanceof CustomChunkGenerator customChunkGenerator) {
chunkGenerator = customChunkGenerator.delegate; chunkGenerator = customChunkGenerator.delegate;
} else { } else {
LOGGER.error("Unsupported generator type {}", originalChunkProvider.getGenerator().getClass().getName()); LOGGER.error("Unsupported generator type {}", originalGenerator.getClass().getName());
return false; return false;
} }
if (generator != null) { if (generator != null) {
@ -280,6 +304,21 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
generateConcurrent = generator.isParallelCapable(); generateConcurrent = generator.isParallelCapable();
} }
if (seed == originalOpts.seed() && !options.hasBiomeType()) {
// Optimisation for needless ring position calculation when the seed and biome is the same.
boolean hasGeneratedPositions = hasGeneratedPositionsField.getBoolean(originalGenerator);
if (hasGeneratedPositions) {
Map<ConcentricRingsStructurePlacement, CompletableFuture<List<ChunkPos>>> ringPositions =
(Map<ConcentricRingsStructurePlacement, CompletableFuture<List<ChunkPos>>>) ringPositionsField.get(
originalGenerator);
Map<ConcentricRingsStructurePlacement, CompletableFuture<List<ChunkPos>>> copy = new Object2ObjectArrayMap<>(ringPositions);
ringPositionsField.set(chunkGenerator, copy);
hasGeneratedPositionsField.setBoolean(chunkGenerator, true);
}
}
chunkGenerator.conf = originalServerWorld.spigotConfig;
freshChunkProvider = new ServerChunkCache( freshChunkProvider = new ServerChunkCache(
freshWorld, freshWorld,
session, session,
@ -297,12 +336,16 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
) { ) {
// redirect to LevelChunks created in #createChunks // redirect to LevelChunks created in #createChunks
@Override @Override
public ChunkAccess getChunk(int x, int z, ChunkStatus chunkstatus, boolean flag) { public ChunkAccess getChunk(int x, int z, ChunkStatus chunkstatus, boolean create) {
return getChunkAt(x, z); ChunkAccess chunkAccess = getChunkAt(x, z);
if (chunkAccess == null && create) {
chunkAccess = createChunk(getProtoChunkAt(x, z));
}
return chunkAccess;
} }
}; };
ReflectionUtils.unsafeSet(chunkProviderField, freshWorld, freshChunkProvider); ReflectionUtils.unsafeSet(chunkSourceField, freshWorld, freshChunkProvider);
//let's start then //let's start then
structureManager = server.getStructureManager(); structureManager = server.getStructureManager();
threadedLevelLightEngine = freshChunkProvider.getLightEngine(); threadedLevelLightEngine = freshChunkProvider.getLightEngine();
@ -385,11 +428,12 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
} }
//util //util
@SuppressWarnings("unchecked")
private void removeWorldFromWorldsMap() { private void removeWorldFromWorldsMap() {
Fawe.instance().getQueueHandler().sync(() -> { Fawe.instance().getQueueHandler().sync(() -> {
try { try {
Map<String, org.bukkit.World> map = (Map<String, org.bukkit.World>) serverWorldsField.get(Bukkit.getServer()); Map<String, org.bukkit.World> map = (Map<String, org.bukkit.World>) serverWorldsField.get(Bukkit.getServer());
map.remove("worldeditregentempworld"); map.remove("faweregentempworld");
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -397,15 +441,11 @@ public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, Level
} }
private ResourceKey<LevelStem> getWorldDimKey(org.bukkit.World.Environment env) { private ResourceKey<LevelStem> getWorldDimKey(org.bukkit.World.Environment env) {
switch (env) { return switch (env) {
case NETHER: case NETHER -> LevelStem.NETHER;
return LevelStem.NETHER; case THE_END -> LevelStem.END;
case THE_END: default -> LevelStem.OVERWORLD;
return LevelStem.END; };
case NORMAL:
default:
return LevelStem.OVERWORLD;
}
} }
private static class RegenNoOpWorldLoadListener implements ChunkProgressListener { private static class RegenNoOpWorldLoadListener implements ChunkProgressListener {

Datei anzeigen

@ -0,0 +1,16 @@
import io.papermc.paperweight.userdev.PaperweightUserDependenciesExtension
plugins {
java
}
applyPaperweightAdapterConfiguration()
repositories {
gradlePluginPortal()
}
dependencies {
the<PaperweightUserDependenciesExtension>().paperDevBundle("1.19.2-R0.1-20221206.184705-189")
compileOnly(libs.paperlib)
}

Datei anzeigen

@ -0,0 +1,99 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.bukkit.adapter.ext.fawe.v1_19_R1;
import com.mojang.authlib.GameProfile;
import net.minecraft.network.chat.ChatType;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ServerboundClientInformationPacket;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.stats.Stat;
import net.minecraft.world.MenuProvider;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.block.entity.SignBlockEntity;
import net.minecraft.world.phys.Vec3;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import java.util.OptionalInt;
import java.util.UUID;
class PaperweightFakePlayer extends ServerPlayer {
private static final GameProfile FAKE_WORLDEDIT_PROFILE = new GameProfile(
UUID.nameUUIDFromBytes("worldedit".getBytes()),
"[WorldEdit]"
);
private static final Vec3 ORIGIN = new Vec3(0.0D, 0.0D, 0.0D);
PaperweightFakePlayer(ServerLevel world) {
super(world.getServer(), world, FAKE_WORLDEDIT_PROFILE, null);
}
@Override
public Vec3 position() {
return ORIGIN;
}
@Override
public void tick() {
}
@Override
public void die(DamageSource damagesource) {
}
@Override
public Entity changeDimension(ServerLevel worldserver, TeleportCause cause) {
return this;
}
@Override
public OptionalInt openMenu(MenuProvider factory) {
return OptionalInt.empty();
}
@Override
public void updateOptions(ServerboundClientInformationPacket packet) {
}
@Override
public void displayClientMessage(Component message, boolean actionBar) {
}
@Override
public void awardStat(Stat<?> stat, int amount) {
}
@Override
public void awardStat(Stat<?> stat) {
}
@Override
public boolean isInvulnerableTo(DamageSource damageSource) {
return true;
}
@Override
public void openTextEdit(SignBlockEntity sign) {
}
}

Datei anzeigen

@ -0,0 +1,210 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.bukkit.adapter.ext.fawe.v1_19_R1;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.internal.block.BlockStateIdAccess;
import com.sk89q.worldedit.internal.wna.WorldNativeAccess;
import com.sk89q.worldedit.util.SideEffect;
import com.sk89q.worldedit.util.SideEffectSet;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.world.block.BlockState;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ChunkHolder;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.chunk.LevelChunk;
import org.bukkit.craftbukkit.v1_19_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_19_R1.block.data.CraftBlockData;
import org.bukkit.event.block.BlockPhysicsEvent;
import javax.annotation.Nullable;
import java.lang.ref.WeakReference;
import java.util.Objects;
public class PaperweightWorldNativeAccess implements
WorldNativeAccess<LevelChunk, net.minecraft.world.level.block.state.BlockState, BlockPos> {
private static final int UPDATE = 1;
private static final int NOTIFY = 2;
private final PaperweightAdapter adapter;
private final WeakReference<ServerLevel> world;
private SideEffectSet sideEffectSet;
public PaperweightWorldNativeAccess(PaperweightAdapter adapter, WeakReference<ServerLevel> world) {
this.adapter = adapter;
this.world = world;
}
private ServerLevel getWorld() {
return Objects.requireNonNull(world.get(), "The reference to the world was lost");
}
@Override
public void setCurrentSideEffectSet(SideEffectSet sideEffectSet) {
this.sideEffectSet = sideEffectSet;
}
@Override
public LevelChunk getChunk(int x, int z) {
return getWorld().getChunk(x, z);
}
@Override
public net.minecraft.world.level.block.state.BlockState toNative(BlockState state) {
int stateId = BlockStateIdAccess.getBlockStateId(state);
return BlockStateIdAccess.isValidInternalId(stateId)
? Block.stateById(stateId)
: ((CraftBlockData) BukkitAdapter.adapt(state)).getState();
}
@Override
public net.minecraft.world.level.block.state.BlockState getBlockState(LevelChunk chunk, BlockPos position) {
return chunk.getBlockState(position);
}
@Nullable
@Override
public net.minecraft.world.level.block.state.BlockState setBlockState(
LevelChunk chunk,
BlockPos position,
net.minecraft.world.level.block.state.BlockState state
) {
return chunk.setBlockState(position, state, false, this.sideEffectSet.shouldApply(SideEffect.UPDATE));
}
@Override
public net.minecraft.world.level.block.state.BlockState getValidBlockForPosition(
net.minecraft.world.level.block.state.BlockState block,
BlockPos position
) {
return Block.updateFromNeighbourShapes(block, getWorld(), position);
}
@Override
public BlockPos getPosition(int x, int y, int z) {
return new BlockPos(x, y, z);
}
@Override
public void updateLightingForBlock(BlockPos position) {
getWorld().getChunkSource().getLightEngine().checkBlock(position);
}
@Override
public boolean updateTileEntity(final BlockPos position, final CompoundBinaryTag tag) {
return false;
}
@Override
public void notifyBlockUpdate(
LevelChunk chunk,
BlockPos position,
net.minecraft.world.level.block.state.BlockState oldState,
net.minecraft.world.level.block.state.BlockState newState
) {
if (chunk.getSections()[getWorld().getSectionIndex(position.getY())] != null) {
getWorld().sendBlockUpdated(position, oldState, newState, UPDATE | NOTIFY);
}
}
@Override
public boolean isChunkTicking(LevelChunk chunk) {
return chunk.getFullStatus().isOrAfter(ChunkHolder.FullChunkStatus.TICKING);
}
@Override
public void markBlockChanged(LevelChunk chunk, BlockPos position) {
if (chunk.getSections()[getWorld().getSectionIndex(position.getY())] != null) {
getWorld().getChunkSource().blockChanged(position);
}
}
@Override
public void notifyNeighbors(
BlockPos pos,
net.minecraft.world.level.block.state.BlockState oldState,
net.minecraft.world.level.block.state.BlockState newState
) {
ServerLevel world = getWorld();
if (sideEffectSet.shouldApply(SideEffect.EVENTS)) {
world.updateNeighborsAt(pos, oldState.getBlock());
} else {
// When we don't want events, manually run the physics without them.
Block block = oldState.getBlock();
fireNeighborChanged(pos, world, block, pos.west());
fireNeighborChanged(pos, world, block, pos.east());
fireNeighborChanged(pos, world, block, pos.below());
fireNeighborChanged(pos, world, block, pos.above());
fireNeighborChanged(pos, world, block, pos.north());
fireNeighborChanged(pos, world, block, pos.south());
}
if (newState.hasAnalogOutputSignal()) {
world.updateNeighbourForOutputSignal(pos, newState.getBlock());
}
}
@SuppressWarnings("deprecation")
private void fireNeighborChanged(BlockPos pos, ServerLevel world, Block block, BlockPos neighborPos) {
world.getBlockState(neighborPos).neighborChanged(world, neighborPos, block, pos, false);
}
@Override
public void updateNeighbors(
BlockPos pos,
net.minecraft.world.level.block.state.BlockState oldState,
net.minecraft.world.level.block.state.BlockState newState,
int recursionLimit
) {
ServerLevel world = getWorld();
// a == updateNeighbors
// b == updateDiagonalNeighbors
oldState.updateIndirectNeighbourShapes(world, pos, NOTIFY, recursionLimit);
if (sideEffectSet.shouldApply(SideEffect.EVENTS)) {
CraftWorld craftWorld = world.getWorld();
BlockPhysicsEvent event = new BlockPhysicsEvent(
craftWorld.getBlockAt(pos.getX(), pos.getY(), pos.getZ()),
CraftBlockData.fromData(newState)
);
world.getCraftServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
}
newState.updateNeighbourShapes(world, pos, NOTIFY, recursionLimit);
newState.updateIndirectNeighbourShapes(world, pos, NOTIFY, recursionLimit);
}
@Override
public void onBlockStateChange(
BlockPos pos,
net.minecraft.world.level.block.state.BlockState oldState,
net.minecraft.world.level.block.state.BlockState newState
) {
getWorld().onBlockStateChange(pos, oldState, newState);
}
@Override
public void flush() {
}
}

Datei anzeigen

@ -0,0 +1,189 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R1;
import com.google.common.base.Suppliers;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.util.ReflectionUtil;
import com.sk89q.worldedit.bukkit.adapter.Refraction;
import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R1.nbt.PaperweightLazyCompoundTag;
import com.sk89q.worldedit.world.registry.BlockMaterial;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.EmptyBlockGetter;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.EntityBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Material;
import net.minecraft.world.level.material.PushReaction;
import org.bukkit.craftbukkit.v1_19_R1.block.data.CraftBlockData;
public class PaperweightBlockMaterial implements BlockMaterial {
private final Block block;
private final BlockState blockState;
private final Material material;
private final boolean isTranslucent;
private final CraftBlockData craftBlockData;
private final org.bukkit.Material craftMaterial;
private final int opacity;
private final CompoundTag tile;
public PaperweightBlockMaterial(Block block) {
this(block, block.defaultBlockState());
}
public PaperweightBlockMaterial(Block block, BlockState blockState) {
this.block = block;
this.blockState = blockState;
this.material = blockState.getMaterial();
this.craftBlockData = CraftBlockData.fromData(blockState);
this.craftMaterial = craftBlockData.getMaterial();
BlockBehaviour.Properties blockInfo = ReflectionUtil.getField(BlockBehaviour.class, block, Refraction.pickName(
"properties", "aO"));
this.isTranslucent = !(boolean) ReflectionUtil.getField(BlockBehaviour.Properties.class, blockInfo,
Refraction.pickName("canOcclude", "n")
);
opacity = blockState.getLightBlock(EmptyBlockGetter.INSTANCE, BlockPos.ZERO);
BlockEntity tileEntity = !(block instanceof EntityBlock) ? null : ((EntityBlock) block).newBlockEntity(
BlockPos.ZERO,
blockState
);
tile = tileEntity == null
? null
: new PaperweightLazyCompoundTag(Suppliers.memoize(tileEntity::saveWithId));
}
public Block getBlock() {
return block;
}
public BlockState getState() {
return blockState;
}
public CraftBlockData getCraftBlockData() {
return craftBlockData;
}
public Material getMaterial() {
return material;
}
@Override
public boolean isAir() {
return blockState.isAir();
}
@Override
public boolean isFullCube() {
return craftMaterial.isOccluding();
}
@Override
public boolean isOpaque() {
return material.isSolidBlocking();
}
@Override
public boolean isPowerSource() {
return blockState.isSignalSource();
}
@Override
public boolean isLiquid() {
return material.isLiquid();
}
@Override
public boolean isSolid() {
return material.isSolid();
}
@Override
public float getHardness() {
return craftBlockData.getState().destroySpeed;
}
@Override
public float getResistance() {
return block.getExplosionResistance();
}
@Override
public float getSlipperiness() {
return block.getFriction();
}
@Override
public int getLightValue() {
return blockState.getLightEmission();
}
@Override
public int getLightOpacity() {
return opacity;
}
@Override
public boolean isFragileWhenPushed() {
return material.getPushReaction() == PushReaction.DESTROY;
}
@Override
public boolean isUnpushable() {
return material.getPushReaction() == PushReaction.BLOCK;
}
@Override
public boolean isTicksRandomly() {
return block.isRandomlyTicking(blockState);
}
@Override
public boolean isMovementBlocker() {
return material.isSolid();
}
@Override
public boolean isBurnable() {
return material.isFlammable();
}
@Override
public boolean isToolRequired() {
// Removed in 1.16.1, this is not present in higher versions
return false;
}
@Override
public boolean isReplacedDuringPlacement() {
return material.isReplaceable();
}
@Override
public boolean isTranslucent() {
return isTranslucent;
}
@Override
public boolean hasContainer() {
return block instanceof EntityBlock;
}
@Override
public boolean isTile() {
return block instanceof EntityBlock;
}
@Override
public CompoundTag getDefaultTile() {
return tile;
}
@Override
public int getMapColor() {
// rgb field
return material.getColor().col;
}
}

Datei anzeigen

@ -0,0 +1,701 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R1;
import com.fastasyncworldedit.bukkit.adapter.CachedBukkitAdapter;
import com.fastasyncworldedit.bukkit.adapter.IDelegateBukkitImplAdapter;
import com.fastasyncworldedit.bukkit.adapter.NMSRelighterFactory;
import com.fastasyncworldedit.core.FaweCache;
import com.fastasyncworldedit.core.entity.LazyBaseEntity;
import com.fastasyncworldedit.core.extent.processor.lighting.RelighterFactory;
import com.fastasyncworldedit.core.queue.IBatchProcessor;
import com.fastasyncworldedit.core.queue.IChunkGet;
import com.fastasyncworldedit.core.queue.implementation.packet.ChunkPacket;
import com.fastasyncworldedit.core.util.NbtUtils;
import com.fastasyncworldedit.core.util.TaskManager;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.blocks.BaseItemStack;
import com.sk89q.worldedit.blocks.TileEntityBlock;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter;
import com.sk89q.worldedit.bukkit.adapter.ext.fawe.v1_19_R1.PaperweightAdapter;
import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R1.nbt.PaperweightLazyCompoundTag;
import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R1.regen.PaperweightRegen;
import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.internal.block.BlockStateIdAccess;
import com.sk89q.worldedit.internal.util.LogManagerCompat;
import com.sk89q.worldedit.internal.wna.WorldNativeAccess;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.registry.state.BooleanProperty;
import com.sk89q.worldedit.registry.state.DirectionalProperty;
import com.sk89q.worldedit.registry.state.EnumProperty;
import com.sk89q.worldedit.registry.state.IntegerProperty;
import com.sk89q.worldedit.registry.state.Property;
import com.sk89q.worldedit.util.Direction;
import com.sk89q.worldedit.util.SideEffect;
import com.sk89q.worldedit.util.SideEffectSet;
import com.sk89q.worldedit.util.TreeGenerator;
import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.util.nbt.BinaryTag;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.util.nbt.StringBinaryTag;
import com.sk89q.worldedit.world.RegenOptions;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldedit.world.block.BlockTypesCache;
import com.sk89q.worldedit.world.entity.EntityType;
import com.sk89q.worldedit.world.item.ItemType;
import com.sk89q.worldedit.world.registry.BlockMaterial;
import io.papermc.lib.PaperLib;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Registry;
import net.minecraft.core.WritableRegistry;
import net.minecraft.nbt.IntTag;
import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ChunkHolder;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.util.StringRepresentable;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.block.state.properties.DirectionProperty;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.LevelChunkSection;
import org.apache.logging.log4j.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.TreeType;
import org.bukkit.block.data.BlockData;
import org.bukkit.craftbukkit.v1_19_R1.CraftChunk;
import org.bukkit.craftbukkit.v1_19_R1.CraftServer;
import org.bukkit.craftbukkit.v1_19_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_19_R1.block.CraftBlockState;
import org.bukkit.craftbukkit.v1_19_R1.block.data.CraftBlockData;
import org.bukkit.craftbukkit.v1_19_R1.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_19_R1.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_19_R1.inventory.CraftItemStack;
import org.bukkit.craftbukkit.v1_19_R1.util.CraftNamespacedKey;
import org.bukkit.entity.Player;
import javax.annotation.Nullable;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.OptionalInt;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
IDelegateBukkitImplAdapter<net.minecraft.nbt.Tag> {
private static final Logger LOGGER = LogManagerCompat.getLogger();
private static Method CHUNK_HOLDER_WAS_ACCESSIBLE_SINCE_LAST_SAVE;
static {
try {
CHUNK_HOLDER_WAS_ACCESSIBLE_SINCE_LAST_SAVE = ChunkHolder.class.getDeclaredMethod("wasAccessibleSinceLastSave");
} catch (NoSuchMethodException ignored) { // may not be present in newer paper versions
}
}
private final PaperweightAdapter parent;
// ------------------------------------------------------------------------
// Code that may break between versions of Minecraft
// ------------------------------------------------------------------------
private final PaperweightMapChunkUtil mapUtil = new PaperweightMapChunkUtil();
private char[] ibdToStateOrdinal = null;
private int[] ordinalToIbdID = null;
private boolean initialised = false;
private Map<String, List<Property<?>>> allBlockProperties = null;
public PaperweightFaweAdapter() throws NoSuchFieldException, NoSuchMethodException {
this.parent = new PaperweightAdapter();
}
@Nullable
private static String getEntityId(Entity entity) {
ResourceLocation resourceLocation = net.minecraft.world.entity.EntityType.getKey(entity.getType());
return resourceLocation == null ? null : resourceLocation.toString();
}
private static void readEntityIntoTag(Entity entity, net.minecraft.nbt.CompoundTag compoundTag) {
entity.save(compoundTag);
}
@Override
public BukkitImplAdapter<net.minecraft.nbt.Tag> getParent() {
return parent;
}
private synchronized boolean init() {
if (ibdToStateOrdinal != null && ibdToStateOrdinal[1] != 0) {
return false;
}
ibdToStateOrdinal = new char[BlockTypesCache.states.length]; // size
ordinalToIbdID = new int[ibdToStateOrdinal.length]; // size
for (int i = 0; i < ibdToStateOrdinal.length; i++) {
BlockState blockState = BlockTypesCache.states[i];
PaperweightBlockMaterial material = (PaperweightBlockMaterial) blockState.getMaterial();
int id = Block.BLOCK_STATE_REGISTRY.getId(material.getState());
char ordinal = blockState.getOrdinalChar();
ibdToStateOrdinal[id] = ordinal;
ordinalToIbdID[ordinal] = id;
}
Map<String, List<Property<?>>> properties = new HashMap<>();
try {
for (Field field : BlockStateProperties.class.getDeclaredFields()) {
Object obj = field.get(null);
if (!(obj instanceof net.minecraft.world.level.block.state.properties.Property<?> state)) {
continue;
}
Property<?> property;
if (state instanceof net.minecraft.world.level.block.state.properties.BooleanProperty) {
property = new BooleanProperty(
state.getName(),
(List<Boolean>) ImmutableList.copyOf(state.getPossibleValues())
);
} else if (state instanceof DirectionProperty) {
property = new DirectionalProperty(
state.getName(),
state
.getPossibleValues()
.stream()
.map(e -> Direction.valueOf(((StringRepresentable) e).getSerializedName().toUpperCase()))
.collect(Collectors.toList())
);
} else if (state instanceof net.minecraft.world.level.block.state.properties.EnumProperty) {
property = new EnumProperty(
state.getName(),
state
.getPossibleValues()
.stream()
.map(e -> ((StringRepresentable) e).getSerializedName())
.collect(Collectors.toList())
);
} else if (state instanceof net.minecraft.world.level.block.state.properties.IntegerProperty) {
property = new IntegerProperty(
state.getName(),
(List<Integer>) ImmutableList.copyOf(state.getPossibleValues())
);
} else {
throw new IllegalArgumentException("FastAsyncWorldEdit needs an update to support " + state
.getClass()
.getSimpleName());
}
properties.compute(property.getName().toLowerCase(Locale.ROOT), (k, v) -> {
if (v == null) {
v = new ArrayList<>(Collections.singletonList(property));
} else {
v.add(property);
}
return v;
});
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} finally {
allBlockProperties = ImmutableMap.copyOf(properties);
}
initialised = true;
return true;
}
@Override
public BlockMaterial getMaterial(BlockType blockType) {
Block block = getBlock(blockType);
return new PaperweightBlockMaterial(block);
}
@Override
public synchronized BlockMaterial getMaterial(BlockState state) {
net.minecraft.world.level.block.state.BlockState blockState = ((CraftBlockData) Bukkit.createBlockData(state.getAsString())).getState();
return new PaperweightBlockMaterial(blockState.getBlock(), blockState);
}
public Block getBlock(BlockType blockType) {
return Registry.BLOCK.get(new ResourceLocation(blockType.getNamespace(), blockType.getResource()));
}
@Deprecated
@Override
public BlockState getBlock(Location location) {
Preconditions.checkNotNull(location);
CraftWorld craftWorld = ((CraftWorld) location.getWorld());
int x = location.getBlockX();
int y = location.getBlockY();
int z = location.getBlockZ();
final ServerLevel handle = craftWorld.getHandle();
LevelChunk chunk = handle.getChunk(x >> 4, z >> 4);
final BlockPos blockPos = new BlockPos(x, y, z);
final net.minecraft.world.level.block.state.BlockState blockData = chunk.getBlockState(blockPos);
BlockState state = adapt(blockData);
if (state == null) {
org.bukkit.block.Block bukkitBlock = location.getBlock();
state = BukkitAdapter.adapt(bukkitBlock.getBlockData());
}
return state;
}
@Override
public BaseBlock getFullBlock(final Location location) {
Preconditions.checkNotNull(location);
CraftWorld craftWorld = ((CraftWorld) location.getWorld());
int x = location.getBlockX();
int y = location.getBlockY();
int z = location.getBlockZ();
final ServerLevel handle = craftWorld.getHandle();
LevelChunk chunk = handle.getChunk(x >> 4, z >> 4);
final BlockPos blockPos = new BlockPos(x, y, z);
final net.minecraft.world.level.block.state.BlockState blockData = chunk.getBlockState(blockPos);
BlockState state = adapt(blockData);
if (state == null) {
org.bukkit.block.Block bukkitBlock = location.getBlock();
state = BukkitAdapter.adapt(bukkitBlock.getBlockData());
}
if (state.getBlockType().getMaterial().hasContainer()) {
// Read the NBT data
BlockEntity blockEntity = chunk.getBlockEntity(blockPos, LevelChunk.EntityCreationType.CHECK);
if (blockEntity != null) {
net.minecraft.nbt.CompoundTag tag = blockEntity.saveWithId();
return state.toBaseBlock((CompoundBinaryTag) toNativeBinary(tag));
}
}
return state.toBaseBlock();
}
@Override
public Set<SideEffect> getSupportedSideEffects() {
return SideEffectSet.defaults().getSideEffectsToApply();
}
public boolean setBlock(org.bukkit.Chunk chunk, int x, int y, int z, BlockStateHolder state, boolean update) {
CraftChunk craftChunk = (CraftChunk) chunk;
LevelChunk levelChunk = craftChunk.getHandle();
Level level = levelChunk.getLevel();
BlockPos blockPos = new BlockPos(x, y, z);
net.minecraft.world.level.block.state.BlockState blockState = ((PaperweightBlockMaterial) state.getMaterial()).getState();
LevelChunkSection[] levelChunkSections = levelChunk.getSections();
int y4 = y >> 4;
LevelChunkSection section = levelChunkSections[y4];
net.minecraft.world.level.block.state.BlockState existing;
if (section == null) {
existing = ((PaperweightBlockMaterial) BlockTypes.AIR.getDefaultState().getMaterial()).getState();
} else {
existing = section.getBlockState(x & 15, y & 15, z & 15);
}
levelChunk.removeBlockEntity(blockPos); // Force delete the old tile entity
CompoundBinaryTag compoundTag = state instanceof BaseBlock ? state.getNbt() : null;
if (compoundTag != null || existing instanceof TileEntityBlock) {
level.setBlock(blockPos, blockState, 0);
// remove tile
if (compoundTag != null) {
// We will assume that the tile entity was created for us,
// though we do not do this on the Forge version
BlockEntity blockEntity = level.getBlockEntity(blockPos);
if (blockEntity != null) {
net.minecraft.nbt.CompoundTag tag = (net.minecraft.nbt.CompoundTag) fromNativeBinary(compoundTag);
tag.put("x", IntTag.valueOf(x));
tag.put("y", IntTag.valueOf(y));
tag.put("z", IntTag.valueOf(z));
blockEntity.load(tag); // readTagIntoTileEntity - load data
}
}
} else {
if (existing == blockState) {
return true;
}
levelChunk.setBlockState(blockPos, blockState, false);
}
if (update) {
level.getMinecraftWorld().sendBlockUpdated(blockPos, existing, blockState, 0);
}
return true;
}
@Override
public WorldNativeAccess<?, ?, ?> createWorldNativeAccess(org.bukkit.World world) {
return new PaperweightFaweWorldNativeAccess(
this,
new WeakReference<>(((CraftWorld) world).getHandle())
);
}
@Override
public BaseEntity getEntity(org.bukkit.entity.Entity entity) {
Preconditions.checkNotNull(entity);
CraftEntity craftEntity = ((CraftEntity) entity);
Entity mcEntity = craftEntity.getHandle();
String id = getEntityId(mcEntity);
if (id != null) {
EntityType type = com.sk89q.worldedit.world.entity.EntityTypes.get(id);
Supplier<CompoundBinaryTag> saveTag = () -> {
final net.minecraft.nbt.CompoundTag minecraftTag = new net.minecraft.nbt.CompoundTag();
readEntityIntoTag(mcEntity, minecraftTag);
//add Id for AbstractChangeSet to work
final CompoundBinaryTag tag = (CompoundBinaryTag) toNativeBinary(minecraftTag);
final Map<String, BinaryTag> tags = NbtUtils.getCompoundBinaryTagValues(tag);
tags.put("Id", StringBinaryTag.of(id));
return CompoundBinaryTag.from(tags);
};
return new LazyBaseEntity(type, saveTag);
} else {
return null;
}
}
@Override
public Component getRichBlockName(BlockType blockType) {
return parent.getRichBlockName(blockType);
}
@Override
public Component getRichItemName(ItemType itemType) {
return parent.getRichItemName(itemType);
}
@Override
public Component getRichItemName(BaseItemStack itemStack) {
return parent.getRichItemName(itemStack);
}
@Override
public OptionalInt getInternalBlockStateId(BlockState state) {
PaperweightBlockMaterial material = (PaperweightBlockMaterial) state.getMaterial();
net.minecraft.world.level.block.state.BlockState mcState = material.getCraftBlockData().getState();
return OptionalInt.of(Block.BLOCK_STATE_REGISTRY.getId(mcState));
}
@Override
public BlockState adapt(BlockData blockData) {
CraftBlockData cbd = ((CraftBlockData) blockData);
net.minecraft.world.level.block.state.BlockState ibd = cbd.getState();
return adapt(ibd);
}
public BlockState adapt(net.minecraft.world.level.block.state.BlockState blockState) {
return BlockTypesCache.states[adaptToChar(blockState)];
}
public char adaptToChar(net.minecraft.world.level.block.state.BlockState blockState) {
int id = Block.BLOCK_STATE_REGISTRY.getId(blockState);
if (initialised) {
return ibdToStateOrdinal[id];
}
synchronized (this) {
if (initialised) {
return ibdToStateOrdinal[id];
}
try {
init();
return ibdToStateOrdinal[id];
} catch (ArrayIndexOutOfBoundsException e1) {
LOGGER.error("Attempted to convert {} with ID {} to char. ibdToStateOrdinal length: {}. Defaulting to air!",
blockState.getBlock(), Block.BLOCK_STATE_REGISTRY.getId(blockState), ibdToStateOrdinal.length, e1
);
return BlockTypesCache.ReservedIDs.AIR;
}
}
}
public char ibdIDToOrdinal(int id) {
if (initialised) {
return ibdToStateOrdinal[id];
}
synchronized (this) {
if (initialised) {
return ibdToStateOrdinal[id];
}
init();
return ibdToStateOrdinal[id];
}
}
@Override
public char[] getIbdToStateOrdinal() {
if (initialised) {
return ibdToStateOrdinal;
}
synchronized (this) {
if (initialised) {
return ibdToStateOrdinal;
}
init();
return ibdToStateOrdinal;
}
}
public int ordinalToIbdID(char ordinal) {
if (initialised) {
return ordinalToIbdID[ordinal];
}
synchronized (this) {
if (initialised) {
return ordinalToIbdID[ordinal];
}
init();
return ordinalToIbdID[ordinal];
}
}
@Override
public int[] getOrdinalToIbdID() {
if (initialised) {
return ordinalToIbdID;
}
synchronized (this) {
if (initialised) {
return ordinalToIbdID;
}
init();
return ordinalToIbdID;
}
}
@Override
public <B extends BlockStateHolder<B>> BlockData adapt(B state) {
PaperweightBlockMaterial material = (PaperweightBlockMaterial) state.getMaterial();
return material.getCraftBlockData();
}
@Override
public void sendFakeChunk(org.bukkit.World world, Player player, ChunkPacket chunkPacket) {
ServerLevel nmsWorld = ((CraftWorld) world).getHandle();
ChunkHolder map = PaperweightPlatformAdapter.getPlayerChunk(nmsWorld, chunkPacket.getChunkX(), chunkPacket.getChunkZ());
if (map != null && wasAccessibleSinceLastSave(map)) {
boolean flag = false;
// PlayerChunk.d players = map.players;
Stream<ServerPlayer> stream = /*players.a(new ChunkCoordIntPair(packet.getChunkX(), packet.getChunkZ()), flag)
*/ Stream.empty();
ServerPlayer checkPlayer = player == null ? null : ((CraftPlayer) player).getHandle();
stream.filter(entityPlayer -> checkPlayer == null || entityPlayer == checkPlayer)
.forEach(entityPlayer -> {
synchronized (chunkPacket) {
ClientboundLevelChunkWithLightPacket nmsPacket = (ClientboundLevelChunkWithLightPacket) chunkPacket.getNativePacket();
if (nmsPacket == null) {
nmsPacket = mapUtil.create(this, chunkPacket);
chunkPacket.setNativePacket(nmsPacket);
}
try {
FaweCache.INSTANCE.CHUNK_FLAG.get().set(true);
entityPlayer.connection.send(nmsPacket);
} finally {
FaweCache.INSTANCE.CHUNK_FLAG.get().set(false);
}
}
});
}
}
@Override
public Map<String, ? extends Property<?>> getProperties(BlockType blockType) {
return getParent().getProperties(blockType);
}
@Override
public boolean canPlaceAt(org.bukkit.World world, BlockVector3 blockVector3, BlockState blockState) {
int internalId = BlockStateIdAccess.getBlockStateId(blockState);
net.minecraft.world.level.block.state.BlockState blockState1 = Block.stateById(internalId);
return blockState1.hasPostProcess(
((CraftWorld) world).getHandle(),
new BlockPos(blockVector3.getX(), blockVector3.getY(), blockVector3.getZ())
);
}
@Override
public org.bukkit.inventory.ItemStack adapt(BaseItemStack baseItemStack) {
ItemStack stack = new ItemStack(
Registry.ITEM.get(ResourceLocation.tryParse(baseItemStack.getType().getId())),
baseItemStack.getAmount()
);
stack.setTag(((net.minecraft.nbt.CompoundTag) fromNative(baseItemStack.getNbtData())));
return CraftItemStack.asCraftMirror(stack);
}
@Override
public boolean generateTree(
TreeGenerator.TreeType treeType, EditSession editSession, BlockVector3 blockVector3,
org.bukkit.World bukkitWorld
) {
TreeType bukkitType = BukkitWorld.toBukkitTreeType(treeType);
if (bukkitType == TreeType.CHORUS_PLANT) {
blockVector3 = blockVector3.add(
0,
1,
0
); // bukkit skips the feature gen which does this offset normally, so we have to add it back
}
ServerLevel serverLevel = ((CraftWorld) bukkitWorld).getHandle();
final BlockVector3 finalBlockVector = blockVector3;
// Sync to main thread to ensure no clashes occur
Map<BlockPos, CraftBlockState> placed = TaskManager.taskManager().sync(() -> {
serverLevel.captureTreeGeneration = true;
serverLevel.captureBlockStates = true;
try {
if (!bukkitWorld.generateTree(BukkitAdapter.adapt(bukkitWorld, finalBlockVector), bukkitType)) {
return null;
}
return ImmutableMap.copyOf(serverLevel.capturedBlockStates);
} finally {
serverLevel.captureBlockStates = false;
serverLevel.captureTreeGeneration = false;
serverLevel.capturedBlockStates.clear();
}
});
if (placed == null || placed.isEmpty()) {
return false;
}
for (CraftBlockState craftBlockState : placed.values()) {
if (craftBlockState == null || craftBlockState.getType() == Material.AIR) {
continue;
}
editSession.setBlock(craftBlockState.getX(), craftBlockState.getY(), craftBlockState.getZ(),
BukkitAdapter.adapt(((org.bukkit.block.BlockState) craftBlockState).getBlockData())
);
}
return true;
}
@Override
public BaseItemStack adapt(org.bukkit.inventory.ItemStack itemStack) {
final ItemStack nmsStack = CraftItemStack.asNMSCopy(itemStack);
final BaseItemStack weStack = new BaseItemStack(BukkitAdapter.asItemType(itemStack.getType()), itemStack.getAmount());
weStack.setNbt(((CompoundBinaryTag) toNativeBinary(nmsStack.getTag())));
return weStack;
}
@Override
public Tag toNative(net.minecraft.nbt.Tag foreign) {
return parent.toNative(foreign);
}
@Override
public net.minecraft.nbt.Tag fromNative(Tag foreign) {
if (foreign instanceof PaperweightLazyCompoundTag) {
return ((PaperweightLazyCompoundTag) foreign).get();
}
return parent.fromNative(foreign);
}
@Override
public boolean regenerate(org.bukkit.World bukkitWorld, Region region, Extent target, RegenOptions options) throws Exception {
return new PaperweightRegen(bukkitWorld, region, target, options).regenerate();
}
@Override
public IChunkGet get(org.bukkit.World world, int chunkX, int chunkZ) {
return new PaperweightGetBlocks(world, chunkX, chunkZ);
}
@Override
public int getInternalBiomeId(BiomeType biomeType) {
final Registry<Biome> registry = MinecraftServer
.getServer()
.registryAccess()
.ownedRegistryOrThrow(Registry.BIOME_REGISTRY);
ResourceLocation resourceLocation = ResourceLocation.tryParse(biomeType.getId());
Biome biome = registry.get(resourceLocation);
return registry.getId(biome);
}
@Override
public Iterable<NamespacedKey> getRegisteredBiomes() {
WritableRegistry<Biome> biomeRegistry = (WritableRegistry<Biome>) ((CraftServer) Bukkit.getServer())
.getServer()
.registryAccess()
.ownedRegistryOrThrow(
Registry.BIOME_REGISTRY);
List<ResourceLocation> keys = biomeRegistry.stream()
.map(biomeRegistry::getKey).filter(Objects::nonNull).toList();
List<NamespacedKey> namespacedKeys = new ArrayList<>();
for (ResourceLocation key : keys) {
try {
namespacedKeys.add(CraftNamespacedKey.fromMinecraft(key));
} catch (IllegalArgumentException e) {
LOGGER.error("Error converting biome key {}", key.toString(), e);
}
}
return namespacedKeys;
}
@Override
public RelighterFactory getRelighterFactory() {
if (PaperLib.isPaper()) {
return new PaperweightStarlightRelighterFactory();
} else {
return new NMSRelighterFactory();
}
}
@Override
public Map<String, List<Property<?>>> getAllProperties() {
if (initialised) {
return allBlockProperties;
}
synchronized (this) {
if (initialised) {
return allBlockProperties;
}
init();
return allBlockProperties;
}
}
@Override
public IBatchProcessor getTickingPostProcessor() {
return new PaperweightPostProcessor();
}
private boolean wasAccessibleSinceLastSave(ChunkHolder holder) {
if (!PaperLib.isPaper() || !PaperweightPlatformAdapter.POST_CHUNK_REWRITE) {
try {
return (boolean) CHUNK_HOLDER_WAS_ACCESSIBLE_SINCE_LAST_SAVE.invoke(holder);
} catch (IllegalAccessException | InvocationTargetException ignored) {
// fall-through
}
}
// Papers new chunk system has no related replacement - therefor we assume true.
return true;
}
}

Datei anzeigen

@ -0,0 +1,286 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R1;
import com.fastasyncworldedit.core.Fawe;
import com.fastasyncworldedit.core.math.IntPair;
import com.fastasyncworldedit.core.util.TaskManager;
import com.fastasyncworldedit.core.util.task.RunnableVal;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.internal.block.BlockStateIdAccess;
import com.sk89q.worldedit.internal.wna.WorldNativeAccess;
import com.sk89q.worldedit.util.SideEffect;
import com.sk89q.worldedit.util.SideEffectSet;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.world.block.BlockState;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ChunkHolder;
import net.minecraft.server.level.ServerChunkCache;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.chunk.LevelChunk;
import org.bukkit.craftbukkit.v1_19_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_19_R1.block.data.CraftBlockData;
import org.bukkit.event.block.BlockPhysicsEvent;
import javax.annotation.Nullable;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
public class PaperweightFaweWorldNativeAccess implements WorldNativeAccess<LevelChunk,
net.minecraft.world.level.block.state.BlockState, BlockPos> {
private static final int UPDATE = 1;
private static final int NOTIFY = 2;
private static final Direction[] NEIGHBOUR_ORDER = {
Direction.EAST,
Direction.WEST,
Direction.DOWN,
Direction.UP,
Direction.NORTH,
Direction.SOUTH
};
private final PaperweightFaweAdapter paperweightFaweAdapter;
private final WeakReference<Level> level;
private final AtomicInteger lastTick;
private final Set<CachedChange> cachedChanges = new HashSet<>();
private final Set<IntPair> cachedChunksToSend = new HashSet<>();
private SideEffectSet sideEffectSet;
public PaperweightFaweWorldNativeAccess(PaperweightFaweAdapter paperweightFaweAdapter, WeakReference<Level> level) {
this.paperweightFaweAdapter = paperweightFaweAdapter;
this.level = level;
// Use the actual tick as minecraft-defined so we don't try to force blocks into the world when the server's already lagging.
// - With the caveat that we don't want to have too many cached changed (1024) so we'd flush those at 1024 anyway.
this.lastTick = new AtomicInteger(MinecraftServer.currentTick);
}
private Level getLevel() {
return Objects.requireNonNull(level.get(), "The reference to the world was lost");
}
@Override
public void setCurrentSideEffectSet(SideEffectSet sideEffectSet) {
this.sideEffectSet = sideEffectSet;
}
@Override
public LevelChunk getChunk(int x, int z) {
return getLevel().getChunk(x, z);
}
@Override
public net.minecraft.world.level.block.state.BlockState toNative(BlockState blockState) {
int stateId = paperweightFaweAdapter.ordinalToIbdID(blockState.getOrdinalChar());
return BlockStateIdAccess.isValidInternalId(stateId)
? Block.stateById(stateId)
: ((CraftBlockData) BukkitAdapter.adapt(blockState)).getState();
}
@Override
public net.minecraft.world.level.block.state.BlockState getBlockState(LevelChunk levelChunk, BlockPos blockPos) {
return levelChunk.getBlockState(blockPos);
}
@Nullable
@Override
public synchronized net.minecraft.world.level.block.state.BlockState setBlockState(
LevelChunk levelChunk, BlockPos blockPos,
net.minecraft.world.level.block.state.BlockState blockState
) {
int currentTick = MinecraftServer.currentTick;
if (Fawe.isMainThread()) {
return levelChunk.setBlockState(blockPos, blockState,
this.sideEffectSet != null && this.sideEffectSet.shouldApply(SideEffect.UPDATE)
);
}
// Since FAWE is.. Async we need to do it on the main thread (wooooo.. :( )
cachedChanges.add(new CachedChange(levelChunk, blockPos, blockState));
cachedChunksToSend.add(new IntPair(levelChunk.bukkitChunk.getX(), levelChunk.bukkitChunk.getZ()));
boolean nextTick = lastTick.get() > currentTick;
if (nextTick || cachedChanges.size() >= 1024) {
if (nextTick) {
lastTick.set(currentTick);
}
flushAsync(nextTick);
}
return blockState;
}
@Override
public net.minecraft.world.level.block.state.BlockState getValidBlockForPosition(
net.minecraft.world.level.block.state.BlockState blockState,
BlockPos blockPos
) {
return Block.updateFromNeighbourShapes(blockState, getLevel(), blockPos);
}
@Override
public BlockPos getPosition(int x, int y, int z) {
return new BlockPos(x, y, z);
}
@Override
public void updateLightingForBlock(BlockPos blockPos) {
getLevel().getChunkSource().getLightEngine().checkBlock(blockPos);
}
@Override
public boolean updateTileEntity(BlockPos blockPos, CompoundBinaryTag tag) {
// We will assume that the tile entity was created for us,
// though we do not do this on the other versions
BlockEntity blockEntity = getLevel().getBlockEntity(blockPos);
if (blockEntity == null) {
return false;
}
net.minecraft.nbt.Tag nativeTag = paperweightFaweAdapter.fromNativeBinary(tag);
blockEntity.load((CompoundTag) nativeTag);
return true;
}
@Override
public void notifyBlockUpdate(
LevelChunk levelChunk, BlockPos blockPos,
net.minecraft.world.level.block.state.BlockState oldState,
net.minecraft.world.level.block.state.BlockState newState
) {
if (levelChunk.getSections()[level.get().getSectionIndex(blockPos.getY())] != null) {
getLevel().sendBlockUpdated(blockPos, oldState, newState, UPDATE | NOTIFY);
}
}
@Override
public boolean isChunkTicking(LevelChunk levelChunk) {
return levelChunk.getFullStatus().isOrAfter(ChunkHolder.FullChunkStatus.TICKING);
}
@Override
public void markBlockChanged(LevelChunk levelChunk, BlockPos blockPos) {
if (levelChunk.getSections()[level.get().getSectionIndex(blockPos.getY())] != null) {
((ServerChunkCache) getLevel().getChunkSource()).blockChanged(blockPos);
}
}
@Override
public void notifyNeighbors(
BlockPos blockPos,
net.minecraft.world.level.block.state.BlockState oldState,
net.minecraft.world.level.block.state.BlockState newState
) {
Level level = getLevel();
if (sideEffectSet.shouldApply(SideEffect.EVENTS)) {
level.blockUpdated(blockPos, oldState.getBlock());
} else {
// When we don't want events, manually run the physics without them.
// Un-nest neighbour updating
for (Direction direction : NEIGHBOUR_ORDER) {
BlockPos shifted = blockPos.relative(direction);
level.getBlockState(shifted).neighborChanged(level, shifted, oldState.getBlock(), blockPos, false);
}
}
if (newState.hasAnalogOutputSignal()) {
level.updateNeighbourForOutputSignal(blockPos, newState.getBlock());
}
}
@Override
public void updateNeighbors(
BlockPos blockPos,
net.minecraft.world.level.block.state.BlockState oldState,
net.minecraft.world.level.block.state.BlockState newState,
int recursionLimit
) {
Level level = getLevel();
// a == updateNeighbors
// b == updateDiagonalNeighbors
oldState.updateIndirectNeighbourShapes(level, blockPos, NOTIFY, recursionLimit);
if (sideEffectSet.shouldApply(SideEffect.EVENTS)) {
CraftWorld craftWorld = level.getWorld();
if (craftWorld != null) {
BlockPhysicsEvent event = new BlockPhysicsEvent(
craftWorld.getBlockAt(blockPos.getX(), blockPos.getY(), blockPos.getZ()),
CraftBlockData.fromData(newState)
);
level.getCraftServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
}
}
newState.triggerEvent(level, blockPos, NOTIFY, recursionLimit);
newState.updateIndirectNeighbourShapes(level, blockPos, NOTIFY, recursionLimit);
}
@Override
public void onBlockStateChange(
BlockPos blockPos,
net.minecraft.world.level.block.state.BlockState oldState,
net.minecraft.world.level.block.state.BlockState newState
) {
getLevel().onBlockStateChange(blockPos, oldState, newState);
}
private synchronized void flushAsync(final boolean sendChunks) {
final Set<CachedChange> changes = Set.copyOf(cachedChanges);
cachedChanges.clear();
final Set<IntPair> toSend;
if (sendChunks) {
toSend = Set.copyOf(cachedChunksToSend);
cachedChunksToSend.clear();
} else {
toSend = Collections.emptySet();
}
RunnableVal<Object> runnableVal = new RunnableVal<>() {
@Override
public void run(Object value) {
changes.forEach(cc -> cc.levelChunk.setBlockState(cc.blockPos, cc.blockState,
sideEffectSet != null && sideEffectSet.shouldApply(SideEffect.UPDATE)
));
if (!sendChunks) {
return;
}
for (IntPair chunk : toSend) {
PaperweightPlatformAdapter.sendChunk(getLevel().getWorld().getHandle(), chunk.x(), chunk.z(), false);
}
}
};
TaskManager.taskManager().async(() -> TaskManager.taskManager().sync(runnableVal));
}
@Override
public synchronized void flush() {
RunnableVal<Object> runnableVal = new RunnableVal<>() {
@Override
public void run(Object value) {
cachedChanges.forEach(cc -> cc.levelChunk.setBlockState(cc.blockPos, cc.blockState,
sideEffectSet != null && sideEffectSet.shouldApply(SideEffect.UPDATE)
));
for (IntPair chunk : cachedChunksToSend) {
PaperweightPlatformAdapter.sendChunk(getLevel().getWorld().getHandle(), chunk.x(), chunk.z(), false);
}
}
};
if (Fawe.isMainThread()) {
runnableVal.run();
} else {
TaskManager.taskManager().sync(runnableVal);
}
cachedChanges.clear();
cachedChunksToSend.clear();
}
private record CachedChange(
LevelChunk levelChunk,
BlockPos blockPos,
net.minecraft.world.level.block.state.BlockState blockState
) {
}
}

Datei anzeigen

@ -0,0 +1,248 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R1;
import com.fastasyncworldedit.core.extent.processor.heightmap.HeightMapType;
import com.fastasyncworldedit.core.queue.IBlocks;
import com.fastasyncworldedit.core.queue.IChunkGet;
import com.fastasyncworldedit.core.queue.IChunkSet;
import com.google.common.base.Suppliers;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter;
import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R1.nbt.PaperweightLazyCompoundTag;
import com.sk89q.worldedit.internal.util.LogManagerCompat;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypesCache;
import net.minecraft.core.Holder;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.PalettedContainer;
import net.minecraft.world.level.chunk.PalettedContainerRO;
import org.apache.logging.log4j.Logger;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Future;
public class PaperweightGetBlocks_Copy implements IChunkGet {
private static final Logger LOGGER = LogManagerCompat.getLogger();
private final Map<BlockVector3, CompoundTag> tiles = new HashMap<>();
private final Set<CompoundTag> entities = new HashSet<>();
private final char[][] blocks;
private final int minHeight;
private final int maxHeight;
final ServerLevel serverLevel;
final LevelChunk levelChunk;
private PalettedContainer<Holder<Biome>>[] biomes = null;
protected PaperweightGetBlocks_Copy(LevelChunk levelChunk) {
this.levelChunk = levelChunk;
this.serverLevel = levelChunk.level;
this.minHeight = serverLevel.getMinBuildHeight();
this.maxHeight = serverLevel.getMaxBuildHeight() - 1; // Minecraft max limit is exclusive.
this.blocks = new char[getSectionCount()][];
}
protected void storeTile(BlockEntity blockEntity) {
tiles.put(
BlockVector3.at(
blockEntity.getBlockPos().getX(),
blockEntity.getBlockPos().getY(),
blockEntity.getBlockPos().getZ()
),
new PaperweightLazyCompoundTag(Suppliers.memoize(blockEntity::saveWithId))
);
}
@Override
public Map<BlockVector3, CompoundTag> getTiles() {
return tiles;
}
@Override
@Nullable
public CompoundTag getTile(int x, int y, int z) {
return tiles.get(BlockVector3.at(x, y, z));
}
@SuppressWarnings({"unchecked", "rawtypes"})
protected void storeEntity(Entity entity) {
BukkitImplAdapter adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter();
net.minecraft.nbt.CompoundTag compoundTag = new net.minecraft.nbt.CompoundTag();
entity.save(compoundTag);
entities.add((CompoundTag) adapter.toNative(compoundTag));
}
@Override
public Set<CompoundTag> getEntities() {
return this.entities;
}
@Override
public CompoundTag getEntity(UUID uuid) {
for (CompoundTag tag : entities) {
if (uuid.equals(tag.getUUID())) {
return tag;
}
}
return null;
}
@Override
public boolean isCreateCopy() {
return false;
}
@Override
public void setCreateCopy(boolean createCopy) {
}
@Override
public void setLightingToGet(char[][] lighting, int minSectionPosition, int maxSectionPosition) {
}
@Override
public void setSkyLightingToGet(char[][] lighting, int minSectionPosition, int maxSectionPosition) {
}
@Override
public void setHeightmapToGet(HeightMapType type, int[] data) {
}
@Override
public int getMaxY() {
return maxHeight;
}
@Override
public int getMinY() {
return minHeight;
}
@Override
public int getMaxSectionPosition() {
return maxHeight >> 4;
}
@Override
public int getMinSectionPosition() {
return minHeight >> 4;
}
@Override
public BiomeType getBiomeType(int x, int y, int z) {
Holder<Biome> biome = biomes[(y >> 4) - getMinSectionPosition()].get(x >> 2, (y & 15) >> 2, z >> 2);
return PaperweightPlatformAdapter.adapt(biome, serverLevel);
}
@Override
public void removeSectionLighting(int layer, boolean sky) {
}
@Override
public boolean trim(boolean aggressive, int layer) {
return false;
}
@Override
public IBlocks reset() {
return null;
}
@Override
public int getSectionCount() {
return serverLevel.getSectionsCount();
}
protected void storeSection(int layer, char[] data) {
blocks[layer] = data;
}
protected void storeBiomes(int layer, PalettedContainerRO<Holder<Biome>> biomeData) {
if (biomes == null) {
biomes = new PalettedContainer[getSectionCount()];
}
if (biomeData instanceof PalettedContainer<Holder<Biome>> palettedContainer) {
biomes[layer] = palettedContainer.copy();
} else {
LOGGER.error(
"Cannot correctly save biomes to history. Expected class type {} but got {}",
PalettedContainer.class.getSimpleName(),
biomeData.getClass().getSimpleName()
);
}
}
@Override
public BaseBlock getFullBlock(int x, int y, int z) {
BlockState state = BlockTypesCache.states[get(x, y, z)];
return state.toBaseBlock(this, x, y, z);
}
@Override
public boolean hasSection(int layer) {
layer -= getMinSectionPosition();
return blocks[layer] != null;
}
@Override
public char[] load(int layer) {
layer -= getMinSectionPosition();
return blocks[layer];
}
@Override
public char[] loadIfPresent(int layer) {
layer -= getMinSectionPosition();
return blocks[layer];
}
@Override
public BlockState getBlock(int x, int y, int z) {
return BlockTypesCache.states[get(x, y, z)];
}
@Override
public int getSkyLight(int x, int y, int z) {
return 0;
}
@Override
public int getEmittedLight(int x, int y, int z) {
return 0;
}
@Override
public int[] getHeightMap(HeightMapType type) {
return new int[0];
}
@Override
public <T extends Future<T>> T call(IChunkSet set, Runnable finalize) {
return null;
}
public char get(int x, int y, int z) {
final int layer = (y >> 4) - getMinSectionPosition();
final int index = (y & 15) << 8 | z << 4 | x;
return blocks[layer][index];
}
@Override
public boolean trim(boolean aggressive) {
return false;
}
}

Datei anzeigen

@ -1,4 +1,4 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_18_R1; package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R1;
import com.fastasyncworldedit.bukkit.adapter.MapChunkUtil; import com.fastasyncworldedit.bukkit.adapter.MapChunkUtil;
import com.sk89q.worldedit.bukkit.adapter.Refraction; import com.sk89q.worldedit.bukkit.adapter.Refraction;

Datei anzeigen

@ -0,0 +1,703 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R1;
import com.destroystokyo.paper.util.maplist.EntityList;
import com.fastasyncworldedit.bukkit.adapter.CachedBukkitAdapter;
import com.fastasyncworldedit.bukkit.adapter.DelegateSemaphore;
import com.fastasyncworldedit.bukkit.adapter.NMSAdapter;
import com.fastasyncworldedit.core.Fawe;
import com.fastasyncworldedit.core.FaweCache;
import com.fastasyncworldedit.core.math.BitArrayUnstretched;
import com.fastasyncworldedit.core.util.MathMan;
import com.fastasyncworldedit.core.util.ReflectionUtils;
import com.fastasyncworldedit.core.util.TaskManager;
import com.mojang.datafixers.util.Either;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter;
import com.sk89q.worldedit.bukkit.adapter.Refraction;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypesCache;
import io.papermc.lib.PaperLib;
import io.papermc.paper.world.ChunkEntitySlices;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.IdMap;
import net.minecraft.core.Registry;
import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket;
import net.minecraft.server.level.ChunkHolder;
import net.minecraft.server.level.ChunkMap;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.level.TicketType;
import net.minecraft.util.BitStorage;
import net.minecraft.util.ExceptionCollector;
import net.minecraft.util.SimpleBitStorage;
import net.minecraft.util.ThreadingDetector;
import net.minecraft.util.Unit;
import net.minecraft.util.ZeroBitStorage;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.EntityBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.chunk.GlobalPalette;
import net.minecraft.world.level.chunk.HashMapPalette;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.LevelChunkSection;
import net.minecraft.world.level.chunk.LinearPalette;
import net.minecraft.world.level.chunk.Palette;
import net.minecraft.world.level.chunk.PalettedContainer;
import net.minecraft.world.level.chunk.SingleValuePalette;
import net.minecraft.world.level.entity.PersistentEntitySectionManager;
import net.minecraft.world.level.gameevent.GameEventDispatcher;
import net.minecraft.world.level.gameevent.GameEventListener;
import org.bukkit.craftbukkit.v1_19_R1.CraftChunk;
import sun.misc.Unsafe;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Semaphore;
import java.util.function.Function;
public final class PaperweightPlatformAdapter extends NMSAdapter {
public static final Field fieldData;
public static final Constructor<?> dataConstructor;
public static final Field fieldStorage;
public static final Field fieldPalette;
private static final Field fieldTickingFluidCount;
private static final Field fieldTickingBlockCount;
private static final Field fieldNonEmptyBlockCount;
private static final MethodHandle methodGetVisibleChunk;
private static final int CHUNKSECTION_BASE;
private static final int CHUNKSECTION_SHIFT;
private static final Field fieldThreadingDetector;
private static final long fieldThreadingDetectorOffset;
private static final Field fieldLock;
private static final long fieldLockOffset;
private static final MethodHandle methodRemoveGameEventListener;
private static final MethodHandle methodremoveTickingBlockEntity;
private static final Field fieldRemove;
static final boolean POST_CHUNK_REWRITE;
private static Method PAPER_CHUNK_GEN_ALL_ENTITIES;
private static Field LEVEL_CHUNK_ENTITIES;
private static Field SERVER_LEVEL_ENTITY_MANAGER;
static {
try {
fieldData = PalettedContainer.class.getDeclaredField(Refraction.pickName("data", "d"));
fieldData.setAccessible(true);
Class<?> dataClazz = fieldData.getType();
dataConstructor = dataClazz.getDeclaredConstructors()[0];
dataConstructor.setAccessible(true);
fieldStorage = dataClazz.getDeclaredField(Refraction.pickName("storage", "b"));
fieldStorage.setAccessible(true);
fieldPalette = dataClazz.getDeclaredField(Refraction.pickName("palette", "c"));
fieldPalette.setAccessible(true);
fieldTickingFluidCount = LevelChunkSection.class.getDeclaredField(Refraction.pickName("tickingFluidCount", "h"));
fieldTickingFluidCount.setAccessible(true);
fieldTickingBlockCount = LevelChunkSection.class.getDeclaredField(Refraction.pickName("tickingBlockCount", "g"));
fieldTickingBlockCount.setAccessible(true);
fieldNonEmptyBlockCount = LevelChunkSection.class.getDeclaredField(Refraction.pickName("nonEmptyBlockCount", "f"));
fieldNonEmptyBlockCount.setAccessible(true);
Method getVisibleChunkIfPresent = ChunkMap.class.getDeclaredMethod(Refraction.pickName(
"getVisibleChunkIfPresent",
"b"
), long.class);
getVisibleChunkIfPresent.setAccessible(true);
methodGetVisibleChunk = MethodHandles.lookup().unreflect(getVisibleChunkIfPresent);
Unsafe unsafe = ReflectionUtils.getUnsafe();
if (!PaperLib.isPaper()) {
fieldThreadingDetector = PalettedContainer.class.getDeclaredField(Refraction.pickName("threadingDetector", "f"));
fieldThreadingDetectorOffset = unsafe.objectFieldOffset(fieldThreadingDetector);
fieldLock = ThreadingDetector.class.getDeclaredField(Refraction.pickName("lock", "c"));
fieldLockOffset = unsafe.objectFieldOffset(fieldLock);
} else {
// in paper, the used methods are synchronized properly
fieldThreadingDetector = null;
fieldThreadingDetectorOffset = -1;
fieldLock = null;
fieldLockOffset = -1;
}
Method removeGameEventListener = LevelChunk.class.getDeclaredMethod(
Refraction.pickName("removeGameEventListener", "a"),
BlockEntity.class,
ServerLevel.class
);
removeGameEventListener.setAccessible(true);
methodRemoveGameEventListener = MethodHandles.lookup().unreflect(removeGameEventListener);
Method removeBlockEntityTicker = LevelChunk.class.getDeclaredMethod(
Refraction.pickName(
"removeBlockEntityTicker",
"l"
), BlockPos.class
);
removeBlockEntityTicker.setAccessible(true);
methodremoveTickingBlockEntity = MethodHandles.lookup().unreflect(removeBlockEntityTicker);
fieldRemove = BlockEntity.class.getDeclaredField(Refraction.pickName("remove", "p"));
fieldRemove.setAccessible(true);
CHUNKSECTION_BASE = unsafe.arrayBaseOffset(LevelChunkSection[].class);
int scale = unsafe.arrayIndexScale(LevelChunkSection[].class);
if ((scale & (scale - 1)) != 0) {
throw new Error("data type scale not a power of two");
}
CHUNKSECTION_SHIFT = 31 - Integer.numberOfLeadingZeros(scale);
boolean chunkRewrite;
try {
ServerLevel.class.getDeclaredMethod("getEntityLookup");
chunkRewrite = true;
PAPER_CHUNK_GEN_ALL_ENTITIES = ChunkEntitySlices.class.getDeclaredMethod("getAllEntities");
PAPER_CHUNK_GEN_ALL_ENTITIES.setAccessible(true);
} catch (NoSuchMethodException ignored) {
chunkRewrite = false;
}
try {
// Paper - Pre-Chunk-Update
LEVEL_CHUNK_ENTITIES = LevelChunk.class.getDeclaredField("entities");
LEVEL_CHUNK_ENTITIES.setAccessible(true);
} catch (NoSuchFieldException ignored) {
}
try {
// Non-Paper
SERVER_LEVEL_ENTITY_MANAGER = ServerLevel.class.getDeclaredField(Refraction.pickName("entityManager", "P"));
SERVER_LEVEL_ENTITY_MANAGER.setAccessible(true);
} catch (NoSuchFieldException ignored) {
}
POST_CHUNK_REWRITE = chunkRewrite;
} catch (RuntimeException e) {
throw e;
} catch (Throwable rethrow) {
rethrow.printStackTrace();
throw new RuntimeException(rethrow);
}
}
static boolean setSectionAtomic(
LevelChunkSection[] sections,
LevelChunkSection expected,
LevelChunkSection value,
int layer
) {
long offset = ((long) layer << CHUNKSECTION_SHIFT) + CHUNKSECTION_BASE;
if (layer >= 0 && layer < sections.length) {
return ReflectionUtils.getUnsafe().compareAndSwapObject(sections, offset, expected, value);
}
return false;
}
// There is no point in having a functional semaphore for paper servers.
private static final ThreadLocal<DelegateSemaphore> SEMAPHORE_THREAD_LOCAL =
ThreadLocal.withInitial(() -> new DelegateSemaphore(1, null));
static DelegateSemaphore applyLock(LevelChunkSection section) {
if (PaperLib.isPaper()) {
return SEMAPHORE_THREAD_LOCAL.get();
}
try {
synchronized (section) {
Unsafe unsafe = ReflectionUtils.getUnsafe();
PalettedContainer<net.minecraft.world.level.block.state.BlockState> blocks = section.getStates();
ThreadingDetector currentThreadingDetector = (ThreadingDetector) unsafe.getObject(
blocks,
fieldThreadingDetectorOffset
);
synchronized (currentThreadingDetector) {
Semaphore currentLock = (Semaphore) unsafe.getObject(currentThreadingDetector, fieldLockOffset);
if (currentLock instanceof DelegateSemaphore delegateSemaphore) {
return delegateSemaphore;
}
DelegateSemaphore newLock = new DelegateSemaphore(1, currentLock);
unsafe.putObject(currentThreadingDetector, fieldLockOffset, newLock);
return newLock;
}
}
} catch (Throwable e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static LevelChunk ensureLoaded(ServerLevel serverLevel, int chunkX, int chunkZ) {
if (!PaperLib.isPaper()) {
LevelChunk nmsChunk = serverLevel.getChunkSource().getChunk(chunkX, chunkZ, false);
if (nmsChunk != null) {
return nmsChunk;
}
if (Fawe.isMainThread()) {
return serverLevel.getChunk(chunkX, chunkZ);
}
} else {
LevelChunk nmsChunk = serverLevel.getChunkSource().getChunkAtIfCachedImmediately(chunkX, chunkZ);
if (nmsChunk != null) {
addTicket(serverLevel, chunkX, chunkZ);
return nmsChunk;
}
nmsChunk = serverLevel.getChunkSource().getChunkAtIfLoadedImmediately(chunkX, chunkZ);
if (nmsChunk != null) {
addTicket(serverLevel, chunkX, chunkZ);
return nmsChunk;
}
// Avoid "async" methods from the main thread.
if (Fawe.isMainThread()) {
return serverLevel.getChunk(chunkX, chunkZ);
}
CompletableFuture<org.bukkit.Chunk> future = serverLevel.getWorld().getChunkAtAsync(chunkX, chunkZ, true, true);
try {
CraftChunk chunk = (CraftChunk) future.get();
return chunk.getHandle();
} catch (Throwable e) {
e.printStackTrace();
}
}
return TaskManager.taskManager().sync(() -> serverLevel.getChunk(chunkX, chunkZ));
}
private static void addTicket(ServerLevel serverLevel, int chunkX, int chunkZ) {
// Ensure chunk is definitely loaded before applying a ticket
io.papermc.paper.util.MCUtil.MAIN_EXECUTOR.execute(() -> serverLevel
.getChunkSource()
.addRegionTicket(TicketType.PLUGIN, new ChunkPos(chunkX, chunkZ), 0, Unit.INSTANCE));
}
public static ChunkHolder getPlayerChunk(ServerLevel nmsWorld, final int chunkX, final int chunkZ) {
ChunkMap chunkMap = nmsWorld.getChunkSource().chunkMap;
try {
return (ChunkHolder) methodGetVisibleChunk.invoke(chunkMap, ChunkPos.asLong(chunkX, chunkZ));
} catch (Throwable thr) {
throw new RuntimeException(thr);
}
}
@SuppressWarnings("deprecation")
public static void sendChunk(ServerLevel nmsWorld, int chunkX, int chunkZ, boolean lighting) {
ChunkHolder chunkHolder = getPlayerChunk(nmsWorld, chunkX, chunkZ);
if (chunkHolder == null) {
return;
}
ChunkPos coordIntPair = new ChunkPos(chunkX, chunkZ);
LevelChunk levelChunk;
if (PaperLib.isPaper()) {
// getChunkAtIfLoadedImmediately is paper only
levelChunk = nmsWorld
.getChunkSource()
.getChunkAtIfLoadedImmediately(chunkX, chunkZ);
} else {
levelChunk = ((Optional<LevelChunk>) ((Either) chunkHolder
.getTickingChunkFuture() // method is not present with new paper chunk system
.getNow(ChunkHolder.UNLOADED_LEVEL_CHUNK)).left())
.orElse(null);
}
if (levelChunk == null) {
return;
}
TaskManager.taskManager().task(() -> {
ClientboundLevelChunkWithLightPacket packet;
if (PaperLib.isPaper()) {
packet = new ClientboundLevelChunkWithLightPacket(
levelChunk,
nmsWorld.getChunkSource().getLightEngine(),
null,
null,
true,
false // last false is to not bother with x-ray
);
} else {
// deprecated on paper - deprecation suppressed
packet = new ClientboundLevelChunkWithLightPacket(
levelChunk,
nmsWorld.getChunkSource().getLightEngine(),
null,
null,
true
);
}
nearbyPlayers(nmsWorld, coordIntPair).forEach(p -> p.connection.send(packet));
});
}
private static List<ServerPlayer> nearbyPlayers(ServerLevel serverLevel, ChunkPos coordIntPair) {
return serverLevel.getChunkSource().chunkMap.getPlayers(coordIntPair, false);
}
/*
NMS conversion
*/
public static LevelChunkSection newChunkSection(
final int layer,
final char[] blocks,
CachedBukkitAdapter adapter,
Registry<Biome> biomeRegistry,
@Nullable PalettedContainer<Holder<Biome>> biomes
) {
return newChunkSection(layer, null, blocks, adapter, biomeRegistry, biomes);
}
public static LevelChunkSection newChunkSection(
final int layer,
final Function<Integer, char[]> get,
char[] set,
CachedBukkitAdapter adapter,
Registry<Biome> biomeRegistry,
@Nullable PalettedContainer<Holder<Biome>> biomes
) {
if (set == null) {
return newChunkSection(layer, biomeRegistry, biomes);
}
final int[] blockToPalette = FaweCache.INSTANCE.BLOCK_TO_PALETTE.get();
final int[] paletteToBlock = FaweCache.INSTANCE.PALETTE_TO_BLOCK.get();
final long[] blockStates = FaweCache.INSTANCE.BLOCK_STATES.get();
final int[] blocksCopy = FaweCache.INSTANCE.SECTION_BLOCKS.get();
try {
int num_palette;
if (get == null) {
num_palette = createPalette(blockToPalette, paletteToBlock, blocksCopy, set, adapter, null);
} else {
num_palette = createPalette(layer, blockToPalette, paletteToBlock, blocksCopy, get, set, adapter, null);
}
int bitsPerEntry = MathMan.log2nlz(num_palette - 1);
if (bitsPerEntry > 0 && bitsPerEntry < 5) {
bitsPerEntry = 4;
} else if (bitsPerEntry > 8) {
bitsPerEntry = MathMan.log2nlz(Block.BLOCK_STATE_REGISTRY.size() - 1);
}
int bitsPerEntryNonZero = Math.max(bitsPerEntry, 1); // We do want to use zero sometimes
final int blocksPerLong = MathMan.floorZero((double) 64 / bitsPerEntryNonZero);
final int blockBitArrayEnd = MathMan.ceilZero((float) 4096 / blocksPerLong);
if (num_palette == 1) {
for (int i = 0; i < blockBitArrayEnd; i++) {
blockStates[i] = 0;
}
} else {
final BitArrayUnstretched bitArray = new BitArrayUnstretched(bitsPerEntryNonZero, 4096, blockStates);
bitArray.fromRaw(blocksCopy);
}
final long[] bits = Arrays.copyOfRange(blockStates, 0, blockBitArrayEnd);
final BitStorage nmsBits;
if (bitsPerEntry == 0) {
nmsBits = new ZeroBitStorage(4096);
} else {
nmsBits = new SimpleBitStorage(bitsPerEntry, 4096, bits);
}
List<net.minecraft.world.level.block.state.BlockState> palette;
if (bitsPerEntry < 9) {
palette = new ArrayList<>();
for (int i = 0; i < num_palette; i++) {
int ordinal = paletteToBlock[i];
blockToPalette[ordinal] = Integer.MAX_VALUE;
final BlockState state = BlockTypesCache.states[ordinal];
palette.add(((PaperweightBlockMaterial) state.getMaterial()).getState());
}
} else {
palette = List.of();
}
// Create palette with data
@SuppressWarnings("deprecation") // constructor is deprecated on paper, but needed to keep compatibility with spigot
final PalettedContainer<net.minecraft.world.level.block.state.BlockState> blockStatePalettedContainer =
new PalettedContainer<>(
Block.BLOCK_STATE_REGISTRY,
PalettedContainer.Strategy.SECTION_STATES,
PalettedContainer.Strategy.SECTION_STATES.getConfiguration(Block.BLOCK_STATE_REGISTRY, bitsPerEntry),
nmsBits,
palette
);
if (biomes == null) {
IdMap<Holder<Biome>> biomeHolderIdMap = biomeRegistry.asHolderIdMap();
biomes = new PalettedContainer<>(
biomeHolderIdMap,
biomeHolderIdMap.byIdOrThrow(WorldEditPlugin
.getInstance()
.getBukkitImplAdapter()
.getInternalBiomeId(
BiomeTypes.PLAINS)),
PalettedContainer.Strategy.SECTION_BIOMES,
null
);
}
return new LevelChunkSection(layer, blockStatePalettedContainer, biomes);
} catch (final Throwable e) {
throw e;
} finally {
Arrays.fill(blockToPalette, Integer.MAX_VALUE);
Arrays.fill(paletteToBlock, Integer.MAX_VALUE);
Arrays.fill(blockStates, 0);
Arrays.fill(blocksCopy, 0);
}
}
@SuppressWarnings("deprecation") // Only deprecated in paper
private static LevelChunkSection newChunkSection(
int layer,
Registry<Biome> biomeRegistry,
@Nullable PalettedContainer<Holder<Biome>> biomes
) {
if (biomes == null) {
return new LevelChunkSection(layer, biomeRegistry);
}
PalettedContainer<net.minecraft.world.level.block.state.BlockState> dataPaletteBlocks = new PalettedContainer<>(
Block.BLOCK_STATE_REGISTRY,
Blocks.AIR.defaultBlockState(),
PalettedContainer.Strategy.SECTION_STATES,
null
);
return new LevelChunkSection(layer, dataPaletteBlocks, biomes);
}
/**
* Create a new {@link PalettedContainer<Biome>}. Should only be used if no biome container existed beforehand.
*/
public static PalettedContainer<Holder<Biome>> getBiomePalettedContainer(
BiomeType[] biomes,
IdMap<Holder<Biome>> biomeRegistry
) {
if (biomes == null) {
return null;
}
BukkitImplAdapter<?> adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter();
// Don't stream this as typically will see 1-4 biomes; stream overhead is large for the small length
Map<BiomeType, Holder<Biome>> palette = new HashMap<>();
for (BiomeType biomeType : new LinkedList<>(Arrays.asList(biomes))) {
Holder<Biome> biome;
if (biomeType == null) {
biome = biomeRegistry.byId(adapter.getInternalBiomeId(BiomeTypes.PLAINS));
} else {
biome = biomeRegistry.byId(adapter.getInternalBiomeId(biomeType));
}
palette.put(biomeType, biome);
}
int biomeCount = palette.size();
int bitsPerEntry = MathMan.log2nlz(biomeCount - 1);
Object configuration = PalettedContainer.Strategy.SECTION_STATES.getConfiguration(
new FakeIdMapBiome(biomeCount),
bitsPerEntry
);
if (bitsPerEntry > 3) {
bitsPerEntry = MathMan.log2nlz(biomeRegistry.size() - 1);
}
PalettedContainer<Holder<Biome>> biomePalettedContainer = new PalettedContainer<>(
biomeRegistry,
biomeRegistry.byIdOrThrow(adapter.getInternalBiomeId(BiomeTypes.PLAINS)),
PalettedContainer.Strategy.SECTION_BIOMES,
null
);
final Palette<Holder<Biome>> biomePalette;
if (bitsPerEntry == 0) {
biomePalette = new SingleValuePalette<>(
biomePalettedContainer.registry,
biomePalettedContainer,
new ArrayList<>(palette.values()) // Must be modifiable
);
} else if (bitsPerEntry == 4) {
biomePalette = LinearPalette.create(
4,
biomePalettedContainer.registry,
biomePalettedContainer,
new ArrayList<>(palette.values()) // Must be modifiable
);
} else if (bitsPerEntry < 9) {
biomePalette = HashMapPalette.create(
bitsPerEntry,
biomePalettedContainer.registry,
biomePalettedContainer,
new ArrayList<>(palette.values()) // Must be modifiable
);
} else {
biomePalette = GlobalPalette.create(
bitsPerEntry,
biomePalettedContainer.registry,
biomePalettedContainer,
null // unused
);
}
int bitsPerEntryNonZero = Math.max(bitsPerEntry, 1); // We do want to use zero sometimes
final int blocksPerLong = MathMan.floorZero((double) 64 / bitsPerEntryNonZero);
final int arrayLength = MathMan.ceilZero(64f / blocksPerLong);
BitStorage bitStorage = bitsPerEntry == 0 ? new ZeroBitStorage(64) : new SimpleBitStorage(
bitsPerEntry,
64,
new long[arrayLength]
);
try {
Object data = dataConstructor.newInstance(configuration, bitStorage, biomePalette);
fieldData.set(biomePalettedContainer, data);
int index = 0;
for (int y = 0; y < 4; y++) {
for (int z = 0; z < 4; z++) {
for (int x = 0; x < 4; x++, index++) {
BiomeType biomeType = biomes[index];
if (biomeType == null) {
continue;
}
Holder<Biome> biome = biomeRegistry.byId(WorldEditPlugin
.getInstance()
.getBukkitImplAdapter()
.getInternalBiomeId(biomeType));
if (biome == null) {
continue;
}
biomePalettedContainer.set(x, y, z, biome);
}
}
}
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
return biomePalettedContainer;
}
public static void clearCounts(final LevelChunkSection section) throws IllegalAccessException {
fieldTickingFluidCount.setShort(section, (short) 0);
fieldTickingBlockCount.setShort(section, (short) 0);
}
public static BiomeType adapt(Holder<Biome> biome, LevelAccessor levelAccessor) {
final Registry<Biome> biomeRegistry = levelAccessor.registryAccess().ownedRegistryOrThrow(Registry.BIOME_REGISTRY);
if (biomeRegistry.getKey(biome.value()) == null) {
return biomeRegistry.asHolderIdMap().getId(biome) == -1 ? BiomeTypes.OCEAN
: null;
}
return BiomeTypes.get(biome.unwrapKey().orElseThrow().location().toString());
}
static void removeBeacon(BlockEntity beacon, LevelChunk levelChunk) {
try {
if (levelChunk.loaded || levelChunk.level.isClientSide()) {
BlockEntity blockEntity = levelChunk.blockEntities.remove(beacon.getBlockPos());
if (blockEntity != null) {
if (!levelChunk.level.isClientSide) {
methodRemoveGameEventListener.invoke(levelChunk, beacon, levelChunk.level);
}
fieldRemove.set(beacon, true);
}
}
methodremoveTickingBlockEntity.invoke(levelChunk, beacon.getBlockPos());
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
static List<Entity> getEntities(LevelChunk chunk) {
ExceptionCollector<RuntimeException> collector = new ExceptionCollector<>();
if (PaperLib.isPaper()) {
if (POST_CHUNK_REWRITE) {
try {
//noinspection unchecked
return (List<Entity>) PAPER_CHUNK_GEN_ALL_ENTITIES.invoke(chunk.level.getEntityLookup().getChunk(chunk.locX, chunk.locZ));
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException("Failed to lookup entities [POST_CHUNK_REWRITE=true]", e);
}
}
try {
EntityList entityList = (EntityList) LEVEL_CHUNK_ENTITIES.get(chunk);
return List.of(entityList.getRawData());
} catch (IllegalAccessException e) {
collector.add(new RuntimeException("Failed to lookup entities [POST_CHUNK_REWRITE=false]", e));
// fall through
}
}
try {
//noinspection unchecked
return ((PersistentEntitySectionManager<Entity>) (SERVER_LEVEL_ENTITY_MANAGER.get(chunk.level))).getEntities(chunk.getPos());
} catch (IllegalAccessException e) {
collector.add(new RuntimeException("Failed to lookup entities [PAPER=false]", e));
}
collector.throwIfPresent();
return List.of();
}
record FakeIdMapBlock(int size) implements IdMap<net.minecraft.world.level.block.state.BlockState> {
@Override
public int getId(final net.minecraft.world.level.block.state.BlockState entry) {
return 0;
}
@Nullable
@Override
public net.minecraft.world.level.block.state.BlockState byId(final int index) {
return null;
}
@Nonnull
@Override
public Iterator<net.minecraft.world.level.block.state.BlockState> iterator() {
return Collections.emptyIterator();
}
}
record FakeIdMapBiome(int size) implements IdMap<Biome> {
@Override
public int getId(final Biome entry) {
return 0;
}
@Nullable
@Override
public Biome byId(final int index) {
return null;
}
@Nonnull
@Override
public Iterator<Biome> iterator() {
return Collections.emptyIterator();
}
}
}

Datei anzeigen

@ -0,0 +1,175 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R1;
import com.fastasyncworldedit.core.configuration.Settings;
import com.fastasyncworldedit.core.extent.processor.ProcessorScope;
import com.fastasyncworldedit.core.queue.IBatchProcessor;
import com.fastasyncworldedit.core.queue.IChunk;
import com.fastasyncworldedit.core.queue.IChunkGet;
import com.fastasyncworldedit.core.queue.IChunkSet;
import com.fastasyncworldedit.core.registry.state.PropertyKey;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldedit.world.block.BlockTypesCache;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.Fluids;
import javax.annotation.Nullable;
public class PaperweightPostProcessor implements IBatchProcessor {
@Override
public IChunkSet processSet(final IChunk chunk, final IChunkGet get, final IChunkSet set) {
return set;
}
@SuppressWarnings("deprecation")
@Override
public void postProcess(final IChunk chunk, final IChunkGet iChunkGet, final IChunkSet iChunkSet) {
boolean tickFluid = Settings.settings().EXPERIMENTAL.ALLOW_TICK_FLUIDS;
// The PostProcessor shouldn't be added, but just in case
if (!tickFluid) {
return;
}
PaperweightGetBlocks_Copy getBlocks = (PaperweightGetBlocks_Copy) iChunkGet;
layer:
for (int layer = iChunkSet.getMinSectionPosition(); layer <= iChunkSet.getMaxSectionPosition(); layer++) {
char[] set = iChunkSet.loadIfPresent(layer);
if (set == null) {
// No edit means no need to process
continue;
}
char[] get = null;
for (int i = 0; i < 4096; i++) {
char ordinal = set[i];
char replacedOrdinal = BlockTypesCache.ReservedIDs.__RESERVED__;
boolean fromGet = false; // Used for liquids
if (ordinal == BlockTypesCache.ReservedIDs.__RESERVED__) {
if (get == null) {
get = getBlocks.load(layer);
}
// If this is null, then it's because we're loading a layer in the range of 0->15, but blocks aren't
// actually being set
if (get == null) {
continue layer;
}
fromGet = true;
ordinal = replacedOrdinal = get[i];
}
if (ordinal == BlockTypesCache.ReservedIDs.__RESERVED__) {
continue;
} else if (!fromGet) { // if fromGet, don't do the same again
if (get == null) {
get = getBlocks.load(layer);
}
replacedOrdinal = get[i];
}
boolean ticking = BlockTypesCache.ticking[ordinal];
boolean replacedWasTicking = BlockTypesCache.ticking[replacedOrdinal];
boolean replacedWasLiquid = false;
BlockState replacedState = null;
if (!ticking) {
// If the block being replaced was not ticking, it cannot be a liquid
if (!replacedWasTicking) {
continue;
}
// If the block being replaced is not fluid, we do not need to worry
if (!(replacedWasLiquid =
(replacedState = BlockState.getFromOrdinal(replacedOrdinal)).getMaterial().isLiquid())) {
continue;
}
}
BlockState state = BlockState.getFromOrdinal(ordinal);
boolean liquid = state.getMaterial().isLiquid();
int x = i & 15;
int y = (i >> 8) & 15;
int z = (i >> 4) & 15;
BlockPos position = new BlockPos((chunk.getX() << 4) + x, (layer << 4) + y, (chunk.getZ() << 4) + z);
if (liquid || replacedWasLiquid) {
if (liquid) {
addFluid(getBlocks.serverLevel, state, position);
continue;
}
// If the replaced fluid (is?) adjacent to water. Do not bother to check adjacent chunks(sections) as this
// may be time consuming. Chances are any fluid blocks in adjacent chunks are being replaced or will end up
// being ticked anyway. We only need it to be "hit" once.
if (!wasAdjacentToWater(get, set, i, x, y, z)) {
continue;
}
addFluid(getBlocks.serverLevel, replacedState, position);
}
}
}
}
@Nullable
@Override
public Extent construct(final Extent child) {
throw new UnsupportedOperationException("Processing only");
}
@Override
public ProcessorScope getScope() {
return ProcessorScope.READING_SET_BLOCKS;
}
private boolean wasAdjacentToWater(char[] get, char[] set, int i, int x, int y, int z) {
if (set == null || get == null) {
return false;
}
char ordinal;
char reserved = BlockTypesCache.ReservedIDs.__RESERVED__;
if (x > 0 && set[i - 1] != reserved) {
if (BlockTypesCache.ticking[(ordinal = get[i - 1])] && isFluid(ordinal)) {
return true;
}
}
if (x < 15 && set[i + 1] != reserved) {
if (BlockTypesCache.ticking[(ordinal = get[i + 1])] && isFluid(ordinal)) {
return true;
}
}
if (z > 0 && set[i - 16] != reserved) {
if (BlockTypesCache.ticking[(ordinal = get[i - 16])] && isFluid(ordinal)) {
return true;
}
}
if (z < 15 && set[i + 16] != reserved) {
if (BlockTypesCache.ticking[(ordinal = get[i + 16])] && isFluid(ordinal)) {
return true;
}
}
if (y > 0 && set[i - 256] != reserved) {
if (BlockTypesCache.ticking[(ordinal = get[i - 256])] && isFluid(ordinal)) {
return true;
}
}
if (y < 15 && set[i + 256] != reserved) {
return BlockTypesCache.ticking[(ordinal = get[i + 256])] && isFluid(ordinal);
}
return false;
}
@SuppressWarnings("deprecation")
private boolean isFluid(char ordinal) {
return BlockState.getFromOrdinal(ordinal).getMaterial().isLiquid();
}
@SuppressWarnings("deprecation")
private void addFluid(final ServerLevel serverLevel, final BlockState replacedState, final BlockPos position) {
Fluid type;
if (replacedState.getBlockType() == BlockTypes.LAVA) {
type = (int) replacedState.getState(PropertyKey.LEVEL) == 0 ? Fluids.LAVA : Fluids.FLOWING_LAVA;
} else {
type = (int) replacedState.getState(PropertyKey.LEVEL) == 0 ? Fluids.WATER : Fluids.FLOWING_WATER;
}
serverLevel.scheduleTick(
position,
type,
type.getTickDelay(serverLevel)
);
}
}

Datei anzeigen

@ -0,0 +1,205 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R1;
import com.fastasyncworldedit.core.configuration.Settings;
import com.fastasyncworldedit.core.extent.processor.lighting.NMSRelighter;
import com.fastasyncworldedit.core.extent.processor.lighting.Relighter;
import com.fastasyncworldedit.core.queue.IQueueChunk;
import com.fastasyncworldedit.core.queue.IQueueExtent;
import com.fastasyncworldedit.core.util.MathMan;
import com.fastasyncworldedit.core.util.TaskManager;
import com.sk89q.worldedit.internal.util.LogManagerCompat;
import it.unimi.dsi.fastutil.longs.Long2ObjectLinkedOpenHashMap;
import it.unimi.dsi.fastutil.longs.LongArraySet;
import it.unimi.dsi.fastutil.longs.LongIterator;
import it.unimi.dsi.fastutil.longs.LongSet;
import net.minecraft.server.level.ChunkMap;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.TicketType;
import net.minecraft.util.Unit;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.chunk.ChunkStatus;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
public class PaperweightStarlightRelighter implements Relighter {
private static final Logger LOGGER = LogManagerCompat.getLogger();
private static final int CHUNKS_PER_BATCH = 1024; // 32 * 32
private static final int CHUNKS_PER_BATCH_SQRT_LOG2 = 5; // for shifting
private static final TicketType<Unit> FAWE_TICKET = TicketType.create("fawe_ticket", (a, b) -> 0);
private static final int LIGHT_LEVEL = ChunkMap.MAX_VIEW_DISTANCE + ChunkStatus.getDistance(ChunkStatus.LIGHT);
private final ServerLevel serverLevel;
private final ReentrantLock lock = new ReentrantLock();
private final Long2ObjectLinkedOpenHashMap<LongSet> regions = new Long2ObjectLinkedOpenHashMap<>();
private final ReentrantLock areaLock = new ReentrantLock();
private final NMSRelighter delegate;
@SuppressWarnings("rawtypes")
public PaperweightStarlightRelighter(ServerLevel serverLevel, IQueueExtent<IQueueChunk> queue) {
this.serverLevel = serverLevel;
this.delegate = new NMSRelighter(queue);
}
@Override
public boolean addChunk(int cx, int cz, byte[] skipReason, int bitmask) {
areaLock.lock();
try {
long key = MathMan.pairInt(cx >> CHUNKS_PER_BATCH_SQRT_LOG2, cz >> CHUNKS_PER_BATCH_SQRT_LOG2);
// TODO probably submit here already if chunks.size == CHUNKS_PER_BATCH?
LongSet chunks = this.regions.computeIfAbsent(key, k -> new LongArraySet(CHUNKS_PER_BATCH >> 2));
chunks.add(ChunkPos.asLong(cx, cz));
} finally {
areaLock.unlock();
}
return true;
}
@Override
public void addLightUpdate(int x, int y, int z) {
delegate.addLightUpdate(x, y, z);
}
/*
* This method is called "recursively", iterating and removing elements
* from the regions linked map. This way, chunks are loaded in batches to avoid
* OOMEs.
*/
@Override
public void fixLightingSafe(boolean sky) {
this.areaLock.lock();
try {
if (regions.isEmpty()) {
return;
}
LongSet first = regions.removeFirst();
fixLighting(first, () -> fixLightingSafe(true));
} finally {
this.areaLock.unlock();
}
}
/*
* Processes a set of chunks and runs an action afterwards.
* The action is run async, the chunks are partly processed on the main thread
* (as required by the server).
*/
private void fixLighting(LongSet chunks, Runnable andThen) {
// convert from long keys to ChunkPos
Set<ChunkPos> coords = new HashSet<>();
LongIterator iterator = chunks.iterator();
while (iterator.hasNext()) {
coords.add(new ChunkPos(iterator.nextLong()));
}
TaskManager.taskManager().task(() -> {
// trigger chunk load and apply ticket on main thread
List<CompletableFuture<?>> futures = new ArrayList<>();
for (ChunkPos pos : coords) {
futures.add(serverLevel.getWorld().getChunkAtAsync(pos.x, pos.z)
.thenAccept(c -> serverLevel.getChunkSource().addTicketAtLevel(
FAWE_TICKET,
pos,
LIGHT_LEVEL,
Unit.INSTANCE
))
);
}
// collect futures and trigger relight once all chunks are loaded
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).thenAccept(v ->
invokeRelight(
coords,
c -> {
}, // no callback for single chunks required
i -> {
if (i != coords.size()) {
LOGGER.warn("Processed {} chunks instead of {}", i, coords.size());
}
// post process chunks on main thread
TaskManager.taskManager().task(() -> postProcessChunks(coords));
// call callback on our own threads
TaskManager.taskManager().async(andThen);
}
)
);
});
}
private void invokeRelight(
Set<ChunkPos> coords,
Consumer<ChunkPos> chunkCallback,
IntConsumer processCallback
) {
try {
serverLevel.getChunkSource().getLightEngine().relight(coords, chunkCallback, processCallback);
} catch (Exception e) {
LOGGER.error("Error occurred on relighting", e);
}
}
/*
* Allow the server to unload the chunks again.
* Also, if chunk packets are sent delayed, we need to do that here
*/
private void postProcessChunks(Set<ChunkPos> coords) {
boolean delay = Settings.settings().LIGHTING.DELAY_PACKET_SENDING;
for (ChunkPos pos : coords) {
int x = pos.x;
int z = pos.z;
if (delay) { // we still need to send the block changes of that chunk
PaperweightPlatformAdapter.sendChunk(serverLevel, x, z, false);
}
serverLevel.getChunkSource().removeTicketAtLevel(FAWE_TICKET, pos, LIGHT_LEVEL, Unit.INSTANCE);
}
}
@Override
public void clear() {
}
@Override
public void removeLighting() {
this.delegate.removeLighting();
}
@Override
public void fixBlockLighting() {
fixLightingSafe(true);
}
@Override
public void fixSkyLighting() {
fixLightingSafe(true);
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public ReentrantLock getLock() {
return this.lock;
}
@Override
public boolean isFinished() {
return false;
}
@Override
public void close() throws Exception {
fixLightingSafe(true);
}
}

Datei anzeigen

@ -0,0 +1,28 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R1;
import com.fastasyncworldedit.core.extent.processor.lighting.NullRelighter;
import com.fastasyncworldedit.core.extent.processor.lighting.RelightMode;
import com.fastasyncworldedit.core.extent.processor.lighting.Relighter;
import com.fastasyncworldedit.core.extent.processor.lighting.RelighterFactory;
import com.fastasyncworldedit.core.queue.IQueueChunk;
import com.fastasyncworldedit.core.queue.IQueueExtent;
import com.sk89q.worldedit.world.World;
import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_19_R1.CraftWorld;
import javax.annotation.Nonnull;
public class PaperweightStarlightRelighterFactory implements RelighterFactory {
@Override
public @Nonnull
@SuppressWarnings("rawtypes")
Relighter createRelighter(RelightMode relightMode, World world, IQueueExtent<IQueueChunk> queue) {
org.bukkit.World w = Bukkit.getWorld(world.getName());
if (w == null) {
return NullRelighter.INSTANCE;
}
return new PaperweightStarlightRelighter(((CraftWorld) w).getHandle(), queue);
}
}

Datei anzeigen

@ -0,0 +1,161 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R1.nbt;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.LazyCompoundTag;
import com.sk89q.jnbt.ListTag;
import com.sk89q.jnbt.StringTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import net.minecraft.nbt.NumericTag;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
public class PaperweightLazyCompoundTag extends LazyCompoundTag {
private final Supplier<net.minecraft.nbt.CompoundTag> compoundTagSupplier;
private CompoundTag compoundTag;
public PaperweightLazyCompoundTag(Supplier<net.minecraft.nbt.CompoundTag> compoundTagSupplier) {
super(new HashMap<>());
this.compoundTagSupplier = compoundTagSupplier;
}
public PaperweightLazyCompoundTag(net.minecraft.nbt.CompoundTag compoundTag) {
this(() -> compoundTag);
}
public net.minecraft.nbt.CompoundTag get() {
return compoundTagSupplier.get();
}
@Override
@SuppressWarnings("unchecked")
public Map<String, Tag> getValue() {
if (compoundTag == null) {
compoundTag = (CompoundTag) WorldEditPlugin.getInstance().getBukkitImplAdapter().toNative(compoundTagSupplier.get());
}
return compoundTag.getValue();
}
@Override
public CompoundBinaryTag asBinaryTag() {
getValue();
return compoundTag.asBinaryTag();
}
public boolean containsKey(String key) {
return compoundTagSupplier.get().contains(key);
}
public byte[] getByteArray(String key) {
return compoundTagSupplier.get().getByteArray(key);
}
public byte getByte(String key) {
return compoundTagSupplier.get().getByte(key);
}
public double getDouble(String key) {
return compoundTagSupplier.get().getDouble(key);
}
public double asDouble(String key) {
net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key);
if (tag instanceof NumericTag numTag) {
return numTag.getAsDouble();
}
return 0;
}
public float getFloat(String key) {
return compoundTagSupplier.get().getFloat(key);
}
public int[] getIntArray(String key) {
return compoundTagSupplier.get().getIntArray(key);
}
public int getInt(String key) {
return compoundTagSupplier.get().getInt(key);
}
public int asInt(String key) {
net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key);
if (tag instanceof NumericTag numTag) {
return numTag.getAsInt();
}
return 0;
}
@SuppressWarnings("unchecked")
public List<Tag> getList(String key) {
net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key);
if (tag instanceof net.minecraft.nbt.ListTag nbtList) {
ArrayList<Tag> list = new ArrayList<>();
for (net.minecraft.nbt.Tag elem : nbtList) {
if (elem instanceof net.minecraft.nbt.CompoundTag compoundTag) {
list.add(new PaperweightLazyCompoundTag(compoundTag));
} else {
list.add(WorldEditPlugin.getInstance().getBukkitImplAdapter().toNative(elem));
}
}
return list;
}
return Collections.emptyList();
}
@SuppressWarnings("unchecked")
public ListTag getListTag(String key) {
net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key);
if (tag instanceof net.minecraft.nbt.ListTag) {
return (ListTag) WorldEditPlugin.getInstance().getBukkitImplAdapter().toNative(tag);
}
return new ListTag(StringTag.class, Collections.emptyList());
}
@SuppressWarnings("unchecked")
public <T extends Tag> List<T> getList(String key, Class<T> listType) {
ListTag listTag = getListTag(key);
if (listTag.getType().equals(listType)) {
return (List<T>) listTag.getValue();
} else {
return Collections.emptyList();
}
}
public long[] getLongArray(String key) {
return compoundTagSupplier.get().getLongArray(key);
}
public long getLong(String key) {
return compoundTagSupplier.get().getLong(key);
}
public long asLong(String key) {
net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key);
if (tag instanceof NumericTag numTag) {
return numTag.getAsLong();
}
return 0;
}
public short getShort(String key) {
return compoundTagSupplier.get().getShort(key);
}
public String getString(String key) {
return compoundTagSupplier.get().getString(key);
}
@Override
public String toString() {
return compoundTagSupplier.get().toString();
}
}

Datei anzeigen

@ -0,0 +1,564 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R1.regen;
import com.fastasyncworldedit.bukkit.adapter.Regenerator;
import com.fastasyncworldedit.core.Fawe;
import com.fastasyncworldedit.core.queue.IChunkCache;
import com.fastasyncworldedit.core.queue.IChunkGet;
import com.fastasyncworldedit.core.util.ReflectionUtils;
import com.fastasyncworldedit.core.util.TaskManager;
import com.google.common.collect.ImmutableList;
import com.mojang.datafixers.util.Either;
import com.mojang.serialization.Lifecycle;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.adapter.Refraction;
import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R1.PaperweightGetBlocks;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.internal.util.LogManagerCompat;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.io.file.SafeFiles;
import com.sk89q.worldedit.world.RegenOptions;
import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.data.BuiltinRegistries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ChunkTaskPriorityQueueSorter.Message;
import net.minecraft.server.level.ServerChunkCache;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ThreadedLevelLightEngine;
import net.minecraft.server.level.progress.ChunkProgressListener;
import net.minecraft.util.thread.ProcessorHandle;
import net.minecraft.util.thread.ProcessorMailbox;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelHeightAccessor;
import net.minecraft.world.level.LevelSettings;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeSource;
import net.minecraft.world.level.biome.FixedBiomeSource;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.chunk.ChunkStatus;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.ProtoChunk;
import net.minecraft.world.level.chunk.UpgradeData;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.levelgen.FlatLevelSource;
import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import net.minecraft.world.level.levelgen.WorldGenSettings;
import net.minecraft.world.level.levelgen.blending.BlendingData;
import net.minecraft.world.level.levelgen.flat.FlatLevelGeneratorSettings;
import net.minecraft.world.level.levelgen.structure.placement.ConcentricRingsStructurePlacement;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.PrimaryLevelData;
import org.apache.logging.log4j.Logger;
import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_19_R1.CraftServer;
import org.bukkit.craftbukkit.v1_19_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_19_R1.generator.CustomChunkGenerator;
import org.bukkit.generator.BiomeProvider;
import org.bukkit.generator.BlockPopulator;
import javax.annotation.Nullable;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.file.Path;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.OptionalLong;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, LevelChunk, PaperweightRegen.ChunkStatusWrap> {
private static final Logger LOGGER = LogManagerCompat.getLogger();
private static final Field serverWorldsField;
private static final Field paperConfigField;
private static final Field flatBedrockField;
private static final Field generatorSettingFlatField;
private static final Field generatorSettingBaseSupplierField;
private static final Field delegateField;
private static final Field chunkSourceField;
private static final Field ringPositionsField;
private static final Field hasGeneratedPositionsField;
//list of chunk stati in correct order without FULL
private static final Map<ChunkStatus, Concurrency> chunkStati = new LinkedHashMap<>();
static {
chunkStati.put(ChunkStatus.EMPTY, Concurrency.FULL); // empty: radius -1, does nothing
chunkStati.put(ChunkStatus.STRUCTURE_STARTS, Concurrency.NONE); // structure starts: uses unsynchronized maps
chunkStati.put(
ChunkStatus.STRUCTURE_REFERENCES,
Concurrency.FULL
); // structure refs: radius 8, but only writes to current chunk
chunkStati.put(ChunkStatus.BIOMES, Concurrency.FULL); // biomes: radius 0
chunkStati.put(ChunkStatus.NOISE, Concurrency.RADIUS); // noise: radius 8
chunkStati.put(ChunkStatus.SURFACE, Concurrency.NONE); // surface: radius 0, requires NONE
chunkStati.put(ChunkStatus.CARVERS, Concurrency.NONE); // carvers: radius 0, but RADIUS and FULL change results
chunkStati.put(
ChunkStatus.LIQUID_CARVERS,
Concurrency.NONE
); // liquid carvers: radius 0, but RADIUS and FULL change results
chunkStati.put(ChunkStatus.FEATURES, Concurrency.NONE); // features: uses unsynchronized maps
chunkStati.put(
ChunkStatus.LIGHT,
Concurrency.FULL
); // light: radius 1, but no writes to other chunks, only current chunk
chunkStati.put(ChunkStatus.SPAWN, Concurrency.FULL); // spawn: radius 0
chunkStati.put(ChunkStatus.HEIGHTMAPS, Concurrency.FULL); // heightmaps: radius 0
try {
serverWorldsField = CraftServer.class.getDeclaredField("worlds");
serverWorldsField.setAccessible(true);
Field tmpPaperConfigField;
Field tmpFlatBedrockField;
try { //only present on paper
tmpPaperConfigField = Level.class.getDeclaredField("paperConfig");
tmpPaperConfigField.setAccessible(true);
tmpFlatBedrockField = tmpPaperConfigField.getType().getDeclaredField("generateFlatBedrock");
tmpFlatBedrockField.setAccessible(true);
} catch (Exception e) {
tmpPaperConfigField = null;
tmpFlatBedrockField = null;
}
paperConfigField = tmpPaperConfigField;
flatBedrockField = tmpFlatBedrockField;
generatorSettingBaseSupplierField = NoiseBasedChunkGenerator.class.getDeclaredField(Refraction.pickName(
"settings", "g"));
generatorSettingBaseSupplierField.setAccessible(true);
generatorSettingFlatField = FlatLevelSource.class.getDeclaredField(Refraction.pickName("settings", "f"));
generatorSettingFlatField.setAccessible(true);
delegateField = CustomChunkGenerator.class.getDeclaredField("delegate");
delegateField.setAccessible(true);
chunkSourceField = ServerLevel.class.getDeclaredField(Refraction.pickName("chunkSource", "L"));
chunkSourceField.setAccessible(true);
ringPositionsField = ChunkGenerator.class.getDeclaredField(Refraction.pickName("ringPositions", "i"));
ringPositionsField.setAccessible(true);
hasGeneratedPositionsField = ChunkGenerator.class.getDeclaredField(Refraction.pickName("hasGeneratedPositions", "j"));
hasGeneratedPositionsField.setAccessible(true);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//runtime
private ServerLevel originalServerWorld;
private ServerChunkCache originalChunkProvider;
private ServerLevel freshWorld;
private ServerChunkCache freshChunkProvider;
private LevelStorageSource.LevelStorageAccess session;
private StructureTemplateManager structureTemplateManager;
private ThreadedLevelLightEngine threadedLevelLightEngine;
private ChunkGenerator chunkGenerator;
private Path tempDir;
private boolean generateFlatBedrock = false;
public PaperweightRegen(org.bukkit.World originalBukkitWorld, Region region, Extent target, RegenOptions options) {
super(originalBukkitWorld, region, target, options);
}
@Override
protected boolean prepare() {
this.originalServerWorld = ((CraftWorld) originalBukkitWorld).getHandle();
originalChunkProvider = originalServerWorld.getChunkSource();
if (!(originalChunkProvider instanceof ServerChunkCache)) {
return false;
}
//flat bedrock? (only on paper)
if (paperConfigField != null) {
try {
generateFlatBedrock = flatBedrockField.getBoolean(paperConfigField.get(originalServerWorld));
} catch (Exception ignored) {
}
}
seed = options.getSeed().orElse(originalServerWorld.getSeed());
chunkStati.forEach((s, c) -> super.chunkStati.put(new ChunkStatusWrap(s), c));
return true;
}
@Override
@SuppressWarnings("unchecked")
protected boolean initNewWorld() throws Exception {
//world folder
tempDir = java.nio.file.Files.createTempDirectory("FastAsyncWorldEditWorldGen");
//prepare for world init (see upstream implementation for reference)
org.bukkit.World.Environment environment = originalBukkitWorld.getEnvironment();
org.bukkit.generator.ChunkGenerator generator = originalBukkitWorld.getGenerator();
LevelStorageSource levelStorageSource = LevelStorageSource.createDefault(tempDir);
ResourceKey<LevelStem> levelStemResourceKey = getWorldDimKey(environment);
session = levelStorageSource.createAccess("faweregentempworld", levelStemResourceKey);
PrimaryLevelData originalWorldData = originalServerWorld.serverLevelData;
MinecraftServer server = originalServerWorld.getCraftServer().getServer();
WorldGenSettings originalOpts = originalWorldData.worldGenSettings();
WorldGenSettings newOpts = options.getSeed().isPresent()
? originalOpts.withSeed(originalWorldData.isHardcore(), OptionalLong.of(seed))
: originalOpts;
LevelSettings newWorldSettings = new LevelSettings(
"faweregentempworld",
originalWorldData.settings.gameType(),
originalWorldData.settings.hardcore(),
originalWorldData.settings.difficulty(),
originalWorldData.settings.allowCommands(),
originalWorldData.settings.gameRules(),
originalWorldData.settings.getDataPackConfig()
);
PrimaryLevelData newWorldData = new PrimaryLevelData(newWorldSettings, newOpts, Lifecycle.stable());
BiomeProvider biomeProvider = getBiomeProvider();
//init world
freshWorld = Fawe.instance().getQueueHandler().sync((Supplier<ServerLevel>) () -> new ServerLevel(
server,
server.executor,
session,
newWorldData,
originalServerWorld.dimension(),
newOpts.dimensions().getOrThrow(levelStemResourceKey),
new RegenNoOpWorldLoadListener(),
originalServerWorld.isDebug(),
seed,
ImmutableList.of(),
false,
environment,
generator,
biomeProvider
) {
private final Holder<Biome> singleBiome = options.hasBiomeType() ? BuiltinRegistries.BIOME.asHolderIdMap().byId(
WorldEditPlugin.getInstance().getBukkitImplAdapter().getInternalBiomeId(options.getBiomeType())
) : null;
@Override
public void tick(BooleanSupplier shouldKeepTicking) { //no ticking
}
@Override
public Holder<Biome> getUncachedNoiseBiome(int biomeX, int biomeY, int biomeZ) {
if (options.hasBiomeType()) {
return singleBiome;
}
return PaperweightRegen.this.chunkGenerator.getBiomeSource().getNoiseBiome(
biomeX, biomeY, biomeZ, getChunkSource().randomState().sampler()
);
}
}).get();
freshWorld.noSave = true;
removeWorldFromWorldsMap();
newWorldData.checkName(originalServerWorld.serverLevelData.getLevelName()); //rename to original world name
if (paperConfigField != null) {
paperConfigField.set(freshWorld, originalServerWorld.paperConfig());
}
ChunkGenerator originalGenerator = originalChunkProvider.getGenerator();
if (originalGenerator instanceof FlatLevelSource flatLevelSource) {
FlatLevelGeneratorSettings generatorSettingFlat = flatLevelSource.settings();
chunkGenerator = new FlatLevelSource(originalGenerator.structureSets, generatorSettingFlat);
} else if (originalGenerator instanceof NoiseBasedChunkGenerator noiseBasedChunkGenerator) {
Holder<NoiseGeneratorSettings> generatorSettingBaseSupplier = (Holder<NoiseGeneratorSettings>) generatorSettingBaseSupplierField.get(
originalGenerator);
BiomeSource biomeSource;
if (options.hasBiomeType()) {
biomeSource = new FixedBiomeSource(BuiltinRegistries.BIOME
.asHolderIdMap()
.byId(WorldEditPlugin.getInstance().getBukkitImplAdapter().getInternalBiomeId(options.getBiomeType())));
} else {
biomeSource = originalGenerator.getBiomeSource();
}
chunkGenerator = new NoiseBasedChunkGenerator(originalGenerator.structureSets,
noiseBasedChunkGenerator.noises,
biomeSource,
generatorSettingBaseSupplier
);
} else if (originalGenerator instanceof CustomChunkGenerator customChunkGenerator) {
chunkGenerator = customChunkGenerator.getDelegate();
} else {
LOGGER.error("Unsupported generator type {}", originalGenerator.getClass().getName());
return false;
}
if (generator != null) {
chunkGenerator = new CustomChunkGenerator(freshWorld, chunkGenerator, generator);
generateConcurrent = generator.isParallelCapable();
}
chunkGenerator.conf = freshWorld.spigotConfig;
if (seed == originalOpts.seed() && !options.hasBiomeType()) {
// Optimisation for needless ring position calculation when the seed and biome is the same.
boolean hasGeneratedPositions = hasGeneratedPositionsField.getBoolean(originalGenerator);
if (hasGeneratedPositions) {
Map<ConcentricRingsStructurePlacement, CompletableFuture<List<ChunkPos>>> ringPositions =
(Map<ConcentricRingsStructurePlacement, CompletableFuture<List<ChunkPos>>>) ringPositionsField.get(
originalGenerator);
Map<ConcentricRingsStructurePlacement, CompletableFuture<List<ChunkPos>>> copy = new Object2ObjectArrayMap<>(ringPositions);
ringPositionsField.set(chunkGenerator, copy);
hasGeneratedPositionsField.setBoolean(chunkGenerator, true);
}
}
freshChunkProvider = new ServerChunkCache(
freshWorld,
session,
server.getFixerUpper(),
server.getStructureManager(),
server.executor,
chunkGenerator,
freshWorld.spigotConfig.viewDistance,
freshWorld.spigotConfig.simulationDistance,
server.forceSynchronousWrites(),
new RegenNoOpWorldLoadListener(),
(chunkCoordIntPair, state) -> {
},
() -> server.overworld().getDataStorage()
) {
// redirect to LevelChunks created in #createChunks
@Override
public ChunkAccess getChunk(int x, int z, ChunkStatus chunkstatus, boolean create) {
ChunkAccess chunkAccess = getChunkAt(x, z);
if (chunkAccess == null && create) {
chunkAccess = createChunk(getProtoChunkAt(x, z));
}
return chunkAccess;
}
};
ReflectionUtils.unsafeSet(chunkSourceField, freshWorld, freshChunkProvider);
//let's start then
structureTemplateManager = server.getStructureManager();
threadedLevelLightEngine = new NoOpLightEngine(freshChunkProvider);
return true;
}
@Override
protected void cleanup() {
try {
session.close();
} catch (Exception ignored) {
}
//shutdown chunk provider
try {
Fawe.instance().getQueueHandler().sync(() -> {
try {
freshChunkProvider.close(false);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
} catch (Exception ignored) {
}
//remove world from server
try {
Fawe.instance().getQueueHandler().sync(this::removeWorldFromWorldsMap);
} catch (Exception ignored) {
}
//delete directory
try {
SafeFiles.tryHardToDeleteDir(tempDir);
} catch (Exception ignored) {
}
}
@Override
protected ProtoChunk createProtoChunk(int x, int z) {
return new FastProtoChunk(new ChunkPos(x, z), UpgradeData.EMPTY, freshWorld,
this.freshWorld.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY), null
);
}
@Override
protected LevelChunk createChunk(ProtoChunk protoChunk) {
return new LevelChunk(
freshWorld,
protoChunk,
null // we don't want to add entities
);
}
@Override
protected ChunkStatusWrap getFullChunkStatus() {
return new ChunkStatusWrap(ChunkStatus.FULL);
}
@Override
protected List<BlockPopulator> getBlockPopulators() {
return originalServerWorld.getWorld().getPopulators();
}
@Override
protected void populate(LevelChunk levelChunk, Random random, BlockPopulator blockPopulator) {
// BlockPopulator#populate has to be called synchronously for TileEntity access
TaskManager.taskManager().task(() -> blockPopulator.populate(freshWorld.getWorld(), random, levelChunk.getBukkitChunk()));
}
@Override
protected IChunkCache<IChunkGet> initSourceQueueCache() {
return (chunkX, chunkZ) -> new PaperweightGetBlocks(freshWorld, chunkX, chunkZ) {
@Override
public LevelChunk ensureLoaded(ServerLevel nmsWorld, int x, int z) {
return getChunkAt(x, z);
}
};
}
//util
@SuppressWarnings("unchecked")
private void removeWorldFromWorldsMap() {
Fawe.instance().getQueueHandler().sync(() -> {
try {
Map<String, org.bukkit.World> map = (Map<String, org.bukkit.World>) serverWorldsField.get(Bukkit.getServer());
map.remove("faweregentempworld");
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
});
}
private ResourceKey<LevelStem> getWorldDimKey(org.bukkit.World.Environment env) {
return switch (env) {
case NETHER -> LevelStem.NETHER;
case THE_END -> LevelStem.END;
default -> LevelStem.OVERWORLD;
};
}
private static class RegenNoOpWorldLoadListener implements ChunkProgressListener {
private RegenNoOpWorldLoadListener() {
}
@Override
public void updateSpawnPos(ChunkPos spawnPos) {
}
@Override
public void onStatusChange(ChunkPos pos, @Nullable ChunkStatus status) {
}
@Override
public void start() {
}
@Override
public void stop() {
}
// TODO Paper only(?) @Override
public void setChunkRadius(int radius) {
}
}
private class FastProtoChunk extends ProtoChunk {
public FastProtoChunk(
final ChunkPos pos,
final UpgradeData upgradeData,
final LevelHeightAccessor world,
final Registry<Biome> biomeRegistry,
@Nullable final BlendingData blendingData
) {
super(pos, upgradeData, world, biomeRegistry, blendingData);
}
// avoid warning on paper
// compatibility with spigot
public boolean generateFlatBedrock() {
return generateFlatBedrock;
}
// no one will ever see the entities!
@Override
public List<CompoundTag> getEntities() {
return Collections.emptyList();
}
}
protected class ChunkStatusWrap extends ChunkStatusWrapper<ChunkAccess> {
private final ChunkStatus chunkStatus;
public ChunkStatusWrap(ChunkStatus chunkStatus) {
this.chunkStatus = chunkStatus;
}
@Override
public int requiredNeighborChunkRadius() {
return chunkStatus.getRange();
}
@Override
public String name() {
return chunkStatus.getName();
}
@Override
public CompletableFuture<?> processChunk(Long xz, List<ChunkAccess> accessibleChunks) {
return chunkStatus.generate(
Runnable::run, // TODO revisit, we might profit from this somehow?
freshWorld,
chunkGenerator,
structureTemplateManager,
threadedLevelLightEngine,
c -> CompletableFuture.completedFuture(Either.left(c)),
accessibleChunks,
true
);
}
}
/**
* A light engine that does nothing. As light is calculated after pasting anyway, we can avoid
* work this way.
*/
static class NoOpLightEngine extends ThreadedLevelLightEngine {
private static final ProcessorMailbox<Runnable> MAILBOX = ProcessorMailbox.create(task -> {}, "fawe-no-op");
private static final ProcessorHandle<Message<Runnable>> HANDLE = ProcessorHandle.of("fawe-no-op", m -> {});
public NoOpLightEngine(final ServerChunkCache chunkProvider) {
super(chunkProvider, chunkProvider.chunkMap, false, MAILBOX, HANDLE);
}
@Override
public CompletableFuture<ChunkAccess> retainData(final ChunkAccess chunk) {
return CompletableFuture.completedFuture(chunk);
}
@Override
public CompletableFuture<ChunkAccess> lightChunk(final ChunkAccess chunk, final boolean excludeBlocks) {
return CompletableFuture.completedFuture(chunk);
}
}
}

Datei anzeigen

@ -0,0 +1,17 @@
import io.papermc.paperweight.userdev.PaperweightUserDependenciesExtension
plugins {
java
}
applyPaperweightAdapterConfiguration()
repositories {
gradlePluginPortal()
}
dependencies {
// https://papermc.io/repo/service/rest/repository/browse/maven-public/io/papermc/paper/dev-bundle/
the<PaperweightUserDependenciesExtension>().paperDevBundle("1.19.3-R0.1-20230312.180621-141")
compileOnly(libs.paperlib)
}

Datei anzeigen

@ -0,0 +1,93 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.bukkit.adapter.ext.fawe.v1_19_R2;
import com.mojang.authlib.GameProfile;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ServerboundClientInformationPacket;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.stats.Stat;
import net.minecraft.world.MenuProvider;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.block.entity.SignBlockEntity;
import net.minecraft.world.phys.Vec3;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import java.util.OptionalInt;
import java.util.UUID;
class PaperweightFakePlayer extends ServerPlayer {
private static final GameProfile FAKE_WORLDEDIT_PROFILE = new GameProfile(UUID.nameUUIDFromBytes("worldedit".getBytes()), "[WorldEdit]");
private static final Vec3 ORIGIN = new Vec3(0.0D, 0.0D, 0.0D);
PaperweightFakePlayer(ServerLevel world) {
super(world.getServer(), world, FAKE_WORLDEDIT_PROFILE);
}
@Override
public Vec3 position() {
return ORIGIN;
}
@Override
public void tick() {
}
@Override
public void die(DamageSource damagesource) {
}
@Override
public Entity changeDimension(ServerLevel worldserver, TeleportCause cause) {
return this;
}
@Override
public OptionalInt openMenu(MenuProvider factory) {
return OptionalInt.empty();
}
@Override
public void updateOptions(ServerboundClientInformationPacket packet) {
}
@Override
public void displayClientMessage(Component message, boolean actionBar) {
}
@Override
public void awardStat(Stat<?> stat, int amount) {
}
@Override
public void awardStat(Stat<?> stat) {
}
@Override
public boolean isInvulnerableTo(DamageSource damageSource) {
return true;
}
@Override
public void openTextEdit(SignBlockEntity sign) {
}
}

Datei anzeigen

@ -0,0 +1,180 @@
/*
* WorldEdit, a Minecraft world manipulation toolkit
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) WorldEdit team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.bukkit.adapter.ext.fawe.v1_19_R2;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.internal.block.BlockStateIdAccess;
import com.sk89q.worldedit.internal.wna.WorldNativeAccess;
import com.sk89q.worldedit.util.SideEffect;
import com.sk89q.worldedit.util.SideEffectSet;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.world.block.BlockState;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ChunkHolder;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.chunk.LevelChunk;
import org.bukkit.craftbukkit.v1_19_R2.CraftWorld;
import org.bukkit.craftbukkit.v1_19_R2.block.data.CraftBlockData;
import org.bukkit.event.block.BlockPhysicsEvent;
import java.lang.ref.WeakReference;
import java.util.Objects;
import javax.annotation.Nullable;
public class PaperweightWorldNativeAccess implements WorldNativeAccess<LevelChunk, net.minecraft.world.level.block.state.BlockState, BlockPos> {
private static final int UPDATE = 1;
private static final int NOTIFY = 2;
private final PaperweightAdapter adapter;
private final WeakReference<ServerLevel> world;
private SideEffectSet sideEffectSet;
public PaperweightWorldNativeAccess(PaperweightAdapter adapter, WeakReference<ServerLevel> world) {
this.adapter = adapter;
this.world = world;
}
private ServerLevel getWorld() {
return Objects.requireNonNull(world.get(), "The reference to the world was lost");
}
@Override
public void setCurrentSideEffectSet(SideEffectSet sideEffectSet) {
this.sideEffectSet = sideEffectSet;
}
@Override
public LevelChunk getChunk(int x, int z) {
return getWorld().getChunk(x, z);
}
@Override
public net.minecraft.world.level.block.state.BlockState toNative(BlockState state) {
int stateId = BlockStateIdAccess.getBlockStateId(state);
return BlockStateIdAccess.isValidInternalId(stateId)
? Block.stateById(stateId)
: ((CraftBlockData) BukkitAdapter.adapt(state)).getState();
}
@Override
public net.minecraft.world.level.block.state.BlockState getBlockState(LevelChunk chunk, BlockPos position) {
return chunk.getBlockState(position);
}
@Nullable
@Override
public net.minecraft.world.level.block.state.BlockState setBlockState(LevelChunk chunk, BlockPos position, net.minecraft.world.level.block.state.BlockState state) {
return chunk.setBlockState(position, state, false, this.sideEffectSet.shouldApply(SideEffect.UPDATE));
}
@Override
public net.minecraft.world.level.block.state.BlockState getValidBlockForPosition(net.minecraft.world.level.block.state.BlockState block, BlockPos position) {
return Block.updateFromNeighbourShapes(block, getWorld(), position);
}
@Override
public BlockPos getPosition(int x, int y, int z) {
return new BlockPos(x, y, z);
}
@Override
public void updateLightingForBlock(BlockPos position) {
getWorld().getChunkSource().getLightEngine().checkBlock(position);
}
@Override
public boolean updateTileEntity(final BlockPos position, final CompoundBinaryTag tag) {
return false;
}
@Override
public void notifyBlockUpdate(LevelChunk chunk, BlockPos position, net.minecraft.world.level.block.state.BlockState oldState, net.minecraft.world.level.block.state.BlockState newState) {
if (chunk.getSections()[getWorld().getSectionIndex(position.getY())] != null) {
getWorld().sendBlockUpdated(position, oldState, newState, UPDATE | NOTIFY);
}
}
@Override
public boolean isChunkTicking(LevelChunk chunk) {
return chunk.getFullStatus().isOrAfter(ChunkHolder.FullChunkStatus.TICKING);
}
@Override
public void markBlockChanged(LevelChunk chunk, BlockPos position) {
if (chunk.getSections()[getWorld().getSectionIndex(position.getY())] != null) {
getWorld().getChunkSource().blockChanged(position);
}
}
@Override
public void notifyNeighbors(BlockPos pos, net.minecraft.world.level.block.state.BlockState oldState, net.minecraft.world.level.block.state.BlockState newState) {
ServerLevel world = getWorld();
if (sideEffectSet.shouldApply(SideEffect.EVENTS)) {
world.updateNeighborsAt(pos, oldState.getBlock());
} else {
// When we don't want events, manually run the physics without them.
Block block = oldState.getBlock();
fireNeighborChanged(pos, world, block, pos.west());
fireNeighborChanged(pos, world, block, pos.east());
fireNeighborChanged(pos, world, block, pos.below());
fireNeighborChanged(pos, world, block, pos.above());
fireNeighborChanged(pos, world, block, pos.north());
fireNeighborChanged(pos, world, block, pos.south());
}
if (newState.hasAnalogOutputSignal()) {
world.updateNeighbourForOutputSignal(pos, newState.getBlock());
}
}
// Not sure why neighborChanged is deprecated
@SuppressWarnings("deprecation")
private void fireNeighborChanged(BlockPos pos, ServerLevel world, Block block, BlockPos neighborPos) {
world.getBlockState(neighborPos).neighborChanged(world, neighborPos, block, pos, false);
}
@Override
public void updateNeighbors(BlockPos pos, net.minecraft.world.level.block.state.BlockState oldState, net.minecraft.world.level.block.state.BlockState newState, int recursionLimit) {
ServerLevel world = getWorld();
// a == updateNeighbors
// b == updateDiagonalNeighbors
oldState.updateIndirectNeighbourShapes(world, pos, NOTIFY, recursionLimit);
if (sideEffectSet.shouldApply(SideEffect.EVENTS)) {
CraftWorld craftWorld = world.getWorld();
BlockPhysicsEvent event = new BlockPhysicsEvent(craftWorld.getBlockAt(pos.getX(), pos.getY(), pos.getZ()), CraftBlockData.fromData(newState));
world.getCraftServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
}
newState.updateNeighbourShapes(world, pos, NOTIFY, recursionLimit);
newState.updateIndirectNeighbourShapes(world, pos, NOTIFY, recursionLimit);
}
@Override
public void onBlockStateChange(BlockPos pos, net.minecraft.world.level.block.state.BlockState oldState, net.minecraft.world.level.block.state.BlockState newState) {
getWorld().onBlockStateChange(pos, oldState, newState);
}
@Override
public void flush() {
}
}

Datei anzeigen

@ -0,0 +1,189 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R2;
import com.google.common.base.Suppliers;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.util.ReflectionUtil;
import com.sk89q.worldedit.bukkit.adapter.Refraction;
import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R2.nbt.PaperweightLazyCompoundTag;
import com.sk89q.worldedit.world.registry.BlockMaterial;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.EmptyBlockGetter;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.EntityBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Material;
import net.minecraft.world.level.material.PushReaction;
import org.bukkit.craftbukkit.v1_19_R2.block.data.CraftBlockData;
public class PaperweightBlockMaterial implements BlockMaterial {
private final Block block;
private final BlockState blockState;
private final Material material;
private final boolean isTranslucent;
private final CraftBlockData craftBlockData;
private final org.bukkit.Material craftMaterial;
private final int opacity;
private final CompoundTag tile;
public PaperweightBlockMaterial(Block block) {
this(block, block.defaultBlockState());
}
public PaperweightBlockMaterial(Block block, BlockState blockState) {
this.block = block;
this.blockState = blockState;
this.material = blockState.getMaterial();
this.craftBlockData = CraftBlockData.fromData(blockState);
this.craftMaterial = craftBlockData.getMaterial();
BlockBehaviour.Properties blockInfo = ReflectionUtil.getField(BlockBehaviour.class, block,
Refraction.pickName("properties", "aP"));
this.isTranslucent = !(boolean) ReflectionUtil.getField(BlockBehaviour.Properties.class, blockInfo,
Refraction.pickName("canOcclude", "n")
);
opacity = blockState.getLightBlock(EmptyBlockGetter.INSTANCE, BlockPos.ZERO);
BlockEntity tileEntity = !(block instanceof EntityBlock) ? null : ((EntityBlock) block).newBlockEntity(
BlockPos.ZERO,
blockState
);
tile = tileEntity == null
? null
: new PaperweightLazyCompoundTag(Suppliers.memoize(tileEntity::saveWithId));
}
public Block getBlock() {
return block;
}
public BlockState getState() {
return blockState;
}
public CraftBlockData getCraftBlockData() {
return craftBlockData;
}
public Material getMaterial() {
return material;
}
@Override
public boolean isAir() {
return blockState.isAir();
}
@Override
public boolean isFullCube() {
return craftMaterial.isOccluding();
}
@Override
public boolean isOpaque() {
return material.isSolidBlocking();
}
@Override
public boolean isPowerSource() {
return blockState.isSignalSource();
}
@Override
public boolean isLiquid() {
return material.isLiquid();
}
@Override
public boolean isSolid() {
return material.isSolid();
}
@Override
public float getHardness() {
return craftBlockData.getState().destroySpeed;
}
@Override
public float getResistance() {
return block.getExplosionResistance();
}
@Override
public float getSlipperiness() {
return block.getFriction();
}
@Override
public int getLightValue() {
return blockState.getLightEmission();
}
@Override
public int getLightOpacity() {
return opacity;
}
@Override
public boolean isFragileWhenPushed() {
return material.getPushReaction() == PushReaction.DESTROY;
}
@Override
public boolean isUnpushable() {
return material.getPushReaction() == PushReaction.BLOCK;
}
@Override
public boolean isTicksRandomly() {
return block.isRandomlyTicking(blockState);
}
@Override
public boolean isMovementBlocker() {
return material.isSolid();
}
@Override
public boolean isBurnable() {
return material.isFlammable();
}
@Override
public boolean isToolRequired() {
// Removed in 1.16.1, this is not present in higher versions
return false;
}
@Override
public boolean isReplacedDuringPlacement() {
return material.isReplaceable();
}
@Override
public boolean isTranslucent() {
return isTranslucent;
}
@Override
public boolean hasContainer() {
return block instanceof EntityBlock;
}
@Override
public boolean isTile() {
return block instanceof EntityBlock;
}
@Override
public CompoundTag getDefaultTile() {
return tile;
}
@Override
public int getMapColor() {
// rgb field
return material.getColor().col;
}
}

Datei anzeigen

@ -0,0 +1,706 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R2;
import com.fastasyncworldedit.bukkit.adapter.CachedBukkitAdapter;
import com.fastasyncworldedit.bukkit.adapter.IDelegateBukkitImplAdapter;
import com.fastasyncworldedit.bukkit.adapter.NMSRelighterFactory;
import com.fastasyncworldedit.core.FaweCache;
import com.fastasyncworldedit.core.entity.LazyBaseEntity;
import com.fastasyncworldedit.core.extent.processor.lighting.RelighterFactory;
import com.fastasyncworldedit.core.queue.IBatchProcessor;
import com.fastasyncworldedit.core.queue.IChunkGet;
import com.fastasyncworldedit.core.queue.implementation.packet.ChunkPacket;
import com.fastasyncworldedit.core.util.NbtUtils;
import com.fastasyncworldedit.core.util.TaskManager;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.blocks.BaseItemStack;
import com.sk89q.worldedit.blocks.TileEntityBlock;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.bukkit.BukkitWorld;
import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter;
import com.sk89q.worldedit.bukkit.adapter.ext.fawe.v1_19_R2.PaperweightAdapter;
import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R2.nbt.PaperweightLazyCompoundTag;
import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R2.regen.PaperweightRegen;
import com.sk89q.worldedit.entity.BaseEntity;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.internal.block.BlockStateIdAccess;
import com.sk89q.worldedit.internal.util.LogManagerCompat;
import com.sk89q.worldedit.internal.wna.WorldNativeAccess;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.registry.state.BooleanProperty;
import com.sk89q.worldedit.registry.state.DirectionalProperty;
import com.sk89q.worldedit.registry.state.EnumProperty;
import com.sk89q.worldedit.registry.state.IntegerProperty;
import com.sk89q.worldedit.registry.state.Property;
import com.sk89q.worldedit.util.Direction;
import com.sk89q.worldedit.util.SideEffect;
import com.sk89q.worldedit.util.SideEffectSet;
import com.sk89q.worldedit.util.TreeGenerator;
import com.sk89q.worldedit.util.formatting.text.Component;
import com.sk89q.worldedit.util.nbt.BinaryTag;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.util.nbt.StringBinaryTag;
import com.sk89q.worldedit.world.RegenOptions;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockStateHolder;
import com.sk89q.worldedit.world.block.BlockType;
import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldedit.world.block.BlockTypesCache;
import com.sk89q.worldedit.world.entity.EntityType;
import com.sk89q.worldedit.world.item.ItemType;
import com.sk89q.worldedit.world.registry.BlockMaterial;
import io.papermc.lib.PaperLib;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Registry;
import net.minecraft.core.WritableRegistry;
import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.IntTag;
import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.dedicated.DedicatedServer;
import net.minecraft.server.level.ChunkHolder;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.util.StringRepresentable;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.block.state.properties.DirectionProperty;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.LevelChunkSection;
import org.apache.logging.log4j.Logger;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.TreeType;
import org.bukkit.block.data.BlockData;
import org.bukkit.craftbukkit.v1_19_R2.CraftChunk;
import org.bukkit.craftbukkit.v1_19_R2.CraftServer;
import org.bukkit.craftbukkit.v1_19_R2.CraftWorld;
import org.bukkit.craftbukkit.v1_19_R2.block.CraftBlockState;
import org.bukkit.craftbukkit.v1_19_R2.block.data.CraftBlockData;
import org.bukkit.craftbukkit.v1_19_R2.entity.CraftEntity;
import org.bukkit.craftbukkit.v1_19_R2.entity.CraftPlayer;
import org.bukkit.craftbukkit.v1_19_R2.inventory.CraftItemStack;
import org.bukkit.craftbukkit.v1_19_R2.util.CraftNamespacedKey;
import org.bukkit.entity.Player;
import javax.annotation.Nullable;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.OptionalInt;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static net.minecraft.core.registries.Registries.BIOME;
public final class PaperweightFaweAdapter extends CachedBukkitAdapter implements
IDelegateBukkitImplAdapter<net.minecraft.nbt.Tag> {
private static final Logger LOGGER = LogManagerCompat.getLogger();
private static Method CHUNK_HOLDER_WAS_ACCESSIBLE_SINCE_LAST_SAVE;
static {
try {
CHUNK_HOLDER_WAS_ACCESSIBLE_SINCE_LAST_SAVE = ChunkHolder.class.getDeclaredMethod("wasAccessibleSinceLastSave");
} catch (NoSuchMethodException ignored) { // may not be present in newer paper versions
}
}
private final PaperweightAdapter parent;
// ------------------------------------------------------------------------
// Code that may break between versions of Minecraft
// ------------------------------------------------------------------------
private final PaperweightMapChunkUtil mapUtil = new PaperweightMapChunkUtil();
private char[] ibdToStateOrdinal = null;
private int[] ordinalToIbdID = null;
private boolean initialised = false;
private Map<String, List<Property<?>>> allBlockProperties = null;
public PaperweightFaweAdapter() throws NoSuchFieldException, NoSuchMethodException {
this.parent = new PaperweightAdapter();
}
@Nullable
private static String getEntityId(Entity entity) {
ResourceLocation resourceLocation = net.minecraft.world.entity.EntityType.getKey(entity.getType());
return resourceLocation == null ? null : resourceLocation.toString();
}
private static void readEntityIntoTag(Entity entity, net.minecraft.nbt.CompoundTag compoundTag) {
entity.save(compoundTag);
}
@Override
public BukkitImplAdapter<net.minecraft.nbt.Tag> getParent() {
return parent;
}
private synchronized boolean init() {
if (ibdToStateOrdinal != null && ibdToStateOrdinal[1] != 0) {
return false;
}
ibdToStateOrdinal = new char[BlockTypesCache.states.length]; // size
ordinalToIbdID = new int[ibdToStateOrdinal.length]; // size
for (int i = 0; i < ibdToStateOrdinal.length; i++) {
BlockState blockState = BlockTypesCache.states[i];
PaperweightBlockMaterial material = (PaperweightBlockMaterial) blockState.getMaterial();
int id = Block.BLOCK_STATE_REGISTRY.getId(material.getState());
char ordinal = blockState.getOrdinalChar();
ibdToStateOrdinal[id] = ordinal;
ordinalToIbdID[ordinal] = id;
}
Map<String, List<Property<?>>> properties = new HashMap<>();
try {
for (Field field : BlockStateProperties.class.getDeclaredFields()) {
Object obj = field.get(null);
if (!(obj instanceof net.minecraft.world.level.block.state.properties.Property<?> state)) {
continue;
}
Property<?> property;
if (state instanceof net.minecraft.world.level.block.state.properties.BooleanProperty) {
property = new BooleanProperty(
state.getName(),
(List<Boolean>) ImmutableList.copyOf(state.getPossibleValues())
);
} else if (state instanceof DirectionProperty) {
property = new DirectionalProperty(
state.getName(),
state
.getPossibleValues()
.stream()
.map(e -> Direction.valueOf(((StringRepresentable) e).getSerializedName().toUpperCase()))
.collect(Collectors.toList())
);
} else if (state instanceof net.minecraft.world.level.block.state.properties.EnumProperty) {
property = new EnumProperty(
state.getName(),
state
.getPossibleValues()
.stream()
.map(e -> ((StringRepresentable) e).getSerializedName())
.collect(Collectors.toList())
);
} else if (state instanceof net.minecraft.world.level.block.state.properties.IntegerProperty) {
property = new IntegerProperty(
state.getName(),
(List<Integer>) ImmutableList.copyOf(state.getPossibleValues())
);
} else {
throw new IllegalArgumentException("FastAsyncWorldEdit needs an update to support " + state
.getClass()
.getSimpleName());
}
properties.compute(property.getName().toLowerCase(Locale.ROOT), (k, v) -> {
if (v == null) {
v = new ArrayList<>(Collections.singletonList(property));
} else {
v.add(property);
}
return v;
});
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} finally {
allBlockProperties = ImmutableMap.copyOf(properties);
}
initialised = true;
return true;
}
@Override
public BlockMaterial getMaterial(BlockType blockType) {
Block block = getBlock(blockType);
return new PaperweightBlockMaterial(block);
}
@Override
public synchronized BlockMaterial getMaterial(BlockState state) {
net.minecraft.world.level.block.state.BlockState blockState = ((CraftBlockData) Bukkit.createBlockData(state.getAsString())).getState();
return new PaperweightBlockMaterial(blockState.getBlock(), blockState);
}
public Block getBlock(BlockType blockType) {
return DedicatedServer.getServer().registryAccess().registryOrThrow(Registries.BLOCK)
.get(new ResourceLocation(blockType.getNamespace(), blockType.getResource()));
}
@Deprecated
@Override
public BlockState getBlock(Location location) {
Preconditions.checkNotNull(location);
CraftWorld craftWorld = ((CraftWorld) location.getWorld());
int x = location.getBlockX();
int y = location.getBlockY();
int z = location.getBlockZ();
final ServerLevel handle = craftWorld.getHandle();
LevelChunk chunk = handle.getChunk(x >> 4, z >> 4);
final BlockPos blockPos = new BlockPos(x, y, z);
final net.minecraft.world.level.block.state.BlockState blockData = chunk.getBlockState(blockPos);
BlockState state = adapt(blockData);
if (state == null) {
org.bukkit.block.Block bukkitBlock = location.getBlock();
state = BukkitAdapter.adapt(bukkitBlock.getBlockData());
}
return state;
}
@Override
public BaseBlock getFullBlock(final Location location) {
Preconditions.checkNotNull(location);
CraftWorld craftWorld = ((CraftWorld) location.getWorld());
int x = location.getBlockX();
int y = location.getBlockY();
int z = location.getBlockZ();
final ServerLevel handle = craftWorld.getHandle();
LevelChunk chunk = handle.getChunk(x >> 4, z >> 4);
final BlockPos blockPos = new BlockPos(x, y, z);
final net.minecraft.world.level.block.state.BlockState blockData = chunk.getBlockState(blockPos);
BlockState state = adapt(blockData);
if (state == null) {
org.bukkit.block.Block bukkitBlock = location.getBlock();
state = BukkitAdapter.adapt(bukkitBlock.getBlockData());
}
if (state.getBlockType().getMaterial().hasContainer()) {
// Read the NBT data
BlockEntity blockEntity = chunk.getBlockEntity(blockPos, LevelChunk.EntityCreationType.CHECK);
if (blockEntity != null) {
net.minecraft.nbt.CompoundTag tag = blockEntity.saveWithId();
return state.toBaseBlock((CompoundBinaryTag) toNativeBinary(tag));
}
}
return state.toBaseBlock();
}
@Override
public Set<SideEffect> getSupportedSideEffects() {
return SideEffectSet.defaults().getSideEffectsToApply();
}
public boolean setBlock(org.bukkit.Chunk chunk, int x, int y, int z, BlockStateHolder state, boolean update) {
CraftChunk craftChunk = (CraftChunk) chunk;
LevelChunk levelChunk = craftChunk.getHandle();
Level level = levelChunk.getLevel();
BlockPos blockPos = new BlockPos(x, y, z);
net.minecraft.world.level.block.state.BlockState blockState = ((PaperweightBlockMaterial) state.getMaterial()).getState();
LevelChunkSection[] levelChunkSections = levelChunk.getSections();
int y4 = y >> 4;
LevelChunkSection section = levelChunkSections[y4];
net.minecraft.world.level.block.state.BlockState existing;
if (section == null) {
existing = ((PaperweightBlockMaterial) BlockTypes.AIR.getDefaultState().getMaterial()).getState();
} else {
existing = section.getBlockState(x & 15, y & 15, z & 15);
}
levelChunk.removeBlockEntity(blockPos); // Force delete the old tile entity
CompoundBinaryTag compoundTag = state instanceof BaseBlock ? state.getNbt() : null;
if (compoundTag != null || existing instanceof TileEntityBlock) {
level.setBlock(blockPos, blockState, 0);
// remove tile
if (compoundTag != null) {
// We will assume that the tile entity was created for us,
// though we do not do this on the Forge version
BlockEntity blockEntity = level.getBlockEntity(blockPos);
if (blockEntity != null) {
net.minecraft.nbt.CompoundTag tag = (net.minecraft.nbt.CompoundTag) fromNativeBinary(compoundTag);
tag.put("x", IntTag.valueOf(x));
tag.put("y", IntTag.valueOf(y));
tag.put("z", IntTag.valueOf(z));
blockEntity.load(tag); // readTagIntoTileEntity - load data
}
}
} else {
if (existing == blockState) {
return true;
}
levelChunk.setBlockState(blockPos, blockState, false);
}
if (update) {
level.getMinecraftWorld().sendBlockUpdated(blockPos, existing, blockState, 0);
}
return true;
}
@Override
public WorldNativeAccess<?, ?, ?> createWorldNativeAccess(org.bukkit.World world) {
return new PaperweightFaweWorldNativeAccess(
this,
new WeakReference<>(((CraftWorld) world).getHandle())
);
}
@Override
public BaseEntity getEntity(org.bukkit.entity.Entity entity) {
Preconditions.checkNotNull(entity);
CraftEntity craftEntity = ((CraftEntity) entity);
Entity mcEntity = craftEntity.getHandle();
String id = getEntityId(mcEntity);
if (id != null) {
EntityType type = com.sk89q.worldedit.world.entity.EntityTypes.get(id);
Supplier<CompoundBinaryTag> saveTag = () -> {
final net.minecraft.nbt.CompoundTag minecraftTag = new net.minecraft.nbt.CompoundTag();
readEntityIntoTag(mcEntity, minecraftTag);
//add Id for AbstractChangeSet to work
final CompoundBinaryTag tag = (CompoundBinaryTag) toNativeBinary(minecraftTag);
final Map<String, BinaryTag> tags = NbtUtils.getCompoundBinaryTagValues(tag);
tags.put("Id", StringBinaryTag.of(id));
return CompoundBinaryTag.from(tags);
};
return new LazyBaseEntity(type, saveTag);
} else {
return null;
}
}
@Override
public Component getRichBlockName(BlockType blockType) {
return parent.getRichBlockName(blockType);
}
@Override
public Component getRichItemName(ItemType itemType) {
return parent.getRichItemName(itemType);
}
@Override
public Component getRichItemName(BaseItemStack itemStack) {
return parent.getRichItemName(itemStack);
}
@Override
public OptionalInt getInternalBlockStateId(BlockState state) {
PaperweightBlockMaterial material = (PaperweightBlockMaterial) state.getMaterial();
net.minecraft.world.level.block.state.BlockState mcState = material.getCraftBlockData().getState();
return OptionalInt.of(Block.BLOCK_STATE_REGISTRY.getId(mcState));
}
@Override
public BlockState adapt(BlockData blockData) {
CraftBlockData cbd = ((CraftBlockData) blockData);
net.minecraft.world.level.block.state.BlockState ibd = cbd.getState();
return adapt(ibd);
}
public BlockState adapt(net.minecraft.world.level.block.state.BlockState blockState) {
return BlockTypesCache.states[adaptToChar(blockState)];
}
public char adaptToChar(net.minecraft.world.level.block.state.BlockState blockState) {
int id = Block.BLOCK_STATE_REGISTRY.getId(blockState);
if (initialised) {
return ibdToStateOrdinal[id];
}
synchronized (this) {
if (initialised) {
return ibdToStateOrdinal[id];
}
try {
init();
return ibdToStateOrdinal[id];
} catch (ArrayIndexOutOfBoundsException e1) {
LOGGER.error("Attempted to convert {} with ID {} to char. ibdToStateOrdinal length: {}. Defaulting to air!",
blockState.getBlock(), Block.BLOCK_STATE_REGISTRY.getId(blockState), ibdToStateOrdinal.length, e1
);
return BlockTypesCache.ReservedIDs.AIR;
}
}
}
public char ibdIDToOrdinal(int id) {
if (initialised) {
return ibdToStateOrdinal[id];
}
synchronized (this) {
if (initialised) {
return ibdToStateOrdinal[id];
}
init();
return ibdToStateOrdinal[id];
}
}
@Override
public char[] getIbdToStateOrdinal() {
if (initialised) {
return ibdToStateOrdinal;
}
synchronized (this) {
if (initialised) {
return ibdToStateOrdinal;
}
init();
return ibdToStateOrdinal;
}
}
public int ordinalToIbdID(char ordinal) {
if (initialised) {
return ordinalToIbdID[ordinal];
}
synchronized (this) {
if (initialised) {
return ordinalToIbdID[ordinal];
}
init();
return ordinalToIbdID[ordinal];
}
}
@Override
public int[] getOrdinalToIbdID() {
if (initialised) {
return ordinalToIbdID;
}
synchronized (this) {
if (initialised) {
return ordinalToIbdID;
}
init();
return ordinalToIbdID;
}
}
@Override
public <B extends BlockStateHolder<B>> BlockData adapt(B state) {
PaperweightBlockMaterial material = (PaperweightBlockMaterial) state.getMaterial();
return material.getCraftBlockData();
}
@Override
public void sendFakeChunk(org.bukkit.World world, Player player, ChunkPacket chunkPacket) {
ServerLevel nmsWorld = ((CraftWorld) world).getHandle();
ChunkHolder map = PaperweightPlatformAdapter.getPlayerChunk(nmsWorld, chunkPacket.getChunkX(), chunkPacket.getChunkZ());
if (map != null && wasAccessibleSinceLastSave(map)) {
boolean flag = false;
// PlayerChunk.d players = map.players;
Stream<ServerPlayer> stream = /*players.a(new ChunkCoordIntPair(packet.getChunkX(), packet.getChunkZ()), flag)
*/ Stream.empty();
ServerPlayer checkPlayer = player == null ? null : ((CraftPlayer) player).getHandle();
stream.filter(entityPlayer -> checkPlayer == null || entityPlayer == checkPlayer)
.forEach(entityPlayer -> {
synchronized (chunkPacket) {
ClientboundLevelChunkWithLightPacket nmsPacket = (ClientboundLevelChunkWithLightPacket) chunkPacket.getNativePacket();
if (nmsPacket == null) {
nmsPacket = mapUtil.create(this, chunkPacket);
chunkPacket.setNativePacket(nmsPacket);
}
try {
FaweCache.INSTANCE.CHUNK_FLAG.get().set(true);
entityPlayer.connection.send(nmsPacket);
} finally {
FaweCache.INSTANCE.CHUNK_FLAG.get().set(false);
}
}
});
}
}
@Override
public Map<String, ? extends Property<?>> getProperties(BlockType blockType) {
return getParent().getProperties(blockType);
}
@Override
public boolean canPlaceAt(org.bukkit.World world, BlockVector3 blockVector3, BlockState blockState) {
int internalId = BlockStateIdAccess.getBlockStateId(blockState);
net.minecraft.world.level.block.state.BlockState blockState1 = Block.stateById(internalId);
return blockState1.hasPostProcess(
((CraftWorld) world).getHandle(),
new BlockPos(blockVector3.getX(), blockVector3.getY(), blockVector3.getZ())
);
}
@Override
public org.bukkit.inventory.ItemStack adapt(BaseItemStack baseItemStack) {
ItemStack stack = new ItemStack(
DedicatedServer.getServer().registryAccess().registryOrThrow(Registries.ITEM)
.get(ResourceLocation.tryParse(baseItemStack.getType().getId())),
baseItemStack.getAmount()
);
stack.setTag(((net.minecraft.nbt.CompoundTag) fromNative(baseItemStack.getNbtData())));
return CraftItemStack.asCraftMirror(stack);
}
@Override
public boolean generateTree(
TreeGenerator.TreeType treeType, EditSession editSession, BlockVector3 blockVector3,
org.bukkit.World bukkitWorld
) {
TreeType bukkitType = BukkitWorld.toBukkitTreeType(treeType);
if (bukkitType == TreeType.CHORUS_PLANT) {
blockVector3 = blockVector3.add(
0,
1,
0
); // bukkit skips the feature gen which does this offset normally, so we have to add it back
}
ServerLevel serverLevel = ((CraftWorld) bukkitWorld).getHandle();
final BlockVector3 finalBlockVector = blockVector3;
// Sync to main thread to ensure no clashes occur
Map<BlockPos, CraftBlockState> placed = TaskManager.taskManager().sync(() -> {
serverLevel.captureTreeGeneration = true;
serverLevel.captureBlockStates = true;
try {
if (!bukkitWorld.generateTree(BukkitAdapter.adapt(bukkitWorld, finalBlockVector), bukkitType)) {
return null;
}
return ImmutableMap.copyOf(serverLevel.capturedBlockStates);
} finally {
serverLevel.captureBlockStates = false;
serverLevel.captureTreeGeneration = false;
serverLevel.capturedBlockStates.clear();
}
});
if (placed == null || placed.isEmpty()) {
return false;
}
for (CraftBlockState craftBlockState : placed.values()) {
if (craftBlockState == null || craftBlockState.getType() == Material.AIR) {
continue;
}
editSession.setBlock(craftBlockState.getX(), craftBlockState.getY(), craftBlockState.getZ(),
BukkitAdapter.adapt(((org.bukkit.block.BlockState) craftBlockState).getBlockData())
);
}
return true;
}
@Override
public BaseItemStack adapt(org.bukkit.inventory.ItemStack itemStack) {
final ItemStack nmsStack = CraftItemStack.asNMSCopy(itemStack);
final BaseItemStack weStack = new BaseItemStack(BukkitAdapter.asItemType(itemStack.getType()), itemStack.getAmount());
weStack.setNbt(((CompoundBinaryTag) toNativeBinary(nmsStack.getTag())));
return weStack;
}
@Override
public Tag toNative(net.minecraft.nbt.Tag foreign) {
return parent.toNative(foreign);
}
@Override
public net.minecraft.nbt.Tag fromNative(Tag foreign) {
if (foreign instanceof PaperweightLazyCompoundTag) {
return ((PaperweightLazyCompoundTag) foreign).get();
}
return parent.fromNative(foreign);
}
@Override
public boolean regenerate(org.bukkit.World bukkitWorld, Region region, Extent target, RegenOptions options) throws Exception {
return new PaperweightRegen(bukkitWorld, region, target, options).regenerate();
}
@Override
public IChunkGet get(org.bukkit.World world, int chunkX, int chunkZ) {
return new PaperweightGetBlocks(world, chunkX, chunkZ);
}
@Override
public int getInternalBiomeId(BiomeType biomeType) {
final Registry<Biome> registry = MinecraftServer
.getServer()
.registryAccess()
.registryOrThrow(BIOME);
ResourceLocation resourceLocation = ResourceLocation.tryParse(biomeType.getId());
Biome biome = registry.get(resourceLocation);
return registry.getId(biome);
}
@Override
public Iterable<NamespacedKey> getRegisteredBiomes() {
WritableRegistry<Biome> biomeRegistry = (WritableRegistry<Biome>) ((CraftServer) Bukkit.getServer())
.getServer()
.registryAccess()
.registryOrThrow(BIOME);
List<ResourceLocation> keys = biomeRegistry.stream()
.map(biomeRegistry::getKey).filter(Objects::nonNull).toList();
List<NamespacedKey> namespacedKeys = new ArrayList<>();
for (ResourceLocation key : keys) {
try {
namespacedKeys.add(CraftNamespacedKey.fromMinecraft(key));
} catch (IllegalArgumentException e) {
LOGGER.error("Error converting biome key {}", key.toString(), e);
}
}
return namespacedKeys;
}
@Override
public RelighterFactory getRelighterFactory() {
if (PaperLib.isPaper()) {
return new PaperweightStarlightRelighterFactory();
} else {
return new NMSRelighterFactory();
}
}
@Override
public Map<String, List<Property<?>>> getAllProperties() {
if (initialised) {
return allBlockProperties;
}
synchronized (this) {
if (initialised) {
return allBlockProperties;
}
init();
return allBlockProperties;
}
}
@Override
public IBatchProcessor getTickingPostProcessor() {
return new PaperweightPostProcessor();
}
private boolean wasAccessibleSinceLastSave(ChunkHolder holder) {
if (!PaperLib.isPaper() || !PaperweightPlatformAdapter.POST_CHUNK_REWRITE) {
try {
return (boolean) CHUNK_HOLDER_WAS_ACCESSIBLE_SINCE_LAST_SAVE.invoke(holder);
} catch (IllegalAccessException | InvocationTargetException ignored) {
// fall-through
}
}
// Papers new chunk system has no related replacement - therefor we assume true.
return true;
}
}

Datei anzeigen

@ -0,0 +1,286 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R2;
import com.fastasyncworldedit.core.Fawe;
import com.fastasyncworldedit.core.math.IntPair;
import com.fastasyncworldedit.core.util.TaskManager;
import com.fastasyncworldedit.core.util.task.RunnableVal;
import com.sk89q.worldedit.bukkit.BukkitAdapter;
import com.sk89q.worldedit.internal.block.BlockStateIdAccess;
import com.sk89q.worldedit.internal.wna.WorldNativeAccess;
import com.sk89q.worldedit.util.SideEffect;
import com.sk89q.worldedit.util.SideEffectSet;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import com.sk89q.worldedit.world.block.BlockState;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ChunkHolder;
import net.minecraft.server.level.ServerChunkCache;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.chunk.LevelChunk;
import org.bukkit.craftbukkit.v1_19_R2.CraftWorld;
import org.bukkit.craftbukkit.v1_19_R2.block.data.CraftBlockData;
import org.bukkit.event.block.BlockPhysicsEvent;
import javax.annotation.Nullable;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
public class PaperweightFaweWorldNativeAccess implements WorldNativeAccess<LevelChunk,
net.minecraft.world.level.block.state.BlockState, BlockPos> {
private static final int UPDATE = 1;
private static final int NOTIFY = 2;
private static final Direction[] NEIGHBOUR_ORDER = {
Direction.EAST,
Direction.WEST,
Direction.DOWN,
Direction.UP,
Direction.NORTH,
Direction.SOUTH
};
private final PaperweightFaweAdapter paperweightFaweAdapter;
private final WeakReference<Level> level;
private final AtomicInteger lastTick;
private final Set<CachedChange> cachedChanges = new HashSet<>();
private final Set<IntPair> cachedChunksToSend = new HashSet<>();
private SideEffectSet sideEffectSet;
public PaperweightFaweWorldNativeAccess(PaperweightFaweAdapter paperweightFaweAdapter, WeakReference<Level> level) {
this.paperweightFaweAdapter = paperweightFaweAdapter;
this.level = level;
// Use the actual tick as minecraft-defined so we don't try to force blocks into the world when the server's already lagging.
// - With the caveat that we don't want to have too many cached changed (1024) so we'd flush those at 1024 anyway.
this.lastTick = new AtomicInteger(MinecraftServer.currentTick);
}
private Level getLevel() {
return Objects.requireNonNull(level.get(), "The reference to the world was lost");
}
@Override
public void setCurrentSideEffectSet(SideEffectSet sideEffectSet) {
this.sideEffectSet = sideEffectSet;
}
@Override
public LevelChunk getChunk(int x, int z) {
return getLevel().getChunk(x, z);
}
@Override
public net.minecraft.world.level.block.state.BlockState toNative(BlockState blockState) {
int stateId = paperweightFaweAdapter.ordinalToIbdID(blockState.getOrdinalChar());
return BlockStateIdAccess.isValidInternalId(stateId)
? Block.stateById(stateId)
: ((CraftBlockData) BukkitAdapter.adapt(blockState)).getState();
}
@Override
public net.minecraft.world.level.block.state.BlockState getBlockState(LevelChunk levelChunk, BlockPos blockPos) {
return levelChunk.getBlockState(blockPos);
}
@Nullable
@Override
public synchronized net.minecraft.world.level.block.state.BlockState setBlockState(
LevelChunk levelChunk, BlockPos blockPos,
net.minecraft.world.level.block.state.BlockState blockState
) {
int currentTick = MinecraftServer.currentTick;
if (Fawe.isMainThread()) {
return levelChunk.setBlockState(blockPos, blockState,
this.sideEffectSet != null && this.sideEffectSet.shouldApply(SideEffect.UPDATE)
);
}
// Since FAWE is.. Async we need to do it on the main thread (wooooo.. :( )
cachedChanges.add(new CachedChange(levelChunk, blockPos, blockState));
cachedChunksToSend.add(new IntPair(levelChunk.bukkitChunk.getX(), levelChunk.bukkitChunk.getZ()));
boolean nextTick = lastTick.get() > currentTick;
if (nextTick || cachedChanges.size() >= 1024) {
if (nextTick) {
lastTick.set(currentTick);
}
flushAsync(nextTick);
}
return blockState;
}
@Override
public net.minecraft.world.level.block.state.BlockState getValidBlockForPosition(
net.minecraft.world.level.block.state.BlockState blockState,
BlockPos blockPos
) {
return Block.updateFromNeighbourShapes(blockState, getLevel(), blockPos);
}
@Override
public BlockPos getPosition(int x, int y, int z) {
return new BlockPos(x, y, z);
}
@Override
public void updateLightingForBlock(BlockPos blockPos) {
getLevel().getChunkSource().getLightEngine().checkBlock(blockPos);
}
@Override
public boolean updateTileEntity(BlockPos blockPos, CompoundBinaryTag tag) {
// We will assume that the tile entity was created for us,
// though we do not do this on the other versions
BlockEntity blockEntity = getLevel().getBlockEntity(blockPos);
if (blockEntity == null) {
return false;
}
net.minecraft.nbt.Tag nativeTag = paperweightFaweAdapter.fromNativeBinary(tag);
blockEntity.load((CompoundTag) nativeTag);
return true;
}
@Override
public void notifyBlockUpdate(
LevelChunk levelChunk, BlockPos blockPos,
net.minecraft.world.level.block.state.BlockState oldState,
net.minecraft.world.level.block.state.BlockState newState
) {
if (levelChunk.getSections()[level.get().getSectionIndex(blockPos.getY())] != null) {
getLevel().sendBlockUpdated(blockPos, oldState, newState, UPDATE | NOTIFY);
}
}
@Override
public boolean isChunkTicking(LevelChunk levelChunk) {
return levelChunk.getFullStatus().isOrAfter(ChunkHolder.FullChunkStatus.TICKING);
}
@Override
public void markBlockChanged(LevelChunk levelChunk, BlockPos blockPos) {
if (levelChunk.getSections()[level.get().getSectionIndex(blockPos.getY())] != null) {
((ServerChunkCache) getLevel().getChunkSource()).blockChanged(blockPos);
}
}
@Override
public void notifyNeighbors(
BlockPos blockPos,
net.minecraft.world.level.block.state.BlockState oldState,
net.minecraft.world.level.block.state.BlockState newState
) {
Level level = getLevel();
if (sideEffectSet.shouldApply(SideEffect.EVENTS)) {
level.blockUpdated(blockPos, oldState.getBlock());
} else {
// When we don't want events, manually run the physics without them.
// Un-nest neighbour updating
for (Direction direction : NEIGHBOUR_ORDER) {
BlockPos shifted = blockPos.relative(direction);
level.getBlockState(shifted).neighborChanged(level, shifted, oldState.getBlock(), blockPos, false);
}
}
if (newState.hasAnalogOutputSignal()) {
level.updateNeighbourForOutputSignal(blockPos, newState.getBlock());
}
}
@Override
public void updateNeighbors(
BlockPos blockPos,
net.minecraft.world.level.block.state.BlockState oldState,
net.minecraft.world.level.block.state.BlockState newState,
int recursionLimit
) {
Level level = getLevel();
// a == updateNeighbors
// b == updateDiagonalNeighbors
oldState.updateIndirectNeighbourShapes(level, blockPos, NOTIFY, recursionLimit);
if (sideEffectSet.shouldApply(SideEffect.EVENTS)) {
CraftWorld craftWorld = level.getWorld();
if (craftWorld != null) {
BlockPhysicsEvent event = new BlockPhysicsEvent(
craftWorld.getBlockAt(blockPos.getX(), blockPos.getY(), blockPos.getZ()),
CraftBlockData.fromData(newState)
);
level.getCraftServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
}
}
newState.triggerEvent(level, blockPos, NOTIFY, recursionLimit);
newState.updateIndirectNeighbourShapes(level, blockPos, NOTIFY, recursionLimit);
}
@Override
public void onBlockStateChange(
BlockPos blockPos,
net.minecraft.world.level.block.state.BlockState oldState,
net.minecraft.world.level.block.state.BlockState newState
) {
getLevel().onBlockStateChange(blockPos, oldState, newState);
}
private synchronized void flushAsync(final boolean sendChunks) {
final Set<CachedChange> changes = Set.copyOf(cachedChanges);
cachedChanges.clear();
final Set<IntPair> toSend;
if (sendChunks) {
toSend = Set.copyOf(cachedChunksToSend);
cachedChunksToSend.clear();
} else {
toSend = Collections.emptySet();
}
RunnableVal<Object> runnableVal = new RunnableVal<>() {
@Override
public void run(Object value) {
changes.forEach(cc -> cc.levelChunk.setBlockState(cc.blockPos, cc.blockState,
sideEffectSet != null && sideEffectSet.shouldApply(SideEffect.UPDATE)
));
if (!sendChunks) {
return;
}
for (IntPair chunk : toSend) {
PaperweightPlatformAdapter.sendChunk(getLevel().getWorld().getHandle(), chunk.x(), chunk.z(), false);
}
}
};
TaskManager.taskManager().async(() -> TaskManager.taskManager().sync(runnableVal));
}
@Override
public synchronized void flush() {
RunnableVal<Object> runnableVal = new RunnableVal<>() {
@Override
public void run(Object value) {
cachedChanges.forEach(cc -> cc.levelChunk.setBlockState(cc.blockPos, cc.blockState,
sideEffectSet != null && sideEffectSet.shouldApply(SideEffect.UPDATE)
));
for (IntPair chunk : cachedChunksToSend) {
PaperweightPlatformAdapter.sendChunk(getLevel().getWorld().getHandle(), chunk.x(), chunk.z(), false);
}
}
};
if (Fawe.isMainThread()) {
runnableVal.run();
} else {
TaskManager.taskManager().sync(runnableVal);
}
cachedChanges.clear();
cachedChunksToSend.clear();
}
private record CachedChange(
LevelChunk levelChunk,
BlockPos blockPos,
net.minecraft.world.level.block.state.BlockState blockState
) {
}
}

Datei anzeigen

@ -0,0 +1,248 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R2;
import com.fastasyncworldedit.core.extent.processor.heightmap.HeightMapType;
import com.fastasyncworldedit.core.queue.IBlocks;
import com.fastasyncworldedit.core.queue.IChunkGet;
import com.fastasyncworldedit.core.queue.IChunkSet;
import com.google.common.base.Suppliers;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter;
import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R2.nbt.PaperweightLazyCompoundTag;
import com.sk89q.worldedit.internal.util.LogManagerCompat;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.block.BaseBlock;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypesCache;
import net.minecraft.core.Holder;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.PalettedContainer;
import net.minecraft.world.level.chunk.PalettedContainerRO;
import org.apache.logging.log4j.Logger;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Future;
public class PaperweightGetBlocks_Copy implements IChunkGet {
private static final Logger LOGGER = LogManagerCompat.getLogger();
private final Map<BlockVector3, CompoundTag> tiles = new HashMap<>();
private final Set<CompoundTag> entities = new HashSet<>();
private final char[][] blocks;
private final int minHeight;
private final int maxHeight;
final ServerLevel serverLevel;
final LevelChunk levelChunk;
private PalettedContainer<Holder<Biome>>[] biomes = null;
protected PaperweightGetBlocks_Copy(LevelChunk levelChunk) {
this.levelChunk = levelChunk;
this.serverLevel = levelChunk.level;
this.minHeight = serverLevel.getMinBuildHeight();
this.maxHeight = serverLevel.getMaxBuildHeight() - 1; // Minecraft max limit is exclusive.
this.blocks = new char[getSectionCount()][];
}
protected void storeTile(BlockEntity blockEntity) {
tiles.put(
BlockVector3.at(
blockEntity.getBlockPos().getX(),
blockEntity.getBlockPos().getY(),
blockEntity.getBlockPos().getZ()
),
new PaperweightLazyCompoundTag(Suppliers.memoize(blockEntity::saveWithId))
);
}
@Override
public Map<BlockVector3, CompoundTag> getTiles() {
return tiles;
}
@Override
@Nullable
public CompoundTag getTile(int x, int y, int z) {
return tiles.get(BlockVector3.at(x, y, z));
}
@SuppressWarnings({"unchecked", "rawtypes"})
protected void storeEntity(Entity entity) {
BukkitImplAdapter adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter();
net.minecraft.nbt.CompoundTag compoundTag = new net.minecraft.nbt.CompoundTag();
entity.save(compoundTag);
entities.add((CompoundTag) adapter.toNative(compoundTag));
}
@Override
public Set<CompoundTag> getEntities() {
return this.entities;
}
@Override
public CompoundTag getEntity(UUID uuid) {
for (CompoundTag tag : entities) {
if (uuid.equals(tag.getUUID())) {
return tag;
}
}
return null;
}
@Override
public boolean isCreateCopy() {
return false;
}
@Override
public void setCreateCopy(boolean createCopy) {
}
@Override
public void setLightingToGet(char[][] lighting, int minSectionPosition, int maxSectionPosition) {
}
@Override
public void setSkyLightingToGet(char[][] lighting, int minSectionPosition, int maxSectionPosition) {
}
@Override
public void setHeightmapToGet(HeightMapType type, int[] data) {
}
@Override
public int getMaxY() {
return maxHeight;
}
@Override
public int getMinY() {
return minHeight;
}
@Override
public int getMaxSectionPosition() {
return maxHeight >> 4;
}
@Override
public int getMinSectionPosition() {
return minHeight >> 4;
}
@Override
public BiomeType getBiomeType(int x, int y, int z) {
Holder<Biome> biome = biomes[(y >> 4) - getMinSectionPosition()].get(x >> 2, (y & 15) >> 2, z >> 2);
return PaperweightPlatformAdapter.adapt(biome, serverLevel);
}
@Override
public void removeSectionLighting(int layer, boolean sky) {
}
@Override
public boolean trim(boolean aggressive, int layer) {
return false;
}
@Override
public IBlocks reset() {
return null;
}
@Override
public int getSectionCount() {
return serverLevel.getSectionsCount();
}
protected void storeSection(int layer, char[] data) {
blocks[layer] = data;
}
protected void storeBiomes(int layer, PalettedContainerRO<Holder<Biome>> biomeData) {
if (biomes == null) {
biomes = new PalettedContainer[getSectionCount()];
}
if (biomeData instanceof PalettedContainer<Holder<Biome>> palettedContainer) {
biomes[layer] = palettedContainer.copy();
} else {
LOGGER.error(
"Cannot correctly save biomes to history. Expected class type {} but got {}",
PalettedContainer.class.getSimpleName(),
biomeData.getClass().getSimpleName()
);
}
}
@Override
public BaseBlock getFullBlock(int x, int y, int z) {
BlockState state = BlockTypesCache.states[get(x, y, z)];
return state.toBaseBlock(this, x, y, z);
}
@Override
public boolean hasSection(int layer) {
layer -= getMinSectionPosition();
return blocks[layer] != null;
}
@Override
public char[] load(int layer) {
layer -= getMinSectionPosition();
return blocks[layer];
}
@Override
public char[] loadIfPresent(int layer) {
layer -= getMinSectionPosition();
return blocks[layer];
}
@Override
public BlockState getBlock(int x, int y, int z) {
return BlockTypesCache.states[get(x, y, z)];
}
@Override
public int getSkyLight(int x, int y, int z) {
return 0;
}
@Override
public int getEmittedLight(int x, int y, int z) {
return 0;
}
@Override
public int[] getHeightMap(HeightMapType type) {
return new int[0];
}
@Override
public <T extends Future<T>> T call(IChunkSet set, Runnable finalize) {
return null;
}
public char get(int x, int y, int z) {
final int layer = (y >> 4) - getMinSectionPosition();
final int index = (y & 15) << 8 | z << 4 | x;
return blocks[layer][index];
}
@Override
public boolean trim(boolean aggressive) {
return false;
}
}

Datei anzeigen

@ -0,0 +1,34 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R2;
import com.fastasyncworldedit.bukkit.adapter.MapChunkUtil;
import com.sk89q.worldedit.bukkit.adapter.Refraction;
import net.minecraft.network.protocol.game.ClientboundLevelChunkPacketData;
import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket;
//TODO un-very-break-this
public class PaperweightMapChunkUtil extends MapChunkUtil<ClientboundLevelChunkWithLightPacket> {
public PaperweightMapChunkUtil() throws NoSuchFieldException {
fieldX = ClientboundLevelChunkPacketData.class.getDeclaredField(Refraction.pickName("TWO_MEGABYTES", "a"));
fieldZ = ClientboundLevelChunkWithLightPacket.class.getDeclaredField(Refraction.pickName("x", "a"));
fieldBitMask = ClientboundLevelChunkWithLightPacket.class.getDeclaredField(Refraction.pickName("z", "b"));
fieldHeightMap = ClientboundLevelChunkPacketData.class.getDeclaredField(Refraction.pickName("heightmaps", "b"));
fieldChunkData = ClientboundLevelChunkWithLightPacket.class.getDeclaredField(Refraction.pickName("chunkData", "c"));
fieldBlockEntities = ClientboundLevelChunkPacketData.class.getDeclaredField(Refraction.pickName("buffer", "c"));
fieldFull = ClientboundLevelChunkPacketData.class.getDeclaredField(Refraction.pickName("blockEntitiesData", "d"));
fieldX.setAccessible(true);
fieldZ.setAccessible(true);
fieldBitMask.setAccessible(true);
fieldHeightMap.setAccessible(true);
fieldChunkData.setAccessible(true);
fieldBlockEntities.setAccessible(true);
fieldFull.setAccessible(true);
}
@Override
public ClientboundLevelChunkWithLightPacket createPacket() {
// TODO ??? return new ClientboundLevelChunkPacket();
throw new UnsupportedOperationException();
}
}

Datei anzeigen

@ -0,0 +1,700 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R2;
import com.destroystokyo.paper.util.maplist.EntityList;
import com.fastasyncworldedit.bukkit.adapter.CachedBukkitAdapter;
import com.fastasyncworldedit.bukkit.adapter.DelegateSemaphore;
import com.fastasyncworldedit.bukkit.adapter.NMSAdapter;
import com.fastasyncworldedit.core.Fawe;
import com.fastasyncworldedit.core.FaweCache;
import com.fastasyncworldedit.core.math.BitArrayUnstretched;
import com.fastasyncworldedit.core.util.MathMan;
import com.fastasyncworldedit.core.util.ReflectionUtils;
import com.fastasyncworldedit.core.util.TaskManager;
import com.mojang.datafixers.util.Either;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.adapter.BukkitImplAdapter;
import com.sk89q.worldedit.bukkit.adapter.Refraction;
import com.sk89q.worldedit.world.biome.BiomeType;
import com.sk89q.worldedit.world.biome.BiomeTypes;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypesCache;
import io.papermc.lib.PaperLib;
import io.papermc.paper.world.ChunkEntitySlices;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.core.IdMap;
import net.minecraft.core.Registry;
import net.minecraft.network.protocol.game.ClientboundLevelChunkWithLightPacket;
import net.minecraft.server.level.ChunkHolder;
import net.minecraft.server.level.ChunkMap;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.level.TicketType;
import net.minecraft.util.BitStorage;
import net.minecraft.util.ExceptionCollector;
import net.minecraft.util.SimpleBitStorage;
import net.minecraft.util.ThreadingDetector;
import net.minecraft.util.Unit;
import net.minecraft.util.ZeroBitStorage;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.chunk.GlobalPalette;
import net.minecraft.world.level.chunk.HashMapPalette;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.LevelChunkSection;
import net.minecraft.world.level.chunk.LinearPalette;
import net.minecraft.world.level.chunk.Palette;
import net.minecraft.world.level.chunk.PalettedContainer;
import net.minecraft.world.level.chunk.SingleValuePalette;
import net.minecraft.world.level.entity.PersistentEntitySectionManager;
import org.bukkit.craftbukkit.v1_19_R2.CraftChunk;
import sun.misc.Unsafe;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Semaphore;
import java.util.function.Function;
import static net.minecraft.core.registries.Registries.BIOME;
public final class PaperweightPlatformAdapter extends NMSAdapter {
public static final Field fieldData;
public static final Constructor<?> dataConstructor;
public static final Field fieldStorage;
public static final Field fieldPalette;
private static final Field fieldTickingFluidCount;
private static final Field fieldTickingBlockCount;
private static final Field fieldNonEmptyBlockCount;
private static final MethodHandle methodGetVisibleChunk;
private static final int CHUNKSECTION_BASE;
private static final int CHUNKSECTION_SHIFT;
private static final Field fieldThreadingDetector;
private static final long fieldThreadingDetectorOffset;
private static final Field fieldLock;
private static final long fieldLockOffset;
private static final MethodHandle methodRemoveGameEventListener;
private static final MethodHandle methodremoveTickingBlockEntity;
private static final Field fieldRemove;
static final boolean POST_CHUNK_REWRITE;
private static Method PAPER_CHUNK_GEN_ALL_ENTITIES;
private static Field LEVEL_CHUNK_ENTITIES;
private static Field SERVER_LEVEL_ENTITY_MANAGER;
static {
try {
fieldData = PalettedContainer.class.getDeclaredField(Refraction.pickName("data", "d"));
fieldData.setAccessible(true);
Class<?> dataClazz = fieldData.getType();
dataConstructor = dataClazz.getDeclaredConstructors()[0];
dataConstructor.setAccessible(true);
fieldStorage = dataClazz.getDeclaredField(Refraction.pickName("storage", "b"));
fieldStorage.setAccessible(true);
fieldPalette = dataClazz.getDeclaredField(Refraction.pickName("palette", "c"));
fieldPalette.setAccessible(true);
fieldTickingFluidCount = LevelChunkSection.class.getDeclaredField(Refraction.pickName("tickingFluidCount", "h"));
fieldTickingFluidCount.setAccessible(true);
fieldTickingBlockCount = LevelChunkSection.class.getDeclaredField(Refraction.pickName("tickingBlockCount", "g"));
fieldTickingBlockCount.setAccessible(true);
fieldNonEmptyBlockCount = LevelChunkSection.class.getDeclaredField(Refraction.pickName("nonEmptyBlockCount", "f"));
fieldNonEmptyBlockCount.setAccessible(true);
Method getVisibleChunkIfPresent = ChunkMap.class.getDeclaredMethod(Refraction.pickName(
"getVisibleChunkIfPresent",
"b"
), long.class);
getVisibleChunkIfPresent.setAccessible(true);
methodGetVisibleChunk = MethodHandles.lookup().unreflect(getVisibleChunkIfPresent);
Unsafe unsafe = ReflectionUtils.getUnsafe();
if (!PaperLib.isPaper()) {
fieldThreadingDetector = PalettedContainer.class.getDeclaredField(Refraction.pickName("threadingDetector", "f"));
fieldThreadingDetectorOffset = unsafe.objectFieldOffset(fieldThreadingDetector);
fieldLock = ThreadingDetector.class.getDeclaredField(Refraction.pickName("lock", "c"));
fieldLockOffset = unsafe.objectFieldOffset(fieldLock);
} else {
// in paper, the used methods are synchronized properly
fieldThreadingDetector = null;
fieldThreadingDetectorOffset = -1;
fieldLock = null;
fieldLockOffset = -1;
}
Method removeGameEventListener = LevelChunk.class.getDeclaredMethod(
Refraction.pickName("removeGameEventListener", "a"),
BlockEntity.class,
ServerLevel.class
);
removeGameEventListener.setAccessible(true);
methodRemoveGameEventListener = MethodHandles.lookup().unreflect(removeGameEventListener);
Method removeBlockEntityTicker = LevelChunk.class.getDeclaredMethod(
Refraction.pickName(
"removeBlockEntityTicker",
"l"
), BlockPos.class
);
removeBlockEntityTicker.setAccessible(true);
methodremoveTickingBlockEntity = MethodHandles.lookup().unreflect(removeBlockEntityTicker);
fieldRemove = BlockEntity.class.getDeclaredField(Refraction.pickName("remove", "p"));
fieldRemove.setAccessible(true);
CHUNKSECTION_BASE = unsafe.arrayBaseOffset(LevelChunkSection[].class);
int scale = unsafe.arrayIndexScale(LevelChunkSection[].class);
if ((scale & (scale - 1)) != 0) {
throw new Error("data type scale not a power of two");
}
CHUNKSECTION_SHIFT = 31 - Integer.numberOfLeadingZeros(scale);
boolean chunkRewrite;
try {
ServerLevel.class.getDeclaredMethod("getEntityLookup");
chunkRewrite = true;
PAPER_CHUNK_GEN_ALL_ENTITIES = ChunkEntitySlices.class.getDeclaredMethod("getAllEntities");
PAPER_CHUNK_GEN_ALL_ENTITIES.setAccessible(true);
} catch (NoSuchMethodException ignored) {
chunkRewrite = false;
}
try {
// Paper - Pre-Chunk-Update
LEVEL_CHUNK_ENTITIES = LevelChunk.class.getDeclaredField("entities");
LEVEL_CHUNK_ENTITIES.setAccessible(true);
} catch (NoSuchFieldException ignored) {
}
try {
// Non-Paper
SERVER_LEVEL_ENTITY_MANAGER = ServerLevel.class.getDeclaredField(Refraction.pickName("entityManager", "P"));
SERVER_LEVEL_ENTITY_MANAGER.setAccessible(true);
} catch (NoSuchFieldException ignored) {
}
POST_CHUNK_REWRITE = chunkRewrite;
} catch (RuntimeException e) {
throw e;
} catch (Throwable rethrow) {
rethrow.printStackTrace();
throw new RuntimeException(rethrow);
}
}
static boolean setSectionAtomic(
LevelChunkSection[] sections,
LevelChunkSection expected,
LevelChunkSection value,
int layer
) {
long offset = ((long) layer << CHUNKSECTION_SHIFT) + CHUNKSECTION_BASE;
if (layer >= 0 && layer < sections.length) {
return ReflectionUtils.getUnsafe().compareAndSwapObject(sections, offset, expected, value);
}
return false;
}
// There is no point in having a functional semaphore for paper servers.
private static final ThreadLocal<DelegateSemaphore> SEMAPHORE_THREAD_LOCAL =
ThreadLocal.withInitial(() -> new DelegateSemaphore(1, null));
static DelegateSemaphore applyLock(LevelChunkSection section) {
if (PaperLib.isPaper()) {
return SEMAPHORE_THREAD_LOCAL.get();
}
try {
synchronized (section) {
Unsafe unsafe = ReflectionUtils.getUnsafe();
PalettedContainer<net.minecraft.world.level.block.state.BlockState> blocks = section.getStates();
ThreadingDetector currentThreadingDetector = (ThreadingDetector) unsafe.getObject(
blocks,
fieldThreadingDetectorOffset
);
synchronized (currentThreadingDetector) {
Semaphore currentLock = (Semaphore) unsafe.getObject(currentThreadingDetector, fieldLockOffset);
if (currentLock instanceof DelegateSemaphore delegateSemaphore) {
return delegateSemaphore;
}
DelegateSemaphore newLock = new DelegateSemaphore(1, currentLock);
unsafe.putObject(currentThreadingDetector, fieldLockOffset, newLock);
return newLock;
}
}
} catch (Throwable e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static LevelChunk ensureLoaded(ServerLevel serverLevel, int chunkX, int chunkZ) {
if (!PaperLib.isPaper()) {
LevelChunk nmsChunk = serverLevel.getChunkSource().getChunk(chunkX, chunkZ, false);
if (nmsChunk != null) {
return nmsChunk;
}
if (Fawe.isMainThread()) {
return serverLevel.getChunk(chunkX, chunkZ);
}
} else {
LevelChunk nmsChunk = serverLevel.getChunkSource().getChunkAtIfCachedImmediately(chunkX, chunkZ);
if (nmsChunk != null) {
addTicket(serverLevel, chunkX, chunkZ);
return nmsChunk;
}
nmsChunk = serverLevel.getChunkSource().getChunkAtIfLoadedImmediately(chunkX, chunkZ);
if (nmsChunk != null) {
addTicket(serverLevel, chunkX, chunkZ);
return nmsChunk;
}
// Avoid "async" methods from the main thread.
if (Fawe.isMainThread()) {
return serverLevel.getChunk(chunkX, chunkZ);
}
CompletableFuture<org.bukkit.Chunk> future = serverLevel.getWorld().getChunkAtAsync(chunkX, chunkZ, true, true);
try {
CraftChunk chunk = (CraftChunk) future.get();
return chunk.getHandle();
} catch (Throwable e) {
e.printStackTrace();
}
}
return TaskManager.taskManager().sync(() -> serverLevel.getChunk(chunkX, chunkZ));
}
private static void addTicket(ServerLevel serverLevel, int chunkX, int chunkZ) {
// Ensure chunk is definitely loaded before applying a ticket
io.papermc.paper.util.MCUtil.MAIN_EXECUTOR.execute(() -> serverLevel
.getChunkSource()
.addRegionTicket(TicketType.PLUGIN, new ChunkPos(chunkX, chunkZ), 0, Unit.INSTANCE));
}
public static ChunkHolder getPlayerChunk(ServerLevel nmsWorld, final int chunkX, final int chunkZ) {
ChunkMap chunkMap = nmsWorld.getChunkSource().chunkMap;
try {
return (ChunkHolder) methodGetVisibleChunk.invoke(chunkMap, ChunkPos.asLong(chunkX, chunkZ));
} catch (Throwable thr) {
throw new RuntimeException(thr);
}
}
@SuppressWarnings("deprecation")
public static void sendChunk(ServerLevel nmsWorld, int chunkX, int chunkZ, boolean lighting) {
ChunkHolder chunkHolder = getPlayerChunk(nmsWorld, chunkX, chunkZ);
if (chunkHolder == null) {
return;
}
ChunkPos coordIntPair = new ChunkPos(chunkX, chunkZ);
LevelChunk levelChunk;
if (PaperLib.isPaper()) {
// getChunkAtIfLoadedImmediately is paper only
levelChunk = nmsWorld
.getChunkSource()
.getChunkAtIfLoadedImmediately(chunkX, chunkZ);
} else {
levelChunk = ((Optional<LevelChunk>) ((Either) chunkHolder
.getTickingChunkFuture() // method is not present with new paper chunk system
.getNow(ChunkHolder.UNLOADED_LEVEL_CHUNK)).left())
.orElse(null);
}
if (levelChunk == null) {
return;
}
TaskManager.taskManager().task(() -> {
ClientboundLevelChunkWithLightPacket packet;
if (PaperLib.isPaper()) {
packet = new ClientboundLevelChunkWithLightPacket(
levelChunk,
nmsWorld.getChunkSource().getLightEngine(),
null,
null,
true,
false // last false is to not bother with x-ray
);
} else {
// deprecated on paper - deprecation suppressed
packet = new ClientboundLevelChunkWithLightPacket(
levelChunk,
nmsWorld.getChunkSource().getLightEngine(),
null,
null,
true
);
}
nearbyPlayers(nmsWorld, coordIntPair).forEach(p -> p.connection.send(packet));
});
}
private static List<ServerPlayer> nearbyPlayers(ServerLevel serverLevel, ChunkPos coordIntPair) {
return serverLevel.getChunkSource().chunkMap.getPlayers(coordIntPair, false);
}
/*
NMS conversion
*/
public static LevelChunkSection newChunkSection(
final int layer,
final char[] blocks,
CachedBukkitAdapter adapter,
Registry<Biome> biomeRegistry,
@Nullable PalettedContainer<Holder<Biome>> biomes
) {
return newChunkSection(layer, null, blocks, adapter, biomeRegistry, biomes);
}
public static LevelChunkSection newChunkSection(
final int layer,
final Function<Integer, char[]> get,
char[] set,
CachedBukkitAdapter adapter,
Registry<Biome> biomeRegistry,
@Nullable PalettedContainer<Holder<Biome>> biomes
) {
if (set == null) {
return newChunkSection(layer, biomeRegistry, biomes);
}
final int[] blockToPalette = FaweCache.INSTANCE.BLOCK_TO_PALETTE.get();
final int[] paletteToBlock = FaweCache.INSTANCE.PALETTE_TO_BLOCK.get();
final long[] blockStates = FaweCache.INSTANCE.BLOCK_STATES.get();
final int[] blocksCopy = FaweCache.INSTANCE.SECTION_BLOCKS.get();
try {
int num_palette;
if (get == null) {
num_palette = createPalette(blockToPalette, paletteToBlock, blocksCopy, set, adapter, null);
} else {
num_palette = createPalette(layer, blockToPalette, paletteToBlock, blocksCopy, get, set, adapter, null);
}
int bitsPerEntry = MathMan.log2nlz(num_palette - 1);
if (bitsPerEntry > 0 && bitsPerEntry < 5) {
bitsPerEntry = 4;
} else if (bitsPerEntry > 8) {
bitsPerEntry = MathMan.log2nlz(Block.BLOCK_STATE_REGISTRY.size() - 1);
}
int bitsPerEntryNonZero = Math.max(bitsPerEntry, 1); // We do want to use zero sometimes
final int blocksPerLong = MathMan.floorZero((double) 64 / bitsPerEntryNonZero);
final int blockBitArrayEnd = MathMan.ceilZero((float) 4096 / blocksPerLong);
if (num_palette == 1) {
for (int i = 0; i < blockBitArrayEnd; i++) {
blockStates[i] = 0;
}
} else {
final BitArrayUnstretched bitArray = new BitArrayUnstretched(bitsPerEntryNonZero, 4096, blockStates);
bitArray.fromRaw(blocksCopy);
}
final long[] bits = Arrays.copyOfRange(blockStates, 0, blockBitArrayEnd);
final BitStorage nmsBits;
if (bitsPerEntry == 0) {
nmsBits = new ZeroBitStorage(4096);
} else {
nmsBits = new SimpleBitStorage(bitsPerEntry, 4096, bits);
}
List<net.minecraft.world.level.block.state.BlockState> palette;
if (bitsPerEntry < 9) {
palette = new ArrayList<>();
for (int i = 0; i < num_palette; i++) {
int ordinal = paletteToBlock[i];
blockToPalette[ordinal] = Integer.MAX_VALUE;
final BlockState state = BlockTypesCache.states[ordinal];
palette.add(((PaperweightBlockMaterial) state.getMaterial()).getState());
}
} else {
palette = List.of();
}
// Create palette with data
@SuppressWarnings("deprecation") // constructor is deprecated on paper, but needed to keep compatibility with spigot
final PalettedContainer<net.minecraft.world.level.block.state.BlockState> blockStatePalettedContainer =
new PalettedContainer<>(
Block.BLOCK_STATE_REGISTRY,
PalettedContainer.Strategy.SECTION_STATES,
PalettedContainer.Strategy.SECTION_STATES.getConfiguration(Block.BLOCK_STATE_REGISTRY, bitsPerEntry),
nmsBits,
palette
);
if (biomes == null) {
IdMap<Holder<Biome>> biomeHolderIdMap = biomeRegistry.asHolderIdMap();
biomes = new PalettedContainer<>(
biomeHolderIdMap,
biomeHolderIdMap.byIdOrThrow(WorldEditPlugin
.getInstance()
.getBukkitImplAdapter()
.getInternalBiomeId(
BiomeTypes.PLAINS)),
PalettedContainer.Strategy.SECTION_BIOMES,
null
);
}
return new LevelChunkSection(layer, blockStatePalettedContainer, biomes);
} catch (final Throwable e) {
throw e;
} finally {
Arrays.fill(blockToPalette, Integer.MAX_VALUE);
Arrays.fill(paletteToBlock, Integer.MAX_VALUE);
Arrays.fill(blockStates, 0);
Arrays.fill(blocksCopy, 0);
}
}
@SuppressWarnings("deprecation") // Only deprecated in paper
private static LevelChunkSection newChunkSection(
int layer,
Registry<Biome> biomeRegistry,
@Nullable PalettedContainer<Holder<Biome>> biomes
) {
if (biomes == null) {
return new LevelChunkSection(layer, biomeRegistry);
}
PalettedContainer<net.minecraft.world.level.block.state.BlockState> dataPaletteBlocks = new PalettedContainer<>(
Block.BLOCK_STATE_REGISTRY,
Blocks.AIR.defaultBlockState(),
PalettedContainer.Strategy.SECTION_STATES,
null
);
return new LevelChunkSection(layer, dataPaletteBlocks, biomes);
}
/**
* Create a new {@link PalettedContainer<Biome>}. Should only be used if no biome container existed beforehand.
*/
public static PalettedContainer<Holder<Biome>> getBiomePalettedContainer(
BiomeType[] biomes,
IdMap<Holder<Biome>> biomeRegistry
) {
if (biomes == null) {
return null;
}
BukkitImplAdapter<?> adapter = WorldEditPlugin.getInstance().getBukkitImplAdapter();
// Don't stream this as typically will see 1-4 biomes; stream overhead is large for the small length
Map<BiomeType, Holder<Biome>> palette = new HashMap<>();
for (BiomeType biomeType : new LinkedList<>(Arrays.asList(biomes))) {
Holder<Biome> biome;
if (biomeType == null) {
biome = biomeRegistry.byId(adapter.getInternalBiomeId(BiomeTypes.PLAINS));
} else {
biome = biomeRegistry.byId(adapter.getInternalBiomeId(biomeType));
}
palette.put(biomeType, biome);
}
int biomeCount = palette.size();
int bitsPerEntry = MathMan.log2nlz(biomeCount - 1);
Object configuration = PalettedContainer.Strategy.SECTION_STATES.getConfiguration(
new FakeIdMapBiome(biomeCount),
bitsPerEntry
);
if (bitsPerEntry > 3) {
bitsPerEntry = MathMan.log2nlz(biomeRegistry.size() - 1);
}
PalettedContainer<Holder<Biome>> biomePalettedContainer = new PalettedContainer<>(
biomeRegistry,
biomeRegistry.byIdOrThrow(adapter.getInternalBiomeId(BiomeTypes.PLAINS)),
PalettedContainer.Strategy.SECTION_BIOMES,
null
);
final Palette<Holder<Biome>> biomePalette;
if (bitsPerEntry == 0) {
biomePalette = new SingleValuePalette<>(
biomePalettedContainer.registry,
biomePalettedContainer,
new ArrayList<>(palette.values()) // Must be modifiable
);
} else if (bitsPerEntry == 4) {
biomePalette = LinearPalette.create(
4,
biomePalettedContainer.registry,
biomePalettedContainer,
new ArrayList<>(palette.values()) // Must be modifiable
);
} else if (bitsPerEntry < 9) {
biomePalette = HashMapPalette.create(
bitsPerEntry,
biomePalettedContainer.registry,
biomePalettedContainer,
new ArrayList<>(palette.values()) // Must be modifiable
);
} else {
biomePalette = GlobalPalette.create(
bitsPerEntry,
biomePalettedContainer.registry,
biomePalettedContainer,
null // unused
);
}
int bitsPerEntryNonZero = Math.max(bitsPerEntry, 1); // We do want to use zero sometimes
final int blocksPerLong = MathMan.floorZero((double) 64 / bitsPerEntryNonZero);
final int arrayLength = MathMan.ceilZero(64f / blocksPerLong);
BitStorage bitStorage = bitsPerEntry == 0 ? new ZeroBitStorage(64) : new SimpleBitStorage(
bitsPerEntry,
64,
new long[arrayLength]
);
try {
Object data = dataConstructor.newInstance(configuration, bitStorage, biomePalette);
fieldData.set(biomePalettedContainer, data);
int index = 0;
for (int y = 0; y < 4; y++) {
for (int z = 0; z < 4; z++) {
for (int x = 0; x < 4; x++, index++) {
BiomeType biomeType = biomes[index];
if (biomeType == null) {
continue;
}
Holder<Biome> biome = biomeRegistry.byId(WorldEditPlugin
.getInstance()
.getBukkitImplAdapter()
.getInternalBiomeId(biomeType));
if (biome == null) {
continue;
}
biomePalettedContainer.set(x, y, z, biome);
}
}
}
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
return biomePalettedContainer;
}
public static void clearCounts(final LevelChunkSection section) throws IllegalAccessException {
fieldTickingFluidCount.setShort(section, (short) 0);
fieldTickingBlockCount.setShort(section, (short) 0);
}
public static BiomeType adapt(Holder<Biome> biome, LevelAccessor levelAccessor) {
final Registry<Biome> biomeRegistry = levelAccessor.registryAccess().registryOrThrow(BIOME);
if (biomeRegistry.getKey(biome.value()) == null) {
return biomeRegistry.asHolderIdMap().getId(biome) == -1 ? BiomeTypes.OCEAN
: null;
}
return BiomeTypes.get(biome.unwrapKey().orElseThrow().location().toString());
}
static void removeBeacon(BlockEntity beacon, LevelChunk levelChunk) {
try {
if (levelChunk.loaded || levelChunk.level.isClientSide()) {
BlockEntity blockEntity = levelChunk.blockEntities.remove(beacon.getBlockPos());
if (blockEntity != null) {
if (!levelChunk.level.isClientSide) {
methodRemoveGameEventListener.invoke(levelChunk, beacon, levelChunk.level);
}
fieldRemove.set(beacon, true);
}
}
methodremoveTickingBlockEntity.invoke(levelChunk, beacon.getBlockPos());
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
static List<Entity> getEntities(LevelChunk chunk) {
ExceptionCollector<RuntimeException> collector = new ExceptionCollector<>();
if (PaperLib.isPaper()) {
if (POST_CHUNK_REWRITE) {
try {
//noinspection unchecked
return (List<Entity>) PAPER_CHUNK_GEN_ALL_ENTITIES.invoke(chunk.level.getEntityLookup().getChunk(chunk.locX, chunk.locZ));
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException("Failed to lookup entities [POST_CHUNK_REWRITE=true]", e);
}
}
try {
EntityList entityList = (EntityList) LEVEL_CHUNK_ENTITIES.get(chunk);
return List.of(entityList.getRawData());
} catch (IllegalAccessException e) {
collector.add(new RuntimeException("Failed to lookup entities [POST_CHUNK_REWRITE=false]", e));
// fall through
}
}
try {
//noinspection unchecked
return ((PersistentEntitySectionManager<Entity>) (SERVER_LEVEL_ENTITY_MANAGER.get(chunk.level))).getEntities(chunk.getPos());
} catch (IllegalAccessException e) {
collector.add(new RuntimeException("Failed to lookup entities [PAPER=false]", e));
}
collector.throwIfPresent();
return List.of();
}
record FakeIdMapBlock(int size) implements IdMap<net.minecraft.world.level.block.state.BlockState> {
@Override
public int getId(final net.minecraft.world.level.block.state.BlockState entry) {
return 0;
}
@Nullable
@Override
public net.minecraft.world.level.block.state.BlockState byId(final int index) {
return null;
}
@Nonnull
@Override
public Iterator<net.minecraft.world.level.block.state.BlockState> iterator() {
return Collections.emptyIterator();
}
}
record FakeIdMapBiome(int size) implements IdMap<Biome> {
@Override
public int getId(final Biome entry) {
return 0;
}
@Nullable
@Override
public Biome byId(final int index) {
return null;
}
@Nonnull
@Override
public Iterator<Biome> iterator() {
return Collections.emptyIterator();
}
}
}

Datei anzeigen

@ -0,0 +1,175 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R2;
import com.fastasyncworldedit.core.configuration.Settings;
import com.fastasyncworldedit.core.extent.processor.ProcessorScope;
import com.fastasyncworldedit.core.queue.IBatchProcessor;
import com.fastasyncworldedit.core.queue.IChunk;
import com.fastasyncworldedit.core.queue.IChunkGet;
import com.fastasyncworldedit.core.queue.IChunkSet;
import com.fastasyncworldedit.core.registry.state.PropertyKey;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.world.block.BlockState;
import com.sk89q.worldedit.world.block.BlockTypes;
import com.sk89q.worldedit.world.block.BlockTypesCache;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.Fluids;
import javax.annotation.Nullable;
public class PaperweightPostProcessor implements IBatchProcessor {
@Override
public IChunkSet processSet(final IChunk chunk, final IChunkGet get, final IChunkSet set) {
return set;
}
@SuppressWarnings("deprecation")
@Override
public void postProcess(final IChunk chunk, final IChunkGet iChunkGet, final IChunkSet iChunkSet) {
boolean tickFluid = Settings.settings().EXPERIMENTAL.ALLOW_TICK_FLUIDS;
// The PostProcessor shouldn't be added, but just in case
if (!tickFluid) {
return;
}
PaperweightGetBlocks_Copy getBlocks = (PaperweightGetBlocks_Copy) iChunkGet;
layer:
for (int layer = iChunkSet.getMinSectionPosition(); layer <= iChunkSet.getMaxSectionPosition(); layer++) {
char[] set = iChunkSet.loadIfPresent(layer);
if (set == null) {
// No edit means no need to process
continue;
}
char[] get = null;
for (int i = 0; i < 4096; i++) {
char ordinal = set[i];
char replacedOrdinal = BlockTypesCache.ReservedIDs.__RESERVED__;
boolean fromGet = false; // Used for liquids
if (ordinal == BlockTypesCache.ReservedIDs.__RESERVED__) {
if (get == null) {
get = getBlocks.load(layer);
}
// If this is null, then it's because we're loading a layer in the range of 0->15, but blocks aren't
// actually being set
if (get == null) {
continue layer;
}
fromGet = true;
ordinal = replacedOrdinal = get[i];
}
if (ordinal == BlockTypesCache.ReservedIDs.__RESERVED__) {
continue;
} else if (!fromGet) { // if fromGet, don't do the same again
if (get == null) {
get = getBlocks.load(layer);
}
replacedOrdinal = get[i];
}
boolean ticking = BlockTypesCache.ticking[ordinal];
boolean replacedWasTicking = BlockTypesCache.ticking[replacedOrdinal];
boolean replacedWasLiquid = false;
BlockState replacedState = null;
if (!ticking) {
// If the block being replaced was not ticking, it cannot be a liquid
if (!replacedWasTicking) {
continue;
}
// If the block being replaced is not fluid, we do not need to worry
if (!(replacedWasLiquid =
(replacedState = BlockState.getFromOrdinal(replacedOrdinal)).getMaterial().isLiquid())) {
continue;
}
}
BlockState state = BlockState.getFromOrdinal(ordinal);
boolean liquid = state.getMaterial().isLiquid();
int x = i & 15;
int y = (i >> 8) & 15;
int z = (i >> 4) & 15;
BlockPos position = new BlockPos((chunk.getX() << 4) + x, (layer << 4) + y, (chunk.getZ() << 4) + z);
if (liquid || replacedWasLiquid) {
if (liquid) {
addFluid(getBlocks.serverLevel, state, position);
continue;
}
// If the replaced fluid (is?) adjacent to water. Do not bother to check adjacent chunks(sections) as this
// may be time consuming. Chances are any fluid blocks in adjacent chunks are being replaced or will end up
// being ticked anyway. We only need it to be "hit" once.
if (!wasAdjacentToWater(get, set, i, x, y, z)) {
continue;
}
addFluid(getBlocks.serverLevel, replacedState, position);
}
}
}
}
@Nullable
@Override
public Extent construct(final Extent child) {
throw new UnsupportedOperationException("Processing only");
}
@Override
public ProcessorScope getScope() {
return ProcessorScope.READING_SET_BLOCKS;
}
private boolean wasAdjacentToWater(char[] get, char[] set, int i, int x, int y, int z) {
if (set == null || get == null) {
return false;
}
char ordinal;
char reserved = BlockTypesCache.ReservedIDs.__RESERVED__;
if (x > 0 && set[i - 1] != reserved) {
if (BlockTypesCache.ticking[(ordinal = get[i - 1])] && isFluid(ordinal)) {
return true;
}
}
if (x < 15 && set[i + 1] != reserved) {
if (BlockTypesCache.ticking[(ordinal = get[i + 1])] && isFluid(ordinal)) {
return true;
}
}
if (z > 0 && set[i - 16] != reserved) {
if (BlockTypesCache.ticking[(ordinal = get[i - 16])] && isFluid(ordinal)) {
return true;
}
}
if (z < 15 && set[i + 16] != reserved) {
if (BlockTypesCache.ticking[(ordinal = get[i + 16])] && isFluid(ordinal)) {
return true;
}
}
if (y > 0 && set[i - 256] != reserved) {
if (BlockTypesCache.ticking[(ordinal = get[i - 256])] && isFluid(ordinal)) {
return true;
}
}
if (y < 15 && set[i + 256] != reserved) {
return BlockTypesCache.ticking[(ordinal = get[i + 256])] && isFluid(ordinal);
}
return false;
}
@SuppressWarnings("deprecation")
private boolean isFluid(char ordinal) {
return BlockState.getFromOrdinal(ordinal).getMaterial().isLiquid();
}
@SuppressWarnings("deprecation")
private void addFluid(final ServerLevel serverLevel, final BlockState replacedState, final BlockPos position) {
Fluid type;
if (replacedState.getBlockType() == BlockTypes.LAVA) {
type = (int) replacedState.getState(PropertyKey.LEVEL) == 0 ? Fluids.LAVA : Fluids.FLOWING_LAVA;
} else {
type = (int) replacedState.getState(PropertyKey.LEVEL) == 0 ? Fluids.WATER : Fluids.FLOWING_WATER;
}
serverLevel.scheduleTick(
position,
type,
type.getTickDelay(serverLevel)
);
}
}

Datei anzeigen

@ -0,0 +1,205 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R2;
import com.fastasyncworldedit.core.configuration.Settings;
import com.fastasyncworldedit.core.extent.processor.lighting.NMSRelighter;
import com.fastasyncworldedit.core.extent.processor.lighting.Relighter;
import com.fastasyncworldedit.core.queue.IQueueChunk;
import com.fastasyncworldedit.core.queue.IQueueExtent;
import com.fastasyncworldedit.core.util.MathMan;
import com.fastasyncworldedit.core.util.TaskManager;
import com.sk89q.worldedit.internal.util.LogManagerCompat;
import it.unimi.dsi.fastutil.longs.Long2ObjectLinkedOpenHashMap;
import it.unimi.dsi.fastutil.longs.LongArraySet;
import it.unimi.dsi.fastutil.longs.LongIterator;
import it.unimi.dsi.fastutil.longs.LongSet;
import net.minecraft.server.level.ChunkMap;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.TicketType;
import net.minecraft.util.Unit;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.chunk.ChunkStatus;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
public class PaperweightStarlightRelighter implements Relighter {
private static final Logger LOGGER = LogManagerCompat.getLogger();
private static final int CHUNKS_PER_BATCH = 1024; // 32 * 32
private static final int CHUNKS_PER_BATCH_SQRT_LOG2 = 5; // for shifting
private static final TicketType<Unit> FAWE_TICKET = TicketType.create("fawe_ticket", (a, b) -> 0);
private static final int LIGHT_LEVEL = ChunkMap.MAX_VIEW_DISTANCE + ChunkStatus.getDistance(ChunkStatus.LIGHT);
private final ServerLevel serverLevel;
private final ReentrantLock lock = new ReentrantLock();
private final Long2ObjectLinkedOpenHashMap<LongSet> regions = new Long2ObjectLinkedOpenHashMap<>();
private final ReentrantLock areaLock = new ReentrantLock();
private final NMSRelighter delegate;
@SuppressWarnings("rawtypes")
public PaperweightStarlightRelighter(ServerLevel serverLevel, IQueueExtent<IQueueChunk> queue) {
this.serverLevel = serverLevel;
this.delegate = new NMSRelighter(queue);
}
@Override
public boolean addChunk(int cx, int cz, byte[] skipReason, int bitmask) {
areaLock.lock();
try {
long key = MathMan.pairInt(cx >> CHUNKS_PER_BATCH_SQRT_LOG2, cz >> CHUNKS_PER_BATCH_SQRT_LOG2);
// TODO probably submit here already if chunks.size == CHUNKS_PER_BATCH?
LongSet chunks = this.regions.computeIfAbsent(key, k -> new LongArraySet(CHUNKS_PER_BATCH >> 2));
chunks.add(ChunkPos.asLong(cx, cz));
} finally {
areaLock.unlock();
}
return true;
}
@Override
public void addLightUpdate(int x, int y, int z) {
delegate.addLightUpdate(x, y, z);
}
/*
* This method is called "recursively", iterating and removing elements
* from the regions linked map. This way, chunks are loaded in batches to avoid
* OOMEs.
*/
@Override
public void fixLightingSafe(boolean sky) {
this.areaLock.lock();
try {
if (regions.isEmpty()) {
return;
}
LongSet first = regions.removeFirst();
fixLighting(first, () -> fixLightingSafe(true));
} finally {
this.areaLock.unlock();
}
}
/*
* Processes a set of chunks and runs an action afterwards.
* The action is run async, the chunks are partly processed on the main thread
* (as required by the server).
*/
private void fixLighting(LongSet chunks, Runnable andThen) {
// convert from long keys to ChunkPos
Set<ChunkPos> coords = new HashSet<>();
LongIterator iterator = chunks.iterator();
while (iterator.hasNext()) {
coords.add(new ChunkPos(iterator.nextLong()));
}
TaskManager.taskManager().task(() -> {
// trigger chunk load and apply ticket on main thread
List<CompletableFuture<?>> futures = new ArrayList<>();
for (ChunkPos pos : coords) {
futures.add(serverLevel.getWorld().getChunkAtAsync(pos.x, pos.z)
.thenAccept(c -> serverLevel.getChunkSource().addTicketAtLevel(
FAWE_TICKET,
pos,
LIGHT_LEVEL,
Unit.INSTANCE
))
);
}
// collect futures and trigger relight once all chunks are loaded
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).thenAccept(v ->
invokeRelight(
coords,
c -> {
}, // no callback for single chunks required
i -> {
if (i != coords.size()) {
LOGGER.warn("Processed {} chunks instead of {}", i, coords.size());
}
// post process chunks on main thread
TaskManager.taskManager().task(() -> postProcessChunks(coords));
// call callback on our own threads
TaskManager.taskManager().async(andThen);
}
)
);
});
}
private void invokeRelight(
Set<ChunkPos> coords,
Consumer<ChunkPos> chunkCallback,
IntConsumer processCallback
) {
try {
serverLevel.getChunkSource().getLightEngine().relight(coords, chunkCallback, processCallback);
} catch (Exception e) {
LOGGER.error("Error occurred on relighting", e);
}
}
/*
* Allow the server to unload the chunks again.
* Also, if chunk packets are sent delayed, we need to do that here
*/
private void postProcessChunks(Set<ChunkPos> coords) {
boolean delay = Settings.settings().LIGHTING.DELAY_PACKET_SENDING;
for (ChunkPos pos : coords) {
int x = pos.x;
int z = pos.z;
if (delay) { // we still need to send the block changes of that chunk
PaperweightPlatformAdapter.sendChunk(serverLevel, x, z, false);
}
serverLevel.getChunkSource().removeTicketAtLevel(FAWE_TICKET, pos, LIGHT_LEVEL, Unit.INSTANCE);
}
}
@Override
public void clear() {
}
@Override
public void removeLighting() {
this.delegate.removeLighting();
}
@Override
public void fixBlockLighting() {
fixLightingSafe(true);
}
@Override
public void fixSkyLighting() {
fixLightingSafe(true);
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public ReentrantLock getLock() {
return this.lock;
}
@Override
public boolean isFinished() {
return false;
}
@Override
public void close() throws Exception {
fixLightingSafe(true);
}
}

Datei anzeigen

@ -0,0 +1,28 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R2;
import com.fastasyncworldedit.core.extent.processor.lighting.NullRelighter;
import com.fastasyncworldedit.core.extent.processor.lighting.RelightMode;
import com.fastasyncworldedit.core.extent.processor.lighting.Relighter;
import com.fastasyncworldedit.core.extent.processor.lighting.RelighterFactory;
import com.fastasyncworldedit.core.queue.IQueueChunk;
import com.fastasyncworldedit.core.queue.IQueueExtent;
import com.sk89q.worldedit.world.World;
import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_19_R2.CraftWorld;
import javax.annotation.Nonnull;
public class PaperweightStarlightRelighterFactory implements RelighterFactory {
@Override
public @Nonnull
@SuppressWarnings("rawtypes")
Relighter createRelighter(RelightMode relightMode, World world, IQueueExtent<IQueueChunk> queue) {
org.bukkit.World w = Bukkit.getWorld(world.getName());
if (w == null) {
return NullRelighter.INSTANCE;
}
return new PaperweightStarlightRelighter(((CraftWorld) w).getHandle(), queue);
}
}

Datei anzeigen

@ -0,0 +1,161 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R2.nbt;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.LazyCompoundTag;
import com.sk89q.jnbt.ListTag;
import com.sk89q.jnbt.StringTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.util.nbt.CompoundBinaryTag;
import net.minecraft.nbt.NumericTag;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
public class PaperweightLazyCompoundTag extends LazyCompoundTag {
private final Supplier<net.minecraft.nbt.CompoundTag> compoundTagSupplier;
private CompoundTag compoundTag;
public PaperweightLazyCompoundTag(Supplier<net.minecraft.nbt.CompoundTag> compoundTagSupplier) {
super(new HashMap<>());
this.compoundTagSupplier = compoundTagSupplier;
}
public PaperweightLazyCompoundTag(net.minecraft.nbt.CompoundTag compoundTag) {
this(() -> compoundTag);
}
public net.minecraft.nbt.CompoundTag get() {
return compoundTagSupplier.get();
}
@Override
@SuppressWarnings("unchecked")
public Map<String, Tag> getValue() {
if (compoundTag == null) {
compoundTag = (CompoundTag) WorldEditPlugin.getInstance().getBukkitImplAdapter().toNative(compoundTagSupplier.get());
}
return compoundTag.getValue();
}
@Override
public CompoundBinaryTag asBinaryTag() {
getValue();
return compoundTag.asBinaryTag();
}
public boolean containsKey(String key) {
return compoundTagSupplier.get().contains(key);
}
public byte[] getByteArray(String key) {
return compoundTagSupplier.get().getByteArray(key);
}
public byte getByte(String key) {
return compoundTagSupplier.get().getByte(key);
}
public double getDouble(String key) {
return compoundTagSupplier.get().getDouble(key);
}
public double asDouble(String key) {
net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key);
if (tag instanceof NumericTag numTag) {
return numTag.getAsDouble();
}
return 0;
}
public float getFloat(String key) {
return compoundTagSupplier.get().getFloat(key);
}
public int[] getIntArray(String key) {
return compoundTagSupplier.get().getIntArray(key);
}
public int getInt(String key) {
return compoundTagSupplier.get().getInt(key);
}
public int asInt(String key) {
net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key);
if (tag instanceof NumericTag numTag) {
return numTag.getAsInt();
}
return 0;
}
@SuppressWarnings("unchecked")
public List<Tag> getList(String key) {
net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key);
if (tag instanceof net.minecraft.nbt.ListTag nbtList) {
ArrayList<Tag> list = new ArrayList<>();
for (net.minecraft.nbt.Tag elem : nbtList) {
if (elem instanceof net.minecraft.nbt.CompoundTag compoundTag) {
list.add(new PaperweightLazyCompoundTag(compoundTag));
} else {
list.add(WorldEditPlugin.getInstance().getBukkitImplAdapter().toNative(elem));
}
}
return list;
}
return Collections.emptyList();
}
@SuppressWarnings("unchecked")
public ListTag getListTag(String key) {
net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key);
if (tag instanceof net.minecraft.nbt.ListTag) {
return (ListTag) WorldEditPlugin.getInstance().getBukkitImplAdapter().toNative(tag);
}
return new ListTag(StringTag.class, Collections.emptyList());
}
@SuppressWarnings("unchecked")
public <T extends Tag> List<T> getList(String key, Class<T> listType) {
ListTag listTag = getListTag(key);
if (listTag.getType().equals(listType)) {
return (List<T>) listTag.getValue();
} else {
return Collections.emptyList();
}
}
public long[] getLongArray(String key) {
return compoundTagSupplier.get().getLongArray(key);
}
public long getLong(String key) {
return compoundTagSupplier.get().getLong(key);
}
public long asLong(String key) {
net.minecraft.nbt.Tag tag = compoundTagSupplier.get().get(key);
if (tag instanceof NumericTag numTag) {
return numTag.getAsLong();
}
return 0;
}
public short getShort(String key) {
return compoundTagSupplier.get().getShort(key);
}
public String getString(String key) {
return compoundTagSupplier.get().getString(key);
}
@Override
public String toString() {
return compoundTagSupplier.get().toString();
}
}

Datei anzeigen

@ -0,0 +1,594 @@
package com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R2.regen;
import com.fastasyncworldedit.bukkit.adapter.Regenerator;
import com.fastasyncworldedit.core.Fawe;
import com.fastasyncworldedit.core.queue.IChunkCache;
import com.fastasyncworldedit.core.queue.IChunkGet;
import com.fastasyncworldedit.core.util.ReflectionUtils;
import com.fastasyncworldedit.core.util.TaskManager;
import com.google.common.collect.ImmutableList;
import com.mojang.datafixers.util.Either;
import com.mojang.serialization.Lifecycle;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.adapter.Refraction;
import com.sk89q.worldedit.bukkit.adapter.impl.fawe.v1_19_R2.PaperweightGetBlocks;
import com.sk89q.worldedit.extent.Extent;
import com.sk89q.worldedit.internal.util.LogManagerCompat;
import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.util.io.file.SafeFiles;
import com.sk89q.worldedit.world.RegenOptions;
import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap;
import net.minecraft.core.Holder;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.dedicated.DedicatedServer;
import net.minecraft.server.level.ChunkMap;
import net.minecraft.server.level.ChunkTaskPriorityQueueSorter.Message;
import net.minecraft.server.level.ServerChunkCache;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ThreadedLevelLightEngine;
import net.minecraft.server.level.progress.ChunkProgressListener;
import net.minecraft.util.thread.ProcessorHandle;
import net.minecraft.util.thread.ProcessorMailbox;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelHeightAccessor;
import net.minecraft.world.level.LevelSettings;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.biome.BiomeSource;
import net.minecraft.world.level.biome.FixedBiomeSource;
import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.chunk.ChunkGeneratorStructureState;
import net.minecraft.world.level.chunk.ChunkStatus;
import net.minecraft.world.level.chunk.LevelChunk;
import net.minecraft.world.level.chunk.ProtoChunk;
import net.minecraft.world.level.chunk.UpgradeData;
import net.minecraft.world.level.dimension.LevelStem;
import net.minecraft.world.level.levelgen.FlatLevelSource;
import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator;
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
import net.minecraft.world.level.levelgen.WorldOptions;
import net.minecraft.world.level.levelgen.blending.BlendingData;
import net.minecraft.world.level.levelgen.flat.FlatLevelGeneratorSettings;
import net.minecraft.world.level.levelgen.structure.placement.ConcentricRingsStructurePlacement;
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
import net.minecraft.world.level.storage.LevelStorageSource;
import net.minecraft.world.level.storage.PrimaryLevelData;
import org.apache.logging.log4j.Logger;
import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_19_R2.CraftServer;
import org.bukkit.craftbukkit.v1_19_R2.CraftWorld;
import org.bukkit.craftbukkit.v1_19_R2.generator.CustomChunkGenerator;
import org.bukkit.generator.BiomeProvider;
import org.bukkit.generator.BlockPopulator;
import javax.annotation.Nullable;
import java.lang.reflect.Field;
import java.nio.file.Path;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.OptionalLong;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
import static net.minecraft.core.registries.Registries.BIOME;
public class PaperweightRegen extends Regenerator<ChunkAccess, ProtoChunk, LevelChunk, PaperweightRegen.ChunkStatusWrap> {
private static final Logger LOGGER = LogManagerCompat.getLogger();
private static final Field serverWorldsField;
private static final Field paperConfigField;
private static final Field flatBedrockField;
private static final Field generatorSettingFlatField;
private static final Field generatorSettingBaseSupplierField;
private static final Field delegateField;
private static final Field chunkSourceField;
private static final Field generatorStructureStateField;
private static final Field ringPositionsField;
private static final Field hasGeneratedPositionsField;
//list of chunk stati in correct order without FULL
private static final Map<ChunkStatus, Concurrency> chunkStati = new LinkedHashMap<>();
static {
chunkStati.put(ChunkStatus.EMPTY, Concurrency.FULL); // empty: radius -1, does nothing
chunkStati.put(ChunkStatus.STRUCTURE_STARTS, Concurrency.NONE); // structure starts: uses unsynchronized maps
chunkStati.put(
ChunkStatus.STRUCTURE_REFERENCES,
Concurrency.FULL
); // structure refs: radius 8, but only writes to current chunk
chunkStati.put(ChunkStatus.BIOMES, Concurrency.FULL); // biomes: radius 0
chunkStati.put(ChunkStatus.NOISE, Concurrency.RADIUS); // noise: radius 8
chunkStati.put(ChunkStatus.SURFACE, Concurrency.NONE); // surface: radius 0, requires NONE
chunkStati.put(ChunkStatus.CARVERS, Concurrency.NONE); // carvers: radius 0, but RADIUS and FULL change results
chunkStati.put(
ChunkStatus.LIQUID_CARVERS,
Concurrency.NONE
); // liquid carvers: radius 0, but RADIUS and FULL change results
chunkStati.put(ChunkStatus.FEATURES, Concurrency.NONE); // features: uses unsynchronized maps
chunkStati.put(
ChunkStatus.LIGHT,
Concurrency.FULL
); // light: radius 1, but no writes to other chunks, only current chunk
chunkStati.put(ChunkStatus.SPAWN, Concurrency.FULL); // spawn: radius 0
chunkStati.put(ChunkStatus.HEIGHTMAPS, Concurrency.FULL); // heightmaps: radius 0
try {
serverWorldsField = CraftServer.class.getDeclaredField("worlds");
serverWorldsField.setAccessible(true);
Field tmpPaperConfigField;
Field tmpFlatBedrockField;
try { //only present on paper
tmpPaperConfigField = Level.class.getDeclaredField("paperConfig");
tmpPaperConfigField.setAccessible(true);
tmpFlatBedrockField = tmpPaperConfigField.getType().getDeclaredField("generateFlatBedrock");
tmpFlatBedrockField.setAccessible(true);
} catch (Exception e) {
tmpPaperConfigField = null;
tmpFlatBedrockField = null;
}
paperConfigField = tmpPaperConfigField;
flatBedrockField = tmpFlatBedrockField;
generatorSettingBaseSupplierField = NoiseBasedChunkGenerator.class.getDeclaredField(Refraction.pickName(
"settings", "e"));
generatorSettingBaseSupplierField.setAccessible(true);
generatorSettingFlatField = FlatLevelSource.class.getDeclaredField(Refraction.pickName("settings", "d"));
generatorSettingFlatField.setAccessible(true);
delegateField = CustomChunkGenerator.class.getDeclaredField("delegate");
delegateField.setAccessible(true);
chunkSourceField = ServerLevel.class.getDeclaredField(Refraction.pickName("chunkSource", "L"));
chunkSourceField.setAccessible(true);
generatorStructureStateField = ChunkMap.class.getDeclaredField(Refraction.pickName("chunkGeneratorState", "w"));
generatorStructureStateField.setAccessible(true);
ringPositionsField = ChunkGeneratorStructureState.class.getDeclaredField(Refraction.pickName("ringPositions", "g"));
ringPositionsField.setAccessible(true);
hasGeneratedPositionsField = ChunkGeneratorStructureState.class.getDeclaredField(
Refraction.pickName("hasGeneratedPositions", "h")
);
hasGeneratedPositionsField.setAccessible(true);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//runtime
private ServerLevel originalServerWorld;
private ServerChunkCache originalChunkProvider;
private ServerLevel freshWorld;
private ServerChunkCache freshChunkProvider;
private LevelStorageSource.LevelStorageAccess session;
private StructureTemplateManager structureTemplateManager;
private ThreadedLevelLightEngine threadedLevelLightEngine;
private ChunkGenerator chunkGenerator;
private Path tempDir;
private boolean generateFlatBedrock = false;
public PaperweightRegen(org.bukkit.World originalBukkitWorld, Region region, Extent target, RegenOptions options) {
super(originalBukkitWorld, region, target, options);
}
@Override
protected boolean prepare() {
this.originalServerWorld = ((CraftWorld) originalBukkitWorld).getHandle();
originalChunkProvider = originalServerWorld.getChunkSource();
if (!(originalChunkProvider instanceof ServerChunkCache)) {
return false;
}
//flat bedrock? (only on paper)
if (paperConfigField != null) {
try {
generateFlatBedrock = flatBedrockField.getBoolean(paperConfigField.get(originalServerWorld));
} catch (Exception ignored) {
}
}
seed = options.getSeed().orElse(originalServerWorld.getSeed());
chunkStati.forEach((s, c) -> super.chunkStati.put(new ChunkStatusWrap(s), c));
return true;
}
@Override
@SuppressWarnings("unchecked")
protected boolean initNewWorld() throws Exception {
//world folder
tempDir = java.nio.file.Files.createTempDirectory("FastAsyncWorldEditWorldGen");
//prepare for world init (see upstream implementation for reference)
org.bukkit.World.Environment environment = originalBukkitWorld.getEnvironment();
org.bukkit.generator.ChunkGenerator generator = originalBukkitWorld.getGenerator();
LevelStorageSource levelStorageSource = LevelStorageSource.createDefault(tempDir);
ResourceKey<LevelStem> levelStemResourceKey = getWorldDimKey(environment);
session = levelStorageSource.createAccess("faweregentempworld", levelStemResourceKey);
PrimaryLevelData originalWorldData = originalServerWorld.serverLevelData;
MinecraftServer server = originalServerWorld.getCraftServer().getServer();
WorldOptions originalOpts = originalWorldData.worldGenOptions();
WorldOptions newOpts = options.getSeed().isPresent()
? originalOpts.withSeed(OptionalLong.of(seed))
: originalOpts;
LevelSettings newWorldSettings = new LevelSettings(
"faweregentempworld",
originalWorldData.settings.gameType(),
originalWorldData.settings.hardcore(),
originalWorldData.settings.difficulty(),
originalWorldData.settings.allowCommands(),
originalWorldData.settings.gameRules(),
originalWorldData.settings.getDataConfiguration()
);
PrimaryLevelData.SpecialWorldProperty specialWorldProperty =
originalWorldData.isFlatWorld()
? PrimaryLevelData.SpecialWorldProperty.FLAT
: originalWorldData.isDebugWorld()
? PrimaryLevelData.SpecialWorldProperty.DEBUG
: PrimaryLevelData.SpecialWorldProperty.NONE;
PrimaryLevelData newWorldData = new PrimaryLevelData(newWorldSettings, newOpts, specialWorldProperty, Lifecycle.stable());
BiomeProvider biomeProvider = getBiomeProvider();
//init world
freshWorld = Fawe.instance().getQueueHandler().sync((Supplier<ServerLevel>) () -> new ServerLevel(
server,
server.executor,
session,
newWorldData,
originalServerWorld.dimension(),
DedicatedServer.getServer().registryAccess().registry(Registries.LEVEL_STEM).orElseThrow()
.getOrThrow(levelStemResourceKey),
new RegenNoOpWorldLoadListener(),
originalServerWorld.isDebug(),
seed,
ImmutableList.of(),
false,
environment,
generator,
biomeProvider
) {
private final Holder<Biome> singleBiome = options.hasBiomeType() ? DedicatedServer.getServer().registryAccess()
.registryOrThrow(BIOME).asHolderIdMap().byIdOrThrow(
WorldEditPlugin.getInstance().getBukkitImplAdapter().getInternalBiomeId(options.getBiomeType())
) : null;
@Override
public void tick(BooleanSupplier shouldKeepTicking) { //no ticking
}
@Override
public Holder<Biome> getUncachedNoiseBiome(int biomeX, int biomeY, int biomeZ) {
if (options.hasBiomeType()) {
return singleBiome;
}
return PaperweightRegen.this.chunkGenerator.getBiomeSource().getNoiseBiome(
biomeX, biomeY, biomeZ, getChunkSource().randomState().sampler()
);
}
}).get();
freshWorld.noSave = true;
removeWorldFromWorldsMap();
newWorldData.checkName(originalServerWorld.serverLevelData.getLevelName()); //rename to original world name
if (paperConfigField != null) {
paperConfigField.set(freshWorld, originalServerWorld.paperConfig());
}
ChunkGenerator originalGenerator = originalChunkProvider.getGenerator();
if (originalGenerator instanceof FlatLevelSource flatLevelSource) {
FlatLevelGeneratorSettings generatorSettingFlat = flatLevelSource.settings();
chunkGenerator = new FlatLevelSource(generatorSettingFlat);
} else if (originalGenerator instanceof NoiseBasedChunkGenerator noiseBasedChunkGenerator) {
Holder<NoiseGeneratorSettings> generatorSettingBaseSupplier = (Holder<NoiseGeneratorSettings>) generatorSettingBaseSupplierField.get(
originalGenerator);
BiomeSource biomeSource;
if (options.hasBiomeType()) {
biomeSource = new FixedBiomeSource(
DedicatedServer.getServer().registryAccess()
.registryOrThrow(BIOME).asHolderIdMap().byIdOrThrow(
WorldEditPlugin.getInstance().getBukkitImplAdapter().getInternalBiomeId(options.getBiomeType())
)
);
} else {
biomeSource = originalGenerator.getBiomeSource();
}
chunkGenerator = new NoiseBasedChunkGenerator(
biomeSource,
generatorSettingBaseSupplier
);
} else if (originalGenerator instanceof CustomChunkGenerator customChunkGenerator) {
chunkGenerator = customChunkGenerator.getDelegate();
} else {
LOGGER.error("Unsupported generator type {}", originalGenerator.getClass().getName());
return false;
}
if (generator != null) {
chunkGenerator = new CustomChunkGenerator(freshWorld, chunkGenerator, generator);
generateConcurrent = generator.isParallelCapable();
}
// chunkGenerator.conf = freshWorld.spigotConfig; - Does not exist anymore, may need to be re-addressed
freshChunkProvider = new ServerChunkCache(
freshWorld,
session,
server.getFixerUpper(),
server.getStructureManager(),
server.executor,
chunkGenerator,
freshWorld.spigotConfig.viewDistance,
freshWorld.spigotConfig.simulationDistance,
server.forceSynchronousWrites(),
new RegenNoOpWorldLoadListener(),
(chunkCoordIntPair, state) -> {
},
() -> server.overworld().getDataStorage()
) {
// redirect to LevelChunks created in #createChunks
@Override
public ChunkAccess getChunk(int x, int z, ChunkStatus chunkstatus, boolean create) {
ChunkAccess chunkAccess = getChunkAt(x, z);
if (chunkAccess == null && create) {
chunkAccess = createChunk(getProtoChunkAt(x, z));
}
return chunkAccess;
}
};
if (seed == originalOpts.seed() && !options.hasBiomeType()) {
// Optimisation for needless ring position calculation when the seed and biome is the same.
ChunkGeneratorStructureState state = (ChunkGeneratorStructureState) generatorStructureStateField.get(originalChunkProvider.chunkMap);
boolean hasGeneratedPositions = hasGeneratedPositionsField.getBoolean(state);
if (hasGeneratedPositions) {
Map<ConcentricRingsStructurePlacement, CompletableFuture<List<ChunkPos>>> origPositions =
(Map<ConcentricRingsStructurePlacement, CompletableFuture<List<ChunkPos>>>) ringPositionsField.get(state);
Map<ConcentricRingsStructurePlacement, CompletableFuture<List<ChunkPos>>> copy = new Object2ObjectArrayMap<>(
origPositions);
ChunkGeneratorStructureState newState = (ChunkGeneratorStructureState) generatorStructureStateField.get(freshChunkProvider.chunkMap);
ringPositionsField.set(newState, copy);
hasGeneratedPositionsField.setBoolean(newState, true);
}
}
ReflectionUtils.unsafeSet(chunkSourceField, freshWorld, freshChunkProvider);
//let's start then
structureTemplateManager = server.getStructureManager();
threadedLevelLightEngine = new NoOpLightEngine(freshChunkProvider);
return true;
}
@Override
protected void cleanup() {
try {
session.close();
} catch (Exception ignored) {
}
//shutdown chunk provider
try {
Fawe.instance().getQueueHandler().sync(() -> {
try {
freshChunkProvider.close(false);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
} catch (Exception ignored) {
}
//remove world from server
try {
Fawe.instance().getQueueHandler().sync(this::removeWorldFromWorldsMap);
} catch (Exception ignored) {
}
//delete directory
try {
SafeFiles.tryHardToDeleteDir(tempDir);
} catch (Exception ignored) {
}
}
@Override
protected ProtoChunk createProtoChunk(int x, int z) {
return new FastProtoChunk(new ChunkPos(x, z), UpgradeData.EMPTY, freshWorld,
this.freshWorld.registryAccess().registryOrThrow(BIOME), null
);
}
@Override
protected LevelChunk createChunk(ProtoChunk protoChunk) {
return new LevelChunk(
freshWorld,
protoChunk,
null // we don't want to add entities
);
}
@Override
protected ChunkStatusWrap getFullChunkStatus() {
return new ChunkStatusWrap(ChunkStatus.FULL);
}
@Override
protected List<BlockPopulator> getBlockPopulators() {
return originalServerWorld.getWorld().getPopulators();
}
@Override
protected void populate(LevelChunk levelChunk, Random random, BlockPopulator blockPopulator) {
// BlockPopulator#populate has to be called synchronously for TileEntity access
TaskManager.taskManager().task(() -> blockPopulator.populate(freshWorld.getWorld(), random, levelChunk.getBukkitChunk()));
}
@Override
protected IChunkCache<IChunkGet> initSourceQueueCache() {
return (chunkX, chunkZ) -> new PaperweightGetBlocks(freshWorld, chunkX, chunkZ) {
@Override
public LevelChunk ensureLoaded(ServerLevel nmsWorld, int x, int z) {
return getChunkAt(x, z);
}
};
}
//util
@SuppressWarnings("unchecked")
private void removeWorldFromWorldsMap() {
Fawe.instance().getQueueHandler().sync(() -> {
try {
Map<String, org.bukkit.World> map = (Map<String, org.bukkit.World>) serverWorldsField.get(Bukkit.getServer());
map.remove("faweregentempworld");
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
});
}
private ResourceKey<LevelStem> getWorldDimKey(org.bukkit.World.Environment env) {
return switch (env) {
case NETHER -> LevelStem.NETHER;
case THE_END -> LevelStem.END;
default -> LevelStem.OVERWORLD;
};
}
private static class RegenNoOpWorldLoadListener implements ChunkProgressListener {
private RegenNoOpWorldLoadListener() {
}
@Override
public void updateSpawnPos(ChunkPos spawnPos) {
}
@Override
public void onStatusChange(ChunkPos pos, @Nullable ChunkStatus status) {
}
@Override
public void start() {
}
@Override
public void stop() {
}
// TODO Paper only(?) @Override
public void setChunkRadius(int radius) {
}
}
private class FastProtoChunk extends ProtoChunk {
public FastProtoChunk(
final ChunkPos pos,
final UpgradeData upgradeData,
final LevelHeightAccessor world,
final Registry<Biome> biomeRegistry,
@Nullable final BlendingData blendingData
) {
super(pos, upgradeData, world, biomeRegistry, blendingData);
}
// avoid warning on paper
// compatibility with spigot
public boolean generateFlatBedrock() {
return generateFlatBedrock;
}
// no one will ever see the entities!
@Override
public List<CompoundTag> getEntities() {
return Collections.emptyList();
}
}
protected class ChunkStatusWrap extends ChunkStatusWrapper<ChunkAccess> {
private final ChunkStatus chunkStatus;
public ChunkStatusWrap(ChunkStatus chunkStatus) {
this.chunkStatus = chunkStatus;
}
@Override
public int requiredNeighborChunkRadius() {
return chunkStatus.getRange();
}
@Override
public String name() {
return chunkStatus.getName();
}
@Override
public CompletableFuture<?> processChunk(Long xz, List<ChunkAccess> accessibleChunks) {
return chunkStatus.generate(
Runnable::run, // TODO revisit, we might profit from this somehow?
freshWorld,
chunkGenerator,
structureTemplateManager,
threadedLevelLightEngine,
c -> CompletableFuture.completedFuture(Either.left(c)),
accessibleChunks,
true
);
}
}
/**
* A light engine that does nothing. As light is calculated after pasting anyway, we can avoid
* work this way.
*/
static class NoOpLightEngine extends ThreadedLevelLightEngine {
private static final ProcessorMailbox<Runnable> MAILBOX = ProcessorMailbox.create(task -> {
}, "fawe-no-op");
private static final ProcessorHandle<Message<Runnable>> HANDLE = ProcessorHandle.of("fawe-no-op", m -> {
});
public NoOpLightEngine(final ServerChunkCache chunkProvider) {
super(chunkProvider, chunkProvider.chunkMap, false, MAILBOX, HANDLE);
}
@Override
public CompletableFuture<ChunkAccess> retainData(final ChunkAccess chunk) {
return CompletableFuture.completedFuture(chunk);
}
@Override
public CompletableFuture<ChunkAccess> lightChunk(final ChunkAccess chunk, final boolean excludeBlocks) {
return CompletableFuture.completedFuture(chunk);
}
}
}

Datei anzeigen

@ -0,0 +1,16 @@
import io.papermc.paperweight.userdev.PaperweightUserDependenciesExtension
plugins {
java
}
applyPaperweightAdapterConfiguration()
repositories {
gradlePluginPortal()
}
dependencies {
the<PaperweightUserDependenciesExtension>().paperDevBundle("1.19.4-R0.1-20230608.201059-104")
compileOnly(libs.paperlib)
}

Einige Dateien werden nicht angezeigt, da zu viele Dateien in diesem Diff geändert wurden Mehr anzeigen