Cut 13d: Real Sion species trees (cosmo_tree_gen, rtd_flow_field wind, Box3D & destruction)
|
|
@ -13,3 +13,8 @@ font assets under their respective licenses:
|
|||
Copyright (C) HarfBuzz Authors (Behdad Esfahbod, Google Inc., Red Hat Inc., et al.)
|
||||
License: HarfBuzz "Old MIT" License
|
||||
Full license text: assets/fonts/HARFBUZZ-COPYING.txt
|
||||
|
||||
3. Cosmo Tree Gen (upstream commit 33d6dc819ae79d5fff21d8b98407857cc2fc4d99, extended for RustToDust)
|
||||
Copyright (c) 2026 CosmonautFrog (https://github.com/FrogCosmonaut/cosmo_tree_gen)
|
||||
License: MIT License
|
||||
Full license text: third_party/cosmo_tree_gen/LICENSE.md
|
||||
|
|
|
|||
BIN
assets/maps/sion/trees/betula_pendula_v0.glb
Normal file
BIN
assets/maps/sion/trees/betula_pendula_v0_impostor_albedo.png
Normal file
|
After Width: | Height: | Size: 93 KiB |
BIN
assets/maps/sion/trees/betula_pendula_v0_impostor_normal.png
Normal file
|
After Width: | Height: | Size: 96 KiB |
BIN
assets/maps/sion/trees/betula_pendula_v1.glb
Normal file
BIN
assets/maps/sion/trees/betula_pendula_v1_impostor_albedo.png
Normal file
|
After Width: | Height: | Size: 99 KiB |
BIN
assets/maps/sion/trees/betula_pendula_v1_impostor_normal.png
Normal file
|
After Width: | Height: | Size: 103 KiB |
BIN
assets/maps/sion/trees/cedrus_v0.glb
Normal file
BIN
assets/maps/sion/trees/cedrus_v0_impostor_albedo.png
Normal file
|
After Width: | Height: | Size: 124 KiB |
BIN
assets/maps/sion/trees/cedrus_v0_impostor_normal.png
Normal file
|
After Width: | Height: | Size: 129 KiB |
BIN
assets/maps/sion/trees/malus_orchard_v0.glb
Normal file
BIN
assets/maps/sion/trees/malus_orchard_v0_impostor_albedo.png
Normal file
|
After Width: | Height: | Size: 90 KiB |
BIN
assets/maps/sion/trees/malus_orchard_v0_impostor_normal.png
Normal file
|
After Width: | Height: | Size: 95 KiB |
BIN
assets/maps/sion/trees/malus_orchard_v1.glb
Normal file
BIN
assets/maps/sion/trees/malus_orchard_v1_impostor_albedo.png
Normal file
|
After Width: | Height: | Size: 87 KiB |
BIN
assets/maps/sion/trees/malus_orchard_v1_impostor_normal.png
Normal file
|
After Width: | Height: | Size: 91 KiB |
BIN
assets/maps/sion/trees/picea_abies_v0.glb
Normal file
BIN
assets/maps/sion/trees/picea_abies_v0_impostor_albedo.png
Normal file
|
After Width: | Height: | Size: 85 KiB |
BIN
assets/maps/sion/trees/picea_abies_v0_impostor_normal.png
Normal file
|
After Width: | Height: | Size: 94 KiB |
BIN
assets/maps/sion/trees/picea_abies_v1.glb
Normal file
BIN
assets/maps/sion/trees/picea_abies_v1_impostor_albedo.png
Normal file
|
After Width: | Height: | Size: 92 KiB |
BIN
assets/maps/sion/trees/picea_abies_v1_impostor_normal.png
Normal file
|
After Width: | Height: | Size: 101 KiB |
BIN
assets/maps/sion/trees/pinus_sylvestris_v0.glb
Normal file
BIN
assets/maps/sion/trees/pinus_sylvestris_v0_impostor_albedo.png
Normal file
|
After Width: | Height: | Size: 77 KiB |
BIN
assets/maps/sion/trees/pinus_sylvestris_v0_impostor_normal.png
Normal file
|
After Width: | Height: | Size: 80 KiB |
BIN
assets/maps/sion/trees/pinus_sylvestris_v1.glb
Normal file
BIN
assets/maps/sion/trees/pinus_sylvestris_v1_impostor_albedo.png
Normal file
|
After Width: | Height: | Size: 72 KiB |
BIN
assets/maps/sion/trees/pinus_sylvestris_v1_impostor_normal.png
Normal file
|
After Width: | Height: | Size: 76 KiB |
BIN
assets/maps/sion/trees/platanus_acerifolia_v0.glb
Normal file
|
After Width: | Height: | Size: 79 KiB |
|
After Width: | Height: | Size: 86 KiB |
BIN
assets/maps/sion/trees/platanus_acerifolia_v1.glb
Normal file
|
After Width: | Height: | Size: 81 KiB |
|
After Width: | Height: | Size: 89 KiB |
BIN
assets/maps/sion/trees/platanus_monumental_v0.glb
Normal file
|
After Width: | Height: | Size: 87 KiB |
|
After Width: | Height: | Size: 94 KiB |
BIN
assets/maps/sion/trees/populus_nigra_v0.glb
Normal file
BIN
assets/maps/sion/trees/populus_nigra_v0_impostor_albedo.png
Normal file
|
After Width: | Height: | Size: 54 KiB |
BIN
assets/maps/sion/trees/populus_nigra_v0_impostor_normal.png
Normal file
|
After Width: | Height: | Size: 58 KiB |
BIN
assets/maps/sion/trees/populus_nigra_v1.glb
Normal file
BIN
assets/maps/sion/trees/populus_nigra_v1_impostor_albedo.png
Normal file
|
After Width: | Height: | Size: 53 KiB |
BIN
assets/maps/sion/trees/populus_nigra_v1_impostor_normal.png
Normal file
|
After Width: | Height: | Size: 58 KiB |
BIN
assets/maps/sion/trees/quercus_pubescens_v0.glb
Normal file
BIN
assets/maps/sion/trees/quercus_pubescens_v0_impostor_albedo.png
Normal file
|
After Width: | Height: | Size: 67 KiB |
BIN
assets/maps/sion/trees/quercus_pubescens_v0_impostor_normal.png
Normal file
|
After Width: | Height: | Size: 76 KiB |
BIN
assets/maps/sion/trees/quercus_pubescens_v1.glb
Normal file
BIN
assets/maps/sion/trees/quercus_pubescens_v1_impostor_albedo.png
Normal file
|
After Width: | Height: | Size: 65 KiB |
BIN
assets/maps/sion/trees/quercus_pubescens_v1_impostor_normal.png
Normal file
|
After Width: | Height: | Size: 75 KiB |
BIN
assets/maps/sion/trees/sequoiadendron_v0.glb
Normal file
BIN
assets/maps/sion/trees/sequoiadendron_v0_impostor_albedo.png
Normal file
|
After Width: | Height: | Size: 95 KiB |
BIN
assets/maps/sion/trees/sequoiadendron_v0_impostor_normal.png
Normal file
|
After Width: | Height: | Size: 102 KiB |
BIN
assets/maps/sion/trees/textures/bark.png
Normal file
|
After Width: | Height: | Size: 32 KiB |
BIN
assets/maps/sion/trees/textures/branchlet_birch.png
Normal file
|
After Width: | Height: | Size: 99 KiB |
BIN
assets/maps/sion/trees/textures/branchlet_broadleaf.png
Normal file
|
After Width: | Height: | Size: 76 KiB |
BIN
assets/maps/sion/trees/textures/branchlet_oak.png
Normal file
|
After Width: | Height: | Size: 38 KiB |
BIN
assets/maps/sion/trees/textures/branchlet_orchard.png
Normal file
|
After Width: | Height: | Size: 47 KiB |
BIN
assets/maps/sion/trees/textures/branchlet_pine.png
Normal file
|
After Width: | Height: | Size: 71 KiB |
BIN
assets/maps/sion/trees/textures/branchlet_spruce.png
Normal file
|
After Width: | Height: | Size: 97 KiB |
501
assets/maps/sion/trees/trees_catalog.json
Normal file
|
|
@ -0,0 +1,501 @@
|
|||
{
|
||||
"archetypes": [
|
||||
{
|
||||
"barkTexture": "textures/bark.png",
|
||||
"barkTint": [
|
||||
0.759999990463257,
|
||||
0.540000021457672,
|
||||
0.400000005960464
|
||||
],
|
||||
"canonicalHeightM": 19.94,
|
||||
"canonicalRadiusM": 0.34,
|
||||
"glb": "pinus_sylvestris_v0.glb",
|
||||
"impostorAlbedo": "pinus_sylvestris_v0_impostor_albedo.png",
|
||||
"impostorFrames": 6,
|
||||
"impostorNormal": "pinus_sylvestris_v0_impostor_normal.png",
|
||||
"impostorOffsetY": 9.8,
|
||||
"impostorScale": 10.86,
|
||||
"leafTexture": "textures/branchlet_pine.png",
|
||||
"leafTint": [
|
||||
0.560000002384186,
|
||||
0.680000007152557,
|
||||
0.439999997615814
|
||||
],
|
||||
"lod0Tris": 906,
|
||||
"lod1Tris": 222,
|
||||
"lod2Tris": 30,
|
||||
"slug": "pinus_sylvestris_v0",
|
||||
"speciesId": 0,
|
||||
"speciesName": "PinusSylvestris",
|
||||
"variant": 0
|
||||
},
|
||||
{
|
||||
"barkTexture": "textures/bark.png",
|
||||
"barkTint": [
|
||||
0.759999990463257,
|
||||
0.540000021457672,
|
||||
0.400000005960464
|
||||
],
|
||||
"canonicalHeightM": 17.19,
|
||||
"canonicalRadiusM": 0.29,
|
||||
"glb": "pinus_sylvestris_v1.glb",
|
||||
"impostorAlbedo": "pinus_sylvestris_v1_impostor_albedo.png",
|
||||
"impostorFrames": 6,
|
||||
"impostorNormal": "pinus_sylvestris_v1_impostor_normal.png",
|
||||
"impostorOffsetY": 8.42,
|
||||
"impostorScale": 9.41,
|
||||
"leafTexture": "textures/branchlet_pine.png",
|
||||
"leafTint": [
|
||||
0.560000002384186,
|
||||
0.680000007152557,
|
||||
0.439999997615814
|
||||
],
|
||||
"lod0Tris": 766,
|
||||
"lod1Tris": 188,
|
||||
"lod2Tris": 34,
|
||||
"slug": "pinus_sylvestris_v1",
|
||||
"speciesId": 0,
|
||||
"speciesName": "PinusSylvestris",
|
||||
"variant": 1
|
||||
},
|
||||
{
|
||||
"barkTexture": "textures/bark.png",
|
||||
"barkTint": [
|
||||
0.560000002384186,
|
||||
0.5,
|
||||
0.439999997615814
|
||||
],
|
||||
"canonicalHeightM": 15.37,
|
||||
"canonicalRadiusM": 0.36,
|
||||
"glb": "quercus_pubescens_v0.glb",
|
||||
"impostorAlbedo": "quercus_pubescens_v0_impostor_albedo.png",
|
||||
"impostorFrames": 6,
|
||||
"impostorNormal": "quercus_pubescens_v0_impostor_normal.png",
|
||||
"impostorOffsetY": 7.51,
|
||||
"impostorScale": 9.38,
|
||||
"leafTexture": "textures/branchlet_oak.png",
|
||||
"leafTint": [
|
||||
0.620000004768372,
|
||||
0.699999988079071,
|
||||
0.400000005960464
|
||||
],
|
||||
"lod0Tris": 626,
|
||||
"lod1Tris": 156,
|
||||
"lod2Tris": 34,
|
||||
"slug": "quercus_pubescens_v0",
|
||||
"speciesId": 1,
|
||||
"speciesName": "QuercusPubescens",
|
||||
"variant": 0
|
||||
},
|
||||
{
|
||||
"barkTexture": "textures/bark.png",
|
||||
"barkTint": [
|
||||
0.560000002384186,
|
||||
0.5,
|
||||
0.439999997615814
|
||||
],
|
||||
"canonicalHeightM": 14.83,
|
||||
"canonicalRadiusM": 0.3,
|
||||
"glb": "quercus_pubescens_v1.glb",
|
||||
"impostorAlbedo": "quercus_pubescens_v1_impostor_albedo.png",
|
||||
"impostorFrames": 6,
|
||||
"impostorNormal": "quercus_pubescens_v1_impostor_normal.png",
|
||||
"impostorOffsetY": 7.24,
|
||||
"impostorScale": 8.83,
|
||||
"leafTexture": "textures/branchlet_oak.png",
|
||||
"leafTint": [
|
||||
0.620000004768372,
|
||||
0.699999988079071,
|
||||
0.400000005960464
|
||||
],
|
||||
"lod0Tris": 666,
|
||||
"lod1Tris": 166,
|
||||
"lod2Tris": 32,
|
||||
"slug": "quercus_pubescens_v1",
|
||||
"speciesId": 1,
|
||||
"speciesName": "QuercusPubescens",
|
||||
"variant": 1
|
||||
},
|
||||
{
|
||||
"barkTexture": "textures/bark.png",
|
||||
"barkTint": [
|
||||
0.680000007152557,
|
||||
0.649999976158142,
|
||||
0.579999983310699
|
||||
],
|
||||
"canonicalHeightM": 22.99,
|
||||
"canonicalRadiusM": 0.38,
|
||||
"glb": "populus_nigra_v0.glb",
|
||||
"impostorAlbedo": "populus_nigra_v0_impostor_albedo.png",
|
||||
"impostorFrames": 6,
|
||||
"impostorNormal": "populus_nigra_v0_impostor_normal.png",
|
||||
"impostorOffsetY": 11.32,
|
||||
"impostorScale": 12.46,
|
||||
"leafTexture": "textures/branchlet_broadleaf.png",
|
||||
"leafTint": [
|
||||
0.660000026226044,
|
||||
0.779999971389771,
|
||||
0.46000000834465
|
||||
],
|
||||
"lod0Tris": 1066,
|
||||
"lod1Tris": 262,
|
||||
"lod2Tris": 46,
|
||||
"slug": "populus_nigra_v0",
|
||||
"speciesId": 2,
|
||||
"speciesName": "PopulusNigra",
|
||||
"variant": 0
|
||||
},
|
||||
{
|
||||
"barkTexture": "textures/bark.png",
|
||||
"barkTint": [
|
||||
0.680000007152557,
|
||||
0.649999976158142,
|
||||
0.579999983310699
|
||||
],
|
||||
"canonicalHeightM": 20.41,
|
||||
"canonicalRadiusM": 0.33,
|
||||
"glb": "populus_nigra_v1.glb",
|
||||
"impostorAlbedo": "populus_nigra_v1_impostor_albedo.png",
|
||||
"impostorFrames": 6,
|
||||
"impostorNormal": "populus_nigra_v1_impostor_normal.png",
|
||||
"impostorOffsetY": 10.03,
|
||||
"impostorScale": 11.1,
|
||||
"leafTexture": "textures/branchlet_broadleaf.png",
|
||||
"leafTint": [
|
||||
0.660000026226044,
|
||||
0.779999971389771,
|
||||
0.46000000834465
|
||||
],
|
||||
"lod0Tris": 906,
|
||||
"lod1Tris": 226,
|
||||
"lod2Tris": 50,
|
||||
"slug": "populus_nigra_v1",
|
||||
"speciesId": 2,
|
||||
"speciesName": "PopulusNigra",
|
||||
"variant": 1
|
||||
},
|
||||
{
|
||||
"barkTexture": "textures/bark.png",
|
||||
"barkTint": [
|
||||
0.759999990463257,
|
||||
0.720000028610229,
|
||||
0.620000004768372
|
||||
],
|
||||
"canonicalHeightM": 25.98,
|
||||
"canonicalRadiusM": 0.42,
|
||||
"glb": "platanus_acerifolia_v0.glb",
|
||||
"impostorAlbedo": "platanus_acerifolia_v0_impostor_albedo.png",
|
||||
"impostorFrames": 6,
|
||||
"impostorNormal": "platanus_acerifolia_v0_impostor_normal.png",
|
||||
"impostorOffsetY": 12.81,
|
||||
"impostorScale": 14.44,
|
||||
"leafTexture": "textures/branchlet_broadleaf.png",
|
||||
"leafTint": [
|
||||
0.639999985694885,
|
||||
0.759999990463257,
|
||||
0.419999986886978
|
||||
],
|
||||
"lod0Tris": 826,
|
||||
"lod1Tris": 206,
|
||||
"lod2Tris": 46,
|
||||
"slug": "platanus_acerifolia_v0",
|
||||
"speciesId": 3,
|
||||
"speciesName": "PlatanusAcerifolia",
|
||||
"variant": 0
|
||||
},
|
||||
{
|
||||
"barkTexture": "textures/bark.png",
|
||||
"barkTint": [
|
||||
0.759999990463257,
|
||||
0.720000028610229,
|
||||
0.620000004768372
|
||||
],
|
||||
"canonicalHeightM": 23.87,
|
||||
"canonicalRadiusM": 0.36,
|
||||
"glb": "platanus_acerifolia_v1.glb",
|
||||
"impostorAlbedo": "platanus_acerifolia_v1_impostor_albedo.png",
|
||||
"impostorFrames": 6,
|
||||
"impostorNormal": "platanus_acerifolia_v1_impostor_normal.png",
|
||||
"impostorOffsetY": 11.76,
|
||||
"impostorScale": 13.17,
|
||||
"leafTexture": "textures/branchlet_broadleaf.png",
|
||||
"leafTint": [
|
||||
0.639999985694885,
|
||||
0.759999990463257,
|
||||
0.419999986886978
|
||||
],
|
||||
"lod0Tris": 826,
|
||||
"lod1Tris": 206,
|
||||
"lod2Tris": 54,
|
||||
"slug": "platanus_acerifolia_v1",
|
||||
"speciesId": 3,
|
||||
"speciesName": "PlatanusAcerifolia",
|
||||
"variant": 1
|
||||
},
|
||||
{
|
||||
"barkTexture": "textures/bark.png",
|
||||
"barkTint": [
|
||||
0.920000016689301,
|
||||
0.899999976158142,
|
||||
0.860000014305115
|
||||
],
|
||||
"canonicalHeightM": 18.06,
|
||||
"canonicalRadiusM": 0.21,
|
||||
"glb": "betula_pendula_v0.glb",
|
||||
"impostorAlbedo": "betula_pendula_v0_impostor_albedo.png",
|
||||
"impostorFrames": 6,
|
||||
"impostorNormal": "betula_pendula_v0_impostor_normal.png",
|
||||
"impostorOffsetY": 8.88,
|
||||
"impostorScale": 9.79,
|
||||
"leafTexture": "textures/branchlet_birch.png",
|
||||
"leafTint": [
|
||||
0.699999988079071,
|
||||
0.819999992847443,
|
||||
0.46000000834465
|
||||
],
|
||||
"lod0Tris": 906,
|
||||
"lod1Tris": 220,
|
||||
"lod2Tris": 42,
|
||||
"slug": "betula_pendula_v0",
|
||||
"speciesId": 4,
|
||||
"speciesName": "BetulaPendula",
|
||||
"variant": 0
|
||||
},
|
||||
{
|
||||
"barkTexture": "textures/bark.png",
|
||||
"barkTint": [
|
||||
0.920000016689301,
|
||||
0.899999976158142,
|
||||
0.860000014305115
|
||||
],
|
||||
"canonicalHeightM": 16.02,
|
||||
"canonicalRadiusM": 0.18,
|
||||
"glb": "betula_pendula_v1.glb",
|
||||
"impostorAlbedo": "betula_pendula_v1_impostor_albedo.png",
|
||||
"impostorFrames": 6,
|
||||
"impostorNormal": "betula_pendula_v1_impostor_normal.png",
|
||||
"impostorOffsetY": 7.86,
|
||||
"impostorScale": 8.82,
|
||||
"leafTexture": "textures/branchlet_birch.png",
|
||||
"leafTint": [
|
||||
0.699999988079071,
|
||||
0.819999992847443,
|
||||
0.46000000834465
|
||||
],
|
||||
"lod0Tris": 906,
|
||||
"lod1Tris": 220,
|
||||
"lod2Tris": 42,
|
||||
"slug": "betula_pendula_v1",
|
||||
"speciesId": 4,
|
||||
"speciesName": "BetulaPendula",
|
||||
"variant": 1
|
||||
},
|
||||
{
|
||||
"barkTexture": "textures/bark.png",
|
||||
"barkTint": [
|
||||
0.540000021457672,
|
||||
0.419999986886978,
|
||||
0.340000003576279
|
||||
],
|
||||
"canonicalHeightM": 20.52,
|
||||
"canonicalRadiusM": 0.32,
|
||||
"glb": "picea_abies_v0.glb",
|
||||
"impostorAlbedo": "picea_abies_v0_impostor_albedo.png",
|
||||
"impostorFrames": 6,
|
||||
"impostorNormal": "picea_abies_v0_impostor_normal.png",
|
||||
"impostorOffsetY": 10.08,
|
||||
"impostorScale": 12.19,
|
||||
"leafTexture": "textures/branchlet_spruce.png",
|
||||
"leafTint": [
|
||||
0.419999986886978,
|
||||
0.560000002384186,
|
||||
0.360000014305115
|
||||
],
|
||||
"lod0Tris": 622,
|
||||
"lod1Tris": 150,
|
||||
"lod2Tris": 66,
|
||||
"slug": "picea_abies_v0",
|
||||
"speciesId": 5,
|
||||
"speciesName": "PiceaAbies",
|
||||
"variant": 0
|
||||
},
|
||||
{
|
||||
"barkTexture": "textures/bark.png",
|
||||
"barkTint": [
|
||||
0.540000021457672,
|
||||
0.419999986886978,
|
||||
0.340000003576279
|
||||
],
|
||||
"canonicalHeightM": 17.52,
|
||||
"canonicalRadiusM": 0.27,
|
||||
"glb": "picea_abies_v1.glb",
|
||||
"impostorAlbedo": "picea_abies_v1_impostor_albedo.png",
|
||||
"impostorFrames": 6,
|
||||
"impostorNormal": "picea_abies_v1_impostor_normal.png",
|
||||
"impostorOffsetY": 8.58,
|
||||
"impostorScale": 10.2,
|
||||
"leafTexture": "textures/branchlet_spruce.png",
|
||||
"leafTint": [
|
||||
0.419999986886978,
|
||||
0.560000002384186,
|
||||
0.360000014305115
|
||||
],
|
||||
"lod0Tris": 542,
|
||||
"lod1Tris": 130,
|
||||
"lod2Tris": 50,
|
||||
"slug": "picea_abies_v1",
|
||||
"speciesId": 5,
|
||||
"speciesName": "PiceaAbies",
|
||||
"variant": 1
|
||||
},
|
||||
{
|
||||
"barkTexture": "textures/bark.png",
|
||||
"barkTint": [
|
||||
0.620000004768372,
|
||||
0.540000021457672,
|
||||
0.46000000834465
|
||||
],
|
||||
"canonicalHeightM": 8.87,
|
||||
"canonicalRadiusM": 0.18,
|
||||
"glb": "malus_orchard_v0.glb",
|
||||
"impostorAlbedo": "malus_orchard_v0_impostor_albedo.png",
|
||||
"impostorFrames": 6,
|
||||
"impostorNormal": "malus_orchard_v0_impostor_normal.png",
|
||||
"impostorOffsetY": 4.31,
|
||||
"impostorScale": 4.9,
|
||||
"leafTexture": "textures/branchlet_orchard.png",
|
||||
"leafTint": [
|
||||
0.680000007152557,
|
||||
0.779999971389771,
|
||||
0.439999997615814
|
||||
],
|
||||
"lod0Tris": 666,
|
||||
"lod1Tris": 164,
|
||||
"lod2Tris": 30,
|
||||
"slug": "malus_orchard_v0",
|
||||
"speciesId": 6,
|
||||
"speciesName": "MalusOrchard",
|
||||
"variant": 0
|
||||
},
|
||||
{
|
||||
"barkTexture": "textures/bark.png",
|
||||
"barkTint": [
|
||||
0.620000004768372,
|
||||
0.540000021457672,
|
||||
0.46000000834465
|
||||
],
|
||||
"canonicalHeightM": 7.66,
|
||||
"canonicalRadiusM": 0.15,
|
||||
"glb": "malus_orchard_v1.glb",
|
||||
"impostorAlbedo": "malus_orchard_v1_impostor_albedo.png",
|
||||
"impostorFrames": 6,
|
||||
"impostorNormal": "malus_orchard_v1_impostor_normal.png",
|
||||
"impostorOffsetY": 3.71,
|
||||
"impostorScale": 4.72,
|
||||
"leafTexture": "textures/branchlet_orchard.png",
|
||||
"leafTint": [
|
||||
0.680000007152557,
|
||||
0.779999971389771,
|
||||
0.439999997615814
|
||||
],
|
||||
"lod0Tris": 666,
|
||||
"lod1Tris": 164,
|
||||
"lod2Tris": 34,
|
||||
"slug": "malus_orchard_v1",
|
||||
"speciesId": 6,
|
||||
"speciesName": "MalusOrchard",
|
||||
"variant": 1
|
||||
},
|
||||
{
|
||||
"barkTexture": "textures/bark.png",
|
||||
"barkTint": [
|
||||
0.720000028610229,
|
||||
0.419999986886978,
|
||||
0.300000011920929
|
||||
],
|
||||
"canonicalHeightM": 29.09,
|
||||
"canonicalRadiusM": 0.88,
|
||||
"glb": "sequoiadendron_v0.glb",
|
||||
"impostorAlbedo": "sequoiadendron_v0_impostor_albedo.png",
|
||||
"impostorFrames": 6,
|
||||
"impostorNormal": "sequoiadendron_v0_impostor_normal.png",
|
||||
"impostorOffsetY": 14.29,
|
||||
"impostorScale": 15.87,
|
||||
"leafTexture": "textures/branchlet_spruce.png",
|
||||
"leafTint": [
|
||||
0.46000000834465,
|
||||
0.600000023841858,
|
||||
0.379999995231628
|
||||
],
|
||||
"lod0Tris": 662,
|
||||
"lod1Tris": 160,
|
||||
"lod2Tris": 74,
|
||||
"slug": "sequoiadendron_v0",
|
||||
"speciesId": 7,
|
||||
"speciesName": "Sequoiadendron",
|
||||
"variant": 0
|
||||
},
|
||||
{
|
||||
"barkTexture": "textures/bark.png",
|
||||
"barkTint": [
|
||||
0.579999983310699,
|
||||
0.519999980926514,
|
||||
0.46000000834465
|
||||
],
|
||||
"canonicalHeightM": 25.51,
|
||||
"canonicalRadiusM": 0.68,
|
||||
"glb": "cedrus_v0.glb",
|
||||
"impostorAlbedo": "cedrus_v0_impostor_albedo.png",
|
||||
"impostorFrames": 6,
|
||||
"impostorNormal": "cedrus_v0_impostor_normal.png",
|
||||
"impostorOffsetY": 12.53,
|
||||
"impostorScale": 13.92,
|
||||
"leafTexture": "textures/branchlet_spruce.png",
|
||||
"leafTint": [
|
||||
0.479999989271164,
|
||||
0.639999985694885,
|
||||
0.46000000834465
|
||||
],
|
||||
"lod0Tris": 986,
|
||||
"lod1Tris": 244,
|
||||
"lod2Tris": 38,
|
||||
"slug": "cedrus_v0",
|
||||
"speciesId": 8,
|
||||
"speciesName": "Cedrus",
|
||||
"variant": 0
|
||||
},
|
||||
{
|
||||
"barkTexture": "textures/bark.png",
|
||||
"barkTint": [
|
||||
0.779999971389771,
|
||||
0.740000009536743,
|
||||
0.639999985694885
|
||||
],
|
||||
"canonicalHeightM": 36.57,
|
||||
"canonicalRadiusM": 0.72,
|
||||
"glb": "platanus_monumental_v0.glb",
|
||||
"impostorAlbedo": "platanus_monumental_v0_impostor_albedo.png",
|
||||
"impostorFrames": 6,
|
||||
"impostorNormal": "platanus_monumental_v0_impostor_normal.png",
|
||||
"impostorOffsetY": 18.06,
|
||||
"impostorScale": 20.0,
|
||||
"leafTexture": "textures/branchlet_broadleaf.png",
|
||||
"leafTint": [
|
||||
0.639999985694885,
|
||||
0.759999990463257,
|
||||
0.419999986886978
|
||||
],
|
||||
"lod0Tris": 906,
|
||||
"lod1Tris": 226,
|
||||
"lod2Tris": 50,
|
||||
"slug": "platanus_monumental_v0",
|
||||
"speciesId": 9,
|
||||
"speciesName": "PlatanusMonumental",
|
||||
"variant": 0
|
||||
}
|
||||
],
|
||||
"beechPresent": false,
|
||||
"impostorFrames": 6,
|
||||
"impostorResolution": 384,
|
||||
"version": 1
|
||||
}
|
||||
BIN
assets/maps/sion/trees_sion.bin
Normal file
|
|
@ -122,6 +122,7 @@ public partial class ArenaRenderer : Node3D
|
|||
private StandardMaterial3D _coverMat = null!;
|
||||
private StandardMaterial3D _bermMat = null!;
|
||||
private StandardMaterial3D _imperialBeaconMat = null!;
|
||||
private ArrayMesh? _fallingLogMesh;
|
||||
private MatchState? _builtForState;
|
||||
private float _lastSafeRingRadius = -1f;
|
||||
|
||||
|
|
@ -437,11 +438,70 @@ public partial class ArenaRenderer : Node3D
|
|||
|
||||
EmitContinuousActorParticles(session, hasCam, camPos, sampleGroundTint);
|
||||
ConsumeDropPodEvents(session, events, camPos, hasCam);
|
||||
ConsumeTreeEvents(state, events, camPos, hasCam);
|
||||
UpdateExplosiveRingsAndCores(events, stepDt);
|
||||
_particles.AdvanceAndCommit(stepDt);
|
||||
_volumetrics.Step(stepDt);
|
||||
}
|
||||
|
||||
private void ConsumeTreeEvents(MatchState state, IReadOnlyList<ISimEvent> events, Vector3 camPos, bool hasCam)
|
||||
{
|
||||
if (state.SionTrees is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var trees = state.SionTrees.Catalog;
|
||||
for (int i = 0; i < events.Count; i++)
|
||||
{
|
||||
if (events[i] is not TreeStateEvent te || te.TreeId >= trees.Count)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
var placement = trees.Trees[te.TreeId];
|
||||
Vector3 canopyPos = new(placement.X, placement.Y + placement.HeightM * 0.55f, placement.Z);
|
||||
var st = (SionTreeState)te.State;
|
||||
if (st == SionTreeState.Snapped)
|
||||
{
|
||||
_fallingLogMesh ??= BuildFallingLogMesh();
|
||||
float trunkLen = Math.Clamp(placement.HeightM * 0.48f, 2.2f, 6.5f);
|
||||
float trunkW = Math.Clamp(placement.TrunkRadiusM * 2.0f, 0.28f, 1.4f);
|
||||
Basis rot = Basis.FromEuler(new Vector3(0.25f, placement.Yaw, 0.18f))
|
||||
.Scaled(new Vector3(trunkW, trunkLen, trunkW));
|
||||
Transform3D xf = new(rot, new Vector3(placement.X, placement.Y + 2.6f, placement.Z));
|
||||
_debris.SpawnDetachedPart(
|
||||
_fallingLogMesh,
|
||||
xf,
|
||||
new Vector3(te.ImpactX, te.ImpactY, te.ImpactZ),
|
||||
Vector3.Up * 2.5f,
|
||||
roleIndex: 2f,
|
||||
impulseScale: 0.75f,
|
||||
applyScorch: true,
|
||||
lifetime: 5.0f);
|
||||
_particles.EmitTreeImpactBurst(canopyPos, placement.HeightM, isChar: false, camPos, hasCam);
|
||||
}
|
||||
else if (st == SionTreeState.Charred)
|
||||
{
|
||||
_particles.EmitTreeImpactBurst(canopyPos, placement.HeightM, isChar: true, camPos, hasCam);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static ArrayMesh BuildFallingLogMesh()
|
||||
{
|
||||
var cyl = new CylinderMesh
|
||||
{
|
||||
TopRadius = 0.36f,
|
||||
BottomRadius = 0.52f,
|
||||
Height = 1.0f,
|
||||
RadialSegments = 6,
|
||||
Rings = 1
|
||||
};
|
||||
var st = new SurfaceTool();
|
||||
st.Begin(Mesh.PrimitiveType.Triangles);
|
||||
st.AppendFrom(cyl, 0, Transform3D.Identity);
|
||||
return st.Commit();
|
||||
}
|
||||
|
||||
private VehicleVisualInstance? ResolveEntityVisual(bool isContender, int id) =>
|
||||
isContender ? GetContenderVisual(id) : GetSpectatorVisual(id);
|
||||
|
||||
|
|
|
|||
618
client/FoliageRenderer.cs
Normal file
|
|
@ -0,0 +1,618 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using Godot;
|
||||
using RustToDust.Core;
|
||||
|
||||
namespace RustToDust.Client;
|
||||
|
||||
/// <summary>
|
||||
/// GPU-instanced MultiMesh + 6x6 octahedral impostor renderer for real Sion trees
|
||||
/// baked via vendored cosmo_tree_gen (MIT) with hierarchical COLOR.rgba wind weights
|
||||
/// bound to global <c>rtd_flow_field</c>.
|
||||
/// </summary>
|
||||
public partial class FoliageRenderer : Node3D
|
||||
{
|
||||
public const float Lod0MaxDistanceM = 85f;
|
||||
public const float Lod1MaxDistanceM = 150f;
|
||||
public const float Lod2MaxDistanceM = 550f;
|
||||
public const float ImpostorMaxDistanceM = 1850f;
|
||||
public const float StumpMaxDistanceM = 450f;
|
||||
private const float RebuildMoveThresholdSq = 10f * 10f;
|
||||
|
||||
private sealed class TreeArchetype
|
||||
{
|
||||
public int SpeciesId;
|
||||
public int Variant;
|
||||
public string Slug = string.Empty;
|
||||
public float CanonicalHeightM;
|
||||
public float ImpostorScale;
|
||||
public float ImpostorOffsetY;
|
||||
public int ImpostorFrames = 6;
|
||||
public ArrayMesh Lod0 = null!;
|
||||
public ArrayMesh Lod1 = null!;
|
||||
public ArrayMesh Lod2 = null!;
|
||||
public ArrayMesh SnappedStump = null!;
|
||||
public ArrayMesh CharredSkeleton = null!;
|
||||
public QuadMesh ImpostorQuad = null!;
|
||||
|
||||
public BucketState BucketLod0 = null!;
|
||||
public BucketState BucketLod1 = null!;
|
||||
public BucketState BucketLod2 = null!;
|
||||
public BucketState BucketImpostor = null!;
|
||||
public BucketState BucketStump = null!;
|
||||
public BucketState BucketCharred = null!;
|
||||
}
|
||||
|
||||
private sealed class BucketState
|
||||
{
|
||||
public MultiMesh MultiMesh = null!;
|
||||
public MultiMeshInstance3D Instance = null!;
|
||||
public readonly List<int> Indices = new(128);
|
||||
}
|
||||
|
||||
private struct PrecomputedTree
|
||||
{
|
||||
public int ArchetypeIdx;
|
||||
public Transform3D WorldXform;
|
||||
public Vector3 Position;
|
||||
public Color CustomDataBase; // (0, phase, height, 1)
|
||||
}
|
||||
|
||||
private readonly List<TreeArchetype> _archetypes = new(17);
|
||||
private readonly int[,] _archetypeLookup = new int[10, 2];
|
||||
private readonly Dictionary<string, Texture2D> _textureCache = new(StringComparer.OrdinalIgnoreCase);
|
||||
private Shader _leavesShader = null!;
|
||||
private Shader _barkShader = null!;
|
||||
private Shader _impostorShader = null!;
|
||||
|
||||
private SionTreeCatalog? _boundCatalog;
|
||||
private PrecomputedTree[] _precomputed = Array.Empty<PrecomputedTree>();
|
||||
private int _lastRenderVersion = -1;
|
||||
private Vector3 _lastCamPos = new(float.NaN, float.NaN, float.NaN);
|
||||
private bool _assetsLoaded;
|
||||
private bool _assetsLoadAttempted;
|
||||
|
||||
public bool IsBuilt => _assetsLoaded && _boundCatalog is not null;
|
||||
public int ArchetypeCount => _archetypes.Count;
|
||||
public int TotalTreeCount => _boundCatalog?.Count ?? 0;
|
||||
public int VisibleLod0Count { get; private set; }
|
||||
public int VisibleLod1Count { get; private set; }
|
||||
public int VisibleLod2Count { get; private set; }
|
||||
public int VisibleImpostorCount { get; private set; }
|
||||
public int VisibleStumpCount { get; private set; }
|
||||
public int VisibleCharredCount { get; private set; }
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
for (int s = 0; s < 10; s++)
|
||||
{
|
||||
for (int v = 0; v < 2; v++)
|
||||
{
|
||||
_archetypeLookup[s, v] = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Invalidate()
|
||||
{
|
||||
_lastRenderVersion = -1;
|
||||
_lastCamPos = new Vector3(float.NaN, float.NaN, float.NaN);
|
||||
}
|
||||
|
||||
public bool VerifyAllLodsHaveVertexColor(out string error)
|
||||
{
|
||||
foreach (var arch in _archetypes)
|
||||
{
|
||||
ArrayMesh[] lods = { arch.Lod0, arch.Lod1, arch.Lod2 };
|
||||
for (int l = 0; l < lods.Length; l++)
|
||||
{
|
||||
var mesh = lods[l];
|
||||
if (mesh is null || mesh.GetSurfaceCount() == 0)
|
||||
{
|
||||
error = $"{arch.Slug} LOD{l} missing mesh surfaces";
|
||||
return false;
|
||||
}
|
||||
for (int s = 0; s < mesh.GetSurfaceCount(); s++)
|
||||
{
|
||||
var arr = mesh.SurfaceGetArrays(s);
|
||||
if (arr.Count <= (int)Mesh.ArrayType.Color ||
|
||||
arr[(int)Mesh.ArrayType.Color].VariantType != Variant.Type.PackedColorArray)
|
||||
{
|
||||
error = $"{arch.Slug} LOD{l} surface {s} missing ARRAY_COLOR";
|
||||
return false;
|
||||
}
|
||||
var colors = arr[(int)Mesh.ArrayType.Color].AsColorArray();
|
||||
bool hasFlexGrad = false;
|
||||
for (int k = 0; k < colors.Length; k++)
|
||||
{
|
||||
if (colors[k].G > 0.05f)
|
||||
{
|
||||
hasFlexGrad = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!hasFlexGrad)
|
||||
{
|
||||
error = $"{arch.Slug} LOD{l} surface {s} has zero wind flex gradient in COLOR.G";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
error = string.Empty;
|
||||
return _archetypes.Count == 17;
|
||||
}
|
||||
|
||||
public void Sync(MatchState state, Vector3 camPos)
|
||||
{
|
||||
if (state.MapKind != ArenaMapKind.Sion || state.SionMap is null || state.SionMap.Trees.Count == 0)
|
||||
{
|
||||
Visible = false;
|
||||
return;
|
||||
}
|
||||
SyncInternal(state.SionMap, state.SionTrees, camPos);
|
||||
}
|
||||
|
||||
public void SyncBackdrop(SionMapData sionMap, Vector3 camPos)
|
||||
{
|
||||
if (sionMap.Trees.Count == 0)
|
||||
{
|
||||
Visible = false;
|
||||
return;
|
||||
}
|
||||
SyncInternal(sionMap, null, camPos);
|
||||
}
|
||||
|
||||
private void SyncInternal(SionMapData sionMap, SionTreeDestructionState? destruction, Vector3 camPos)
|
||||
{
|
||||
Visible = true;
|
||||
EnsureAssetsLoaded(sionMap.DirectoryPath);
|
||||
if (!_assetsLoaded)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var catalog = sionMap.Trees;
|
||||
if (!ReferenceEquals(_boundCatalog, catalog))
|
||||
{
|
||||
BindCatalog(catalog);
|
||||
}
|
||||
|
||||
int curVer = destruction?.RenderVersion ?? 0;
|
||||
bool movedFar = !_lastCamPos.IsFinite() || _lastCamPos.DistanceSquaredTo(camPos) >= RebuildMoveThresholdSq;
|
||||
if (!movedFar && curVer == _lastRenderVersion)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_lastCamPos = camPos;
|
||||
_lastRenderVersion = curVer;
|
||||
RebuildBuckets(destruction, camPos);
|
||||
}
|
||||
|
||||
private void EnsureAssetsLoaded(string sionDir)
|
||||
{
|
||||
if (_assetsLoadAttempted)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_assetsLoadAttempted = true;
|
||||
|
||||
string treesDir = Path.Combine(sionDir, "trees");
|
||||
string catalogPath = Path.Combine(treesDir, "trees_catalog.json");
|
||||
if (!File.Exists(catalogPath))
|
||||
{
|
||||
GD.PrintErr($"FoliageRenderer: missing tree catalog at '{catalogPath}'.");
|
||||
return;
|
||||
}
|
||||
|
||||
_leavesShader = GD.Load<Shader>("res://tree_leaves.gdshader")
|
||||
?? throw new InvalidOperationException("Missing res://tree_leaves.gdshader");
|
||||
_barkShader = GD.Load<Shader>("res://tree_bark.gdshader")
|
||||
?? throw new InvalidOperationException("Missing res://tree_bark.gdshader");
|
||||
_impostorShader = GD.Load<Shader>("res://tree_impostor.gdshader")
|
||||
?? throw new InvalidOperationException("Missing res://tree_impostor.gdshader");
|
||||
|
||||
using var stream = File.OpenRead(catalogPath);
|
||||
using var doc = JsonDocument.Parse(stream);
|
||||
var arr = doc.RootElement.GetProperty("archetypes");
|
||||
|
||||
foreach (var item in arr.EnumerateArray())
|
||||
{
|
||||
int speciesId = item.GetProperty("speciesId").GetInt32();
|
||||
int variant = item.GetProperty("variant").GetInt32();
|
||||
string slug = item.GetProperty("slug").GetString() ?? "";
|
||||
string glbRel = item.GetProperty("glb").GetString() ?? "";
|
||||
string leafRel = item.GetProperty("leafTexture").GetString() ?? "";
|
||||
string barkRel = item.GetProperty("barkTexture").GetString() ?? "";
|
||||
string impAlbRel = item.GetProperty("impostorAlbedo").GetString() ?? "";
|
||||
string impNrmRel = item.GetProperty("impostorNormal").GetString() ?? "";
|
||||
float canonH = item.GetProperty("canonicalHeightM").GetSingle();
|
||||
float impScale = item.GetProperty("impostorScale").GetSingle();
|
||||
float impOffsetY = item.GetProperty("impostorOffsetY").GetSingle();
|
||||
int impFrames = item.GetProperty("impostorFrames").GetInt32();
|
||||
Color barkTint = ReadColor3(item.GetProperty("barkTint"));
|
||||
Color leafTint = ReadColor3(item.GetProperty("leafTint"));
|
||||
|
||||
var meshes = LoadArchetypeMeshes(Path.Combine(treesDir, glbRel));
|
||||
if (meshes is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
Texture2D barkTex = LoadTextureCached(Path.Combine(treesDir, barkRel));
|
||||
Texture2D leafTex = LoadTextureCached(Path.Combine(treesDir, leafRel));
|
||||
|
||||
var barkMat = new ShaderMaterial { Shader = _barkShader };
|
||||
barkMat.SetShaderParameter("albedo", barkTint);
|
||||
barkMat.SetShaderParameter("albedo_texture", barkTex);
|
||||
|
||||
var leafMat = new ShaderMaterial { Shader = _leavesShader };
|
||||
leafMat.SetShaderParameter("albedo", leafTint);
|
||||
leafMat.SetShaderParameter("albedo_texture", leafTex);
|
||||
|
||||
ApplyTreeMaterials(meshes.Value.Lod0, barkMat, leafMat);
|
||||
ApplyTreeMaterials(meshes.Value.Lod1, barkMat, leafMat);
|
||||
ApplyTreeMaterials(meshes.Value.Lod2, barkMat, leafMat);
|
||||
ApplyTreeMaterials(meshes.Value.SnappedStump, barkMat, leafMat);
|
||||
ApplyTreeMaterials(meshes.Value.CharredSkeleton, barkMat, leafMat);
|
||||
|
||||
var impMat = new ShaderMaterial { Shader = _impostorShader };
|
||||
string impAlbPath = Path.Combine(treesDir, impAlbRel);
|
||||
string impNrmPath = Path.Combine(treesDir, impNrmRel);
|
||||
if (File.Exists(impAlbPath) && File.Exists(impNrmPath))
|
||||
{
|
||||
impMat.SetShaderParameter("albedo_texture", LoadTextureCached(impAlbPath));
|
||||
impMat.SetShaderParameter("normal_texture", LoadTextureCached(impNrmPath));
|
||||
}
|
||||
impMat.SetShaderParameter("impostor_frames", new Vector2(impFrames, impFrames));
|
||||
impMat.SetShaderParameter("scale", impScale);
|
||||
impMat.SetShaderParameter("position_offset", new Vector3(0f, impOffsetY, 0f));
|
||||
|
||||
var impQuad = new QuadMesh { Size = Vector2.One, Material = impMat };
|
||||
|
||||
var arch = new TreeArchetype
|
||||
{
|
||||
SpeciesId = speciesId,
|
||||
Variant = variant,
|
||||
Slug = slug,
|
||||
CanonicalHeightM = MathF.Max(1f, canonH),
|
||||
ImpostorScale = impScale,
|
||||
ImpostorOffsetY = impOffsetY,
|
||||
ImpostorFrames = impFrames,
|
||||
Lod0 = meshes.Value.Lod0,
|
||||
Lod1 = meshes.Value.Lod1,
|
||||
Lod2 = meshes.Value.Lod2,
|
||||
SnappedStump = meshes.Value.SnappedStump,
|
||||
CharredSkeleton = meshes.Value.CharredSkeleton,
|
||||
ImpostorQuad = impQuad
|
||||
};
|
||||
|
||||
arch.BucketLod0 = CreateBucket($"{slug}_LOD0", arch.Lod0, castShadows: true);
|
||||
arch.BucketLod1 = CreateBucket($"{slug}_LOD1", arch.Lod1, castShadows: false);
|
||||
arch.BucketLod2 = CreateBucket($"{slug}_LOD2", arch.Lod2, castShadows: false);
|
||||
arch.BucketImpostor = CreateBucket($"{slug}_Impostor", arch.ImpostorQuad, castShadows: false);
|
||||
arch.BucketStump = CreateBucket($"{slug}_Stump", arch.SnappedStump, castShadows: false);
|
||||
arch.BucketCharred = CreateBucket($"{slug}_Charred", arch.CharredSkeleton, castShadows: true);
|
||||
|
||||
int idx = _archetypes.Count;
|
||||
_archetypes.Add(arch);
|
||||
if ((uint)speciesId < 10 && (uint)variant < 2)
|
||||
{
|
||||
_archetypeLookup[speciesId, variant] = idx;
|
||||
}
|
||||
}
|
||||
|
||||
_assetsLoaded = _archetypes.Count > 0;
|
||||
}
|
||||
|
||||
private BucketState CreateBucket(string name, Mesh mesh, bool castShadows)
|
||||
{
|
||||
var mm = new MultiMesh
|
||||
{
|
||||
TransformFormat = MultiMesh.TransformFormatEnum.Transform3D,
|
||||
UseColors = false,
|
||||
UseCustomData = true,
|
||||
Mesh = mesh,
|
||||
InstanceCount = 0,
|
||||
VisibleInstanceCount = 0
|
||||
};
|
||||
var mmi = new MultiMeshInstance3D
|
||||
{
|
||||
Name = name,
|
||||
Multimesh = mm,
|
||||
CastShadow = castShadows
|
||||
? GeometryInstance3D.ShadowCastingSetting.On
|
||||
: GeometryInstance3D.ShadowCastingSetting.Off,
|
||||
CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)),
|
||||
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off,
|
||||
Visible = false
|
||||
};
|
||||
AddChild(mmi);
|
||||
return new BucketState { MultiMesh = mm, Instance = mmi };
|
||||
}
|
||||
|
||||
private void BindCatalog(SionTreeCatalog catalog)
|
||||
{
|
||||
_boundCatalog = catalog;
|
||||
var trees = catalog.Trees;
|
||||
_precomputed = new PrecomputedTree[trees.Count];
|
||||
|
||||
for (int i = 0; i < trees.Count; i++)
|
||||
{
|
||||
var t = trees[i];
|
||||
int sp = Math.Clamp((int)t.Species, 0, 9);
|
||||
int vr = Math.Clamp((int)t.Variant, 0, 1);
|
||||
int archIdx = _archetypeLookup[sp, vr];
|
||||
if (archIdx < 0)
|
||||
{
|
||||
archIdx = _archetypeLookup[sp, 0];
|
||||
}
|
||||
if (archIdx < 0)
|
||||
{
|
||||
archIdx = 0;
|
||||
}
|
||||
|
||||
var arch = _archetypes[archIdx];
|
||||
float scaleY = Math.Clamp(t.HeightM / arch.CanonicalHeightM, 0.35f, 2.2f);
|
||||
float scaleXz = scaleY;
|
||||
Basis rot = Basis.FromEuler(new Vector3(0f, t.Yaw, 0f)).Scaled(new Vector3(scaleXz, scaleY, scaleXz));
|
||||
Vector3 pos = new(t.X, t.Y, t.Z);
|
||||
float phase = ((t.TreeId * 0x9E3779B9u) & 0xFFFFu) / 65536f;
|
||||
|
||||
_precomputed[i] = new PrecomputedTree
|
||||
{
|
||||
ArchetypeIdx = archIdx,
|
||||
WorldXform = new Transform3D(rot, pos),
|
||||
Position = pos,
|
||||
CustomDataBase = new Color(0f, phase, t.HeightM, 1f)
|
||||
};
|
||||
}
|
||||
|
||||
Invalidate();
|
||||
}
|
||||
|
||||
private void RebuildBuckets(SionTreeDestructionState? destruction, Vector3 camPos)
|
||||
{
|
||||
for (int a = 0; a < _archetypes.Count; a++)
|
||||
{
|
||||
var arch = _archetypes[a];
|
||||
arch.BucketLod0.Indices.Clear();
|
||||
arch.BucketLod1.Indices.Clear();
|
||||
arch.BucketLod2.Indices.Clear();
|
||||
arch.BucketImpostor.Indices.Clear();
|
||||
arch.BucketStump.Indices.Clear();
|
||||
arch.BucketCharred.Indices.Clear();
|
||||
}
|
||||
|
||||
const float lod0Sq = Lod0MaxDistanceM * Lod0MaxDistanceM;
|
||||
const float lod1Sq = Lod1MaxDistanceM * Lod1MaxDistanceM;
|
||||
const float lod2Sq = Lod2MaxDistanceM * Lod2MaxDistanceM;
|
||||
const float impSq = ImpostorMaxDistanceM * ImpostorMaxDistanceM;
|
||||
const float stumpSq = StumpMaxDistanceM * StumpMaxDistanceM;
|
||||
|
||||
for (int i = 0; i < _precomputed.Length; i++)
|
||||
{
|
||||
ref readonly var pt = ref _precomputed[i];
|
||||
float dx = pt.Position.X - camPos.X;
|
||||
float dz = pt.Position.Z - camPos.Z;
|
||||
float dSq = dx * dx + dz * dz;
|
||||
if (dSq > impSq)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
SionTreeState st = destruction is not null
|
||||
? destruction.GetState((ushort)i)
|
||||
: SionTreeState.Intact;
|
||||
|
||||
var arch = _archetypes[pt.ArchetypeIdx];
|
||||
if (st == SionTreeState.Snapped)
|
||||
{
|
||||
if (dSq <= stumpSq)
|
||||
{
|
||||
arch.BucketStump.Indices.Add(i);
|
||||
}
|
||||
}
|
||||
else if (st == SionTreeState.Charred)
|
||||
{
|
||||
if (dSq <= lod2Sq)
|
||||
{
|
||||
arch.BucketCharred.Indices.Add(i);
|
||||
}
|
||||
else
|
||||
{
|
||||
arch.BucketImpostor.Indices.Add(i);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (dSq <= lod0Sq)
|
||||
{
|
||||
arch.BucketLod0.Indices.Add(i);
|
||||
}
|
||||
else if (dSq <= lod1Sq)
|
||||
{
|
||||
arch.BucketLod1.Indices.Add(i);
|
||||
}
|
||||
else if (dSq <= lod2Sq)
|
||||
{
|
||||
arch.BucketLod2.Indices.Add(i);
|
||||
}
|
||||
else
|
||||
{
|
||||
arch.BucketImpostor.Indices.Add(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int c0 = 0, c1 = 0, c2 = 0, cImp = 0, cStump = 0, cChar = 0;
|
||||
for (int a = 0; a < _archetypes.Count; a++)
|
||||
{
|
||||
var arch = _archetypes[a];
|
||||
c0 += CommitBucket(arch.BucketLod0, destruction, forceCharred: false);
|
||||
c1 += CommitBucket(arch.BucketLod1, destruction, forceCharred: false);
|
||||
c2 += CommitBucket(arch.BucketLod2, destruction, forceCharred: false);
|
||||
cImp += CommitBucket(arch.BucketImpostor, destruction, forceCharred: false);
|
||||
cStump += CommitBucket(arch.BucketStump, destruction, forceCharred: false);
|
||||
cChar += CommitBucket(arch.BucketCharred, destruction, forceCharred: true);
|
||||
}
|
||||
|
||||
VisibleLod0Count = c0;
|
||||
VisibleLod1Count = c1;
|
||||
VisibleLod2Count = c2;
|
||||
VisibleImpostorCount = cImp;
|
||||
VisibleStumpCount = cStump;
|
||||
VisibleCharredCount = cChar;
|
||||
}
|
||||
|
||||
private int CommitBucket(BucketState bucket, SionTreeDestructionState? destruction, bool forceCharred)
|
||||
{
|
||||
int count = bucket.Indices.Count;
|
||||
if (count == 0)
|
||||
{
|
||||
bucket.MultiMesh.VisibleInstanceCount = 0;
|
||||
bucket.Instance.Visible = false;
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (bucket.MultiMesh.InstanceCount < count)
|
||||
{
|
||||
int cap = Math.Max(16, (int)BitOperationsRoundUp((uint)count));
|
||||
bucket.MultiMesh.InstanceCount = cap;
|
||||
}
|
||||
bucket.MultiMesh.VisibleInstanceCount = count;
|
||||
bucket.Instance.Visible = true;
|
||||
|
||||
for (int k = 0; k < count; k++)
|
||||
{
|
||||
int treeIdx = bucket.Indices[k];
|
||||
ref readonly var pt = ref _precomputed[treeIdx];
|
||||
bucket.MultiMesh.SetInstanceTransform(k, pt.WorldXform);
|
||||
|
||||
float isChar = forceCharred || (destruction is not null && destruction.GetState((ushort)treeIdx) == SionTreeState.Charred)
|
||||
? 1f
|
||||
: 0f;
|
||||
Color c = pt.CustomDataBase;
|
||||
c.R = isChar;
|
||||
bucket.MultiMesh.SetInstanceCustomData(k, c);
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
private static uint BitOperationsRoundUp(uint v)
|
||||
{
|
||||
v--;
|
||||
v |= v >> 1;
|
||||
v |= v >> 2;
|
||||
v |= v >> 4;
|
||||
v |= v >> 8;
|
||||
v |= v >> 16;
|
||||
return v + 1;
|
||||
}
|
||||
|
||||
private Texture2D LoadTextureCached(string absPath)
|
||||
{
|
||||
if (_textureCache.TryGetValue(absPath, out var tex))
|
||||
{
|
||||
return tex;
|
||||
}
|
||||
var img = Image.LoadFromFile(absPath);
|
||||
if (img is null)
|
||||
{
|
||||
throw new InvalidOperationException($"FoliageRenderer: failed to load texture '{absPath}'.");
|
||||
}
|
||||
img.GenerateMipmaps();
|
||||
var itex = ImageTexture.CreateFromImage(img);
|
||||
_textureCache[absPath] = itex;
|
||||
return itex;
|
||||
}
|
||||
|
||||
private static Color ReadColor3(JsonElement arr) =>
|
||||
new(arr[0].GetSingle(), arr[1].GetSingle(), arr[2].GetSingle(), 1f);
|
||||
|
||||
private static void ApplyTreeMaterials(ArrayMesh mesh, ShaderMaterial barkMat, ShaderMaterial leafMat)
|
||||
{
|
||||
for (int s = 0; s < mesh.GetSurfaceCount(); s++)
|
||||
{
|
||||
string sName = mesh.SurfaceGetName(s) ?? string.Empty;
|
||||
if (sName.Contains("foliage", StringComparison.OrdinalIgnoreCase) || s == 1)
|
||||
{
|
||||
mesh.SurfaceSetMaterial(s, leafMat);
|
||||
}
|
||||
else
|
||||
{
|
||||
mesh.SurfaceSetMaterial(s, barkMat);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private readonly record struct ArchetypeMeshes(
|
||||
ArrayMesh Lod0,
|
||||
ArrayMesh Lod1,
|
||||
ArrayMesh Lod2,
|
||||
ArrayMesh SnappedStump,
|
||||
ArrayMesh CharredSkeleton);
|
||||
|
||||
private static ArchetypeMeshes? LoadArchetypeMeshes(string glbPath)
|
||||
{
|
||||
if (!File.Exists(glbPath))
|
||||
{
|
||||
GD.PrintErr($"FoliageRenderer: missing GLB '{glbPath}'.");
|
||||
return null;
|
||||
}
|
||||
|
||||
var doc = new GltfDocument();
|
||||
var state = new GltfState();
|
||||
Error err = doc.AppendFromFile(glbPath, state, flags: 0, basePath: Path.GetDirectoryName(glbPath) ?? string.Empty);
|
||||
if (err != Error.Ok)
|
||||
{
|
||||
GD.PrintErr($"FoliageRenderer: GltfDocument failed on '{glbPath}': {err}");
|
||||
return null;
|
||||
}
|
||||
|
||||
Node? root = doc.GenerateScene(state);
|
||||
if (root is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
ArrayMesh? lod0 = null, lod1 = null, lod2 = null, stump = null, charred = null;
|
||||
var stack = new Stack<Node>();
|
||||
stack.Push(root);
|
||||
while (stack.Count > 0)
|
||||
{
|
||||
Node n = stack.Pop();
|
||||
if (n is MeshInstance3D mi && mi.Mesh is ArrayMesh am)
|
||||
{
|
||||
string name = mi.Name.ToString();
|
||||
if (name.Contains("Intact_LOD0", StringComparison.OrdinalIgnoreCase)) lod0 = am;
|
||||
else if (name.Contains("Intact_LOD1", StringComparison.OrdinalIgnoreCase)) lod1 = am;
|
||||
else if (name.Contains("Intact_LOD2", StringComparison.OrdinalIgnoreCase)) lod2 = am;
|
||||
else if (name.Contains("SnappedStump", StringComparison.OrdinalIgnoreCase)) stump = am;
|
||||
else if (name.Contains("CharredSkeleton", StringComparison.OrdinalIgnoreCase)) charred = am;
|
||||
}
|
||||
for (int i = 0; i < n.GetChildCount(); i++)
|
||||
{
|
||||
stack.Push(n.GetChild(i));
|
||||
}
|
||||
}
|
||||
|
||||
if (lod0 is null || lod1 is null || lod2 is null || stump is null || charred is null)
|
||||
{
|
||||
GD.PrintErr($"FoliageRenderer: incomplete meshes in '{glbPath}'.");
|
||||
return null;
|
||||
}
|
||||
return new ArchetypeMeshes(lod0, lod1, lod2, stump, charred);
|
||||
}
|
||||
finally
|
||||
{
|
||||
root.Free();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -33,6 +33,7 @@ public partial class Main : Node3D
|
|||
|
||||
private TerrainRenderer _terrain = null!;
|
||||
private SionMapRenderer _sionMap = null!;
|
||||
private FoliageRenderer _foliage = null!;
|
||||
private ArenaRenderer _arena = null!;
|
||||
private ArenaAudioSystem _audio = null!;
|
||||
private Camera3D _camera = null!;
|
||||
|
|
@ -119,6 +120,7 @@ public partial class Main : Node3D
|
|||
public ClientScreenMode ScreenMode => _screenMode;
|
||||
public TerrainRenderer Terrain => _terrain;
|
||||
public SionMapRenderer SionMap => _sionMap;
|
||||
public FoliageRenderer Foliage => _foliage;
|
||||
public ArenaRenderer Arena => _arena;
|
||||
public ArenaAudioSystem Audio => _audio;
|
||||
public WalkerFootstepTracker Footsteps => _footsteps;
|
||||
|
|
@ -161,6 +163,9 @@ public partial class Main : Node3D
|
|||
_sionMap = new SionMapRenderer { Name = "SionMap" };
|
||||
AddChild(_sionMap);
|
||||
|
||||
_foliage = new FoliageRenderer { Name = "Foliage" };
|
||||
AddChild(_foliage);
|
||||
|
||||
_arena = new ArenaRenderer { Name = "Arena" };
|
||||
AddChild(_arena);
|
||||
_arena.AssetCache.PreloadAll();
|
||||
|
|
@ -575,6 +580,7 @@ public partial class Main : Node3D
|
|||
_terrain.UpdateTileLod(_camera.GlobalPosition);
|
||||
_terrain.Sync(_menuSionTerrain, _menuSionData);
|
||||
_sionMap.UpdateLod(_camera.GlobalPosition);
|
||||
_foliage.SyncBackdrop(_menuSionData, _camera.GlobalPosition);
|
||||
}
|
||||
|
||||
private void UpdateLobbyOrMenuOrbitCamera(ArenaMapKind mapKind, TerrainField terrain)
|
||||
|
|
@ -969,10 +975,12 @@ public partial class Main : Node3D
|
|||
}
|
||||
_terrain.UpdateTileLod(_camera.GlobalPosition);
|
||||
_sionMap.UpdateLod(_camera.GlobalPosition);
|
||||
_foliage.Sync(state, _camera.GlobalPosition);
|
||||
}
|
||||
else
|
||||
{
|
||||
_sionMap.Visible = false;
|
||||
_foliage.Visible = false;
|
||||
if (!inLobby)
|
||||
{
|
||||
_arena.Sync(_session, _elapsedSeconds, 0f, 1f);
|
||||
|
|
@ -1536,6 +1544,7 @@ public partial class Main : Node3D
|
|||
if (_mapKind == ArenaMapKind.Sion)
|
||||
{
|
||||
_sionMap.UpdateLod(_camera.GlobalPosition);
|
||||
_foliage.Sync(_session.ViewState, _camera.GlobalPosition);
|
||||
}
|
||||
_lobbyScreen.Sync(_session);
|
||||
return;
|
||||
|
|
@ -1567,6 +1576,7 @@ public partial class Main : Node3D
|
|||
if (_mapKind == ArenaMapKind.Sion)
|
||||
{
|
||||
_sionMap.UpdateLod(_camera.GlobalPosition);
|
||||
_foliage.Sync(_session.ViewState, _camera.GlobalPosition);
|
||||
}
|
||||
long th0 = Stopwatch.GetTimestamp();
|
||||
var localP = _session.LocalContender;
|
||||
|
|
@ -1623,6 +1633,7 @@ public partial class Main : Node3D
|
|||
if (_mapKind == ArenaMapKind.Sion)
|
||||
{
|
||||
_sionMap.UpdateLod(_camera.GlobalPosition);
|
||||
_foliage.Sync(_session.ViewState, _camera.GlobalPosition);
|
||||
}
|
||||
var localP = _session.LocalContender;
|
||||
float coreRatio = localP.Grid.MaxCoreHp > 0f ? localP.Grid.CoreHp / localP.Grid.MaxCoreHp : 1f;
|
||||
|
|
|
|||
|
|
@ -308,6 +308,33 @@ public partial class ParticlePool : Node3D
|
|||
_gpuSparks?.EmitThermalPoolEmber(pos, radius, accentCol);
|
||||
}
|
||||
|
||||
public void EmitTreeImpactBurst(Vector3 canopyPos, float treeHeightM, bool isChar, Vector3 camPos, bool hasCam)
|
||||
{
|
||||
EnsureInitialized();
|
||||
if (hasCam && canopyPos.DistanceSquaredTo(camPos) > 260f * 260f)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (isChar)
|
||||
{
|
||||
_gpuSparks?.EmitEmberBurst(canopyPos, 24, new Color(4.0f, 1.4f, 0.25f, 0.92f), 3.6f, 0.036f);
|
||||
_volumetrics?.EmitDamageSmokePlume(canopyPos, 0.35f);
|
||||
}
|
||||
else
|
||||
{
|
||||
_gpuSparks?.EmitDustMotes(canopyPos, Vector3.Up, 44, new Color(0.28f, 0.44f, 0.16f, 0.88f), 6.5f, 0.075f);
|
||||
_gpuSparks?.EmitDustMotes(
|
||||
canopyPos - Vector3.Up * (treeHeightM * 0.25f),
|
||||
Vector3.Up,
|
||||
20,
|
||||
new Color(0.54f, 0.40f, 0.24f, 0.85f),
|
||||
5.0f,
|
||||
0.055f);
|
||||
_volumetrics?.EmitFootstepOrTirePuff(canopyPos, new Color(0.32f, 0.38f, 0.22f, 1f), 1.35f);
|
||||
}
|
||||
}
|
||||
|
||||
public void EmitPodReentryStreak(Vector3 podPos, Vector3 podVel, float heatGlow, bool isContender, Vector3 camPos, bool hasCam)
|
||||
{
|
||||
EnsureInitialized();
|
||||
|
|
|
|||
|
|
@ -1865,6 +1865,14 @@ public partial class Smoke : Node
|
|||
Check(_main.SionMap.BuildingTileCount == 36, $"Expected 36 Sion building tiles, got {_main.SionMap.BuildingTileCount}");
|
||||
Check(_main.SionMap.ActiveLod1TileCount > 0, $"Expected > 0 LOD1 tiles near Sion spawn, got {_main.SionMap.ActiveLod1TileCount}");
|
||||
Check(_main.SionMap.ActiveLod2TileCount > 0, $"Expected > 0 LOD2 tiles in Sion valley, got {_main.SionMap.ActiveLod2TileCount}");
|
||||
Check(_main.Foliage.Visible && _main.Foliage.IsBuilt, "Expected FoliageRenderer visible and built on Sion");
|
||||
Check(_main.Foliage.VerifyAllLodsHaveVertexColor(out string foliageColorErr),
|
||||
$"Expected all 17 Sion tree archetypes LOD0/1/2 to preserve COLOR flex gradient: {foliageColorErr}");
|
||||
Check(_main.Foliage.TotalTreeCount > 0 && _main.Foliage.TotalTreeCount <= SionTreeCatalog.MaxTrees,
|
||||
$"Expected Sion tree count in (0..{SionTreeCatalog.MaxTrees}], got {_main.Foliage.TotalTreeCount}");
|
||||
int visibleTrees = _main.Foliage.VisibleLod0Count + _main.Foliage.VisibleLod1Count +
|
||||
_main.Foliage.VisibleLod2Count + _main.Foliage.VisibleImpostorCount;
|
||||
Check(visibleTrees > 0, $"Expected > 0 visible Sion trees, got {visibleTrees}");
|
||||
|
||||
var cam = _main.GetViewport().GetCamera3D();
|
||||
Check(cam is not null && cam.Far >= 3600f, $"Expected Camera3D.Far >= 3600m on Sion, got {cam?.Far ?? 0f}");
|
||||
|
|
@ -1932,7 +1940,7 @@ public partial class Smoke : Node
|
|||
$"Expected Sion GPU crater height ({sionGpuPost:F3}m) to depress below pre-crater ({sionCpuPre:F3}m)");
|
||||
}
|
||||
|
||||
GD.Print($"SMOKE INFO: Sion verified (terrainTiles={_main.Terrain.BakedTileCount}, gpuScarSlots={_main.Terrain.ActiveGpuScarSlots}, bldgTiles={_main.SionMap.BuildingTileCount}, lod1={_main.SionMap.ActiveLod1TileCount}, lod2={_main.SionMap.ActiveLod2TileCount}, disp={disp:F2}m, tint=({inBoundsTint.R:F2},{inBoundsTint.G:F2},{inBoundsTint.B:F2}))");
|
||||
GD.Print($"SMOKE INFO: Sion verified (terrainTiles={_main.Terrain.BakedTileCount}, gpuScarSlots={_main.Terrain.ActiveGpuScarSlots}, bldgTiles={_main.SionMap.BuildingTileCount}, lod1={_main.SionMap.ActiveLod1TileCount}, lod2={_main.SionMap.ActiveLod2TileCount}, trees={_main.Foliage.TotalTreeCount}, visTrees={visibleTrees}, archetypes={_main.Foliage.ArchetypeCount}, disp={disp:F2}m, tint=({inBoundsTint.R:F2},{inBoundsTint.G:F2},{inBoundsTint.B:F2}))");
|
||||
}
|
||||
|
||||
private async Task VerifyOrbitalDropSequenceAsync()
|
||||
|
|
|
|||
68
client/tree_bark.gdshader
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
shader_type spatial;
|
||||
render_mode cull_back, depth_draw_opaque;
|
||||
|
||||
global uniform sampler3D rtd_flow_field;
|
||||
global uniform vec3 rtd_flow_origin;
|
||||
global uniform vec3 rtd_flow_inv_extent;
|
||||
|
||||
uniform vec4 albedo : source_color = vec4(0.7, 0.62, 0.52, 1.0);
|
||||
uniform sampler2D albedo_texture : source_color, filter_linear_mipmap, repeat_enable;
|
||||
uniform float ao_light_affect : hint_range(0.0, 1.0) = 0.6;
|
||||
uniform vec3 ambient_wind_dir = vec3(0.85, 0.04, -0.52);
|
||||
uniform float ambient_wind_speed = 1.6;
|
||||
uniform float gust_scale = 0.045;
|
||||
|
||||
varying flat float v_charred;
|
||||
|
||||
void vertex() {
|
||||
v_charred = INSTANCE_CUSTOM.r;
|
||||
vec3 world_pos = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz;
|
||||
float flex = COLOR.g;
|
||||
float limb_phase = COLOR.b;
|
||||
float norm_h = COLOR.a;
|
||||
float inst_phase = INSTANCE_CUSTOM.g;
|
||||
|
||||
if (flex > 0.001) {
|
||||
vec3 flow_uv = (world_pos - rtd_flow_origin) * rtd_flow_inv_extent;
|
||||
vec3 edge_fade = smoothstep(vec3(0.0), vec3(0.10), flow_uv) *
|
||||
smoothstep(vec3(1.0), vec3(0.90), flow_uv);
|
||||
float in_flow = edge_fade.x * edge_fade.y * edge_fade.z;
|
||||
|
||||
vec4 flow_sample = vec4(0.0);
|
||||
if (in_flow > 0.001) {
|
||||
flow_sample = textureLod(rtd_flow_field, clamp(flow_uv, vec3(0.0), vec3(1.0)), 0.0);
|
||||
}
|
||||
|
||||
float phase = (limb_phase + inst_phase) * 6.2831853 + dot(world_pos.xz, vec2(0.17, 0.23));
|
||||
float t = TIME * ambient_wind_speed;
|
||||
float macro_gust = 0.65 + 0.35 * sin(t * 0.7 + dot(world_pos.xz, vec2(gust_scale, gust_scale * 0.6)));
|
||||
float branch_osc = sin(t * 1.45 + phase) * 0.65 + sin(t * 3.1 + phase * 1.7) * 0.35;
|
||||
|
||||
vec3 wind_dir = normalize(ambient_wind_dir);
|
||||
vec3 ambient_disp = wind_dir * (macro_gust * 0.20 + branch_osc * 0.24);
|
||||
vec3 flow_vel = flow_sample.rgb;
|
||||
float shock_p = flow_sample.a;
|
||||
vec3 flow_disp = flow_vel * (0.04 + shock_p * 0.12);
|
||||
|
||||
vec3 total_world_disp = mix(ambient_disp, ambient_disp * 0.5 + flow_disp, in_flow) * flex * (0.25 + 0.75 * norm_h);
|
||||
mat3 inv_model = transpose(mat3(MODEL_MATRIX));
|
||||
vec3 inv_scale = vec3(
|
||||
1.0 / max(0.01, length(MODEL_MATRIX[0].xyz)),
|
||||
1.0 / max(0.01, length(MODEL_MATRIX[1].xyz)),
|
||||
1.0 / max(0.01, length(MODEL_MATRIX[2].xyz))
|
||||
);
|
||||
VERTEX += (inv_model * total_world_disp) * (inv_scale * inv_scale);
|
||||
}
|
||||
}
|
||||
|
||||
void fragment() {
|
||||
vec3 tex = texture(albedo_texture, UV).rgb;
|
||||
float is_charred = v_charred;
|
||||
vec3 base_col = albedo.rgb * tex;
|
||||
vec3 char_col = vec3(0.07, 0.06, 0.055) + base_col * 0.14;
|
||||
ALBEDO = mix(base_col, char_col, clamp(is_charred, 0.0, 1.0));
|
||||
AO = clamp(COLOR.r, 0.15, 1.0);
|
||||
AO_LIGHT_AFFECT = ao_light_affect;
|
||||
ROUGHNESS = mix(0.92, 0.98, is_charred);
|
||||
SPECULAR = 0.12;
|
||||
}
|
||||
143
client/tree_impostor.gdshader
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
shader_type spatial;
|
||||
render_mode cull_back, depth_draw_opaque;
|
||||
|
||||
global uniform sampler3D rtd_flow_field;
|
||||
global uniform vec3 rtd_flow_origin;
|
||||
global uniform vec3 rtd_flow_inv_extent;
|
||||
|
||||
uniform sampler2D albedo_texture : source_color, filter_linear_mipmap, repeat_disable;
|
||||
uniform sampler2D normal_texture : hint_normal, filter_linear_mipmap, repeat_disable;
|
||||
uniform vec2 impostor_frames = vec2(6.0);
|
||||
uniform float scale = 1.0;
|
||||
uniform vec3 position_offset = vec3(0.0);
|
||||
uniform float alpha_scissor_threshold : hint_range(0.0, 1.0) = 0.45;
|
||||
uniform vec3 backlight : source_color = vec3(0.35, 0.44, 0.20);
|
||||
uniform float roughness : hint_range(0.0, 1.0) = 0.92;
|
||||
uniform float specular : hint_range(0.0, 1.0) = 0.18;
|
||||
uniform vec3 ambient_wind_dir = vec3(0.85, 0.04, -0.52);
|
||||
|
||||
varying vec2 uv_a;
|
||||
varying vec2 uv_b;
|
||||
varying vec2 uv_c;
|
||||
varying flat vec2 frame_a;
|
||||
varying flat vec2 frame_b;
|
||||
varying flat vec2 frame_c;
|
||||
varying flat vec3 normal_a;
|
||||
varying flat vec3 normal_b;
|
||||
varying flat vec3 normal_c;
|
||||
varying flat vec3 weights;
|
||||
varying flat float v_charred;
|
||||
|
||||
vec2 hemi_octahedron_grid(vec3 direction) {
|
||||
direction.y = max(direction.y, 0.001);
|
||||
direction = normalize(direction);
|
||||
vec3 octahedron = direction / dot(direction, sign(direction));
|
||||
return vec2(octahedron.x + octahedron.z, octahedron.z - octahedron.x);
|
||||
}
|
||||
|
||||
vec3 hemi_octahedron(vec2 coord) {
|
||||
vec3 direction = vec3(coord.x - coord.y, 0.0, -1.0 + coord.x + coord.y);
|
||||
direction.y = 1.0 - abs(direction.x) - abs(direction.z);
|
||||
return normalize(direction);
|
||||
}
|
||||
|
||||
vec2 frame_uv(vec3 frame_direction, vec3 pivot_to_camera, vec3 vertex_to_camera) {
|
||||
vec3 up = abs(frame_direction.y) > 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(0.0, 1.0, 0.0);
|
||||
vec3 plane_x = normalize(cross(frame_direction, up));
|
||||
vec3 plane_y = normalize(cross(plane_x, frame_direction));
|
||||
float t = dot(frame_direction, pivot_to_camera) / dot(frame_direction, vertex_to_camera);
|
||||
vec3 offset = vertex_to_camera * t - pivot_to_camera;
|
||||
return vec2(dot(plane_x, offset), dot(plane_y, offset)) / (2.0 * scale) + 0.5;
|
||||
}
|
||||
|
||||
void vertex() {
|
||||
v_charred = INSTANCE_CUSTOM.r;
|
||||
vec2 frames_minus_one = impostor_frames - 1.0;
|
||||
vec3 camera = (inverse(MODEL_MATRIX) * vec4(INV_VIEW_MATRIX[3].xyz, 1.0)).xyz;
|
||||
vec3 pivot_to_camera = camera * 10.0;
|
||||
vec3 view_direction = normalize(camera);
|
||||
|
||||
vec2 grid = clamp((hemi_octahedron_grid(view_direction) + 1.0) * 0.5, 0.0, 1.0) * frames_minus_one;
|
||||
vec2 grid_fract = fract(grid);
|
||||
frame_a = floor(grid);
|
||||
frame_b = clamp(
|
||||
frame_a + (grid_fract.x > grid_fract.y ? vec2(1.0, 0.0) : vec2(0.0, 1.0)),
|
||||
vec2(0.0), frames_minus_one
|
||||
);
|
||||
frame_c = min(frame_a + 1.0, frames_minus_one);
|
||||
weights = vec3(
|
||||
min(1.0 - grid_fract.x, 1.0 - grid_fract.y),
|
||||
abs(grid_fract.x - grid_fract.y),
|
||||
min(grid_fract.x, grid_fract.y)
|
||||
);
|
||||
|
||||
vec3 direction_a = hemi_octahedron(frame_a / frames_minus_one);
|
||||
vec3 direction_b = hemi_octahedron(frame_b / frames_minus_one);
|
||||
vec3 direction_c = hemi_octahedron(frame_c / frames_minus_one);
|
||||
normal_a = (MODELVIEW_MATRIX * vec4(direction_a, 0.0)).xyz;
|
||||
normal_b = (MODELVIEW_MATRIX * vec4(direction_b, 0.0)).xyz;
|
||||
normal_c = (MODELVIEW_MATRIX * vec4(direction_c, 0.0)).xyz;
|
||||
|
||||
vec3 up = abs(view_direction.y) > 0.999 ? vec3(0.0, 0.0, -1.0) : vec3(0.0, 1.0, 0.0);
|
||||
vec3 right = normalize(cross(up, view_direction));
|
||||
vec3 down = normalize(cross(right, view_direction));
|
||||
vec2 corner = (UV * 2.0 - 1.0) * scale;
|
||||
vec3 offset = right * corner.x + down * corner.y;
|
||||
|
||||
// Subtle top-crown sway synced to valley wind / rtd_flow_field
|
||||
float top_w = clamp(1.0 - UV.y, 0.0, 1.0);
|
||||
vec3 world_pos = (MODEL_MATRIX * vec4(offset + position_offset, 1.0)).xyz;
|
||||
float phase = INSTANCE_CUSTOM.g * 6.2831853 + dot(world_pos.xz, vec2(0.11, 0.17));
|
||||
float sway = sin(TIME * 1.6 + phase) * 0.22 * top_w * top_w;
|
||||
vec3 flow_uv = (world_pos - rtd_flow_origin) * rtd_flow_inv_extent;
|
||||
if (all(greaterThanEqual(flow_uv, vec3(0.0))) && all(lessThanEqual(flow_uv, vec3(1.0)))) {
|
||||
vec4 fs = textureLod(rtd_flow_field, flow_uv, 0.0);
|
||||
offset += fs.rgb * (0.04 * top_w);
|
||||
}
|
||||
offset += normalize(ambient_wind_dir * mat3(MODEL_MATRIX)) * sway;
|
||||
|
||||
vec3 vertex_to_camera = pivot_to_camera - offset;
|
||||
uv_a = frame_uv(direction_a, pivot_to_camera, vertex_to_camera);
|
||||
uv_b = frame_uv(direction_b, pivot_to_camera, vertex_to_camera);
|
||||
uv_c = frame_uv(direction_c, pivot_to_camera, vertex_to_camera);
|
||||
|
||||
VERTEX = offset + position_offset;
|
||||
NORMAL = view_direction;
|
||||
TANGENT = -right;
|
||||
BINORMAL = -down;
|
||||
}
|
||||
|
||||
vec2 atlas_uv(vec2 uv, vec2 frame, vec2 frame_size) {
|
||||
return clamp(frame_size * (frame + clamp(uv, 0.0, 1.0)), 0.0, 1.0);
|
||||
}
|
||||
|
||||
vec3 unpack_normal(vec4 tex, vec3 tangent, vec3 binormal, vec3 normal) {
|
||||
vec3 n = normalize(tex.xyz * 2.0 - 1.0);
|
||||
return normalize(tangent * n.x + binormal * n.y + normal * n.z);
|
||||
}
|
||||
|
||||
void fragment() {
|
||||
vec2 frame_size = 1.0 / impostor_frames;
|
||||
vec2 atlas_a = atlas_uv(uv_a, frame_a, frame_size);
|
||||
vec2 atlas_b = atlas_uv(uv_b, frame_b, frame_size);
|
||||
vec2 atlas_c = atlas_uv(uv_c, frame_c, frame_size);
|
||||
|
||||
vec4 color = texture(albedo_texture, atlas_a) * weights.x
|
||||
+ texture(albedo_texture, atlas_b) * weights.y
|
||||
+ texture(albedo_texture, atlas_c) * weights.z;
|
||||
vec4 tex_a = texture(normal_texture, atlas_a);
|
||||
vec4 tex_b = texture(normal_texture, atlas_b);
|
||||
vec4 tex_c = texture(normal_texture, atlas_c);
|
||||
vec3 normal = unpack_normal(tex_a, TANGENT, BINORMAL, normal_a) * weights.x
|
||||
+ unpack_normal(tex_b, TANGENT, BINORMAL, normal_b) * weights.y
|
||||
+ unpack_normal(tex_c, TANGENT, BINORMAL, normal_c) * weights.z;
|
||||
|
||||
vec3 char_col = vec3(dot(color.rgb, vec3(0.25)) * 0.22);
|
||||
ALBEDO = mix(color.rgb, char_col, clamp(v_charred, 0.0, 1.0));
|
||||
NORMAL = normalize(normal);
|
||||
BACKLIGHT = mix(backlight, vec3(0.0), v_charred) * (tex_a.a * weights.x + tex_b.a * weights.y + tex_c.a * weights.z);
|
||||
ROUGHNESS = roughness;
|
||||
SPECULAR = specular;
|
||||
ALPHA = color.a;
|
||||
ALPHA_SCISSOR_THRESHOLD = alpha_scissor_threshold;
|
||||
}
|
||||
75
client/tree_leaves.gdshader
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
shader_type spatial;
|
||||
render_mode cull_disabled, depth_draw_opaque;
|
||||
|
||||
global uniform sampler3D rtd_flow_field;
|
||||
global uniform vec3 rtd_flow_origin;
|
||||
global uniform vec3 rtd_flow_inv_extent;
|
||||
|
||||
uniform vec4 albedo : source_color = vec4(1.0);
|
||||
uniform sampler2D albedo_texture : source_color, filter_linear_mipmap, repeat_disable;
|
||||
uniform float alpha_scissor_threshold : hint_range(0.0, 1.0) = 0.45;
|
||||
uniform vec3 backlight : source_color = vec3(0.42, 0.50, 0.22);
|
||||
uniform float ao_light_affect : hint_range(0.0, 1.0) = 0.55;
|
||||
uniform vec3 ambient_wind_dir = vec3(0.85, 0.04, -0.52);
|
||||
uniform float ambient_wind_speed = 1.6;
|
||||
uniform float gust_scale = 0.045;
|
||||
|
||||
void vertex() {
|
||||
vec3 world_pos = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz;
|
||||
float flex = COLOR.g;
|
||||
float limb_phase = COLOR.b;
|
||||
float norm_h = COLOR.a;
|
||||
float inst_phase = INSTANCE_CUSTOM.g;
|
||||
|
||||
vec3 flow_uv = (world_pos - rtd_flow_origin) * rtd_flow_inv_extent;
|
||||
vec3 edge_fade = smoothstep(vec3(0.0), vec3(0.10), flow_uv) *
|
||||
smoothstep(vec3(1.0), vec3(0.90), flow_uv);
|
||||
float in_flow = edge_fade.x * edge_fade.y * edge_fade.z;
|
||||
|
||||
vec4 flow_sample = vec4(0.0);
|
||||
if (in_flow > 0.001) {
|
||||
flow_sample = textureLod(rtd_flow_field, clamp(flow_uv, vec3(0.0), vec3(1.0)), 0.0);
|
||||
}
|
||||
|
||||
float phase = (limb_phase + inst_phase) * 6.2831853 + dot(world_pos.xz, vec2(0.17, 0.23));
|
||||
float t = TIME * ambient_wind_speed;
|
||||
float macro_gust = 0.65 + 0.35 * sin(t * 0.7 + dot(world_pos.xz, vec2(gust_scale, gust_scale * 0.6)));
|
||||
float branch_osc = sin(t * 1.45 + phase) * 0.65 + sin(t * 3.1 + phase * 1.7) * 0.35;
|
||||
float flutter = sin(t * 6.8 + phase * 3.3 + (1.0 - UV.y) * 2.4) * (1.0 - UV.y) * 0.14;
|
||||
|
||||
vec3 wind_dir = normalize(ambient_wind_dir);
|
||||
vec3 ambient_disp = wind_dir * (macro_gust * 0.22 + branch_osc * 0.28) + vec3(-wind_dir.z, 0.15, wind_dir.x) * flutter;
|
||||
|
||||
vec3 flow_vel = flow_sample.rgb;
|
||||
float shock_p = flow_sample.a;
|
||||
float flow_speed = length(flow_vel);
|
||||
vec3 flow_disp = flow_vel * (0.045 + shock_p * 0.14) +
|
||||
(flow_speed > 0.05 ? normalize(flow_vel) * (shock_p * 0.45 * sin(TIME * 14.0 + phase)) : vec3(0.0));
|
||||
|
||||
vec3 total_world_disp = mix(ambient_disp, ambient_disp * 0.5 + flow_disp, in_flow) * flex * (0.35 + 0.65 * norm_h);
|
||||
// Convert world displacement into instance local space
|
||||
mat3 inv_model = transpose(mat3(MODEL_MATRIX));
|
||||
vec3 inv_scale = vec3(
|
||||
1.0 / max(0.01, length(MODEL_MATRIX[0].xyz)),
|
||||
1.0 / max(0.01, length(MODEL_MATRIX[1].xyz)),
|
||||
1.0 / max(0.01, length(MODEL_MATRIX[2].xyz))
|
||||
);
|
||||
VERTEX += (inv_model * total_world_disp) * (inv_scale * inv_scale);
|
||||
}
|
||||
|
||||
void fragment() {
|
||||
vec2 tex_size = vec2(textureSize(albedo_texture, 0));
|
||||
vec2 texel = UV * tex_size;
|
||||
float mip = 0.5 * log2(max(dot(dFdx(texel), dFdx(texel)), dot(dFdy(texel), dFdy(texel))));
|
||||
vec4 tex = textureLod(albedo_texture, UV, clamp(mip, 0.0, log2(min(tex_size.x, tex_size.y)) - 3.0));
|
||||
|
||||
ALBEDO = albedo.rgb * tex.rgb;
|
||||
ALPHA = albedo.a * tex.a;
|
||||
ALPHA_SCISSOR_THRESHOLD = alpha_scissor_threshold;
|
||||
NORMAL = FRONT_FACING ? NORMAL : -NORMAL;
|
||||
AO = clamp(COLOR.r, 0.15, 1.0);
|
||||
AO_LIGHT_AFFECT = ao_light_affect;
|
||||
BACKLIGHT = backlight;
|
||||
ROUGHNESS = 0.92;
|
||||
SPECULAR = 0.18;
|
||||
}
|
||||
|
|
@ -138,6 +138,21 @@ namespace RustToDust.Core
|
|||
IsDirty = true;
|
||||
}
|
||||
|
||||
public void RecordTreeState(ushort treeId, byte state)
|
||||
{
|
||||
if (_trees.TryGetValue(treeId, out var existing) && existing.State == state)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_trees[treeId] = new TreeScarEntry
|
||||
{
|
||||
TreeId = treeId,
|
||||
State = state
|
||||
};
|
||||
LedgerRevision++;
|
||||
IsDirty = true;
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_terrain.Clear();
|
||||
|
|
|
|||
|
|
@ -368,6 +368,10 @@ namespace RustToDust.Core
|
|||
if (mapKind == ArenaMapKind.Sion)
|
||||
{
|
||||
SionMap = SionMapLoader.Load();
|
||||
if (SionMap.Trees.Count > 0)
|
||||
{
|
||||
SionTrees = new SionTreeDestructionState(SionMap.Trees);
|
||||
}
|
||||
Terrain = TerrainField.LoadSharedHeightmap(
|
||||
SionMap.Metadata.SizeMeters,
|
||||
SionMap.Metadata.GridRes,
|
||||
|
|
@ -546,12 +550,27 @@ namespace RustToDust.Core
|
|||
|
||||
public TerrainField Terrain { get; }
|
||||
public ArenaScarLedger ScarLedger { get; }
|
||||
public SionTreeDestructionState? SionTrees { get; }
|
||||
public List<ContenderState> Contenders { get; } = new();
|
||||
|
||||
public void ApplyPersistentScars(ArenaScarLedgerSnapshot snapshot)
|
||||
{
|
||||
ScarLedger.LoadFromSnapshot(snapshot);
|
||||
ScarLedger.ApplyToTerrain(Terrain);
|
||||
SionTrees?.ApplyScarEntries(ScarLedger.Trees.Values);
|
||||
}
|
||||
|
||||
public bool ApplyTreeState(ushort treeId, SionTreeState state, bool recordInLedger = true)
|
||||
{
|
||||
if (SionTrees is null || !SionTrees.SetState(treeId, state))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (recordInLedger)
|
||||
{
|
||||
ScarLedger.RecordTreeState(treeId, (byte)state);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void ApplyTerrainStamp(TerrainStampEvent stamp, bool recordInLedger = true)
|
||||
|
|
@ -580,6 +599,7 @@ namespace RustToDust.Core
|
|||
public void RepairArenaScars()
|
||||
{
|
||||
Terrain.ClearDynamicScars();
|
||||
SionTrees?.RepairAll();
|
||||
ScarLedger.Clear();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ namespace RustToDust.Core
|
|||
[Union(12, typeof(DropPodEvent))]
|
||||
[Union(13, typeof(OrdnanceNodeEvent))]
|
||||
[Union(14, typeof(MatchStartedEvent))]
|
||||
[Union(16, typeof(TreeStateEvent))]
|
||||
[Union(17, typeof(ArenaRepairEvent))]
|
||||
public interface ISimEvent
|
||||
{
|
||||
|
|
@ -503,6 +504,16 @@ namespace RustToDust.Core
|
|||
[Key(1)] public LobbySnapshotDto Snapshot { get; set; } = new();
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
public sealed class TreeStateEvent : ISimEvent
|
||||
{
|
||||
[Key(0)] public ushort TreeId { get; set; }
|
||||
[Key(1)] public byte State { get; set; }
|
||||
[Key(2)] public float ImpactX { get; set; }
|
||||
[Key(3)] public float ImpactY { get; set; }
|
||||
[Key(4)] public float ImpactZ { get; set; }
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
public sealed class ArenaRepairEvent : ISimEvent
|
||||
{
|
||||
|
|
|
|||
|
|
@ -99,7 +99,8 @@ namespace RustToDust.Core
|
|||
float baseDemMinY,
|
||||
float baseDemScale,
|
||||
SionBuildingAabb[] buildings,
|
||||
SionCollisionMesh[] collisionMeshes)
|
||||
SionCollisionMesh[] collisionMeshes,
|
||||
SionTreeCatalog? trees = null)
|
||||
{
|
||||
DirectoryPath = directoryPath;
|
||||
Metadata = metadata;
|
||||
|
|
@ -111,6 +112,7 @@ namespace RustToDust.Core
|
|||
: $"sion:{metadata.GridRes}:{metadata.CellSizeMeters:F3}";
|
||||
_buildings = buildings;
|
||||
CollisionMeshes = collisionMeshes;
|
||||
Trees = trees ?? SionTreeCatalog.Empty;
|
||||
|
||||
_halfExtent = metadata.SizeMeters * 0.5f;
|
||||
_cellSize = metadata.SizeMeters / SpatialGridRes;
|
||||
|
|
@ -153,6 +155,7 @@ namespace RustToDust.Core
|
|||
public float SampleBaseDemAtIndex(int index) => BaseDemMinY + _baseDem[index] * BaseDemScale;
|
||||
public IReadOnlyList<SionBuildingAabb> Buildings => _buildings;
|
||||
public IReadOnlyList<SionCollisionMesh> CollisionMeshes { get; }
|
||||
public SionTreeCatalog Trees { get; }
|
||||
|
||||
public bool IsInsideAnyBuildingXz(float x, float z, float padding = 0f)
|
||||
{
|
||||
|
|
@ -378,7 +381,12 @@ namespace RustToDust.Core
|
|||
colMeshes[i] = LoadRcolFile(colPath, t.Tx, t.Tz);
|
||||
}
|
||||
|
||||
var data = new SionMapData(root, meta, baseDem, demMinY, demScale, buildings, colMeshes);
|
||||
string treesPath = Path.Combine(root, "trees_sion.bin");
|
||||
SionTreeCatalog trees = File.Exists(treesPath)
|
||||
? SionTreeCatalog.LoadBinary(treesPath)
|
||||
: SionTreeCatalog.Empty;
|
||||
|
||||
var data = new SionMapData(root, meta, baseDem, demMinY, demScale, buildings, colMeshes, trees);
|
||||
lock (CacheLock)
|
||||
{
|
||||
Cache[root] = data;
|
||||
|
|
|
|||
513
src/RustToDust.Core/SionTreeField.cs
Normal file
|
|
@ -0,0 +1,513 @@
|
|||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Numerics;
|
||||
|
||||
namespace RustToDust.Core
|
||||
{
|
||||
/// <summary>
|
||||
/// Canonical Sion tree species presets (0..9). Wild beech (Fagus sylvatica) is intentionally excluded.
|
||||
/// </summary>
|
||||
public enum SionTreeSpecies : byte
|
||||
{
|
||||
PinusSylvestris = 0,
|
||||
QuercusPubescens = 1,
|
||||
PopulusNigra = 2,
|
||||
PlatanusAcerifolia = 3,
|
||||
BetulaPendula = 4,
|
||||
PiceaAbies = 5,
|
||||
MalusOrchard = 6,
|
||||
Sequoiadendron = 7,
|
||||
Cedrus = 8,
|
||||
PlatanusMonumental = 9
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Packed 2-bit runtime state per tree instance.
|
||||
/// </summary>
|
||||
public enum SionTreeState : byte
|
||||
{
|
||||
Intact = 0,
|
||||
Charred = 1,
|
||||
Snapped = 2
|
||||
}
|
||||
|
||||
public readonly record struct SionTreePlacement(
|
||||
ushort TreeId,
|
||||
byte Tx,
|
||||
byte Tz,
|
||||
float X,
|
||||
float Y,
|
||||
float Z,
|
||||
float Yaw,
|
||||
float HeightM,
|
||||
float TrunkRadiusM,
|
||||
SionTreeSpecies Species,
|
||||
byte Variant)
|
||||
{
|
||||
public bool IsMonumental =>
|
||||
Species is SionTreeSpecies.Sequoiadendron or SionTreeSpecies.Cedrus or SionTreeSpecies.PlatanusMonumental;
|
||||
|
||||
public int TileIndex => Tz * SionTreeCatalog.TileGrid + Tx;
|
||||
}
|
||||
|
||||
public sealed class SionTreeCatalog
|
||||
{
|
||||
public const int MaxTrees = 6500;
|
||||
public const int TileGrid = 16;
|
||||
public const int TileCount = TileGrid * TileGrid;
|
||||
public const float TileSizeMeters = 192f;
|
||||
public const float ArenaHalfExtent = 1536f;
|
||||
public const int HeaderBytes = 16;
|
||||
public const int RecordBytes = 30;
|
||||
|
||||
private readonly SionTreePlacement[] _trees;
|
||||
private readonly int[][] _tileTreeIndices;
|
||||
|
||||
public static readonly SionTreeCatalog Empty = new(Array.Empty<SionTreePlacement>());
|
||||
|
||||
public SionTreeCatalog(SionTreePlacement[] trees)
|
||||
{
|
||||
_trees = trees ?? throw new ArgumentNullException(nameof(trees));
|
||||
var buckets = new List<int>[TileCount];
|
||||
for (int i = 0; i < TileCount; i++)
|
||||
{
|
||||
buckets[i] = new List<int>(16);
|
||||
}
|
||||
|
||||
for (int i = 0; i < _trees.Length; i++)
|
||||
{
|
||||
ref readonly var t = ref _trees[i];
|
||||
if (t.TreeId != i)
|
||||
{
|
||||
throw new InvalidDataException($"TreeId mismatch at index {i}: got {t.TreeId}.");
|
||||
}
|
||||
if (t.Tx >= TileGrid || t.Tz >= TileGrid)
|
||||
{
|
||||
throw new InvalidDataException($"Tree {t.TreeId} tile ({t.Tx},{t.Tz}) out of [0..15] bounds.");
|
||||
}
|
||||
if ((byte)t.Species > (byte)SionTreeSpecies.PlatanusMonumental)
|
||||
{
|
||||
throw new InvalidDataException($"Tree {t.TreeId} has unsupported species {(byte)t.Species}.");
|
||||
}
|
||||
buckets[t.TileIndex].Add(i);
|
||||
}
|
||||
|
||||
_tileTreeIndices = new int[TileCount][];
|
||||
for (int i = 0; i < TileCount; i++)
|
||||
{
|
||||
_tileTreeIndices[i] = buckets[i].ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
public int Count => _trees.Length;
|
||||
public IReadOnlyList<SionTreePlacement> Trees => _trees;
|
||||
public ReadOnlySpan<SionTreePlacement> AsSpan() => _trees;
|
||||
|
||||
public ReadOnlySpan<int> GetTileTreeIndices(int tx, int tz)
|
||||
{
|
||||
if ((uint)tx >= TileGrid || (uint)tz >= TileGrid)
|
||||
{
|
||||
return ReadOnlySpan<int>.Empty;
|
||||
}
|
||||
return _tileTreeIndices[tz * TileGrid + tx];
|
||||
}
|
||||
|
||||
public static SionTreeCatalog LoadBinary(string path)
|
||||
{
|
||||
byte[] raw = File.ReadAllBytes(path);
|
||||
if (raw.Length < HeaderBytes)
|
||||
{
|
||||
throw new InvalidDataException($"Sion tree binary '{path}' too small ({raw.Length} bytes).");
|
||||
}
|
||||
|
||||
ReadOnlySpan<byte> s = raw;
|
||||
if (s[0] != (byte)'R' || s[1] != (byte)'D' || s[2] != (byte)'T' || s[3] != (byte)'R')
|
||||
{
|
||||
throw new InvalidDataException($"Invalid RDTR magic in '{path}'.");
|
||||
}
|
||||
|
||||
uint version = BinaryPrimitives.ReadUInt32LittleEndian(s.Slice(4, 4));
|
||||
if (version != 1)
|
||||
{
|
||||
throw new InvalidDataException($"Unsupported RDTR version {version} in '{path}'.");
|
||||
}
|
||||
|
||||
int count = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(s.Slice(8, 4)));
|
||||
if (count < 0 || count > MaxTrees)
|
||||
{
|
||||
throw new InvalidDataException($"RDTR treeCount {count} exceeds [0..{MaxTrees}] in '{path}'.");
|
||||
}
|
||||
|
||||
int expectedBytes = HeaderBytes + count * RecordBytes;
|
||||
if (raw.Length != expectedBytes)
|
||||
{
|
||||
throw new InvalidDataException($"RDTR length mismatch in '{path}': expected {expectedBytes}, got {raw.Length}.");
|
||||
}
|
||||
|
||||
var trees = new SionTreePlacement[count];
|
||||
int offset = HeaderBytes;
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
ushort treeId = BinaryPrimitives.ReadUInt16LittleEndian(s.Slice(offset, 2));
|
||||
byte tx = s[offset + 2];
|
||||
byte tz = s[offset + 3];
|
||||
float x = BinaryPrimitives.ReadSingleLittleEndian(s.Slice(offset + 4, 4));
|
||||
float y = BinaryPrimitives.ReadSingleLittleEndian(s.Slice(offset + 8, 4));
|
||||
float z = BinaryPrimitives.ReadSingleLittleEndian(s.Slice(offset + 12, 4));
|
||||
float yaw = BinaryPrimitives.ReadSingleLittleEndian(s.Slice(offset + 16, 4));
|
||||
float heightM = BinaryPrimitives.ReadSingleLittleEndian(s.Slice(offset + 20, 4));
|
||||
float trunkRadiusM = BinaryPrimitives.ReadSingleLittleEndian(s.Slice(offset + 24, 4));
|
||||
var species = (SionTreeSpecies)s[offset + 28];
|
||||
byte variant = s[offset + 29];
|
||||
trees[i] = new SionTreePlacement(treeId, tx, tz, x, y, z, yaw, heightM, trunkRadiusM, species, variant);
|
||||
offset += RecordBytes;
|
||||
}
|
||||
|
||||
return new SionTreeCatalog(trees);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Authoritative match-lifetime destruction state for Sion trees (2 bits/tree, ~1.6 KiB).
|
||||
/// </summary>
|
||||
public sealed class SionTreeDestructionState
|
||||
{
|
||||
public const float MinColliderTrunkRadiusM = 0.20f;
|
||||
public const float WalkerTrampleMaxTrunkRadiusM = 0.30f;
|
||||
public const float HeavyWalkerMinMassKg = 30_000f;
|
||||
|
||||
private readonly SionTreeCatalog _catalog;
|
||||
private readonly byte[] _packedStates;
|
||||
private readonly int[] _tileColVersions = new int[SionTreeCatalog.TileCount];
|
||||
|
||||
public SionTreeDestructionState(SionTreeCatalog catalog)
|
||||
{
|
||||
_catalog = catalog ?? throw new ArgumentNullException(nameof(catalog));
|
||||
_packedStates = new byte[(catalog.Count + 3) / 4];
|
||||
}
|
||||
|
||||
public SionTreeCatalog Catalog => _catalog;
|
||||
public int RenderVersion { get; private set; }
|
||||
public int[] TileColVersions => _tileColVersions;
|
||||
|
||||
public SionTreeState GetState(ushort treeId)
|
||||
{
|
||||
if (treeId >= _catalog.Count)
|
||||
{
|
||||
return SionTreeState.Intact;
|
||||
}
|
||||
int byteIdx = treeId >> 2;
|
||||
int shift = (treeId & 3) << 1;
|
||||
return (SionTreeState)((_packedStates[byteIdx] >> shift) & 0x3);
|
||||
}
|
||||
|
||||
public bool SetState(ushort treeId, SionTreeState newState)
|
||||
{
|
||||
if (treeId >= _catalog.Count || newState > SionTreeState.Snapped)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
SionTreeState prev = GetState(treeId);
|
||||
if (prev == newState)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
// During a match, trees degrade monotonically (Intact -> Charred -> Snapped).
|
||||
if (prev == SionTreeState.Snapped || (prev == SionTreeState.Charred && newState == SionTreeState.Intact))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
int byteIdx = treeId >> 2;
|
||||
int shift = (treeId & 3) << 1;
|
||||
byte mask = (byte)~(0x3 << shift);
|
||||
_packedStates[byteIdx] = (byte)((_packedStates[byteIdx] & mask) | (((byte)newState & 0x3) << shift));
|
||||
|
||||
RenderVersion++;
|
||||
if (newState == SionTreeState.Snapped)
|
||||
{
|
||||
ref readonly var t = ref _catalog.AsSpan()[treeId];
|
||||
if (t.TrunkRadiusM >= MinColliderTrunkRadiusM)
|
||||
{
|
||||
_tileColVersions[t.TileIndex]++;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void RepairAll()
|
||||
{
|
||||
if (_catalog.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
ReadOnlySpan<SionTreePlacement> trees = _catalog.AsSpan();
|
||||
bool anyChanged = false;
|
||||
for (int i = 0; i < trees.Length; i++)
|
||||
{
|
||||
SionTreeState st = GetState((ushort)i);
|
||||
if (st != SionTreeState.Intact)
|
||||
{
|
||||
anyChanged = true;
|
||||
if (st == SionTreeState.Snapped && trees[i].TrunkRadiusM >= MinColliderTrunkRadiusM)
|
||||
{
|
||||
_tileColVersions[trees[i].TileIndex]++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (anyChanged)
|
||||
{
|
||||
Array.Clear(_packedStates);
|
||||
RenderVersion++;
|
||||
}
|
||||
}
|
||||
|
||||
public void ApplyScarEntries(IEnumerable<TreeScarEntry> entries)
|
||||
{
|
||||
if (entries is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
foreach (var e in entries)
|
||||
{
|
||||
if (e.State <= (byte)SionTreeState.Snapped)
|
||||
{
|
||||
SetState(e.TreeId, (SionTreeState)e.State);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int ApplyBlast(
|
||||
Vector3 center,
|
||||
float splashRadius,
|
||||
float blastDamage,
|
||||
List<TreeStateEvent>? outEvents = null)
|
||||
{
|
||||
if (_catalog.Count == 0 || blastDamage <= 0f)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
float effectiveRadius = MathF.Max(2.5f, splashRadius);
|
||||
float charRadius = effectiveRadius * 1.35f;
|
||||
float snapCoreRadius = MathF.Max(2.2f, effectiveRadius * 0.45f);
|
||||
float charRadiusSq = charRadius * charRadius;
|
||||
|
||||
GetTileRange(center.X, center.Z, charRadius + 1.0f, out int minTx, out int maxTx, out int minTz, out int maxTz);
|
||||
ReadOnlySpan<SionTreePlacement> trees = _catalog.AsSpan();
|
||||
int changed = 0;
|
||||
|
||||
for (int tz = minTz; tz <= maxTz; tz++)
|
||||
{
|
||||
for (int tx = minTx; tx <= maxTx; tx++)
|
||||
{
|
||||
ReadOnlySpan<int> indices = _catalog.GetTileTreeIndices(tx, tz);
|
||||
for (int i = 0; i < indices.Length; i++)
|
||||
{
|
||||
int id = indices[i];
|
||||
ref readonly var t = ref trees[id];
|
||||
SionTreeState cur = GetState(t.TreeId);
|
||||
if (cur == SionTreeState.Snapped)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
float dx = t.X - center.X;
|
||||
float dz = t.Z - center.Z;
|
||||
float distSq = dx * dx + dz * dz;
|
||||
if (distSq > charRadiusSq)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (center.Y < t.Y - 3.0f || center.Y > t.Y + t.HeightM + effectiveRadius + 2.0f)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
float dist = MathF.Sqrt(distSq);
|
||||
float atten = MathF.Max(0f, 1f - dist / effectiveRadius);
|
||||
float impulse = blastDamage * atten;
|
||||
float snapThreshold = 45f + t.TrunkRadiusM * 220f;
|
||||
|
||||
SionTreeState targetState = cur;
|
||||
if ((dist <= snapCoreRadius && blastDamage >= 65f) || impulse >= snapThreshold)
|
||||
{
|
||||
targetState = SionTreeState.Snapped;
|
||||
}
|
||||
else if (cur == SionTreeState.Intact && blastDamage >= 25f)
|
||||
{
|
||||
targetState = SionTreeState.Charred;
|
||||
}
|
||||
|
||||
if (targetState != cur && SetState(t.TreeId, targetState))
|
||||
{
|
||||
changed++;
|
||||
outEvents?.Add(new TreeStateEvent
|
||||
{
|
||||
TreeId = t.TreeId,
|
||||
State = (byte)targetState,
|
||||
ImpactX = center.X,
|
||||
ImpactY = center.Y,
|
||||
ImpactZ = center.Z
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return changed;
|
||||
}
|
||||
|
||||
public int ApplyWalkerTrample(
|
||||
float worldX,
|
||||
float worldZ,
|
||||
float walkerRadius,
|
||||
float massKg,
|
||||
List<TreeStateEvent>? outEvents = null)
|
||||
{
|
||||
if (_catalog.Count == 0 || massKg < HeavyWalkerMinMassKg)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
float searchRadius = walkerRadius + WalkerTrampleMaxTrunkRadiusM + 0.40f;
|
||||
GetTileRange(worldX, worldZ, searchRadius, out int minTx, out int maxTx, out int minTz, out int maxTz);
|
||||
ReadOnlySpan<SionTreePlacement> trees = _catalog.AsSpan();
|
||||
int changed = 0;
|
||||
|
||||
for (int tz = minTz; tz <= maxTz; tz++)
|
||||
{
|
||||
for (int tx = minTx; tx <= maxTx; tx++)
|
||||
{
|
||||
ReadOnlySpan<int> indices = _catalog.GetTileTreeIndices(tx, tz);
|
||||
for (int i = 0; i < indices.Length; i++)
|
||||
{
|
||||
int id = indices[i];
|
||||
ref readonly var t = ref trees[id];
|
||||
if (t.TrunkRadiusM >= WalkerTrampleMaxTrunkRadiusM || t.IsMonumental)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (GetState(t.TreeId) == SionTreeState.Snapped)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
float hitR = walkerRadius + t.TrunkRadiusM + 0.25f;
|
||||
float dx = t.X - worldX;
|
||||
float dz = t.Z - worldZ;
|
||||
if (dx * dx + dz * dz <= hitR * hitR && SetState(t.TreeId, SionTreeState.Snapped))
|
||||
{
|
||||
changed++;
|
||||
outEvents?.Add(new TreeStateEvent
|
||||
{
|
||||
TreeId = t.TreeId,
|
||||
State = (byte)SionTreeState.Snapped,
|
||||
ImpactX = worldX,
|
||||
ImpactY = t.Y + 1.0f,
|
||||
ImpactZ = worldZ
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return changed;
|
||||
}
|
||||
|
||||
public bool BuildTileTrunkCollisionMesh(int tx, int tz, List<Vector3> outVerts, List<int> outIndices)
|
||||
{
|
||||
outVerts.Clear();
|
||||
outIndices.Clear();
|
||||
|
||||
ReadOnlySpan<int> indices = _catalog.GetTileTreeIndices(tx, tz);
|
||||
if (indices.IsEmpty)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
ReadOnlySpan<SionTreePlacement> trees = _catalog.AsSpan();
|
||||
const int sides = 6;
|
||||
for (int i = 0; i < indices.Length; i++)
|
||||
{
|
||||
ref readonly var t = ref trees[indices[i]];
|
||||
if (t.TrunkRadiusM < MinColliderTrunkRadiusM || GetState(t.TreeId) == SionTreeState.Snapped)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
float rBase = t.TrunkRadiusM * 1.10f;
|
||||
float rTop = t.TrunkRadiusM * 0.65f;
|
||||
float yBase = t.Y - 1.0f;
|
||||
float yTop = t.Y + MathF.Min(t.HeightM * 0.55f, 7.5f);
|
||||
int baseVert = outVerts.Count;
|
||||
|
||||
for (int s = 0; s < sides; s++)
|
||||
{
|
||||
float ang = MathF.Tau * s / sides + t.Yaw;
|
||||
float ca = MathF.Cos(ang);
|
||||
float sa = MathF.Sin(ang);
|
||||
outVerts.Add(new Vector3(t.X + ca * rBase, yBase, t.Z + sa * rBase));
|
||||
}
|
||||
for (int s = 0; s < sides; s++)
|
||||
{
|
||||
float ang = MathF.Tau * s / sides + t.Yaw;
|
||||
float ca = MathF.Cos(ang);
|
||||
float sa = MathF.Sin(ang);
|
||||
outVerts.Add(new Vector3(t.X + ca * rTop, yTop, t.Z + sa * rTop));
|
||||
}
|
||||
|
||||
// 6-sided tapered prism (outward CCW)
|
||||
for (int s = 0; s < sides; s++)
|
||||
{
|
||||
int sn = (s + 1) % sides;
|
||||
int b0 = baseVert + s;
|
||||
int b1 = baseVert + sn;
|
||||
int t0 = baseVert + sides + s;
|
||||
int t1 = baseVert + sides + sn;
|
||||
outIndices.Add(b0); outIndices.Add(t0); outIndices.Add(t1);
|
||||
outIndices.Add(b0); outIndices.Add(t1); outIndices.Add(b1);
|
||||
}
|
||||
// Top cap
|
||||
for (int s = 1; s < sides - 1; s++)
|
||||
{
|
||||
outIndices.Add(baseVert + sides);
|
||||
outIndices.Add(baseVert + sides + s + 1);
|
||||
outIndices.Add(baseVert + sides + s);
|
||||
}
|
||||
// Bottom cap
|
||||
for (int s = 1; s < sides - 1; s++)
|
||||
{
|
||||
outIndices.Add(baseVert);
|
||||
outIndices.Add(baseVert + s);
|
||||
outIndices.Add(baseVert + s + 1);
|
||||
}
|
||||
}
|
||||
|
||||
return outIndices.Count > 0;
|
||||
}
|
||||
|
||||
public static void GetTileRange(
|
||||
float worldX,
|
||||
float worldZ,
|
||||
float radiusMeters,
|
||||
out int minTx,
|
||||
out int maxTx,
|
||||
out int minTz,
|
||||
out int maxTz)
|
||||
{
|
||||
float r = MathF.Max(0f, radiusMeters);
|
||||
minTx = Math.Clamp((int)MathF.Floor((worldX - r + SionTreeCatalog.ArenaHalfExtent) / SionTreeCatalog.TileSizeMeters), 0, SionTreeCatalog.TileGrid - 1);
|
||||
maxTx = Math.Clamp((int)MathF.Floor((worldX + r + SionTreeCatalog.ArenaHalfExtent) / SionTreeCatalog.TileSizeMeters), 0, SionTreeCatalog.TileGrid - 1);
|
||||
minTz = Math.Clamp((int)MathF.Floor((worldZ - r + SionTreeCatalog.ArenaHalfExtent) / SionTreeCatalog.TileSizeMeters), 0, SionTreeCatalog.TileGrid - 1);
|
||||
maxTz = Math.Clamp((int)MathF.Floor((worldZ + r + SionTreeCatalog.ArenaHalfExtent) / SionTreeCatalog.TileSizeMeters), 0, SionTreeCatalog.TileGrid - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -964,6 +964,10 @@ namespace RustToDust.Net
|
|||
{
|
||||
_predTileSync.SyncWindow(_predWorld, _viewState.Terrain, local.X, local.Z, halfTileRadius: 1);
|
||||
}
|
||||
if (_viewState.SionTrees is not null)
|
||||
{
|
||||
_predTileSync.SyncTreeWindow(_predWorld, _viewState.SionTrees, local.X, local.Z, halfTileRadius: 1);
|
||||
}
|
||||
_predBody = null;
|
||||
_predWalker = null;
|
||||
_predChassisId = string.Empty;
|
||||
|
|
@ -1202,6 +1206,10 @@ namespace RustToDust.Net
|
|||
{
|
||||
_predTileSync.SyncWindow(_predWorld, _viewState.Terrain, local.X, local.Z, halfTileRadius: 1);
|
||||
}
|
||||
if (_viewState.SionTrees is not null)
|
||||
{
|
||||
_predTileSync.SyncTreeWindow(_predWorld, _viewState.SionTrees, local.X, local.Z, halfTileRadius: 1);
|
||||
}
|
||||
_predWorld.Step(ArenaSession.FixedDt, subSteps);
|
||||
ArenaSession.SyncContenderPoseFromLane(local, _predWorld.View, _predBody.Value.Lane, _predWalker);
|
||||
}
|
||||
|
|
@ -1295,6 +1303,10 @@ namespace RustToDust.Net
|
|||
{
|
||||
_predTileSync.SyncWindow(_predWorld, _viewState.Terrain, local.X, local.Z, halfTileRadius: 1);
|
||||
}
|
||||
if (_predWorld is not null && _viewState.SionTrees is not null)
|
||||
{
|
||||
_predTileSync.SyncTreeWindow(_predWorld, _viewState.SionTrees, local.X, local.Z, halfTileRadius: 1);
|
||||
}
|
||||
SpawnLocalPredictionBody(pkt.LocalPos, pkt.LocalRot, pkt.LocalVel, pkt.LocalAngVel);
|
||||
|
||||
if (local.Lifecycle == ContenderLifecycle.Deploying &&
|
||||
|
|
@ -1654,12 +1666,23 @@ namespace RustToDust.Net
|
|||
case TerrainStampEvent stamp:
|
||||
ApplyTerrainStamp(stamp);
|
||||
break;
|
||||
case TreeStateEvent treeEv:
|
||||
if (_viewState.ApplyTreeState(treeEv.TreeId, (SionTreeState)treeEv.State, recordInLedger: true) &&
|
||||
_predWorld is not null && _viewState.SionTrees is not null)
|
||||
{
|
||||
_predTileSync.FlushDirtyTreeTiles(_predWorld, _viewState.SionTrees, maxTilesPerTick: 16);
|
||||
}
|
||||
break;
|
||||
case ArenaRepairEvent:
|
||||
_viewState.RepairArenaScars();
|
||||
if (_predWorld is not null && _viewState.Terrain.IsHeightmapMode)
|
||||
{
|
||||
_predTileSync.SyncWindow(_predWorld, _viewState.Terrain, LocalContender.X, LocalContender.Z, halfTileRadius: 1);
|
||||
}
|
||||
if (_predWorld is not null && _viewState.SionTrees is not null)
|
||||
{
|
||||
_predTileSync.FlushDirtyTreeTiles(_predWorld, _viewState.SionTrees, maxTilesPerTick: 16);
|
||||
}
|
||||
break;
|
||||
case DropSpawnedEvent ds:
|
||||
_viewState.ApplyReplicatedDropSpawned(
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ namespace RustToDust.Net
|
|||
public readonly HashSet<int> SentOrdnanceIds = new();
|
||||
public readonly HashSet<int> SentTerrainStampIndices = new();
|
||||
public readonly int[,] SentTileVersions = new int[16, 16];
|
||||
public readonly Dictionary<ushort, byte> SentTreeStates = new();
|
||||
}
|
||||
|
||||
private struct EntityPvsTracker
|
||||
|
|
@ -55,6 +56,8 @@ namespace RustToDust.Net
|
|||
private readonly List<ISimEvent> _hostPendingEvents = new();
|
||||
private readonly List<TerrainStampEvent> _terrainStampHistory = new();
|
||||
private readonly List<int>[,] _tileStampHistory = new List<int>[16, 16];
|
||||
private readonly Dictionary<ushort, TreeStateEvent> _treeChangeHistory = new();
|
||||
private readonly HashSet<ushort>[,] _tileTreeChanges = new HashSet<ushort>[16, 16];
|
||||
private readonly string? _configuredScarPath;
|
||||
private readonly ArenaMapKind _initialMapKind;
|
||||
private readonly bool _persistScars;
|
||||
|
|
@ -117,6 +120,7 @@ namespace RustToDust.Net
|
|||
for (int tx = 0; tx < 16; tx++)
|
||||
{
|
||||
_tileStampHistory[tx, tz] = new List<int>(4);
|
||||
_tileTreeChanges[tx, tz] = new HashSet<ushort>();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -267,6 +271,8 @@ namespace RustToDust.Net
|
|||
_lastBroadcastCountdownSec = -1;
|
||||
_terrainStampHistory.Clear();
|
||||
ClearTileStampHistory();
|
||||
_treeChangeHistory.Clear();
|
||||
ClearTileTreeChanges();
|
||||
_stepEvents.Clear();
|
||||
_hostPendingEvents.Clear();
|
||||
_reconnectTokens.Clear();
|
||||
|
|
@ -677,6 +683,12 @@ namespace RustToDust.Net
|
|||
_session.State.Terrain.MapWorldToTile(ts.X, ts.Z, out int tx, out int tz);
|
||||
_tileStampHistory[tx, tz].Add(stampIdx);
|
||||
}
|
||||
else if (_stepEvents[i] is TreeStateEvent te && _session.State.SionTrees is { } trees && te.TreeId < trees.Catalog.Count)
|
||||
{
|
||||
_treeChangeHistory[te.TreeId] = te;
|
||||
var placement = trees.Catalog.Trees[te.TreeId];
|
||||
_tileTreeChanges[placement.Tx, placement.Tz].Add(te.TreeId);
|
||||
}
|
||||
}
|
||||
|
||||
FlushEventsAndPvsEnter();
|
||||
|
|
@ -1099,6 +1111,15 @@ namespace RustToDust.Net
|
|||
peer.SentOrdnanceIds.Clear();
|
||||
peer.SentTerrainStampIndices.Clear();
|
||||
Array.Clear(peer.SentTileVersions);
|
||||
peer.SentTreeStates.Clear();
|
||||
foreach (var kv in _treeChangeHistory)
|
||||
{
|
||||
peer.SentTreeStates[kv.Key] = kv.Value.State;
|
||||
}
|
||||
foreach (var ts in _session.State.ScarLedger.Trees)
|
||||
{
|
||||
peer.SentTreeStates[ts.Key] = ts.Value.State;
|
||||
}
|
||||
for (int i = 0; i < _terrainStampHistory.Count; i++)
|
||||
{
|
||||
peer.SentTerrainStampIndices.Add(i);
|
||||
|
|
@ -1306,6 +1327,10 @@ namespace RustToDust.Net
|
|||
// Delivered via 576m local geometry bubble sync below so distant live fire is never leaked
|
||||
// while _predWorld stays 1:1 physics-synchronized before the player enters tile range.
|
||||
break;
|
||||
case TreeStateEvent:
|
||||
// Delivered via 576m local geometry bubble sync below so distant tree snaps stay synced
|
||||
// for _predWorld without leaking remote combat telemetry.
|
||||
break;
|
||||
case OverheatAlertEvent oh:
|
||||
if (oh.ContenderId == obsId)
|
||||
{
|
||||
|
|
@ -1983,6 +2008,8 @@ namespace RustToDust.Net
|
|||
_inMemoryScarsByMap.Remove(_session.State.MapKind);
|
||||
_terrainStampHistory.Clear();
|
||||
ClearTileStampHistory();
|
||||
_treeChangeHistory.Clear();
|
||||
ClearTileTreeChanges();
|
||||
FlushScarLedgerIfDirty();
|
||||
|
||||
uint rev = _session.State.ScarLedger.LedgerRevision;
|
||||
|
|
@ -1997,6 +2024,7 @@ namespace RustToDust.Net
|
|||
if (!peer.Active) continue;
|
||||
peer.SentTerrainStampIndices.Clear();
|
||||
Array.Clear(peer.SentTileVersions);
|
||||
peer.SentTreeStates.Clear();
|
||||
SendSchemaToPeer(peer, new SimEventBatchMsg
|
||||
{
|
||||
BatchSeq = _eventBatchSeq++,
|
||||
|
|
@ -2010,7 +2038,8 @@ namespace RustToDust.Net
|
|||
|
||||
private void SyncPeerLocalGeometryBubble(ConnectedPeer peer, int obsId, List<ISimEvent> filtered)
|
||||
{
|
||||
if (_terrainStampHistory.Count == 0 || obsId < 0 || obsId >= _session.State.Contenders.Count)
|
||||
if ((_terrainStampHistory.Count == 0 && _treeChangeHistory.Count == 0) ||
|
||||
obsId < 0 || obsId >= _session.State.Contenders.Count)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
|
@ -2028,38 +2057,66 @@ namespace RustToDust.Net
|
|||
{
|
||||
for (int tx = minTx; tx <= maxTx; tx++)
|
||||
{
|
||||
var list = _tileStampHistory[tx, tz];
|
||||
if (list.Count == 0)
|
||||
if (_terrainStampHistory.Count > 0)
|
||||
{
|
||||
peer.SentTileVersions[tx, tz] = terrain.VisualTileVersions[tx, tz];
|
||||
continue;
|
||||
}
|
||||
|
||||
bool allSent = true;
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
int stampIdx = list[i];
|
||||
if (peer.SentTerrainStampIndices.Contains(stampIdx))
|
||||
var list = _tileStampHistory[tx, tz];
|
||||
if (list.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
var ts = _terrainStampHistory[stampIdx];
|
||||
float dx = obs.X - ts.X;
|
||||
float dz = obs.Z - ts.Z;
|
||||
if (dx * dx + dz * dz <= bubbleRadiusSq)
|
||||
{
|
||||
peer.SentTerrainStampIndices.Add(stampIdx);
|
||||
filtered.Add(ts);
|
||||
peer.SentTileVersions[tx, tz] = terrain.VisualTileVersions[tx, tz];
|
||||
}
|
||||
else
|
||||
{
|
||||
allSent = false;
|
||||
bool allSent = true;
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
int stampIdx = list[i];
|
||||
if (peer.SentTerrainStampIndices.Contains(stampIdx))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
var ts = _terrainStampHistory[stampIdx];
|
||||
float dx = obs.X - ts.X;
|
||||
float dz = obs.Z - ts.Z;
|
||||
if (dx * dx + dz * dz <= bubbleRadiusSq)
|
||||
{
|
||||
peer.SentTerrainStampIndices.Add(stampIdx);
|
||||
filtered.Add(ts);
|
||||
}
|
||||
else
|
||||
{
|
||||
allSent = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (allSent)
|
||||
{
|
||||
peer.SentTileVersions[tx, tz] = terrain.VisualTileVersions[tx, tz];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (allSent)
|
||||
if (_treeChangeHistory.Count > 0 && _session.State.SionTrees is { } trees)
|
||||
{
|
||||
peer.SentTileVersions[tx, tz] = terrain.VisualTileVersions[tx, tz];
|
||||
var treeIds = _tileTreeChanges[tx, tz];
|
||||
foreach (ushort treeId in treeIds)
|
||||
{
|
||||
if (!_treeChangeHistory.TryGetValue(treeId, out var te))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (peer.SentTreeStates.TryGetValue(treeId, out byte sentState) && sentState == te.State)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
var placement = trees.Catalog.Trees[treeId];
|
||||
float dx = obs.X - placement.X;
|
||||
float dz = obs.Z - placement.Z;
|
||||
if (dx * dx + dz * dz <= bubbleRadiusSq)
|
||||
{
|
||||
peer.SentTreeStates[treeId] = te.State;
|
||||
filtered.Add(te);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -2076,6 +2133,17 @@ namespace RustToDust.Net
|
|||
}
|
||||
}
|
||||
|
||||
private void ClearTileTreeChanges()
|
||||
{
|
||||
for (int tz = 0; tz < 16; tz++)
|
||||
{
|
||||
for (int tx = 0; tx < 16; tx++)
|
||||
{
|
||||
_tileTreeChanges[tx, tz].Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static string ResolveScarFilePath(string? configuredPath, ArenaMapKind initialMapKind, ArenaMapKind targetMapKind)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(configuredPath))
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ namespace RustToDust.Ymir
|
|||
private readonly bool[,] _contenderPvs = new bool[MatchState.ContenderCount, MatchState.ContenderCount];
|
||||
private readonly bool[,] _spectatorPvs;
|
||||
private readonly List<ISimEvent> _stepEvents = new();
|
||||
private readonly List<TreeStateEvent> _treeEventsScratch = new(16);
|
||||
private readonly List<OrdnanceNetEvent> _ordnanceNetScratch = new(64);
|
||||
private long _forwardedPodEventId;
|
||||
private bool _disposed;
|
||||
|
|
@ -109,6 +110,10 @@ namespace RustToDust.Ymir
|
|||
_tileSync.FlushDirtyHeightfields(_world, State.Terrain, maxTilesPerTick: budget);
|
||||
}
|
||||
}
|
||||
if (State.SionTrees is not null)
|
||||
{
|
||||
_tileSync.FlushDirtyTreeTiles(_world, State.SionTrees, maxTilesPerTick: 256);
|
||||
}
|
||||
}
|
||||
|
||||
public static bool IsStaticWorldStableId(ulong stableId) =>
|
||||
|
|
@ -780,6 +785,7 @@ namespace RustToDust.Ymir
|
|||
Span<bool> immediate = stackalloc bool[Box3DPhysicsTileSync.MaxTiles];
|
||||
MarkPhysicsOccupancyTiles(state, needed, immediate);
|
||||
tileSync.SyncNeededTiles(world, state.Terrain, needed, immediate);
|
||||
tileSync.SyncNeededTreeTiles(world, state.SionTrees, needed, immediate);
|
||||
}
|
||||
|
||||
ulong boxId = StaticBoxStableIdBase;
|
||||
|
|
@ -868,6 +874,9 @@ namespace RustToDust.Ymir
|
|||
if (c.IsHuman)
|
||||
{
|
||||
_tileSync.EnsureTileRegion(_world, State.Terrain, c.X, c.Z, halfTileRadius: 1);
|
||||
_tileSync.EnsureTreeTileResident(_world, State.SionTrees,
|
||||
Math.Clamp((int)MathF.Floor((c.X + SionTreeCatalog.ArenaHalfExtent) / SionTreeCatalog.TileSizeMeters), 0, SionTreeCatalog.TileGrid - 1),
|
||||
Math.Clamp((int)MathF.Floor((c.Z + SionTreeCatalog.ArenaHalfExtent) / SionTreeCatalog.TileSizeMeters), 0, SionTreeCatalog.TileGrid - 1));
|
||||
}
|
||||
else
|
||||
{
|
||||
|
|
@ -992,6 +1001,11 @@ namespace RustToDust.Ymir
|
|||
MarkPhysicsOccupancyTiles(State, needed, immediate);
|
||||
_tileSync.SyncNeededTiles(_world, State.Terrain, needed, immediate, maxNewPrefetchPerTick: 1);
|
||||
_tileSync.FlushDirtyHeightfields(_world, State.Terrain, maxTilesPerTick: 4);
|
||||
if (State.SionTrees is not null)
|
||||
{
|
||||
_tileSync.SyncNeededTreeTiles(_world, State.SionTrees, needed, immediate, maxNewPrefetchPerTick: 1);
|
||||
_tileSync.FlushDirtyTreeTiles(_world, State.SionTrees, maxTilesPerTick: 4);
|
||||
}
|
||||
}
|
||||
|
||||
public DropSurfaceSample QueryDropSurface(float x, float z, float footRadius, float referenceMaxY)
|
||||
|
|
@ -2092,6 +2106,18 @@ namespace RustToDust.Ymir
|
|||
State.Terrain.StampTrack(c.X, c.Z, c.Yaw, c.Grid.Spec.HalfWidth * 1.4f, 2.5f);
|
||||
}
|
||||
}
|
||||
if (State.SionTrees is { } trees &&
|
||||
c.Grid.Spec.MassKg >= SionTreeDestructionState.HeavyWalkerMinMassKg &&
|
||||
!c.TouchdownOnRoof &&
|
||||
c.Y - c.Grid.Spec.HalfHeight <= groundY + 3.5f)
|
||||
{
|
||||
_treeEventsScratch.Clear();
|
||||
float wRad = MathF.Max(c.Grid.Spec.HalfWidth, c.Grid.Spec.HalfLength);
|
||||
if (trees.ApplyWalkerTrample(c.X, c.Z, wRad, c.Grid.Spec.MassKg, _treeEventsScratch) > 0)
|
||||
{
|
||||
EmitTreeStateEvents(_treeEventsScratch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < State.Spectators.Spectators.Count; i++)
|
||||
|
|
@ -2120,6 +2146,16 @@ namespace RustToDust.Ymir
|
|||
{
|
||||
ws.SyncBodyPoseOnly(new Vector3(s.X, s.Y, s.Z), Quaternion.Normalize(q), view.Mass[lane]);
|
||||
}
|
||||
if (State.SionTrees is { } trees &&
|
||||
s.Grid.Spec.MassKg >= SionTreeDestructionState.HeavyWalkerMinMassKg)
|
||||
{
|
||||
_treeEventsScratch.Clear();
|
||||
float wRad = MathF.Max(s.Grid.Spec.HalfWidth, s.Grid.Spec.HalfLength);
|
||||
if (trees.ApplyWalkerTrample(s.X, s.Z, wRad, s.Grid.Spec.MassKg, _treeEventsScratch) > 0)
|
||||
{
|
||||
EmitTreeStateEvents(_treeEventsScratch);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -3247,6 +3283,15 @@ namespace RustToDust.Ymir
|
|||
return;
|
||||
}
|
||||
|
||||
if (State.SionTrees is { } sionTrees && splashDamage > 0f)
|
||||
{
|
||||
_treeEventsScratch.Clear();
|
||||
if (sionTrees.ApplyBlast(center, radius, splashDamage, _treeEventsScratch) > 0)
|
||||
{
|
||||
EmitTreeStateEvents(_treeEventsScratch);
|
||||
}
|
||||
}
|
||||
|
||||
var view = _world.View;
|
||||
for (int i = 0; i < State.Contenders.Count; i++)
|
||||
{
|
||||
|
|
@ -3448,6 +3493,36 @@ namespace RustToDust.Ymir
|
|||
}
|
||||
}
|
||||
|
||||
void IOrdnanceTargetSink.PrewarmTreeRayTiles(Vector3 origin, Vector3 dir, float distance)
|
||||
{
|
||||
if (State.SionTrees is { } trees)
|
||||
{
|
||||
_tileSync.EnsureTreeTilesAlongRay(_world, trees, origin.X, origin.Z, dir.X, dir.Z, distance);
|
||||
}
|
||||
}
|
||||
|
||||
void IOrdnanceTargetSink.ApplyTreeImpact(ulong targetStableId, Vector3 hitPoint, float splashRadius, float damage)
|
||||
{
|
||||
if (State.SionTrees is { } trees && Box3DPhysicsTileSync.IsTreeTileStableId(targetStableId))
|
||||
{
|
||||
_treeEventsScratch.Clear();
|
||||
if (trees.ApplyBlast(hitPoint, MathF.Max(2.5f, splashRadius), damage, _treeEventsScratch) > 0)
|
||||
{
|
||||
EmitTreeStateEvents(_treeEventsScratch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void EmitTreeStateEvents(List<TreeStateEvent> events)
|
||||
{
|
||||
for (int i = 0; i < events.Count; i++)
|
||||
{
|
||||
var ev = events[i];
|
||||
State.ScarLedger.RecordTreeState(ev.TreeId, ev.State);
|
||||
_stepEvents.Add(ev);
|
||||
}
|
||||
}
|
||||
|
||||
private static Vector3 ComputeBoxFaceNormal(
|
||||
(float X, float Y, float Z) hitPoint,
|
||||
int lane,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,7 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using RustToDust.Core;
|
||||
using Ymir.Box3D;
|
||||
|
||||
|
|
@ -16,10 +19,20 @@ namespace RustToDust.Ymir
|
|||
private readonly int[] _syncedStructuralVersions = new int[MaxTiles];
|
||||
private float[]? _scratchHeights;
|
||||
|
||||
private readonly Box3DSoaBodyHandle[] _treeHandles = new Box3DSoaBodyHandle[MaxTiles];
|
||||
private readonly bool[] _treeResidentFlags = new bool[MaxTiles];
|
||||
private readonly int[] _syncedTreeVersions = new int[MaxTiles];
|
||||
private readonly List<Vector3> _scratchTreeVerts = new(512);
|
||||
private readonly List<int> _scratchTreeIndices = new(1536);
|
||||
|
||||
public static bool IsHeightfieldTileStableId(ulong stableId) =>
|
||||
stableId >= HeightfieldTileStableIdBase && stableId < HeightfieldTileStableIdBase + MaxTiles;
|
||||
|
||||
public static bool IsTreeTileStableId(ulong stableId) =>
|
||||
stableId >= TreeTileStableIdBase && stableId < TreeTileStableIdBase + MaxTiles;
|
||||
|
||||
public int ResidentTileCount { get; private set; }
|
||||
public int ResidentTreeTileCount { get; private set; }
|
||||
|
||||
public bool TryGetResidentHandle(int tx, int tz, int tileGridCount, out Box3DSoaBodyHandle handle)
|
||||
{
|
||||
|
|
@ -36,12 +49,32 @@ namespace RustToDust.Ymir
|
|||
return false;
|
||||
}
|
||||
|
||||
public bool TryGetResidentTreeHandle(int tx, int tz, out Box3DSoaBodyHandle handle)
|
||||
{
|
||||
if ((uint)tx < (uint)SionTreeCatalog.TileGrid && (uint)tz < (uint)SionTreeCatalog.TileGrid)
|
||||
{
|
||||
int idx = tz * SionTreeCatalog.TileGrid + tx;
|
||||
if (_treeResidentFlags[idx])
|
||||
{
|
||||
handle = _treeHandles[idx];
|
||||
return true;
|
||||
}
|
||||
}
|
||||
handle = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
Array.Clear(_residentHandles);
|
||||
Array.Clear(_residentFlags);
|
||||
Array.Clear(_syncedStructuralVersions);
|
||||
ResidentTileCount = 0;
|
||||
|
||||
Array.Clear(_treeHandles);
|
||||
Array.Clear(_treeResidentFlags);
|
||||
Array.Clear(_syncedTreeVersions);
|
||||
ResidentTreeTileCount = 0;
|
||||
}
|
||||
|
||||
public bool EnsureTileResident(Box3DSoaWorld world, TerrainField terrain, int tx, int tz)
|
||||
|
|
@ -126,6 +159,275 @@ namespace RustToDust.Ymir
|
|||
}
|
||||
}
|
||||
|
||||
public bool EnsureTreeTileResident(Box3DSoaWorld world, SionTreeDestructionState? trees, int tx, int tz)
|
||||
{
|
||||
if (trees is null || trees.Catalog.Count == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if ((uint)tx >= (uint)SionTreeCatalog.TileGrid || (uint)tz >= (uint)SionTreeCatalog.TileGrid)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
int idx = tz * SionTreeCatalog.TileGrid + tx;
|
||||
int curVer = trees.TileColVersions[idx];
|
||||
if (_treeResidentFlags[idx] && _syncedTreeVersions[idx] == curVer)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (_treeResidentFlags[idx])
|
||||
{
|
||||
world.RemoveBody(_treeHandles[idx]);
|
||||
_treeHandles[idx] = default;
|
||||
_treeResidentFlags[idx] = false;
|
||||
ResidentTreeTileCount--;
|
||||
}
|
||||
|
||||
if (trees.BuildTileTrunkCollisionMesh(tx, tz, _scratchTreeVerts, _scratchTreeIndices))
|
||||
{
|
||||
if (world.FreeBodySlots < 2)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
var handle = world.AddStaticMesh(
|
||||
TreeTileStableIdBase + (ulong)idx,
|
||||
(0f, 0f, 0f),
|
||||
CollectionsMarshal.AsSpan(_scratchTreeVerts),
|
||||
CollectionsMarshal.AsSpan(_scratchTreeIndices),
|
||||
friction: 0.45f,
|
||||
restitution: 0.05f);
|
||||
_treeHandles[idx] = handle;
|
||||
_treeResidentFlags[idx] = true;
|
||||
ResidentTreeTileCount++;
|
||||
}
|
||||
|
||||
_syncedTreeVersions[idx] = curVer;
|
||||
return true;
|
||||
}
|
||||
|
||||
public void SyncNeededTreeTiles(
|
||||
Box3DSoaWorld world,
|
||||
SionTreeDestructionState? trees,
|
||||
ReadOnlySpan<bool> needed,
|
||||
ReadOnlySpan<bool> immediate = default,
|
||||
int maxNewPrefetchPerTick = int.MaxValue)
|
||||
{
|
||||
if (trees is null || trees.Catalog.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
const int grid = SionTreeCatalog.TileGrid;
|
||||
for (int tz = 0; tz < grid; tz++)
|
||||
{
|
||||
for (int tx = 0; tx < grid; tx++)
|
||||
{
|
||||
int idx = tz * grid + tx;
|
||||
bool keep = needed[idx] || (!immediate.IsEmpty && immediate[idx]);
|
||||
if (_treeResidentFlags[idx] && !keep)
|
||||
{
|
||||
world.RemoveBody(_treeHandles[idx]);
|
||||
_treeHandles[idx] = default;
|
||||
_treeResidentFlags[idx] = false;
|
||||
_syncedTreeVersions[idx] = 0;
|
||||
ResidentTreeTileCount--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!immediate.IsEmpty)
|
||||
{
|
||||
for (int tz = 0; tz < grid; tz++)
|
||||
{
|
||||
for (int tx = 0; tx < grid; tx++)
|
||||
{
|
||||
int idx = tz * grid + tx;
|
||||
if (immediate[idx] && !_treeResidentFlags[idx])
|
||||
{
|
||||
EnsureTreeTileResident(world, trees, tx, tz);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int newPrefetch = 0;
|
||||
for (int tz = 0; tz < grid; tz++)
|
||||
{
|
||||
for (int tx = 0; tx < grid; tx++)
|
||||
{
|
||||
if (newPrefetch >= maxNewPrefetchPerTick)
|
||||
{
|
||||
return;
|
||||
}
|
||||
int idx = tz * grid + tx;
|
||||
if (needed[idx] && !_treeResidentFlags[idx])
|
||||
{
|
||||
if (EnsureTreeTileResident(world, trees, tx, tz))
|
||||
{
|
||||
newPrefetch++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int FlushDirtyTreeTiles(Box3DSoaWorld world, SionTreeDestructionState? trees, int maxTilesPerTick = 4)
|
||||
{
|
||||
if (trees is null || trees.Catalog.Count == 0 || maxTilesPerTick <= 0)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
int rebuilt = 0;
|
||||
const int grid = SionTreeCatalog.TileGrid;
|
||||
for (int tz = 0; tz < grid; tz++)
|
||||
{
|
||||
for (int tx = 0; tx < grid; tx++)
|
||||
{
|
||||
int idx = tz * grid + tx;
|
||||
if (trees.TileColVersions[idx] != _syncedTreeVersions[idx])
|
||||
{
|
||||
if (!_treeResidentFlags[idx])
|
||||
{
|
||||
_syncedTreeVersions[idx] = trees.TileColVersions[idx];
|
||||
continue;
|
||||
}
|
||||
if (world.FreeBodySlots < 8)
|
||||
{
|
||||
return rebuilt;
|
||||
}
|
||||
if (EnsureTreeTileResident(world, trees, tx, tz))
|
||||
{
|
||||
rebuilt++;
|
||||
if (rebuilt >= maxTilesPerTick)
|
||||
{
|
||||
return rebuilt;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return rebuilt;
|
||||
}
|
||||
|
||||
public void SyncTreeWindow(Box3DSoaWorld world, SionTreeDestructionState? trees, float centerX, float centerZ, int halfTileRadius = 1)
|
||||
{
|
||||
if (trees is null || trees.Catalog.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
const int grid = SionTreeCatalog.TileGrid;
|
||||
int cx = Math.Clamp((int)MathF.Floor((centerX + SionTreeCatalog.ArenaHalfExtent) / SionTreeCatalog.TileSizeMeters), 0, grid - 1);
|
||||
int cz = Math.Clamp((int)MathF.Floor((centerZ + SionTreeCatalog.ArenaHalfExtent) / SionTreeCatalog.TileSizeMeters), 0, grid - 1);
|
||||
int minTx = Math.Max(0, cx - halfTileRadius);
|
||||
int maxTx = Math.Min(grid - 1, cx + halfTileRadius);
|
||||
int minTz = Math.Max(0, cz - halfTileRadius);
|
||||
int maxTz = Math.Min(grid - 1, cz + halfTileRadius);
|
||||
|
||||
for (int tz = 0; tz < grid; tz++)
|
||||
{
|
||||
for (int tx = 0; tx < grid; tx++)
|
||||
{
|
||||
int idx = tz * grid + tx;
|
||||
if (_treeResidentFlags[idx] && (tx < minTx || tx > maxTx || tz < minTz || tz > maxTz))
|
||||
{
|
||||
world.RemoveBody(_treeHandles[idx]);
|
||||
_treeHandles[idx] = default;
|
||||
_treeResidentFlags[idx] = false;
|
||||
_syncedTreeVersions[idx] = 0;
|
||||
ResidentTreeTileCount--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int tz = minTz; tz <= maxTz; tz++)
|
||||
{
|
||||
for (int tx = minTx; tx <= maxTx; tx++)
|
||||
{
|
||||
EnsureTreeTileResident(world, trees, tx, tz);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void EnsureTreeTilesAlongRay(
|
||||
Box3DSoaWorld world,
|
||||
SionTreeDestructionState? trees,
|
||||
float ox, float oz,
|
||||
float dx, float dz,
|
||||
float maxDistance)
|
||||
{
|
||||
if (trees is null || trees.Catalog.Count == 0 || maxDistance <= 0f)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
const float half = SionTreeCatalog.ArenaHalfExtent;
|
||||
const float tileSize = SionTreeCatalog.TileSizeMeters;
|
||||
const int grid = SionTreeCatalog.TileGrid;
|
||||
|
||||
float tMin = 0f;
|
||||
float tMax = maxDistance;
|
||||
if (!SlabClip(ox, dx, -half, half, ref tMin, ref tMax)) return;
|
||||
if (!SlabClip(oz, dz, -half, half, ref tMin, ref tMax)) return;
|
||||
|
||||
float sx = ox + dx * tMin;
|
||||
float sz = oz + dz * tMin;
|
||||
int tx = Math.Clamp((int)MathF.Floor((sx + half) / tileSize), 0, grid - 1);
|
||||
int tz = Math.Clamp((int)MathF.Floor((sz + half) / tileSize), 0, grid - 1);
|
||||
|
||||
float ex = ox + dx * tMax;
|
||||
float ez = oz + dz * tMax;
|
||||
int endTx = Math.Clamp((int)MathF.Floor((ex + half) / tileSize), 0, grid - 1);
|
||||
int endTz = Math.Clamp((int)MathF.Floor((ez + half) / tileSize), 0, grid - 1);
|
||||
|
||||
int stepX = dx > 1e-9f ? 1 : (dx < -1e-9f ? -1 : 0);
|
||||
int stepZ = dz > 1e-9f ? 1 : (dz < -1e-9f ? -1 : 0);
|
||||
float tDeltaX = stepX != 0 ? tileSize / MathF.Abs(dx) : float.PositiveInfinity;
|
||||
float tDeltaZ = stepZ != 0 ? tileSize / MathF.Abs(dz) : float.PositiveInfinity;
|
||||
|
||||
float nextBoundaryX = -half + (tx + (stepX > 0 ? 1 : 0)) * tileSize;
|
||||
float nextBoundaryZ = -half + (tz + (stepZ > 0 ? 1 : 0)) * tileSize;
|
||||
float tMaxX = stepX != 0 ? tMin + MathF.Max(0f, (nextBoundaryX - sx) / dx) : float.PositiveInfinity;
|
||||
float tMaxZ = stepZ != 0 ? tMin + MathF.Max(0f, (nextBoundaryZ - sz) / dz) : float.PositiveInfinity;
|
||||
|
||||
const int maxSteps = grid * 2 + 4;
|
||||
for (int iter = 0; iter < maxSteps; iter++)
|
||||
{
|
||||
EnsureTreeTileResident(world, trees, tx, tz);
|
||||
if (tx == endTx && tz == endTz)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
float curT;
|
||||
if (tMaxX <= tMaxZ)
|
||||
{
|
||||
curT = tMaxX;
|
||||
tMaxX += tDeltaX;
|
||||
tx += stepX;
|
||||
}
|
||||
else
|
||||
{
|
||||
curT = tMaxZ;
|
||||
tMaxZ += tDeltaZ;
|
||||
tz += stepZ;
|
||||
}
|
||||
|
||||
if ((uint)tx >= grid || (uint)tz >= grid || curT > tMax)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ((uint)endTx < grid && (uint)endTz < grid)
|
||||
{
|
||||
EnsureTreeTileResident(world, trees, endTx, endTz);
|
||||
}
|
||||
}
|
||||
|
||||
public static void MarkTileRegion(TerrainField terrain, Span<bool> needed, float worldX, float worldZ, int halfTileRadius)
|
||||
{
|
||||
if (!terrain.IsHeightmapMode)
|
||||
|
|
|
|||
|
|
@ -103,6 +103,8 @@ namespace RustToDust.Ymir
|
|||
bool isSpectatorShooter,
|
||||
int shooterEntityId);
|
||||
void StampTerrainImpact(float x, float z, float craterRadius, float craterDepth, float scorchRadius);
|
||||
void PrewarmTreeRayTiles(Vector3 origin, Vector3 dir, float distance);
|
||||
void ApplyTreeImpact(ulong targetStableId, Vector3 hitPoint, float splashRadius, float damage);
|
||||
}
|
||||
|
||||
public struct LiveOrdnanceInstance
|
||||
|
|
@ -757,6 +759,7 @@ namespace RustToDust.Ymir
|
|||
}
|
||||
|
||||
Vector3 dir = segDelta / segLen;
|
||||
_sink.PrewarmTreeRayTiles(segStart, dir, segLen);
|
||||
Vector3 castOrigin = segStart;
|
||||
float remaining = segLen;
|
||||
bool skipSelf = inst.Age < 0.25f;
|
||||
|
|
@ -1191,6 +1194,10 @@ namespace RustToDust.Ymir
|
|||
}
|
||||
else
|
||||
{
|
||||
if (targetKind == HitTargetKind.StaticCover && Box3DPhysicsTileSync.IsTreeTileStableId(targetStableId))
|
||||
{
|
||||
_sink.ApplyTreeImpact(targetStableId, hitPoint, MathF.Max(2.5f, def.SplashRadius), (def.DirectDamage + def.SplashDamage) * inst.DamageScale);
|
||||
}
|
||||
_sink.EmitNonActorHit(
|
||||
HitTargetKind.StaticCover,
|
||||
targetId,
|
||||
|
|
@ -1278,6 +1285,7 @@ namespace RustToDust.Ymir
|
|||
float range = MathF.Max(5f, def.Range);
|
||||
Vector3 castOrigin = muzzle;
|
||||
float remainingRange = range;
|
||||
_sink.PrewarmTreeRayTiles(muzzle, dir, range);
|
||||
int penetrations = 0;
|
||||
ulong lastPenetratedId = 0;
|
||||
float currDmgScale = damageScale;
|
||||
|
|
@ -1500,6 +1508,10 @@ namespace RustToDust.Ymir
|
|||
}
|
||||
else if (hitAny && hitStableId != shooterStableId)
|
||||
{
|
||||
if (Box3DPhysicsTileSync.IsTreeTileStableId(hitStableId))
|
||||
{
|
||||
_sink.ApplyTreeImpact(hitStableId, endPt, MathF.Max(2.5f, def.SplashRadius), (def.DirectDamage + def.SplashDamage) * currDmgScale);
|
||||
}
|
||||
_sink.EmitNonActorHit(
|
||||
HitTargetKind.StaticCover,
|
||||
(int)hitStableId,
|
||||
|
|
|
|||
|
|
@ -737,7 +737,7 @@ namespace RustToDust.Tests
|
|||
|
||||
var sion = session.State.SionMap!;
|
||||
var sites = new System.Collections.Generic.List<(float X, float Z, float Yaw, float Ny)>();
|
||||
for (float r = 60f; r <= 720f && sites.Count < 3; r += 25f)
|
||||
for (float r = 60f; r <= 1350f && sites.Count < 3; r += 25f)
|
||||
{
|
||||
for (int a = 0; a < 48 && sites.Count < 3; a++)
|
||||
{
|
||||
|
|
@ -770,6 +770,22 @@ namespace RustToDust.Tests
|
|||
clear = false;
|
||||
break;
|
||||
}
|
||||
if (lat == 0f && sion.Trees is not null)
|
||||
{
|
||||
for (int ti = 0; ti < sion.Trees.Count; ti++)
|
||||
{
|
||||
var tr = sion.Trees.Trees[ti];
|
||||
if (tr.TrunkRadiusM < SionTreeDestructionState.MinColliderTrunkRadiusM) continue;
|
||||
float tdx = tr.X - ax;
|
||||
float tdz = tr.Z - az;
|
||||
if (tdx * tdx + tdz * tdz <= 4.0f * 4.0f)
|
||||
{
|
||||
clear = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!clear) break;
|
||||
}
|
||||
float gyA = session.State.Terrain.SampleHeight(ax, az);
|
||||
float gyB = session.State.Terrain.SampleHeight(bx, bz);
|
||||
if (!session.HasLineOfSight(ax, gyA + 2.5f, az, bx, gyB + 2.5f, bz))
|
||||
|
|
|
|||
|
|
@ -149,7 +149,8 @@ namespace RustToDust.Tests
|
|||
}
|
||||
Assert.InRange(hfCount, 1, 45);
|
||||
Assert.Equal(hfCount, session.TileSync.ResidentTileCount);
|
||||
Assert.Equal(36, meshCount);
|
||||
Assert.InRange(session.TileSync.ResidentTreeTileCount, 1, 45);
|
||||
Assert.Equal(36 + session.TileSync.ResidentTreeTileCount, meshCount);
|
||||
|
||||
// Verify zero contenders, spectators, or drops spawned inside any building
|
||||
foreach (var c in state.Contenders)
|
||||
|
|
|
|||
301
tests/RustToDust.Tests/SionTreeTests.cs
Normal file
|
|
@ -0,0 +1,301 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Numerics;
|
||||
using System.Text.Json;
|
||||
using RustToDust.Core;
|
||||
using RustToDust.Net;
|
||||
using RustToDust.Ymir;
|
||||
using Xunit;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace RustToDust.Tests
|
||||
{
|
||||
public sealed class SionTreeTests
|
||||
{
|
||||
[Fact]
|
||||
public void SionTreeCatalog_LoadsWithoutBeechExcludesBuildingsAndMatchesArbresRemarquables()
|
||||
{
|
||||
var sion = SionMapLoader.Load();
|
||||
var catalog = sion.Trees;
|
||||
|
||||
Assert.InRange(catalog.Count, 500, SionTreeCatalog.MaxTrees);
|
||||
|
||||
// Check binary disk budget + tree assets directory <= 12.4 MiB
|
||||
string treesBin = Path.Combine(sion.DirectoryPath, "trees_sion.bin");
|
||||
string treesDir = Path.Combine(sion.DirectoryPath, "trees");
|
||||
long totalBytes = new FileInfo(treesBin).Length;
|
||||
foreach (var f in Directory.EnumerateFiles(treesDir, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
totalBytes += new FileInfo(f).Length;
|
||||
}
|
||||
Assert.True(totalBytes <= 13_000_000L, $"Expected Sion tree assets + bin <= 12.4 MiB, got {totalBytes:N0} B");
|
||||
|
||||
bool hasSequoia = false;
|
||||
bool hasCedrus = false;
|
||||
bool hasMonumentalPlane = false;
|
||||
|
||||
// Planta d'en Haut Giant Sequoia: LV95 (2593636.1374, 1120075.402) -> (-513.8626, -25.402)
|
||||
float seqWx = 2593636.1374f - 2594150.0f;
|
||||
float seqWz = 1120050.0f - 1120075.402f;
|
||||
|
||||
// Pratifori / Cimetiere Lebanon Cedar: LV95 (2593522.9419, 1119968.4164) -> (-627.0581, 81.5836)
|
||||
float cedWx = 2593522.9419f - 2594150.0f;
|
||||
float cedWz = 1120050.0f - 1119968.4164f;
|
||||
|
||||
// Planta d'en Haut Monumental Avenue (Aesculus/PlatanusMonumental archetype #9): LV95 (2593619.7614, 1120373.0299)
|
||||
float plaWx = 2593619.7614f - 2594150.0f;
|
||||
float plaWz = 1120050.0f - 1120373.0299f;
|
||||
|
||||
for (int i = 0; i < catalog.Count; i++)
|
||||
{
|
||||
var t = catalog.Trees[i];
|
||||
Assert.True((byte)t.Species <= (byte)SionTreeSpecies.PlatanusMonumental);
|
||||
string spName = t.Species.ToString();
|
||||
Assert.DoesNotContain("Fagus", spName, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Beech", spName, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
Assert.False(sion.IsInsideAnyBuildingXz(t.X, t.Z, 0f),
|
||||
$"Tree {t.TreeId} ({t.Species}) placed inside building at ({t.X:F2}, {t.Z:F2})");
|
||||
|
||||
Assert.InRange(t.HeightM, 4.0f, 38.0f);
|
||||
Assert.InRange(t.TrunkRadiusM, 0.10f, 1.20f);
|
||||
|
||||
if (t.Species == SionTreeSpecies.Sequoiadendron &&
|
||||
MathF.Sqrt((t.X - seqWx) * (t.X - seqWx) + (t.Z - seqWz) * (t.Z - seqWz)) < 0.25f)
|
||||
{
|
||||
hasSequoia = true;
|
||||
}
|
||||
if (t.Species == SionTreeSpecies.Cedrus &&
|
||||
MathF.Sqrt((t.X - cedWx) * (t.X - cedWx) + (t.Z - cedWz) * (t.Z - cedWz)) < 0.25f)
|
||||
{
|
||||
hasCedrus = true;
|
||||
}
|
||||
if (t.Species == SionTreeSpecies.PlatanusMonumental &&
|
||||
MathF.Sqrt((t.X - plaWx) * (t.X - plaWx) + (t.Z - plaWz) * (t.Z - plaWz)) < 0.25f)
|
||||
{
|
||||
hasMonumentalPlane = true;
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(hasSequoia, "Expected Planta d'en Haut Sequoiadendron at exact Sion coordinates");
|
||||
Assert.True(hasCedrus, "Expected Lebanon Cedrus at exact Sion coordinates");
|
||||
Assert.True(hasMonumentalPlane, "Expected En Ville PlatanusMonumental at exact Sion coordinates");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SionTreeDestruction_OrdnanceSnapsAndChars_UpdatesBox3DColliderPersistsAndHeals()
|
||||
{
|
||||
string tempDir = Path.Combine(Path.GetTempPath(), "rtd-cut13d-tree-scar-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(tempDir);
|
||||
string scarPath = Path.Combine(tempDir, "sion_tree_scars.cultcache");
|
||||
|
||||
try
|
||||
{
|
||||
ushort targetId = 0;
|
||||
SionTreePlacement targetTree = default;
|
||||
bool foundTarget = false;
|
||||
|
||||
using (var host = new ServerMatchHost(
|
||||
IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion,
|
||||
autoRestartSec: 0, scarFilePath: scarPath, persistScars: true))
|
||||
{
|
||||
var trees = host.Session.State.SionTrees!;
|
||||
var catalog = trees.Catalog;
|
||||
|
||||
// Pick an isolated solid tree (TrunkRadiusM >= 0.28m) with no nearby buildings/neighbors on the ray
|
||||
for (int i = 0; i < catalog.Count; i++)
|
||||
{
|
||||
var t = catalog.Trees[i];
|
||||
if (t.TrunkRadiusM < 0.28f || t.IsMonumental) continue;
|
||||
if (host.Session.State.SionMap!.IsInsideAnyBuildingXz(t.X, t.Z, 12f)) continue;
|
||||
targetTree = t;
|
||||
targetId = t.TreeId;
|
||||
foundTarget = true;
|
||||
break;
|
||||
}
|
||||
Assert.True(foundTarget, "Expected a solid non-monumental tree outside buildings");
|
||||
|
||||
host.Session.TileSync.EnsureTreeTileResident(host.Session.World, trees, targetTree.Tx, targetTree.Tz);
|
||||
ulong expectedStableId = Box3DPhysicsTileSync.TreeTileStableIdBase + (ulong)targetTree.TileIndex;
|
||||
|
||||
// Horizontal ray through the trunk must hit the Box3D tree tile mesh
|
||||
var rayOrigin = new Vector3(targetTree.X - 4.0f, targetTree.Y + 1.4f, targetTree.Z);
|
||||
var raySpan = new Vector3(8.0f, 0f, 0f);
|
||||
var preHit = host.Session.CastWorldRayClosest(rayOrigin, raySpan);
|
||||
Assert.True(preHit.Hit, "Expected horizontal ray to strike solid tree trunk collider");
|
||||
Assert.Equal(expectedStableId, preHit.StableId);
|
||||
|
||||
// Artillery blast at trunk base snaps target tree; verify outer char radius on a second tree
|
||||
var hitEvents = new List<TreeStateEvent>();
|
||||
int changed = trees.ApplyBlast(new Vector3(targetTree.X, targetTree.Y + 0.5f, targetTree.Z), splashRadius: 10f, blastDamage: 240f, hitEvents);
|
||||
Assert.True(changed >= 1);
|
||||
Assert.Equal(SionTreeState.Snapped, trees.GetState(targetId));
|
||||
foreach (var ev in hitEvents)
|
||||
{
|
||||
host.Session.State.ScarLedger.RecordTreeState(ev.TreeId, ev.State);
|
||||
}
|
||||
|
||||
// Flush dirty tree tiles -> Box3D collider for snapped trunk must be gone
|
||||
host.Session.TileSync.FlushDirtyTreeTiles(host.Session.World, trees, maxTilesPerTick: 4);
|
||||
var postHit = host.Session.CastWorldRayClosest(rayOrigin, raySpan);
|
||||
Assert.False(postHit.Hit && postHit.StableId == expectedStableId &&
|
||||
MathF.Abs(postHit.Point.X - targetTree.X) <= targetTree.TrunkRadiusM * 1.5f,
|
||||
"Expected snapped tree trunk collider to be removed from Box3D tile mesh");
|
||||
|
||||
// Also test outer thermal char state on a distant intact tree
|
||||
ushort charId = 0;
|
||||
for (int i = 0; i < catalog.Count; i++)
|
||||
{
|
||||
var t = catalog.Trees[i];
|
||||
if (t.TreeId == targetId || trees.GetState(t.TreeId) != SionTreeState.Intact) continue;
|
||||
if (t.TrunkRadiusM < 0.30f) continue;
|
||||
var evs = new List<TreeStateEvent>();
|
||||
// Blast 8.5m away (outside snapCore, inside charRadius = 1.35 * 9.0) with moderate heat/blast
|
||||
trees.ApplyBlast(new Vector3(t.X + 8.5f, t.Y + 1.0f, t.Z), splashRadius: 9.0f, blastDamage: 60f, evs);
|
||||
if (trees.GetState(t.TreeId) == SionTreeState.Charred)
|
||||
{
|
||||
charId = t.TreeId;
|
||||
host.Session.State.ScarLedger.RecordTreeState(charId, (byte)SionTreeState.Charred);
|
||||
break;
|
||||
}
|
||||
}
|
||||
Assert.NotEqual(0, charId);
|
||||
|
||||
// ResetMatch must preserve both Snapped and Charred tree scars
|
||||
host.ResetMatch(43, ArenaMapKind.Sion);
|
||||
Assert.Equal(SionTreeState.Snapped, host.Session.State.SionTrees!.GetState(targetId));
|
||||
Assert.Equal(SionTreeState.Charred, host.Session.State.SionTrees!.GetState(charId));
|
||||
|
||||
// RepairArenaScars restores all trees to Intact and restores Box3D trunk collider
|
||||
host.RepairArenaScars();
|
||||
Assert.Equal(SionTreeState.Intact, host.Session.State.SionTrees!.GetState(targetId));
|
||||
Assert.Equal(SionTreeState.Intact, host.Session.State.SionTrees!.GetState(charId));
|
||||
|
||||
host.Session.TileSync.EnsureTreeTileResident(host.Session.World, host.Session.State.SionTrees, targetTree.Tx, targetTree.Tz);
|
||||
var healedHit = host.Session.CastWorldRayClosest(rayOrigin, raySpan);
|
||||
Assert.True(healedHit.Hit && healedHit.StableId == expectedStableId,
|
||||
"Expected repaired tree trunk collider to be restored in Box3D");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (Directory.Exists(tempDir))
|
||||
{
|
||||
Directory.Delete(tempDir, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SionTreeDestruction_HeavyWalkerTramplesThinTreesButNotThickOrMonumental()
|
||||
{
|
||||
var sion = SionMapLoader.Load();
|
||||
var trees = new SionTreeDestructionState(sion.Trees);
|
||||
|
||||
SionTreePlacement thin = default;
|
||||
SionTreePlacement thick = default;
|
||||
bool foundThin = false, foundThick = false;
|
||||
foreach (var t in sion.Trees.Trees)
|
||||
{
|
||||
if (!foundThin && t.TrunkRadiusM >= 0.14f && t.TrunkRadiusM < SionTreeDestructionState.WalkerTrampleMaxTrunkRadiusM)
|
||||
{
|
||||
thin = t;
|
||||
foundThin = true;
|
||||
}
|
||||
if (!foundThick && t.TrunkRadiusM >= 0.45f)
|
||||
{
|
||||
thick = t;
|
||||
foundThick = true;
|
||||
}
|
||||
if (foundThin && foundThick) break;
|
||||
}
|
||||
Assert.True(foundThin && foundThick);
|
||||
|
||||
// Light < 30t mech does not trample
|
||||
trees.ApplyWalkerTrample(thin.X, thin.Z, 2.0f, 20_000f);
|
||||
Assert.Equal(SionTreeState.Intact, trees.GetState(thin.TreeId));
|
||||
|
||||
// Heavy >= 30t walker tramples thin (< 0.30m) tree
|
||||
trees.ApplyWalkerTrample(thin.X, thin.Z, 2.0f, 35_000f);
|
||||
Assert.Equal(SionTreeState.Snapped, trees.GetState(thin.TreeId));
|
||||
|
||||
// Heavy walker does NOT trample thick (>= 0.30m) / monumental trees
|
||||
trees.ApplyWalkerTrample(thick.X, thick.Z, 2.0f, 65_000f);
|
||||
Assert.Equal(SionTreeState.Intact, trees.GetState(thick.TreeId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CultNet_RemoteClientSyncsTreeScarsInPersistentSnapshotBubbleAndRepair()
|
||||
{
|
||||
using var host = new ServerMatchHost(
|
||||
IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion,
|
||||
autoRestartSec: 0, persistScars: false);
|
||||
|
||||
var hostTrees = host.Session.State.SionTrees!;
|
||||
// Snap a historical tree before client joins
|
||||
var histTree = hostTrees.Catalog.Trees[0];
|
||||
host.Session.State.ApplyTreeState(histTree.TreeId, SionTreeState.Snapped, recordInLedger: true);
|
||||
|
||||
using var client = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "TreeTester");
|
||||
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
for (int i = 0; i < 120 && !client.IsJoined; i++)
|
||||
{
|
||||
nowMs += 16;
|
||||
host.StepOnce(nowMs);
|
||||
client.BeginRenderFrame(1f / 60f, 0f);
|
||||
System.Threading.Thread.Sleep(5);
|
||||
}
|
||||
Assert.True(client.IsJoined, "Remote client failed to join Sion ServerMatchHost");
|
||||
Assert.Equal(SionTreeState.Snapped, client.ViewState.SionTrees!.GetState(histTree.TreeId));
|
||||
|
||||
// Find a tree near the remote client's local contender (within 576m local geometry bubble)
|
||||
var local = client.LocalContender;
|
||||
SionTreePlacement liveTree = default;
|
||||
bool foundLive = false;
|
||||
foreach (var t in hostTrees.Catalog.Trees)
|
||||
{
|
||||
if (t.TreeId == histTree.TreeId || t.TrunkRadiusM < 0.25f) continue;
|
||||
float dx = t.X - local.X;
|
||||
float dz = t.Z - local.Z;
|
||||
float dist = MathF.Sqrt(dx * dx + dz * dz);
|
||||
if (dist <= 500f)
|
||||
{
|
||||
liveTree = t;
|
||||
foundLive = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Assert.True(foundLive, "Expected a solid tree within 500m of local contender");
|
||||
|
||||
// Snap it via Ordnance sink on host so TreeStateEvent flows through the 576m bubble
|
||||
((IOrdnanceTargetSink)host.Session).ApplyTreeImpact(
|
||||
Box3DPhysicsTileSync.TreeTileStableIdBase + (ulong)liveTree.TileIndex,
|
||||
new Vector3(liveTree.X, liveTree.Y + 0.5f, liveTree.Z),
|
||||
splashRadius: 6.0f,
|
||||
damage: 250f);
|
||||
|
||||
for (int i = 0; i < 60 && client.ViewState.SionTrees!.GetState(liveTree.TreeId) != SionTreeState.Snapped; i++)
|
||||
{
|
||||
nowMs += 16;
|
||||
host.StepOnce(nowMs);
|
||||
client.BeginRenderFrame(1f / 60f, 0f);
|
||||
System.Threading.Thread.Sleep(5);
|
||||
}
|
||||
Assert.Equal(SionTreeState.Snapped, client.ViewState.SionTrees!.GetState(liveTree.TreeId));
|
||||
|
||||
// RepairArenaScars propagates to remote client
|
||||
host.RepairArenaScars();
|
||||
for (int i = 0; i < 60 && client.ViewState.SionTrees!.GetState(liveTree.TreeId) != SionTreeState.Intact; i++)
|
||||
{
|
||||
nowMs += 16;
|
||||
host.StepOnce(nowMs);
|
||||
client.BeginRenderFrame(1f / 60f, 0f);
|
||||
System.Threading.Thread.Sleep(5);
|
||||
}
|
||||
Assert.Equal(SionTreeState.Intact, client.ViewState.SionTrees!.GetState(histTree.TreeId));
|
||||
Assert.Equal(SionTreeState.Intact, client.ViewState.SionTrees!.GetState(liveTree.TreeId));
|
||||
}
|
||||
}
|
||||
}
|
||||
4
third_party/cosmo_tree_gen/.editorconfig
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
7
third_party/cosmo_tree_gen/.gitattributes
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
# Normalize EOL for all files that Git considers text files.
|
||||
* text=auto eol=lf
|
||||
|
||||
# Only include the addons folder when downloading from the Asset Library.
|
||||
/** export-ignore
|
||||
/addons !export-ignore
|
||||
/addons/** !export-ignore
|
||||
7
third_party/cosmo_tree_gen/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
releases/
|
||||
test/
|
||||
exports/
|
||||
|
||||
# Godot 4+ specific ignores
|
||||
.godot/
|
||||
/android/
|
||||
21
third_party/cosmo_tree_gen/LICENSE.md
vendored
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2026 CosmonautFrog
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
110
third_party/cosmo_tree_gen/README.md
vendored
Normal file
|
|
@ -0,0 +1,110 @@
|
|||

|
||||
|
||||
# Cosmo Tree Gen
|
||||
|
||||
Procedural tree generator for Godot 4. Create and tweak trees live in the editor, save them as presets, and export them to glb/glTF with LODs and collisions.
|
||||
|
||||
Also available on: [Godot Asset Store](https://store.godotengine.org/asset/cosmonaut-frog/cosmo-tree-gen/) - [Godot Asset Library](https://godotengine.org/asset-library/asset/5594)
|
||||
|
||||
Mainly inspired by Dan Shiffman and EZTree.
|
||||
|
||||
_100% Human made. No AI was or ever will be used in this project._
|
||||
|
||||
## Showcase
|
||||
|
||||
| Save and load presets fast | Randomize by seed |
|
||||
| :------------------------: | :---------------: |
|
||||
|  |  |
|
||||
| **Live generation** | **Curve editor for fine changes** |
|
||||
|  |  |
|
||||
|
||||
[More videos](https://www.youtube.com/@cosmonautfrogstudios/videos)
|
||||
|
||||
## Features
|
||||
- Live generation and auto-updated in the editor.
|
||||
- Configurable tree parameters using custom Resources.
|
||||
- Trunk and branches.
|
||||
- Multiple trunks per node, roots and broken branches by chance.
|
||||
- Branch level length and leaf card size by curve.
|
||||
- Optional flat shading for PSX/PS2 aesthetic.
|
||||
- Foliage.
|
||||
- Icospheres, with configurable subdivisions level.
|
||||
- Card leaves, configurable amount and double sided, with canopy normals and inner AO.
|
||||
- Leaves shader with wind sway and limited mipmaps, so alpha scissor doesn't make distant leaves disappear.
|
||||
- Automatic collision generation.
|
||||
- Three shape types: one convex shape per branch, one convex shape per branch segment, or a single trimesh.
|
||||
- Covers branches up to a configurable level (0 = trunk only).
|
||||
- Collision preview in the editor.
|
||||
- Foliage collision: hull (covers all the foliage), spheres on each leaf/branch end.
|
||||
- Automatic LOD generation.
|
||||
- LOD0, LOD1 and LOD2 MeshInstance3Ds can be generated with customizable ratios and distances.
|
||||
- Billboard impostor baked on export as the last LOD, static or octahedral: 2 triangles and 1 draw call for distant trees. See [Impostor types](docs/exporting.md#impostor-types)
|
||||
- The trunk is simplified and the rest of the tris budget goes to the leaves.
|
||||
- Leaf cards are not simplified, fewer and bigger cards are kept instead.
|
||||
- Presets.
|
||||
- 4 premade presets included (Ash, Bush, Low Poly Bush and Low Poly Tree)
|
||||
- 7 more premade presets can be found in the `demo` folder.
|
||||
- Can be saved as `CosmoTreePreset` resources.
|
||||
- Export as glb/glTF with LODs, impostor and collisions, optionally linking the materials in the .import file.
|
||||
- Exposed API for script generation, see [Batch Generation](docs/batch_generation.md).
|
||||
- Editor toolbar: load/save presets, randomize seed, export, and it shows draw calls and tris counter per tree.
|
||||
|
||||
## Requirements
|
||||
Godot 4.6+ required. Developed in 4.6.2.stable.
|
||||
|
||||
## Installation
|
||||
Copy the `addons/cosmo_tree_gen/` folder into your project, enable it.
|
||||
You can see more examples and presets in the `demo` folder.
|
||||
|
||||
## Usage
|
||||
Add a `CosmoTreeGen` node and pick a preset from the toolbar.
|
||||
See [Getting Started](docs/getting_started.md) for the full walkthrough.
|
||||
|
||||
## Documentation
|
||||
- [Getting Started](docs/getting_started.md)
|
||||
- [Parameters](docs/parameters.md)
|
||||
- [Settings](docs/settings.md)
|
||||
- [Exporting](docs/exporting.md)
|
||||
- [Batch Generation](docs/batch_generation.md)
|
||||
|
||||
## Roadmap
|
||||
By priority.
|
||||
|
||||
1. Add more low-poly foliage variations. (Pine, Boxes)
|
||||
1. Add a tree age slider. From sapling to old tree.
|
||||
1. Add min-max ranges to presets. It should define a species, from young to old.
|
||||
1. Hierarchical wind for trunk, branches and leaves.
|
||||
1. Shadow proxy. Low poly mesh for foliage with `SHADOWS_ONLY`.
|
||||
1. Bake tree in-place and make the node game-ready. So it can be used without extracting to `.glb`.
|
||||
1. Add stumps, fallen trunk and felled trees. From the same seed.
|
||||
1. Add flowers, fruits and mushrooms/fungus on the trunk/branches.
|
||||
1. Generate one texture atlas per bark+foliage to reduce 1 draw call.
|
||||
1. Make it compatible with older Godot versions.
|
||||
1. Preset gallery with preview.
|
||||
1. Branchlet texture generator.
|
||||
1. Graph editor.
|
||||
|
||||
## Credits
|
||||
<details>
|
||||
<summary>Code, assets and references</summary>
|
||||
|
||||
**Code**
|
||||
- Octahedral impostor shader: [godot-imposter](https://github.com/zhangjt93/godot-imposter) by Zhang Juntao,
|
||||
a Godot 4 port of [Godot-Octahedral-Impostors](https://github.com/wojtekpil/Godot-Octahedral-Impostors) by wojtekpil and iFire (MIT).
|
||||
Modified to add backlight and mipmaps. License in `addons/cosmo_tree_gen/shaders/impostor_octahedral.gdshader`.
|
||||
|
||||
**Assets**
|
||||
- Leaves: [60 CC0 vegetation textures](https://opengameart.org/content/60-cc0-vegetation-textures)
|
||||
- Bark: [ambientCG Bark014](https://ambientcg.com/view?id=Bark014)
|
||||
- Icosphere foliage: Made manually with GIMP.
|
||||
- Logo: Procreate + Inkscape, background rendered in Blender, font [Neuropol](https://www.dafont.com/es/neuropol.font).
|
||||
|
||||
**References**
|
||||
- Icosphere: [lslabs](https://blog.lslabs.dev/posts/generating_icosphere_with_code), [schneide.blog](https://schneide.blog/2016/07/15/generating-an-icosphere-in-c/)
|
||||
- Trees/branching: [EZ-Tree](https://tympanus.net/codrops/2025/01/27/fractals-to-forests-creating-realistic-3d-trees-with-three-js/), [Coding Train](https://www.youtube.com/watch?v=MwLyeEWnMCY), [Algorithmic Botany](https://algorithmicbotany.org/)
|
||||
- Impostors: [ShaderBits: Octahedral Impostors](https://www.shaderbits.com/blog/octahedral-impostors), [IMP](https://github.com/MaxRoetzler/IMP)
|
||||
|
||||
</details>
|
||||
|
||||
## LICENSE
|
||||
Released under the [MIT License](LICENSE.md).
|
||||
21
third_party/cosmo_tree_gen/addons/cosmo_tree_gen/LICENSE.md
vendored
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2026 CosmonautFrog
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
72
third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/branch.gd
vendored
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
# Copyright © 2026 CosmonautFrog - MIT License
|
||||
|
||||
extends RefCounted
|
||||
## A polyline definition, a radius per point.
|
||||
|
||||
const Branch := preload("./branch.gd")
|
||||
|
||||
var branch_seed: int = 0
|
||||
var points := PackedVector3Array()
|
||||
var radii := PackedFloat32Array()
|
||||
var level: int = 0
|
||||
|
||||
## Branch grown from this terminal branch's tip
|
||||
var terminal: Branch = null
|
||||
var is_terminal: bool = false
|
||||
var is_broken: bool = false
|
||||
|
||||
var base_rings: int = 0
|
||||
var sink_depth: float = 0.0
|
||||
|
||||
|
||||
func _segment_at(t: float) -> int:
|
||||
return mini(int(_index_at(t)), points.size() - 2)
|
||||
|
||||
|
||||
func _index_at(t: float) -> float:
|
||||
return clampf(t, 0.0, 1.0) * (points.size() - 1)
|
||||
|
||||
|
||||
func add_point(point: Vector3, radius: float) -> void:
|
||||
points.push_back(point)
|
||||
radii.push_back(radius)
|
||||
|
||||
|
||||
func sample(t: float) -> Vector3:
|
||||
var i := _segment_at(t)
|
||||
return points[i].lerp(points[i + 1], _index_at(t) - i)
|
||||
|
||||
|
||||
func radius_at(t: float) -> float:
|
||||
var i := _segment_at(t)
|
||||
return lerpf(radii[i], radii[i + 1], _index_at(t) - i)
|
||||
|
||||
|
||||
func tangent_at(t: float) -> Vector3:
|
||||
var i := _segment_at(t)
|
||||
return (points[i + 1] - points[i]).normalized()
|
||||
|
||||
|
||||
func get_length() -> float:
|
||||
var total: float = 0.0
|
||||
for i in points.size() - 1:
|
||||
total += points[i].distance_to(points[i + 1])
|
||||
return total
|
||||
|
||||
|
||||
func tip() -> Vector3:
|
||||
return points[points.size() - 1]
|
||||
|
||||
|
||||
func with_base_rings() -> Branch:
|
||||
var out := Branch.new()
|
||||
out.points = points.duplicate()
|
||||
out.radii = radii.duplicate()
|
||||
|
||||
# bunched towards the ground, where the flare changes the most
|
||||
for k in base_rings:
|
||||
var s := pow(float(k + 1) / (base_rings + 1), 2.0)
|
||||
out.points.insert(k + 1, points[0].lerp(points[1], s))
|
||||
out.radii.insert(k + 1, lerpf(radii[0], radii[1], s))
|
||||
|
||||
return out
|
||||
101
third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/branch_gen.gd
vendored
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
# Copyright © 2026 CosmonautFrog - MIT License
|
||||
|
||||
extends RefCounted
|
||||
## Grows child branches out of a parent Branch.
|
||||
|
||||
const Branch := preload("./branch.gd")
|
||||
|
||||
## PI * (3 - sqrt(5)), ~137.5° - https://en.wikipedia.org/wiki/Golden_angle
|
||||
const GOLDEN_ANGLE: float = 2.399963229728653
|
||||
|
||||
|
||||
static func _grow_branch(
|
||||
level: CosmoBranchLevel,
|
||||
rng: RandomNumberGenerator,
|
||||
origin: Vector3,
|
||||
dir: Vector3,
|
||||
r0: float,
|
||||
step: float
|
||||
) -> Branch:
|
||||
var branch := Branch.new()
|
||||
|
||||
var is_broken: bool = rng.randf() < level.broken_chance
|
||||
branch.is_broken = is_broken
|
||||
|
||||
var pos := origin
|
||||
var segment_count := maxi(level.segments, 1)
|
||||
var extent := rng.randf_range(0.33, 0.66) if is_broken else 1.0
|
||||
var length: float = maxf(step, 0.01) * extent
|
||||
var up_force: float = -absf(level.up_force) if is_broken else level.up_force
|
||||
|
||||
for i in segment_count + 1:
|
||||
var progress := float(i) / segment_count * extent
|
||||
var radius := lerpf(r0, r0 * 0.2, progress)
|
||||
branch.add_point(pos, radius)
|
||||
var random := Vector3(rng.randf_range(-1.0, 1.0), rng.randf_range(-1.0, 1.0), rng.randf_range(-1.0, 1.0))
|
||||
dir = (dir + (Vector3.UP * up_force + random * level.gnarl) / segment_count).normalized()
|
||||
pos += dir * length
|
||||
|
||||
return branch
|
||||
|
||||
|
||||
static func grow_branches(parent: Branch, level: CosmoBranchLevel) -> Array[Branch]:
|
||||
var branches: Array[Branch] = []
|
||||
if parent.is_broken:
|
||||
return branches
|
||||
|
||||
var step := parent.get_length() * level.length / level.segments
|
||||
|
||||
for k in level.count:
|
||||
var branch_seed := hash([parent.branch_seed, k])
|
||||
var rng := RandomNumberGenerator.new()
|
||||
rng.seed = branch_seed
|
||||
|
||||
var t := lerpf(level.start, level.end, (k + rng.randf()) / level.count)
|
||||
var origin := parent.sample(t)
|
||||
var tangent := parent.tangent_at(t)
|
||||
var parent_radius := parent.radius_at(t)
|
||||
|
||||
var helper := Vector3.RIGHT if absf(tangent.y) > 0.9 else Vector3.UP
|
||||
var azimuth := k * GOLDEN_ANGLE + rng.randf_range(-0.3, 0.3)
|
||||
var side := tangent.cross(helper).normalized().rotated(tangent, azimuth)
|
||||
var tilt := deg_to_rad(level.angle)
|
||||
var dir := tangent * cos(tilt) + side * sin(tilt)
|
||||
var r0 := parent_radius * minf(level.radius, 0.8)
|
||||
|
||||
var branch_step := step
|
||||
if level.length_curve != null and level.length_curve.point_count > 0:
|
||||
branch_step *= level.length_curve.sample(t)
|
||||
if branch_step <= 0.0:
|
||||
continue
|
||||
|
||||
var branch := _grow_branch(level, rng, origin, dir, r0, branch_step)
|
||||
branch.branch_seed = branch_seed
|
||||
branch.level = parent.level + 1
|
||||
branches.append(branch)
|
||||
|
||||
# terminal branch, continues the parent from the tip, same direction and radius
|
||||
if level.terminal:
|
||||
var branch_seed := hash([parent.branch_seed, "terminal"])
|
||||
var rng := RandomNumberGenerator.new()
|
||||
rng.seed = branch_seed
|
||||
|
||||
var terminal_step := step
|
||||
if level.length_curve != null and level.length_curve.point_count > 0:
|
||||
terminal_step *= level.length_curve.sample(1.0)
|
||||
|
||||
var terminal := _grow_branch(
|
||||
level,
|
||||
rng,
|
||||
parent.tip(),
|
||||
parent.tangent_at(1.0),
|
||||
parent.radius_at(1.0),
|
||||
terminal_step
|
||||
)
|
||||
terminal.branch_seed = branch_seed
|
||||
terminal.level = parent.level + 1
|
||||
terminal.is_terminal = true
|
||||
parent.terminal = terminal
|
||||
branches.append(terminal)
|
||||
|
||||
return branches
|
||||
121
third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/collision_gen.gd
vendored
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
# Copyright © 2026 CosmonautFrog - MIT License
|
||||
|
||||
extends RefCounted
|
||||
## Builds collision shapes from the tree skeleton.
|
||||
|
||||
const Branch := preload("./branch.gd")
|
||||
const MeshUtils := preload("./mesh_utils.gd")
|
||||
const TrunkGen := preload("./trunk_gen.gd")
|
||||
|
||||
|
||||
static func _convex(points: PackedVector3Array) -> ConvexPolygonShape3D:
|
||||
var shape := ConvexPolygonShape3D.new()
|
||||
shape.points = points
|
||||
return shape
|
||||
|
||||
|
||||
## Cuts `branch` in place where it first rises above `max_y`. Returns true if it was cut.
|
||||
static func _clip_height(branch: Branch, max_y: float) -> bool:
|
||||
for i in range(1, branch.points.size()):
|
||||
var a := branch.points[i - 1]
|
||||
var b := branch.points[i]
|
||||
if b.y <= max_y:
|
||||
continue
|
||||
|
||||
var t := (max_y - a.y) / (b.y - a.y)
|
||||
var radius := lerpf(branch.radii[i - 1], branch.radii[i], t)
|
||||
branch.points.resize(i)
|
||||
branch.radii.resize(i)
|
||||
# a point right at the limit would make a zero length segment
|
||||
if a.y < max_y:
|
||||
branch.add_point(a.lerp(b, t), radius)
|
||||
return true
|
||||
|
||||
return false
|
||||
|
||||
|
||||
## `sphere_radii` is one radius per foliage cluster, only used by SPHERES.
|
||||
static func create_foliage_shapes(
|
||||
type: CosmoTreeGen.FoliageCollisionType,
|
||||
foliage_mesh: ArrayMesh,
|
||||
sphere_radii: PackedFloat32Array,
|
||||
) -> Array[Shape3D]:
|
||||
var shapes: Array[Shape3D] = []
|
||||
|
||||
match type:
|
||||
CosmoTreeGen.FoliageCollisionType.HULL:
|
||||
shapes.append(foliage_mesh.create_convex_shape(true, true))
|
||||
CosmoTreeGen.FoliageCollisionType.SPHERES:
|
||||
for radius in sphere_radii:
|
||||
var sphere := SphereShape3D.new()
|
||||
sphere.radius = radius
|
||||
shapes.append(sphere)
|
||||
|
||||
return shapes
|
||||
|
||||
|
||||
static func create_branch_shapes(
|
||||
type: CosmoTreeGen.CollisionType,
|
||||
branches: Array[Branch],
|
||||
max_level: int,
|
||||
max_height: float,
|
||||
radial: int,
|
||||
trunk_params: CosmoTrunkParams,
|
||||
) -> Array[Shape3D]:
|
||||
var shapes: Array[Shape3D] = []
|
||||
var faces := PackedVector3Array()
|
||||
|
||||
for branch in branches:
|
||||
if branch.level > max_level:
|
||||
continue
|
||||
|
||||
var part := branch
|
||||
while part != null:
|
||||
if part.points[0].y >= max_height:
|
||||
break
|
||||
|
||||
var ringed: Branch = part.with_base_rings()
|
||||
var cut := _clip_height(ringed, max_height)
|
||||
var vertices := PackedVector3Array()
|
||||
var indices := PackedInt32Array()
|
||||
# a cut end gets a flat cap below instead of the cone poking above the limit
|
||||
MeshUtils.append_tube(
|
||||
vertices, indices, ringed.points, ringed.radii, radial,
|
||||
not cut and part.terminal == null,
|
||||
)
|
||||
|
||||
if part.base_rings > 0 and type != CosmoTreeGen.CollisionType.SIMPLE_CONVEX:
|
||||
TrunkGen.flare_base(vertices, 0, part, trunk_params)
|
||||
|
||||
if cut:
|
||||
# leaning rings tilt above the limit, flatten them onto it
|
||||
for i in vertices.size():
|
||||
vertices[i].y = minf(vertices[i].y, max_height)
|
||||
|
||||
if type == CosmoTreeGen.CollisionType.TRIMESH:
|
||||
var last := (ringed.points.size() - 1) * (radial + 1)
|
||||
for j in radial:
|
||||
faces.append_array(PackedVector3Array([
|
||||
ringed.tip(), vertices[last + j], vertices[last + j + 1],
|
||||
]))
|
||||
|
||||
match type:
|
||||
CosmoTreeGen.CollisionType.SIMPLE_CONVEX:
|
||||
shapes.append(_convex(vertices))
|
||||
CosmoTreeGen.CollisionType.MULTIPLE_CONVEX:
|
||||
# two consecutive rings make a frustum, which is already convex
|
||||
var ring := radial + 1
|
||||
for i in ringed.points.size() - 1:
|
||||
shapes.append(_convex(vertices.slice(i * ring, (i + 2) * ring)))
|
||||
CosmoTreeGen.CollisionType.TRIMESH:
|
||||
for i in indices:
|
||||
faces.push_back(vertices[i])
|
||||
|
||||
part = null if cut else part.terminal
|
||||
|
||||
if not faces.is_empty():
|
||||
var trimesh := ConcavePolygonShape3D.new()
|
||||
trimesh.set_faces(faces)
|
||||
shapes.append(trimesh)
|
||||
|
||||
return shapes
|
||||
495
third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/cosmo_tree_gen.gd
vendored
Normal file
|
|
@ -0,0 +1,495 @@
|
|||
# Copyright © 2026 CosmonautFrog - MIT License
|
||||
|
||||
@tool
|
||||
@icon("../tree.svg")
|
||||
class_name CosmoTreeGen
|
||||
extends Node3D
|
||||
|
||||
## Emitted after [method generate] builds the tree.
|
||||
signal generated
|
||||
|
||||
enum CollisionType {
|
||||
## Do not generate collision shapes.
|
||||
NONE,
|
||||
## Generate one convex collision shape per branch, up to [member collision_level].
|
||||
## Curved branches get a looser fit.
|
||||
SIMPLE_CONVEX,
|
||||
## Generate one convex collision shape per branch segment, up to [member collision_level].
|
||||
## More precise than Simple Convex, it's solid so pushes out bodies. Uses more memory than Trimesh.
|
||||
MULTIPLE_CONVEX,
|
||||
## Generate a single trimesh collision shape, using branch levels up to [member collision_level].
|
||||
## The cheapest and closest fit, but hollow and one-sided. Fast or overlapping bodies can pass through it.
|
||||
## Doesn't work on a [RigidBody3D]. Avoid this if you want falling trees.
|
||||
TRIMESH,
|
||||
}
|
||||
|
||||
enum FoliageCollisionType {
|
||||
## Do not generate collision shapes for foliage.
|
||||
NONE,
|
||||
## Generate one convex collision shape around the whole canopy.
|
||||
HULL,
|
||||
## Generate one SphereShape3D per branch tip.
|
||||
SPHERES,
|
||||
}
|
||||
|
||||
const TreeBuilder := preload("./tree_builder.gd")
|
||||
const MeshUtils := preload("./mesh_utils.gd")
|
||||
const Settings := preload("./settings.gd")
|
||||
|
||||
const COMBINED_NODE_NAME: String = "CosmoTree"
|
||||
const TRUNK_NODE_NAME: String = "Trunk"
|
||||
const FOLIAGE_NODE_NAME: String = "Foliage"
|
||||
const PART_NODE_NAMES: Dictionary[TreeBuilder.Part, String] = {
|
||||
TreeBuilder.Part.COMBINED: COMBINED_NODE_NAME,
|
||||
TreeBuilder.Part.TRUNK: TRUNK_NODE_NAME,
|
||||
TreeBuilder.Part.FOLIAGE: FOLIAGE_NODE_NAME,
|
||||
}
|
||||
const COLLISION_NODE_NAME: String = "Collision"
|
||||
const FOLIAGE_COLLISION_NODE_NAME: String = "FoliageCollision"
|
||||
const COLLISION_PREVIEW_NODE_NAME: String = "CollisionPreview"
|
||||
const LOD_SUFFIXES: Array[String] = ["_LOD0", "_LOD1", "_LOD2"]
|
||||
const LOD_HYSTERESIS: float = 1.0
|
||||
const FALLBACK_TEXTURE_WIDTH: int = 128
|
||||
|
||||
@export_tool_button("Generate tree", "Reload")
|
||||
var generate_button: Callable = generate
|
||||
## Rebuilds the tree every time a parameter changes. Turn it off for heavy trees and use Generate tree.
|
||||
@export var auto_generate: bool = true:
|
||||
set(value):
|
||||
auto_generate = value
|
||||
if auto_generate:
|
||||
_regenerate()
|
||||
|
||||
## Seed of all the random values. The same seed and parameters always make the same tree.
|
||||
@export var noise_seed: int = 42:
|
||||
set(value):
|
||||
noise_seed = value
|
||||
_regenerate()
|
||||
|
||||
@export_category("Tree Parameters")
|
||||
## Shape of the trunks and their roots.
|
||||
@export var trunk_params: CosmoTrunkParams = CosmoTrunkParams.new():
|
||||
set(value):
|
||||
_swap_watch(trunk_params, value)
|
||||
trunk_params = value
|
||||
_regenerate()
|
||||
|
||||
## Branch levels, from the trunk out. [br][br]
|
||||
## The first level grows from the trunks, the second from the first level branches, and so on.
|
||||
@export var branch_levels: Array[CosmoBranchLevel] = []:
|
||||
set(value):
|
||||
for level in branch_levels:
|
||||
_swap_watch(level, null)
|
||||
branch_levels = value
|
||||
for level in branch_levels:
|
||||
_swap_watch(null, level)
|
||||
_regenerate()
|
||||
|
||||
## Foliage type and shape. It grows on the branches of the last level, or on the trunks if there are none.
|
||||
@export var foliage_params: CosmoFoliageParams = CosmoFoliageParams.new():
|
||||
set(value):
|
||||
_swap_watch(foliage_params, value)
|
||||
foliage_params = value
|
||||
_regenerate()
|
||||
|
||||
@export_group("Meshes")
|
||||
## Generates 3 LODs (_LOD0, _LOD1 and _LOD2) that swap with the distance. [br][br]
|
||||
## Their triangle ratios and distances are in Project Settings > Cosmo Tree Gen > Generator.
|
||||
@export var generate_lod: bool = false:
|
||||
set(value):
|
||||
generate_lod = value
|
||||
_regenerate()
|
||||
## Share of each LOD triangle budget kept for the trunk, the foliage gets the rest. [br][br]
|
||||
## Raise it to keep more trunk detail, lower it to keep more leaves. Only used with [member generate_lod].
|
||||
@export_range(0.0, 1.0, 0.01) var lod_trunk_share: float = 0.33:
|
||||
set(value):
|
||||
lod_trunk_share = value
|
||||
_regenerate()
|
||||
## Puts the trunk and the foliage in a single mesh, one surface each. [br][br]
|
||||
## Turn it off to get separate Trunk and Foliage nodes, e.g. to change the shadows of the foliage only.
|
||||
## Both ways it's 2 draw calls (2 materials).
|
||||
@export var combine_trunk_and_foliage: bool = true:
|
||||
set(value):
|
||||
combine_trunk_and_foliage = value
|
||||
_regenerate()
|
||||
## One normal per face for a low-poly/PSX look, on the trunk, branches, roots and icospheres.
|
||||
## Leaf cards aren't affected.
|
||||
@export var flat_shading: bool = false:
|
||||
set(value):
|
||||
flat_shading = value
|
||||
_regenerate()
|
||||
## Builds the trunk, branches and roots mesh. [br][br]
|
||||
## When off, the branches are still generated, so the foliage and the collisions don't change.
|
||||
@export var create_trunk: bool = true:
|
||||
set(value):
|
||||
create_trunk = value
|
||||
_regenerate()
|
||||
## Builds the foliage mesh. When off, there's no foliage collision either.
|
||||
@export var create_foliage: bool = true:
|
||||
set(value):
|
||||
create_foliage = value
|
||||
_regenerate()
|
||||
|
||||
@export_group("Collision")
|
||||
## Type of collision to generate for the trunk, roots and branches.
|
||||
@export var collision_type: CollisionType = CollisionType.NONE:
|
||||
set(value):
|
||||
collision_type = value
|
||||
_regenerate()
|
||||
## Maximum level of branches to create collisions for. [br][br]
|
||||
## Level 0 generates collisions just for the trunk/s and
|
||||
## level 1 for trunks, roots and first level of branches.
|
||||
@export_range(0, 6, 1, "or_greater") var collision_level: int = 0:
|
||||
set(value):
|
||||
collision_level = value
|
||||
_regenerate()
|
||||
## Cuts the trunk, root and branch collisions at this height, in local space. [br][br]
|
||||
## Branches starting above it get no collision. 0 means no limit.
|
||||
@export_range(0.0, 25.0, 0.1, "or_greater", "suffix:m") var collision_max_height: float = 0.0:
|
||||
set(value):
|
||||
collision_max_height = value
|
||||
_regenerate()
|
||||
## Type of collision to generate for the foliage.
|
||||
@export var foliage_collision_type: FoliageCollisionType = FoliageCollisionType.NONE:
|
||||
set(value):
|
||||
foliage_collision_type = value
|
||||
_regenerate()
|
||||
## Draws the collision shapes on top of the tree. Editor only, never exported.
|
||||
@export var preview_collision: bool = false:
|
||||
set(value):
|
||||
preview_collision = value
|
||||
if is_node_ready():
|
||||
_update_collision_preview()
|
||||
## Physics layers of the generated StaticBody3Ds, trunk and foliage.
|
||||
@export_flags_3d_physics var collision_layer: int = 1:
|
||||
set(value):
|
||||
collision_layer = value
|
||||
for body in get_collisions():
|
||||
body.collision_layer = collision_layer
|
||||
## Physics layers scanned by the generated StaticBody3Ds, trunk and foliage.
|
||||
@export_flags_3d_physics var collision_mask: int = 1:
|
||||
set(value):
|
||||
collision_mask = value
|
||||
for body in get_collisions():
|
||||
body.collision_mask = collision_mask
|
||||
|
||||
@export_group("Materials")
|
||||
## Material of the trunk, branches and roots. [br][br]
|
||||
## The width of its albedo texture (the [code]albedo_texture[/code] uniform on a ShaderMaterial)
|
||||
## and [member texel_density] set the bark UV scale.
|
||||
@export_custom(PROPERTY_HINT_RESOURCE_TYPE, "BaseMaterial3D,ShaderMaterial")
|
||||
var trunk_material: Material: set = _set_trunk_material
|
||||
## Material of the leaf cards or the icospheres. [br][br]
|
||||
## Leaf cards take the shape of its albedo texture (the [code]albedo_texture[/code] uniform on a
|
||||
## ShaderMaterial), see [member CosmoFoliageParams.leaf_aspect]. Icospheres have no UVs, they need
|
||||
## a material with UV1 Triplanar. The included leaves shader adds wind sway and uses
|
||||
## [member CosmoFoliageParams.leaf_inner_ao].
|
||||
@export_custom(PROPERTY_HINT_RESOURCE_TYPE, "BaseMaterial3D,ShaderMaterial")
|
||||
var foliage_material: Material: set = _set_foliage_material
|
||||
## Bark texture pixels per meter, the same on trunks, branches and roots. [br][br]
|
||||
## More info about texel density:
|
||||
## https://www.artstation.com/blogs/bendvfx/G1nB/texel-density-importance-in-3d-game-asset-creation
|
||||
@export_range(32.0, 2048.0, 32.0, "or_greater", "suffix:px/m") var texel_density: float = 64.0:
|
||||
set(value):
|
||||
texel_density = value
|
||||
_regenerate()
|
||||
|
||||
var _applying_preset: bool = false
|
||||
|
||||
|
||||
func _init() -> void:
|
||||
name = "CosmoTreeGen"
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
_swap_watch(null, trunk_params)
|
||||
_swap_watch(null, foliage_params)
|
||||
generate()
|
||||
|
||||
|
||||
func _set_trunk_material(value: Material) -> void:
|
||||
var old_density := get_uv_density()
|
||||
trunk_material = value
|
||||
# the bark UVs scale with the albedo texture width, only regenerate when it changes
|
||||
# so generate() -> _apply_materials() doesn't loop
|
||||
if get_uv_density() != old_density:
|
||||
_regenerate()
|
||||
|
||||
_set_surface_material(TreeBuilder.TRUNK_SURFACE_NAME, trunk_material)
|
||||
|
||||
|
||||
func _set_foliage_material(value: Material) -> void:
|
||||
var old_aspect := _get_leaf_aspect()
|
||||
foliage_material = value
|
||||
# the leaf cards take the albedo texture shape, only regenerate when it changes
|
||||
# so generate() -> _apply_materials() doesn't loop
|
||||
if _get_leaf_aspect() != old_aspect:
|
||||
_regenerate()
|
||||
|
||||
if not _set_surface_material(TreeBuilder.FOLIAGE_SURFACE_NAME, foliage_material):
|
||||
return
|
||||
|
||||
if foliage_params.type == CosmoFoliageParams.Type.ICOSPHERES and foliage_material is StandardMaterial3D:
|
||||
if not (foliage_material as StandardMaterial3D).uv1_triplanar:
|
||||
push_warning("CosmoTreeGen: foliage_material should use UV1 triplanar!")
|
||||
|
||||
|
||||
func _get_leaf_aspect() -> float:
|
||||
if foliage_params == null or foliage_params.type != CosmoFoliageParams.Type.LEAVES:
|
||||
return 1.0
|
||||
return foliage_params.get_leaf_aspect(foliage_material)
|
||||
|
||||
|
||||
func _set_surface_material(surface_name: String, material: Material) -> bool:
|
||||
var found: bool = false
|
||||
for node_name: String in _get_generated_node_names():
|
||||
var mi := get_node_or_null(node_name) as MeshInstance3D
|
||||
if mi == null:
|
||||
continue
|
||||
var mesh := mi.mesh as ArrayMesh
|
||||
if mesh == null:
|
||||
continue
|
||||
var idx := mesh.surface_find_by_name(surface_name)
|
||||
if idx != -1:
|
||||
mesh.surface_set_material(idx, material)
|
||||
found = true
|
||||
|
||||
return found
|
||||
|
||||
|
||||
func _apply_materials() -> void:
|
||||
_set_trunk_material(trunk_material)
|
||||
_set_foliage_material(foliage_material)
|
||||
|
||||
|
||||
func _swap_watch(old: Resource, new: Resource) -> void:
|
||||
if old and old.changed.is_connected(_regenerate):
|
||||
old.changed.disconnect(_regenerate)
|
||||
if new and not new.changed.is_connected(_regenerate):
|
||||
new.changed.connect(_regenerate)
|
||||
|
||||
|
||||
func _regenerate() -> void:
|
||||
if is_node_ready() and auto_generate and not _applying_preset:
|
||||
generate()
|
||||
|
||||
|
||||
func _get_generated_node_names() -> Array[String]:
|
||||
var out: Array[String] = [COLLISION_NODE_NAME, FOLIAGE_COLLISION_NODE_NAME, COLLISION_PREVIEW_NODE_NAME]
|
||||
|
||||
for node_name: String in [COMBINED_NODE_NAME, TRUNK_NODE_NAME, FOLIAGE_NODE_NAME]:
|
||||
out.append(node_name)
|
||||
for suffix in LOD_SUFFIXES:
|
||||
out.append(node_name + suffix)
|
||||
|
||||
return out
|
||||
|
||||
|
||||
func _clear_generated() -> void:
|
||||
for node_name: String in _get_generated_node_names():
|
||||
var node := get_node_or_null(node_name)
|
||||
if node:
|
||||
remove_child(node)
|
||||
node.free()
|
||||
|
||||
|
||||
func _add_collision(node_name: String, collision: TreeBuilder.Collision) -> void:
|
||||
if collision.shapes.is_empty():
|
||||
return
|
||||
|
||||
var static_body := StaticBody3D.new()
|
||||
static_body.name = node_name
|
||||
static_body.collision_layer = collision_layer
|
||||
static_body.collision_mask = collision_mask
|
||||
|
||||
for i in collision.shapes.size():
|
||||
var col_shape := CollisionShape3D.new()
|
||||
col_shape.name = "CollisionShape%d" % i
|
||||
col_shape.shape = collision.shapes[i]
|
||||
col_shape.transform = collision.transforms[i]
|
||||
static_body.add_child(col_shape)
|
||||
|
||||
add_child(static_body)
|
||||
|
||||
|
||||
func _update_collision_preview() -> void:
|
||||
var old := get_node_or_null(COLLISION_PREVIEW_NODE_NAME)
|
||||
if old:
|
||||
remove_child(old)
|
||||
old.free()
|
||||
|
||||
var cols := get_collisions()
|
||||
if not Engine.is_editor_hint() or not preview_collision or cols.is_empty():
|
||||
return
|
||||
|
||||
var st := SurfaceTool.new()
|
||||
st.begin(Mesh.PRIMITIVE_LINES)
|
||||
for col in cols:
|
||||
for col_shape: CollisionShape3D in col.get_children():
|
||||
# surface 0 is the wireframe, 1 the fill, so draw only surface 0
|
||||
st.append_from(col_shape.shape.get_debug_mesh(), 0, col_shape.transform)
|
||||
|
||||
var material := StandardMaterial3D.new()
|
||||
material.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
|
||||
material.no_depth_test = true
|
||||
material.albedo_color = ProjectSettings.get_setting("debug/shapes/collision/shape_color")
|
||||
|
||||
var mi := MeshInstance3D.new()
|
||||
mi.name = COLLISION_PREVIEW_NODE_NAME
|
||||
mi.mesh = st.commit()
|
||||
mi.material_override = material
|
||||
mi.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
|
||||
add_child(mi)
|
||||
|
||||
|
||||
func _add_mesh_instance(node_name: String, mesh: ArrayMesh) -> void:
|
||||
var mi := MeshInstance3D.new()
|
||||
mi.name = node_name
|
||||
mi.mesh = mesh
|
||||
add_child(mi)
|
||||
|
||||
|
||||
## Godot measures the ranges from the center of the AABB. Sharing `bounds` makes all
|
||||
## the meshes of a tree swap LOD at once, with no gaps between them.
|
||||
func _setup_lod_ranges(bounds: AABB) -> void:
|
||||
var lod1: float = Settings.get_setting(Settings.LOD1_DISTANCE, 50.0)
|
||||
var lod2: float = Settings.get_setting(Settings.LOD2_DISTANCE, 100.0)
|
||||
var end: float = Settings.get_setting(Settings.LOD_END_DISTANCE, 0.0)
|
||||
var distances: Array[float] = [0.0, lod1, lod2, end]
|
||||
|
||||
for lod in LOD_SUFFIXES.size():
|
||||
for mi in get_meshes(lod):
|
||||
mi.visibility_range_begin = distances[lod]
|
||||
mi.visibility_range_begin_margin = LOD_HYSTERESIS
|
||||
mi.visibility_range_end = distances[lod + 1]
|
||||
mi.visibility_range_end_margin = LOD_HYSTERESIS
|
||||
mi.custom_aabb = bounds
|
||||
|
||||
|
||||
func _load_core_script(file_name: String) -> Script:
|
||||
var settings_script: Script = Settings
|
||||
return load(
|
||||
settings_script.resource_path.get_base_dir().path_join(file_name)
|
||||
)
|
||||
|
||||
|
||||
## Copies the parameters and materials of [param preset] to this tree, and rebuilds it if
|
||||
## [member auto_generate] is on. The preset is duplicated, editing the tree doesn't change it.
|
||||
func apply_preset(preset: CosmoTreePreset) -> void:
|
||||
# deep copy, so editing the tree doesn't edit the preset file
|
||||
var p := preset.duplicate(true) as CosmoTreePreset
|
||||
|
||||
_applying_preset = true
|
||||
trunk_params = p.trunk_params
|
||||
branch_levels = p.branch_levels
|
||||
foliage_params = p.foliage_params
|
||||
combine_trunk_and_foliage = p.combine_trunk_and_foliage
|
||||
flat_shading = p.flat_shading
|
||||
create_trunk = p.create_trunk
|
||||
create_foliage = p.create_foliage
|
||||
lod_trunk_share = p.lod_trunk_share
|
||||
trunk_material = p.trunk_material
|
||||
foliage_material = p.foliage_material
|
||||
texel_density = p.texel_density
|
||||
_applying_preset = false
|
||||
_regenerate()
|
||||
|
||||
|
||||
## Returns a new preset with the current parameters and materials. They're shared with this tree, not copied.
|
||||
func to_preset() -> CosmoTreePreset:
|
||||
var preset := CosmoTreePreset.new()
|
||||
preset.trunk_params = trunk_params
|
||||
preset.branch_levels = branch_levels
|
||||
preset.foliage_params = foliage_params
|
||||
preset.combine_trunk_and_foliage = combine_trunk_and_foliage
|
||||
preset.flat_shading = flat_shading
|
||||
preset.create_trunk = create_trunk
|
||||
preset.create_foliage = create_foliage
|
||||
preset.lod_trunk_share = lod_trunk_share
|
||||
preset.trunk_material = trunk_material
|
||||
preset.foliage_material = foliage_material
|
||||
preset.texel_density = texel_density
|
||||
return preset
|
||||
|
||||
|
||||
## Returns the meshes of a LOD, or of all the LODs if [param lod] is negative.
|
||||
## Without [member generate_lod], all the meshes are LOD 0.
|
||||
func get_meshes(lod: int = -1) -> Array[MeshInstance3D]:
|
||||
var suffixes: Array[String] = []
|
||||
if lod <= 0:
|
||||
suffixes.append("")
|
||||
for i in LOD_SUFFIXES.size():
|
||||
if lod < 0 or lod == i:
|
||||
suffixes.append(LOD_SUFFIXES[i])
|
||||
|
||||
var meshes: Array[MeshInstance3D]
|
||||
for suffix in suffixes:
|
||||
for node_name: String in [COMBINED_NODE_NAME, TRUNK_NODE_NAME, FOLIAGE_NODE_NAME]:
|
||||
var node := get_node_or_null(node_name + suffix) as MeshInstance3D
|
||||
if node != null:
|
||||
meshes.append(node)
|
||||
|
||||
return meshes
|
||||
|
||||
|
||||
## Returns the generated StaticBody3Ds: the trunk collision and the foliage collision, if they exist.
|
||||
func get_collisions() -> Array[StaticBody3D]:
|
||||
var out: Array[StaticBody3D]
|
||||
|
||||
var col_node := get_node_or_null(COLLISION_NODE_NAME)
|
||||
if col_node != null:
|
||||
out.append(col_node)
|
||||
|
||||
var foliage_col_node := get_node_or_null(FOLIAGE_COLLISION_NODE_NAME)
|
||||
if foliage_col_node != null:
|
||||
out.append(foliage_col_node)
|
||||
|
||||
return out
|
||||
|
||||
|
||||
## Bark texture repeats per meter, from the width of the trunk material albedo texture.
|
||||
func get_uv_density() -> float:
|
||||
var texture := MeshUtils.get_albedo_texture(trunk_material)
|
||||
var width: int = texture.get_width() if texture != null and texture.get_width() > 0 else FALLBACK_TEXTURE_WIDTH
|
||||
return texel_density / width
|
||||
|
||||
|
||||
## Sets a random [member noise_seed]. Rebuilds the tree if [member auto_generate] is on.
|
||||
func set_random_seed() -> void:
|
||||
noise_seed = randi_range(-2147483648, 2147483647)
|
||||
|
||||
|
||||
## Rebuilds the meshes, collisions and LODs from the current parameters, replacing the old child nodes.
|
||||
func generate() -> void:
|
||||
_clear_generated()
|
||||
var result := TreeBuilder.build(self)
|
||||
|
||||
var has_lods := result.lods.size() > 1
|
||||
for lod in result.lods.size():
|
||||
var suffix: String = LOD_SUFFIXES[lod] if has_lods else ""
|
||||
var meshes := result.lods[lod].meshes
|
||||
for part: TreeBuilder.Part in meshes:
|
||||
_add_mesh_instance(PART_NODE_NAMES[part] + suffix, meshes[part])
|
||||
|
||||
if has_lods:
|
||||
_setup_lod_ranges(result.bounds)
|
||||
|
||||
_add_collision(COLLISION_NODE_NAME, result.collision)
|
||||
_add_collision(FOLIAGE_COLLISION_NODE_NAME, result.foliage_collision)
|
||||
|
||||
_apply_materials()
|
||||
_update_collision_preview()
|
||||
|
||||
generated.emit()
|
||||
|
||||
|
||||
## Exports the tree to a .glb or .gltf file at [param path]. Editor only, it must be awaited. [br][br]
|
||||
## [param options] uses the option names of the export dialog, the missing ones are off.
|
||||
func export_gltf(path: String = "res://tree.glb", options: Dictionary = {}) -> Error:
|
||||
if not Engine.is_editor_hint():
|
||||
return ERR_UNAVAILABLE
|
||||
|
||||
# lazy loaded to prevent errors in shipped games (cannot load EditorInterface,etc..)
|
||||
var exporter := _load_core_script("exporter.gd")
|
||||
@warning_ignore("unsafe_method_access")
|
||||
return await exporter.export_gltf(path, self, options)
|
||||
195
third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/exporter.gd
vendored
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
# Copyright © 2026 CosmonautFrog - MIT License
|
||||
|
||||
@tool
|
||||
extends RefCounted
|
||||
|
||||
const LOD_POST_IMPORT: Script = preload("./lod_post_import.gd")
|
||||
|
||||
const ImpostorGen := preload("./impostor_gen.gd")
|
||||
const Settings := preload("./settings.gd")
|
||||
|
||||
|
||||
static func _get_import_file(path: String) -> ConfigFile:
|
||||
var import := ConfigFile.new()
|
||||
var err := import.load(path + ".import")
|
||||
if err != OK:
|
||||
push_warning("CosmoTreeGen: exporter - error loading %s '%s'" % [path + ".import", error_string(err)])
|
||||
return null
|
||||
|
||||
return import
|
||||
|
||||
|
||||
static func _write_import_materials(path: String, state: GLTFState, only: Material = null) -> Error:
|
||||
var import := _get_import_file(path)
|
||||
if import == null:
|
||||
return ERR_CANT_OPEN
|
||||
|
||||
var subresources: Dictionary = import.get_value("params", "_subresources", {})
|
||||
var materials: Dictionary = subresources.get("materials", {})
|
||||
|
||||
var json_materials: Array = state.json.get("materials", [])
|
||||
var state_materials := state.get_materials()
|
||||
for i in json_materials.size():
|
||||
var material_path := state_materials[i].resource_path
|
||||
# creating a new Resource will create a resource_path like "...::xxxxx"
|
||||
# this is a bit hacky, couldn't find another way
|
||||
if material_path.is_empty() or material_path.contains("::"):
|
||||
continue
|
||||
if only != null and state_materials[i] != only:
|
||||
continue
|
||||
materials[json_materials[i]["name"]] = {
|
||||
"use_external/enabled": true,
|
||||
"use_external/path": ResourceUID.path_to_uid(material_path),
|
||||
"use_external/fallback_path": material_path,
|
||||
}
|
||||
|
||||
subresources["materials"] = materials
|
||||
import.set_value("params", "_subresources", subresources)
|
||||
return import.save(path + ".import")
|
||||
|
||||
|
||||
static func _write_import_lods(path: String, tree: CosmoTreeGen, impostor: MeshInstance3D) -> Error:
|
||||
var import := _get_import_file(path)
|
||||
if import == null:
|
||||
return ERR_CANT_OPEN
|
||||
|
||||
var subresources: Dictionary = import.get_value("params", "_subresources", {})
|
||||
var nodes: Dictionary = subresources.get("nodes", {})
|
||||
|
||||
var impostor_distance: float = Settings.get_setting(Settings.IMPOSTOR_DISTANCE, 150.0)
|
||||
var last_lod := tree.get_meshes(CosmoTreeGen.LOD_SUFFIXES.size() - 1 if tree.generate_lod else 0)
|
||||
for mesh: MeshInstance3D in tree.get_meshes():
|
||||
var end := mesh.visibility_range_end
|
||||
if impostor != null and mesh in last_lod:
|
||||
end = impostor_distance
|
||||
nodes["PATH:%s" % mesh.name] = _range(mesh.visibility_range_begin, end)
|
||||
|
||||
if impostor != null:
|
||||
if impostor_distance <= last_lod[0].visibility_range_begin:
|
||||
push_warning("CosmoTreeGen: the impostor distance must be greater than the last LOD distance")
|
||||
var lod_end: float = Settings.get_setting(Settings.LOD_END_DISTANCE, 0.0)
|
||||
var cast_shadow: bool = Settings.get_setting(Settings.IMPOSTOR_CAST_SHADOW, false)
|
||||
var node := _range(impostor_distance, lod_end)
|
||||
node["mesh_instance/cast_shadow"] = (
|
||||
GeometryInstance3D.SHADOW_CASTING_SETTING_ON if cast_shadow
|
||||
else GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
|
||||
)
|
||||
nodes["PATH:%s" % impostor.name] = node
|
||||
|
||||
subresources["nodes"] = nodes
|
||||
import.set_value("params", "_subresources", subresources)
|
||||
|
||||
# Godot automatic LODs break the leaf cards
|
||||
import.set_value("params", "meshes/generate_lods", false)
|
||||
return import.save(path + ".import")
|
||||
|
||||
|
||||
static func _range(begin: float, end: float) -> Dictionary:
|
||||
return {
|
||||
"mesh_instance/visibility_range_begin": begin,
|
||||
"mesh_instance/visibility_range_begin_margin": CosmoTreeGen.LOD_HYSTERESIS,
|
||||
"mesh_instance/visibility_range_end": end,
|
||||
"mesh_instance/visibility_range_end_margin": CosmoTreeGen.LOD_HYSTERESIS,
|
||||
}
|
||||
|
||||
|
||||
static func _write_import_root(path: String, name: String) -> Error:
|
||||
var import := _get_import_file(path)
|
||||
import.set_value("params", "nodes/root_name", name)
|
||||
import.set_value("params", "import_script/path", LOD_POST_IMPORT.resource_path)
|
||||
return import.save(path + ".import")
|
||||
|
||||
|
||||
static func _wait_for_import_file(path: String) -> Error:
|
||||
if FileAccess.file_exists(path + ".import"):
|
||||
return OK
|
||||
|
||||
var fs := EditorInterface.get_resource_filesystem()
|
||||
var tree := Engine.get_main_loop() as SceneTree
|
||||
var res_path := ProjectSettings.localize_path(path)
|
||||
|
||||
fs.scan()
|
||||
while true:
|
||||
var reimported: PackedStringArray = await fs.resources_reimported
|
||||
if reimported.has(res_path):
|
||||
break
|
||||
|
||||
await tree.process_frame
|
||||
|
||||
if not FileAccess.file_exists(path + ".import"):
|
||||
return ERR_CANT_OPEN
|
||||
|
||||
return OK
|
||||
|
||||
|
||||
static func export_gltf(path: String, tree: CosmoTreeGen, options: Dictionary = {}) -> Error:
|
||||
if tree == null:
|
||||
return ERR_UNCONFIGURED
|
||||
if (
|
||||
path.get_file().get_basename().is_empty()
|
||||
or path.get_extension() not in ["gltf", "glb"]
|
||||
):
|
||||
return ERR_FILE_BAD_PATH
|
||||
|
||||
var impostor: MeshInstance3D = null
|
||||
var impostor_type: ImpostorGen.Type = options.get("Impostor", ImpostorGen.Type.NONE)
|
||||
if impostor_type != ImpostorGen.Type.NONE:
|
||||
impostor = await ImpostorGen.bake(tree, impostor_type)
|
||||
var material := impostor.mesh.surface_get_material(0)
|
||||
var material_path := path.get_basename() + "_impostor.res"
|
||||
if ResourceSaver.save(material, material_path) != OK:
|
||||
impostor.free()
|
||||
return ERR_FILE_CANT_WRITE
|
||||
material.take_over_path(material_path)
|
||||
|
||||
var exported: Array[Node] = []
|
||||
for mesh: MeshInstance3D in tree.get_meshes():
|
||||
exported.append(mesh.duplicate())
|
||||
|
||||
if impostor != null:
|
||||
exported.append(impostor)
|
||||
|
||||
if options.get("Include Collisions", false):
|
||||
for collision: StaticBody3D in tree.get_collisions():
|
||||
exported.append(collision.duplicate())
|
||||
|
||||
var file_name := path.get_file().get_basename()
|
||||
var root := Node3D.new()
|
||||
root.name = file_name
|
||||
for node: Node in exported:
|
||||
root.add_child(node)
|
||||
node.owner = root
|
||||
for child in node.get_children():
|
||||
child.owner = root
|
||||
|
||||
var document := GLTFDocument.new()
|
||||
if not options.get("Export Images", false):
|
||||
document.set_image_format("None")
|
||||
# FIXME: texture images are not being saved properly, missing name (saved as ".png")
|
||||
|
||||
var state := GLTFState.new()
|
||||
var err := document.append_from_scene(root, state)
|
||||
if err == OK:
|
||||
err = document.write_to_filesystem(state, path)
|
||||
|
||||
if err == OK:
|
||||
err = await _wait_for_import_file(path)
|
||||
|
||||
var use_external: bool = options.get("Use External Material", false)
|
||||
if err == OK and (use_external or impostor != null):
|
||||
err = _write_import_materials(
|
||||
path, state, null if use_external else impostor.mesh.surface_get_material(0)
|
||||
)
|
||||
|
||||
if err == OK and (tree.generate_lod or impostor != null):
|
||||
err = _write_import_lods(path, tree, impostor)
|
||||
|
||||
if err == OK:
|
||||
err = _write_import_root(path, tree.name)
|
||||
|
||||
if err == OK:
|
||||
var fs := EditorInterface.get_resource_filesystem()
|
||||
fs.reimport_files(PackedStringArray([ProjectSettings.localize_path(path)]))
|
||||
|
||||
root.free()
|
||||
return err
|
||||
439
third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/foliage_gen.gd
vendored
Normal file
|
|
@ -0,0 +1,439 @@
|
|||
# Copyright © 2026 CosmonautFrog - MIT License
|
||||
|
||||
extends RefCounted
|
||||
## Foliage generator: textured quads along a branch and icospheres on tips.
|
||||
## References:
|
||||
## - https://tympanus.net/codrops/2025/01/27/fractals-to-forests-creating-realistic-3d-trees-with-three-js/
|
||||
## Icosphere math's from:
|
||||
## - https://blog.lslabs.dev/posts/generating_icosphere_with_code
|
||||
## - https://schneide.blog/2016/07/15/generating-an-icosphere-in-c/
|
||||
|
||||
const Branch := preload("./branch.gd")
|
||||
const BranchGen := preload("./branch_gen.gd")
|
||||
const MeshUtils := preload("./mesh_utils.gd")
|
||||
|
||||
## (1 + sqrt(5)) / 2 - https://en.wikipedia.org/wiki/Golden_ratio
|
||||
const GOLDEN_RATIO: float = 1.618033988749895
|
||||
|
||||
## 1 / golden ratio. Multiples of it spread evenly over [0, 1).
|
||||
const GOLDEN_RATIO_CONJUGATE: float = 0.618033988749895
|
||||
|
||||
|
||||
static func _append_icosphere(
|
||||
vertices: PackedVector3Array,
|
||||
indices: PackedInt32Array,
|
||||
center: Vector3,
|
||||
noise_seed: int = 0,
|
||||
radius: float = 1.0,
|
||||
subdivisions: int = 0,
|
||||
amplitude: float = 0.0,
|
||||
frequency: float = 1.5,
|
||||
) -> void:
|
||||
const T := GOLDEN_RATIO
|
||||
|
||||
var sphere_vertices := PackedVector3Array([
|
||||
Vector3(-1, T, 0), Vector3(1, T, 0), Vector3(-1, -T, 0), Vector3(1, -T, 0),
|
||||
Vector3(0, -1, T), Vector3(0, 1, T), Vector3(0, -1, -T), Vector3(0, 1, -T),
|
||||
Vector3(T, 0, -1), Vector3(T, 0, 1), Vector3(-T, 0, -1), Vector3(-T, 0, 1),
|
||||
])
|
||||
for i in sphere_vertices.size():
|
||||
sphere_vertices[i] = sphere_vertices[i].normalized()
|
||||
|
||||
var sphere_indices := PackedInt32Array([
|
||||
0, 5, 11, 0, 1, 5, 0, 7, 1, 0, 10, 7, 0, 11, 10,
|
||||
1, 9, 5, 5, 4, 11, 11, 2, 10, 10, 6, 7, 7, 8, 1,
|
||||
3, 4, 9, 3, 2, 4, 3, 6, 2, 3, 8, 6, 3, 9, 8,
|
||||
4, 5, 9, 2, 11, 4, 6, 10, 2, 8, 7, 6, 9, 1, 8,
|
||||
])
|
||||
|
||||
sphere_indices = _subdivide(sphere_vertices, sphere_indices, subdivisions)
|
||||
_displace(sphere_vertices, noise_seed, amplitude, frequency)
|
||||
|
||||
var base := vertices.size()
|
||||
for v in sphere_vertices:
|
||||
vertices.push_back(center + v * radius)
|
||||
for i in sphere_indices:
|
||||
indices.push_back(base + i)
|
||||
|
||||
|
||||
static func _limb_phase(branch_seed: int, jitter: float = 0.0) -> float:
|
||||
var h := float(posmod(hash(branch_seed), 10000)) / 10000.0
|
||||
return fposmod(h + jitter, 1.0)
|
||||
|
||||
|
||||
static func _append_leaf(
|
||||
vertices: PackedVector3Array,
|
||||
indices: PackedInt32Array,
|
||||
uvs: PackedVector2Array,
|
||||
colors: PackedColorArray,
|
||||
origin: Vector3,
|
||||
tangent: Vector3,
|
||||
azimuth: float,
|
||||
size: float,
|
||||
tilt: float,
|
||||
gravity: float,
|
||||
double: bool,
|
||||
flex_base: float,
|
||||
flex_tip: float,
|
||||
limb_phase: float,
|
||||
aspect: float = 1.0,
|
||||
) -> void:
|
||||
var helper := Vector3.RIGHT if absf(tangent.y) > 0.9 else Vector3.UP
|
||||
var side := tangent.cross(helper).normalized().rotated(tangent, azimuth)
|
||||
var dir := tangent * cos(tilt) + side * sin(tilt)
|
||||
var hang := Quaternion.IDENTITY.slerp(Quaternion(dir, Vector3.DOWN), gravity)
|
||||
var up := hang * dir * size
|
||||
var right := hang * tangent.cross(side).normalized() * size * aspect
|
||||
_append_quad(vertices, indices, uvs, colors, origin, up, right, flex_base, flex_tip, limb_phase)
|
||||
if double:
|
||||
var double_right := up.cross(right).normalized() * size * aspect
|
||||
_append_quad(vertices, indices, uvs, colors, origin, up, double_right, flex_base, flex_tip, limb_phase)
|
||||
|
||||
|
||||
static func _append_leaves(
|
||||
vertices: PackedVector3Array,
|
||||
indices: PackedInt32Array,
|
||||
uvs: PackedVector2Array,
|
||||
colors: PackedColorArray,
|
||||
branch: Branch,
|
||||
params: CosmoFoliageParams,
|
||||
length_influence: float = 1.0,
|
||||
aspect: float = 1.0,
|
||||
) -> void:
|
||||
var rng := RandomNumberGenerator.new()
|
||||
rng.seed = hash([branch.branch_seed, "ayylmao"])
|
||||
var tilt := deg_to_rad(params.leaf_angle)
|
||||
var base_phase := _limb_phase(branch.branch_seed)
|
||||
|
||||
for k in params.leaf_count:
|
||||
var t := lerpf(params.leaf_start, 1.0, (k + rng.randf()) / params.leaf_count)
|
||||
var origin := branch.sample(t) + params.leaf_position_offset
|
||||
var tangent := branch.tangent_at(t)
|
||||
var azimuth := k * BranchGen.GOLDEN_ANGLE + rng.randf_range(-0.3, 0.3)
|
||||
var size := _get_leaf_size_at(rng, params, t, length_influence)
|
||||
|
||||
if size <= 0.0 or branch.is_broken:
|
||||
continue
|
||||
|
||||
var flex_base := lerpf(0.68, 0.85, t)
|
||||
var flex_tip := lerpf(0.88, 1.0, t)
|
||||
var phase := fposmod(base_phase + float(k) * 0.037, 1.0)
|
||||
_append_leaf(
|
||||
vertices, indices, uvs, colors,
|
||||
origin, tangent, azimuth, size, tilt,
|
||||
params.leaf_gravity, params.leaf_double,
|
||||
flex_base, flex_tip, phase, aspect,
|
||||
)
|
||||
|
||||
# terminal leaf, after the loop so it doesn't reshuffle the other leaves
|
||||
if params.leaf_tip:
|
||||
var leaf_tip_tilt: float = 0.0 # TODO: set this as a foliage param maybe
|
||||
var size := _get_leaf_size_at(rng, params, 1.0, length_influence)
|
||||
var azimuth := rng.randf() * TAU - PI / 2.0
|
||||
var origin := branch.tip() + params.leaf_position_offset
|
||||
var tangent := branch.tangent_at(1.0)
|
||||
|
||||
if size <= 0.0 or branch.is_broken:
|
||||
return
|
||||
|
||||
_append_leaf(
|
||||
vertices, indices, uvs, colors,
|
||||
origin, tangent, azimuth, size, leaf_tip_tilt,
|
||||
params.leaf_gravity, params.leaf_double,
|
||||
0.85, 1.0, base_phase, aspect,
|
||||
)
|
||||
|
||||
|
||||
static func _append_quad(
|
||||
vertices: PackedVector3Array,
|
||||
indices: PackedInt32Array,
|
||||
uvs: PackedVector2Array,
|
||||
colors: PackedColorArray,
|
||||
base: Vector3,
|
||||
up: Vector3,
|
||||
right: Vector3,
|
||||
flex_base: float,
|
||||
flex_tip: float,
|
||||
limb_phase: float,
|
||||
) -> void:
|
||||
var first := vertices.size()
|
||||
var half := right * 0.5
|
||||
vertices.append_array(PackedVector3Array([base - half, base + half, base + half + up, base - half + up]))
|
||||
uvs.append_array(PackedVector2Array([Vector2(0, 1), Vector2(1, 1), Vector2(1, 0), Vector2(0, 0)]))
|
||||
colors.append_array(PackedColorArray([
|
||||
Color(1.0, flex_base, limb_phase, 1.0),
|
||||
Color(1.0, flex_base, limb_phase, 1.0),
|
||||
Color(1.0, flex_tip, limb_phase, 1.0),
|
||||
Color(1.0, flex_tip, limb_phase, 1.0),
|
||||
]))
|
||||
indices.append_array(PackedInt32Array([first, first + 3, first + 2, first, first + 2, first + 1]))
|
||||
|
||||
|
||||
static func _canopy_direction(p: Vector3, radii: Vector3) -> Vector3:
|
||||
var outward := (p / radii).normalized()
|
||||
return Vector3.UP.lerp(outward, smoothstep(0.0, 0.5, p.length())).normalized()
|
||||
|
||||
|
||||
## Blends the card normals towards an ellipsoid around all the leaves, so
|
||||
## is lit as one rounded volume (like EZ-Tree "rounded normals", but for the whole thing).
|
||||
## Encodes COLOR.rgba: R=AO (0.15..1.0), G=flex, B=limb phase, A=normalized height y/H.
|
||||
static func _canopy_shading(
|
||||
vertices: PackedVector3Array,
|
||||
normals: PackedVector3Array,
|
||||
colors: PackedColorArray,
|
||||
params: CosmoFoliageParams,
|
||||
tree_height: float,
|
||||
) -> void:
|
||||
var bounds := AABB(vertices[0], Vector3.ZERO)
|
||||
for v in vertices:
|
||||
bounds = bounds.expand(v)
|
||||
var center := bounds.get_center()
|
||||
var radii := (bounds.size * 0.5).max(Vector3.ONE * 0.01)
|
||||
var inv_h := 1.0 / maxf(tree_height, maxf(bounds.end.y, 0.5))
|
||||
|
||||
normals.resize(vertices.size())
|
||||
# 4 vertices per card, see _append_quad
|
||||
for q in range(0, vertices.size(), 4):
|
||||
var card := (vertices[q + 1] - vertices[q]).cross(vertices[q + 3] - vertices[q]).normalized()
|
||||
var mid := (vertices[q] + vertices[q + 2]) * 0.5
|
||||
if card.dot(_canopy_direction((mid - center) / radii, radii)) < 0.0:
|
||||
card = -card
|
||||
for k in 4:
|
||||
var p := (vertices[q + k] - center) / radii
|
||||
normals[q + k] = card.lerp(_canopy_direction(p, radii), params.leaf_canopy_normals).normalized()
|
||||
var ao := clampf(lerpf(params.leaf_inner_ao, 1.0, minf(p.length(), 1.0)), 0.15, 1.0)
|
||||
var c := colors[q + k]
|
||||
var norm_y := clampf(vertices[q + k].y * inv_h, 0.0, 1.0)
|
||||
colors[q + k] = Color(ao, c.g, c.b, norm_y)
|
||||
|
||||
|
||||
static func _displace(
|
||||
vertices: PackedVector3Array,
|
||||
noise_seed: int,
|
||||
amplitude: float,
|
||||
frequency: float,
|
||||
) -> void:
|
||||
if is_zero_approx(amplitude):
|
||||
return
|
||||
|
||||
var noise := FastNoiseLite.new()
|
||||
noise.seed = noise_seed
|
||||
noise.frequency = frequency
|
||||
|
||||
for i in vertices.size():
|
||||
var dir := vertices[i]
|
||||
vertices[i] = dir * (1.0 + amplitude * noise.get_noise_3dv(dir))
|
||||
|
||||
|
||||
static func _get_leaf_size_at(
|
||||
rng: RandomNumberGenerator,
|
||||
params: CosmoFoliageParams,
|
||||
t: float,
|
||||
length_influence: float,
|
||||
) -> float:
|
||||
var size := params.leaf_size * length_influence * (1.0 + rng.randf_range(-1.0, 1.0) * params.leaf_size_variance)
|
||||
if params.leaf_size_curve != null and params.leaf_size_curve.point_count > 0:
|
||||
size *= params.leaf_size_curve.sample(t)
|
||||
return size
|
||||
|
||||
|
||||
static func _subdivide(
|
||||
vertices: PackedVector3Array,
|
||||
indices: PackedInt32Array,
|
||||
levels: int,
|
||||
) -> PackedInt32Array:
|
||||
var mid := PackedInt32Array([0, 0, 0]) # ab, bc, ca
|
||||
|
||||
for level in levels:
|
||||
var cache := {}
|
||||
var new_indices := PackedInt32Array()
|
||||
new_indices.resize(indices.size() * 4)
|
||||
var n := 0
|
||||
|
||||
for t in range(0, indices.size(), 3):
|
||||
for e in 3:
|
||||
var p := indices[t + e]
|
||||
var q := indices[t + (e + 1) % 3]
|
||||
var key := (mini(p, q) << 32) | maxi(p, q)
|
||||
var m: int = cache.get(key, -1)
|
||||
if m == -1:
|
||||
m = vertices.size()
|
||||
vertices.push_back((vertices[p] + vertices[q]).normalized())
|
||||
cache[key] = m
|
||||
mid[e] = m
|
||||
|
||||
var a := indices[t]
|
||||
var b := indices[t + 1]
|
||||
var c := indices[t + 2]
|
||||
var ab := mid[0]
|
||||
var bc := mid[1]
|
||||
var ca := mid[2]
|
||||
|
||||
new_indices[n] = a
|
||||
new_indices[n + 1] = ab
|
||||
new_indices[n + 2] = ca
|
||||
new_indices[n + 3] = b
|
||||
new_indices[n + 4] = bc
|
||||
new_indices[n + 5] = ab
|
||||
new_indices[n + 6] = c
|
||||
new_indices[n + 7] = ca
|
||||
new_indices[n + 8] = bc
|
||||
new_indices[n + 9] = ab
|
||||
new_indices[n + 10] = bc
|
||||
new_indices[n + 11] = ca
|
||||
n += 12
|
||||
|
||||
indices = new_indices
|
||||
|
||||
return indices
|
||||
|
||||
|
||||
## Fills `sphere_centers` and `sphere_radii` with one sphere per icosphere.
|
||||
static func create_icospheres_mesh(
|
||||
tree: CosmoTreeGen,
|
||||
branches: Array[Branch],
|
||||
sphere_centers: PackedVector3Array,
|
||||
sphere_radii: PackedFloat32Array,
|
||||
tree_height: float = 0.0,
|
||||
) -> ArrayMesh:
|
||||
var vertices := PackedVector3Array()
|
||||
var indices := PackedInt32Array()
|
||||
var colors := PackedColorArray()
|
||||
var trunk := branches[0]
|
||||
var max_y := maxf(tree_height, tree.trunk_params.height)
|
||||
for branch in branches:
|
||||
if branch.is_broken:
|
||||
continue
|
||||
|
||||
var length_ratio := branch.get_length() / trunk.get_length()
|
||||
var length_influence := lerpf(1.0, length_ratio, tree.foliage_params.icosphere_length_influence)
|
||||
var radius := tree.foliage_params.icosphere_radius * length_influence
|
||||
var base_vert := vertices.size()
|
||||
_append_icosphere(
|
||||
vertices,
|
||||
indices,
|
||||
branch.tip(),
|
||||
branch.branch_seed,
|
||||
radius,
|
||||
tree.foliage_params.icosphere_subdivisions,
|
||||
tree.foliage_params.icosphere_amplitude,
|
||||
tree.foliage_params.icosphere_frequency,
|
||||
)
|
||||
var phase := _limb_phase(branch.branch_seed)
|
||||
for vi in range(base_vert, vertices.size()):
|
||||
max_y = maxf(max_y, vertices[vi].y)
|
||||
for vi in range(base_vert, vertices.size()):
|
||||
var rel := (vertices[vi] - branch.tip()).length() / maxf(radius, 0.01)
|
||||
var ao := clampf(lerpf(0.35, 0.95, rel * 0.8), 0.15, 1.0)
|
||||
var flex := lerpf(0.75, 1.0, clampf(rel, 0.0, 1.0))
|
||||
colors.push_back(Color(ao, flex, phase, clampf(vertices[vi].y / maxf(max_y, 0.5), 0.0, 1.0)))
|
||||
# the noise displaces it +-amplitude, so the base radius is the average fit
|
||||
sphere_centers.append(branch.tip())
|
||||
sphere_radii.append(radius)
|
||||
|
||||
return MeshUtils.build_mesh(vertices, indices, false, PackedVector2Array(), colors)
|
||||
|
||||
|
||||
static func create_leaves_lod(params: CosmoFoliageParams, src: ArrayMesh, keep: float) -> ArrayMesh:
|
||||
var arrays := src.surface_get_arrays(0)
|
||||
var src_vertices: PackedVector3Array = arrays[Mesh.ARRAY_VERTEX]
|
||||
var src_normals: PackedVector3Array = arrays[Mesh.ARRAY_NORMAL]
|
||||
var src_colors: PackedColorArray = arrays[Mesh.ARRAY_COLOR]
|
||||
var src_uvs: PackedVector2Array = arrays[Mesh.ARRAY_TEX_UV]
|
||||
|
||||
# 4 vertices per card, see _append_quad
|
||||
var cards_per_leaf: int = 2 if params.leaf_double else 1
|
||||
@warning_ignore("integer_division")
|
||||
var leaves: int = src_vertices.size() / 4 / cards_per_leaf
|
||||
var kept := clampf(keep, 1.0 / leaves, 1.0)
|
||||
var card_scale := sqrt(1.0 / kept)
|
||||
|
||||
var vertices := PackedVector3Array()
|
||||
var normals := PackedVector3Array()
|
||||
var colors := PackedColorArray()
|
||||
var uvs := PackedVector2Array()
|
||||
var indices := PackedInt32Array()
|
||||
|
||||
for leaf in leaves:
|
||||
if fposmod(leaf * GOLDEN_RATIO_CONJUGATE, 1.0) >= kept:
|
||||
continue
|
||||
|
||||
for card in cards_per_leaf:
|
||||
var q := (leaf * cards_per_leaf + card) * 4
|
||||
var center := (src_vertices[q] + src_vertices[q + 2]) * 0.5
|
||||
var first := vertices.size()
|
||||
for k in 4:
|
||||
vertices.push_back(center + (src_vertices[q + k] - center) * card_scale)
|
||||
normals.push_back(src_normals[q + k])
|
||||
colors.push_back(src_colors[q + k])
|
||||
uvs.push_back(src_uvs[q + k])
|
||||
indices.append_array(
|
||||
PackedInt32Array([first, first + 3, first + 2, first, first + 2, first + 1])
|
||||
)
|
||||
|
||||
var out_arrays := []
|
||||
out_arrays.resize(Mesh.ARRAY_MAX)
|
||||
out_arrays[Mesh.ARRAY_VERTEX] = vertices
|
||||
out_arrays[Mesh.ARRAY_NORMAL] = normals
|
||||
out_arrays[Mesh.ARRAY_COLOR] = colors
|
||||
out_arrays[Mesh.ARRAY_TEX_UV] = uvs
|
||||
out_arrays[Mesh.ARRAY_INDEX] = indices
|
||||
|
||||
var out := ArrayMesh.new()
|
||||
out.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, out_arrays)
|
||||
out.surface_set_name(0, src.surface_get_name(0))
|
||||
return out
|
||||
|
||||
|
||||
## Fills `sphere_centers` and `sphere_radii` with one sphere per tip leaf cluster.
|
||||
static func create_leaves_mesh(
|
||||
tree: CosmoTreeGen,
|
||||
tips: Array[Branch],
|
||||
trunk_count: int,
|
||||
sphere_centers: PackedVector3Array,
|
||||
sphere_radii: PackedFloat32Array,
|
||||
tree_height: float = 0.0,
|
||||
) -> ArrayMesh:
|
||||
var vertices := PackedVector3Array()
|
||||
var indices := PackedInt32Array()
|
||||
var uvs := PackedVector2Array()
|
||||
var colors := PackedColorArray()
|
||||
|
||||
# tips starts with the trunks, they only get leaves when there are no branches
|
||||
var first := trunk_count if tips.size() > trunk_count else 0
|
||||
var aspect: float = tree.foliage_params.get_leaf_aspect(tree.foliage_material)
|
||||
var longest := 0.0
|
||||
for i in range(first, tips.size()):
|
||||
longest = maxf(longest, tips[i].get_length())
|
||||
for i in range(first, tips.size()):
|
||||
var length_ratio := tips[i].get_length() / longest
|
||||
var length_influence := lerpf(1.0, length_ratio, tree.foliage_params.leaf_length_influence)
|
||||
var tip_first := vertices.size()
|
||||
_append_leaves(vertices, indices, uvs, colors, tips[i], tree.foliage_params, length_influence, aspect)
|
||||
|
||||
# broken tips get no leaves
|
||||
if vertices.size() == tip_first:
|
||||
continue
|
||||
var bounds := AABB(vertices[tip_first], Vector3.ZERO)
|
||||
for k in range(tip_first, vertices.size()):
|
||||
bounds = bounds.expand(vertices[k])
|
||||
sphere_centers.append(bounds.get_center())
|
||||
# average of the half extents, the corners of the box are mostly empty
|
||||
sphere_radii.append((bounds.size.x + bounds.size.y + bounds.size.z) / 6.0)
|
||||
|
||||
if vertices.is_empty():
|
||||
return null
|
||||
|
||||
var normals := PackedVector3Array()
|
||||
_canopy_shading(vertices, normals, colors, tree.foliage_params, tree_height)
|
||||
|
||||
var arrays := []
|
||||
arrays.resize(Mesh.ARRAY_MAX)
|
||||
arrays[Mesh.ARRAY_VERTEX] = vertices
|
||||
arrays[Mesh.ARRAY_NORMAL] = normals
|
||||
arrays[Mesh.ARRAY_COLOR] = colors
|
||||
arrays[Mesh.ARRAY_TEX_UV] = uvs
|
||||
arrays[Mesh.ARRAY_INDEX] = indices
|
||||
var mesh := ArrayMesh.new()
|
||||
mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arrays)
|
||||
return mesh
|
||||
405
third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/impostor_gen.gd
vendored
Normal file
|
|
@ -0,0 +1,405 @@
|
|||
# Copyright © 2026 CosmonautFrog - MIT License
|
||||
|
||||
@tool
|
||||
extends RefCounted
|
||||
|
||||
const MeshUtils := preload("./mesh_utils.gd")
|
||||
const Settings := preload("./settings.gd")
|
||||
const TreeBuilder := preload("./tree_builder.gd")
|
||||
|
||||
const CAPTURE_SHADER := preload("../shaders/impostor_capture.gdshader")
|
||||
const STATIC_SHADER := preload("../shaders/impostor_static.gdshader")
|
||||
const OCTAHEDRAL_SHADER := preload("../shaders/impostor_octahedral.gdshader")
|
||||
|
||||
enum Type {
|
||||
NONE,
|
||||
STATIC,
|
||||
OCTAHEDRAL,
|
||||
}
|
||||
|
||||
enum Output {
|
||||
ALBEDO,
|
||||
NORMAL,
|
||||
MASK,
|
||||
}
|
||||
|
||||
const NODE_NAME: String = "Impostor_LOD3"
|
||||
const PADDING_PX: int = 2
|
||||
const PIXEL_ALIGNMENT: int = 4
|
||||
const ALPHA_THRESHOLD: float = 0.5
|
||||
const FLAT_NORMAL := Color(0.5, 0.5, 1.0, 0.0)
|
||||
const OCTAHEDRAL_NORMAL_SIGN := Vector3(-1.0, 1.0, 1.0)
|
||||
|
||||
|
||||
static func _create_capture_material(source: Material, is_foliage: bool) -> ShaderMaterial:
|
||||
var mat := ShaderMaterial.new()
|
||||
mat.shader = CAPTURE_SHADER
|
||||
mat.set_shader_parameter("albedo_texture", MeshUtils.get_albedo_texture(source))
|
||||
mat.set_shader_parameter("is_foliage", is_foliage)
|
||||
|
||||
if source is BaseMaterial3D:
|
||||
var base := source as BaseMaterial3D
|
||||
mat.set_shader_parameter("albedo", base.albedo_color)
|
||||
mat.set_shader_parameter("uv_scale", base.uv1_scale)
|
||||
mat.set_shader_parameter("uv_offset", base.uv1_offset)
|
||||
mat.set_shader_parameter("triplanar", base.uv1_triplanar)
|
||||
mat.set_shader_parameter("triplanar_sharpness", base.uv1_triplanar_sharpness)
|
||||
if base.transparency != BaseMaterial3D.TRANSPARENCY_DISABLED:
|
||||
mat.set_shader_parameter("alpha_scissor_threshold", base.alpha_scissor_threshold)
|
||||
elif source is ShaderMaterial:
|
||||
var shader_mat := source as ShaderMaterial
|
||||
mat.set_shader_parameter("albedo", _get_shader_param(shader_mat, &"albedo", Color.WHITE))
|
||||
mat.set_shader_parameter(
|
||||
"alpha_scissor_threshold", _get_shader_param(shader_mat, &"alpha_scissor_threshold", 0.5)
|
||||
)
|
||||
mat.set_shader_parameter("ao_strength", _get_shader_param(shader_mat, &"ao_light_affect", 0.0))
|
||||
|
||||
return mat
|
||||
|
||||
|
||||
static func _get_shader_param(
|
||||
material: ShaderMaterial, param: StringName, fallback: Variant,
|
||||
) -> Variant:
|
||||
var value: Variant = material.get_shader_parameter(param)
|
||||
if value == null:
|
||||
value = RenderingServer.shader_get_parameter_default(material.shader.get_rid(), param)
|
||||
return fallback if value == null else value
|
||||
|
||||
|
||||
static func _average_color(image: Image) -> Color:
|
||||
var small := image.duplicate() as Image
|
||||
small.generate_mipmaps()
|
||||
var c := small.get_data().slice(-4)
|
||||
return Color(c[0], c[1], c[2], 0.0) / maxf(c[3], 1.0)
|
||||
|
||||
|
||||
static func _fill_transparent(image: Image, color: Color) -> Image:
|
||||
var out := Image.create_empty(image.get_width(), image.get_height(), false, Image.FORMAT_RGBA8)
|
||||
out.fill(color)
|
||||
out.blit_rect_mask(image, image, Rect2i(Vector2i.ZERO, image.get_size()), Vector2i.ZERO)
|
||||
out.fix_alpha_edges()
|
||||
return out
|
||||
|
||||
|
||||
static func _write_alpha(image: Image, mask: Image) -> void:
|
||||
var data := image.get_data()
|
||||
var src := mask.get_data()
|
||||
for i in range(3, data.size(), 4):
|
||||
data[i] = src[i - 3] if src[i] > 0 else 255
|
||||
|
||||
image.set_data(image.get_width(), image.get_height(), false, Image.FORMAT_RGBA8, data)
|
||||
|
||||
|
||||
static func _preserve_coverage(image: Image) -> void:
|
||||
var data := image.get_data()
|
||||
var cutoff := roundi(ALPHA_THRESHOLD * 255.0)
|
||||
var target: float = 0.0
|
||||
var mm_count := image.get_mipmap_count()
|
||||
|
||||
for level in image.get_mipmap_count() + 1:
|
||||
var start := image.get_mipmap_offset(level)
|
||||
var end := image.get_mipmap_offset(level + 1) if level < mm_count else data.size()
|
||||
var count := (end - start) / 4.0
|
||||
var histogram := PackedInt32Array()
|
||||
histogram.resize(256)
|
||||
for i in range(start + 3, end, 4):
|
||||
histogram[data[i]] += 1
|
||||
|
||||
if level == 0:
|
||||
for value in range(cutoff, 256):
|
||||
target += histogram[value] / count
|
||||
continue
|
||||
|
||||
var alpha: int = 255
|
||||
var covered := histogram[alpha]
|
||||
while alpha > 1 and covered < target * count:
|
||||
alpha -= 1
|
||||
covered += histogram[alpha]
|
||||
|
||||
var scale := float(cutoff) / alpha
|
||||
for i in range(start + 3, end, 4):
|
||||
data[i] = mini(roundi(data[i] * scale), 255)
|
||||
|
||||
var w := image.get_width()
|
||||
var h := image.get_height()
|
||||
image.set_data(w, h, true, Image.FORMAT_RGBA8, data)
|
||||
|
||||
|
||||
static func _create_texture(image: Image) -> PortableCompressedTexture2D:
|
||||
var texture := PortableCompressedTexture2D.new()
|
||||
# without keep_compressed_buffer set,
|
||||
# PortableCompressedTexture2D would save without data
|
||||
texture.keep_compressed_buffer = true
|
||||
texture.create_from_image(image, PortableCompressedTexture2D.COMPRESSION_MODE_BASIS_UNIVERSAL)
|
||||
return texture
|
||||
|
||||
|
||||
static func _create_textures(albedo: Image, normal: Image, mask: Image) -> Array[PortableCompressedTexture2D]:
|
||||
if RenderingServer.get_current_rendering_method() != "gl_compatibility":
|
||||
normal.srgb_to_linear()
|
||||
normal = _fill_transparent(normal, FLAT_NORMAL)
|
||||
_write_alpha(normal, mask)
|
||||
normal.generate_mipmaps()
|
||||
|
||||
albedo = _fill_transparent(albedo, _average_color(albedo))
|
||||
albedo.generate_mipmaps()
|
||||
_preserve_coverage(albedo)
|
||||
|
||||
return [_create_texture(albedo), _create_texture(normal)]
|
||||
|
||||
|
||||
static func _get_bounds(sources: Array[MeshInstance3D]) -> AABB:
|
||||
var bounds := AABB()
|
||||
for mi: MeshInstance3D in sources:
|
||||
bounds = bounds.merge(mi.get_aabb())
|
||||
return bounds
|
||||
|
||||
|
||||
static func _add_sources(
|
||||
parent: Node, sources: Array[MeshInstance3D], normal_sign: Vector3,
|
||||
) -> Array[ShaderMaterial]:
|
||||
var materials: Array[ShaderMaterial] = []
|
||||
for src: MeshInstance3D in sources:
|
||||
var mesh := src.mesh as ArrayMesh
|
||||
var mi := MeshInstance3D.new()
|
||||
mi.mesh = mesh
|
||||
for s in mesh.get_surface_count():
|
||||
var is_foliage := mesh.surface_get_name(s) == TreeBuilder.FOLIAGE_SURFACE_NAME
|
||||
var mat := _create_capture_material(src.get_active_material(s), is_foliage)
|
||||
mat.set_shader_parameter("normal_sign", normal_sign)
|
||||
mi.set_surface_override_material(s, mat)
|
||||
materials.append(mat)
|
||||
parent.add_child(mi)
|
||||
return materials
|
||||
|
||||
|
||||
static func _create_viewport(
|
||||
size: Vector2i, camera_size: float, camera_far: float, camera_transform: Transform3D,
|
||||
) -> SubViewport:
|
||||
var viewport := SubViewport.new()
|
||||
viewport.size = size
|
||||
viewport.transparent_bg = true
|
||||
viewport.render_target_update_mode = SubViewport.UPDATE_DISABLED
|
||||
|
||||
var camera := Camera3D.new()
|
||||
camera.projection = Camera3D.PROJECTION_ORTHOGONAL
|
||||
camera.size = camera_size
|
||||
camera.far = camera_far
|
||||
camera.transform = camera_transform
|
||||
|
||||
viewport.add_child(camera)
|
||||
return viewport
|
||||
|
||||
|
||||
static func _capture(viewports: Array[SubViewport], materials: Array[ShaderMaterial]) -> Array[Array]:
|
||||
var root := (Engine.get_main_loop() as SceneTree).root
|
||||
for viewport in viewports:
|
||||
root.add_child(viewport)
|
||||
|
||||
var images: Array[Array] = []
|
||||
for output: Output in Output.values():
|
||||
for mat in materials:
|
||||
mat.set_shader_parameter("output", output)
|
||||
for viewport in viewports:
|
||||
viewport.render_target_update_mode = SubViewport.UPDATE_ONCE
|
||||
await RenderingServer.frame_post_draw
|
||||
var pass_images: Array[Image] = []
|
||||
for viewport in viewports:
|
||||
pass_images.append(viewport.get_texture().get_image())
|
||||
images.append(pass_images)
|
||||
|
||||
for viewport in viewports:
|
||||
viewport.queue_free()
|
||||
return images
|
||||
|
||||
|
||||
static func _get_backlight(tree: CosmoTreeGen) -> Color:
|
||||
if tree.foliage_material is ShaderMaterial:
|
||||
return _get_shader_param(tree.foliage_material as ShaderMaterial, &"backlight", Color.BLACK)
|
||||
return Color.BLACK
|
||||
|
||||
|
||||
static func _get_specular(tree: CosmoTreeGen) -> float:
|
||||
if tree.foliage_material is ShaderMaterial:
|
||||
return _get_shader_param(tree.foliage_material as ShaderMaterial, &"specular", 0.2)
|
||||
if tree.foliage_material is BaseMaterial3D:
|
||||
return (tree.foliage_material as BaseMaterial3D).metallic_specular
|
||||
return 0.5
|
||||
|
||||
|
||||
static func _hemi_octahedron(coord: Vector2) -> Vector3:
|
||||
var x := coord.x - coord.y
|
||||
var z := coord.x + coord.y - 1.0
|
||||
return Vector3(x, 1.0 - absf(x) - absf(z), z).normalized()
|
||||
|
||||
|
||||
static func _bake_static(tree: CosmoTreeGen) -> QuadMesh:
|
||||
var sources := tree.get_meshes(0)
|
||||
var bounds := _get_bounds(sources)
|
||||
|
||||
var resolution: int = Settings.get_setting(Settings.IMPOSTOR_STATIC_RESOLUTION, 512)
|
||||
var half_width := maxf(-bounds.position.x, bounds.end.x)
|
||||
var depth := maxf(-bounds.position.z, bounds.end.z)
|
||||
var texel := maxf(2.0 * half_width, bounds.size.y) / (resolution - 2 * PADDING_PX)
|
||||
|
||||
var content_size := Vector2(2.0 * half_width, bounds.size.y)
|
||||
var content_pixels := content_size / texel
|
||||
var padding_pixels := Vector2.ONE * (2.0 * PADDING_PX)
|
||||
var required_pixels := content_pixels + padding_pixels
|
||||
var aligned_pixels := (required_pixels / PIXEL_ALIGNMENT).ceil() * PIXEL_ALIGNMENT
|
||||
var pixels := Vector2i(aligned_pixels)
|
||||
|
||||
var size := Vector2(pixels) * texel
|
||||
var center := Vector3(0.0, bounds.get_center().y, 0.0)
|
||||
|
||||
var camera_transform := Transform3D(Basis(), center + Vector3(0.0, 0.0, depth + 1.0))
|
||||
var viewport := _create_viewport(pixels, size.y, 2.0 * depth + 2.0, camera_transform)
|
||||
viewport.own_world_3d = true
|
||||
|
||||
var materials := _add_sources(viewport, sources, Vector3.ONE)
|
||||
var images := await _capture([viewport], materials)
|
||||
var albedo: Image = images[Output.ALBEDO][0]
|
||||
var normal: Image = images[Output.NORMAL][0]
|
||||
var mask: Image = images[Output.MASK][0]
|
||||
var textures := _create_textures(albedo, normal, mask)
|
||||
|
||||
var material := ShaderMaterial.new()
|
||||
material.shader = STATIC_SHADER
|
||||
material.set_shader_parameter("albedo_texture", textures[0])
|
||||
material.set_shader_parameter("normal_texture", textures[1])
|
||||
material.set_shader_parameter("backlight", _get_backlight(tree))
|
||||
material.set_shader_parameter("specular", _get_specular(tree))
|
||||
|
||||
var quad := QuadMesh.new()
|
||||
quad.size = size
|
||||
quad.center_offset = center
|
||||
quad.material = material
|
||||
return quad
|
||||
|
||||
|
||||
static func _bake_octahedral(tree: CosmoTreeGen) -> QuadMesh:
|
||||
var sources := tree.get_meshes(0)
|
||||
var center := Vector3(0.0, _get_bounds(sources).get_center().y, 0.0)
|
||||
var radius := 0.0
|
||||
for mi: MeshInstance3D in sources:
|
||||
for s in mi.mesh.get_surface_count():
|
||||
var vertices: PackedVector3Array = mi.mesh.surface_get_arrays(s)[Mesh.ARRAY_VERTEX]
|
||||
for vertex: Vector3 in vertices:
|
||||
radius = maxf(radius, vertex.distance_squared_to(center))
|
||||
radius = sqrt(radius)
|
||||
|
||||
var frames: int = Settings.get_setting(Settings.IMPOSTOR_OCTAHEDRAL_FRAMES, 12)
|
||||
var resolution: int = Settings.get_setting(Settings.IMPOSTOR_OCTAHEDRAL_RESOLUTION, 1024)
|
||||
var frame_pixels := floori(float(resolution) / frames / PIXEL_ALIGNMENT) * PIXEL_ALIGNMENT
|
||||
var scale := radius * frame_pixels / (frame_pixels - 2 * PADDING_PX)
|
||||
|
||||
var world := World3D.new()
|
||||
var viewports: Array[SubViewport] = []
|
||||
for y in frames:
|
||||
for x in frames:
|
||||
var direction := _hemi_octahedron(Vector2(x, y) / (frames - 1))
|
||||
var up := Vector3.BACK if absf(direction.y) > 0.999 else Vector3.UP
|
||||
var camera_transform := Transform3D(Basis.looking_at(-direction, up), center + direction * (scale + 1.0))
|
||||
var viewport := _create_viewport(Vector2i.ONE * frame_pixels, 2.0 * scale, 2.0 * scale + 2.0, camera_transform)
|
||||
viewport.world_3d = world
|
||||
viewports.append(viewport)
|
||||
|
||||
var materials := _add_sources(viewports[0], sources, OCTAHEDRAL_NORMAL_SIGN)
|
||||
var images := await _capture(viewports, materials)
|
||||
|
||||
var atlases: Array[Image] = []
|
||||
for pass_images: Array in images:
|
||||
var atlas := Image.create_empty(frames * frame_pixels, frames * frame_pixels, false, Image.FORMAT_RGBA8)
|
||||
for y in frames:
|
||||
for x in frames:
|
||||
var frame: Image = pass_images[y * frames + x]
|
||||
atlas.blit_rect(frame, Rect2i(Vector2i.ZERO, frame.get_size()), Vector2i(x, y) * frame_pixels)
|
||||
atlases.append(atlas)
|
||||
var textures := _create_textures(atlases[Output.ALBEDO], atlases[Output.NORMAL], atlases[Output.MASK])
|
||||
|
||||
var material := ShaderMaterial.new()
|
||||
material.shader = OCTAHEDRAL_SHADER
|
||||
material.set_shader_parameter("albedo_texture", textures[0])
|
||||
material.set_shader_parameter("normal_texture", textures[1])
|
||||
material.set_shader_parameter("impostor_frames", Vector2(frames, frames))
|
||||
material.set_shader_parameter("scale", scale)
|
||||
material.set_shader_parameter("position_offset", center)
|
||||
material.set_shader_parameter("backlight", _get_backlight(tree))
|
||||
material.set_shader_parameter("specular", _get_specular(tree))
|
||||
|
||||
var quad := QuadMesh.new()
|
||||
quad.size = Vector2.ONE * 2.0 * scale
|
||||
quad.center_offset = center
|
||||
quad.material = material
|
||||
return quad
|
||||
|
||||
|
||||
static func bake_octahedral_images(tree: CosmoTreeGen, frames: int = 6, resolution: int = 384) -> Dictionary:
|
||||
var sources := tree.get_meshes(0)
|
||||
var center := Vector3(0.0, _get_bounds(sources).get_center().y, 0.0)
|
||||
var radius := 0.0
|
||||
for mi: MeshInstance3D in sources:
|
||||
for s in mi.mesh.get_surface_count():
|
||||
var vertices: PackedVector3Array = mi.mesh.surface_get_arrays(s)[Mesh.ARRAY_VERTEX]
|
||||
for vertex: Vector3 in vertices:
|
||||
radius = maxf(radius, vertex.distance_squared_to(center))
|
||||
radius = sqrt(radius)
|
||||
|
||||
var frame_pixels := floori(float(resolution) / frames / PIXEL_ALIGNMENT) * PIXEL_ALIGNMENT
|
||||
var scale := radius * frame_pixels / (frame_pixels - 2 * PADDING_PX)
|
||||
|
||||
var world := World3D.new()
|
||||
var viewports: Array[SubViewport] = []
|
||||
for y in frames:
|
||||
for x in frames:
|
||||
var direction := _hemi_octahedron(Vector2(x, y) / (frames - 1))
|
||||
var up := Vector3.BACK if absf(direction.y) > 0.999 else Vector3.UP
|
||||
var camera_transform := Transform3D(Basis.looking_at(-direction, up), center + direction * (scale + 1.0))
|
||||
var viewport := _create_viewport(Vector2i.ONE * frame_pixels, 2.0 * scale, 2.0 * scale + 2.0, camera_transform)
|
||||
viewport.world_3d = world
|
||||
viewports.append(viewport)
|
||||
|
||||
var materials := _add_sources(viewports[0], sources, OCTAHEDRAL_NORMAL_SIGN)
|
||||
var images := await _capture(viewports, materials)
|
||||
|
||||
var atlases: Array[Image] = []
|
||||
for pass_images: Array in images:
|
||||
var atlas := Image.create_empty(frames * frame_pixels, frames * frame_pixels, false, Image.FORMAT_RGBA8)
|
||||
for y in frames:
|
||||
for x in frames:
|
||||
var frame: Image = pass_images[y * frames + x]
|
||||
atlas.blit_rect(frame, Rect2i(Vector2i.ZERO, frame.get_size()), Vector2i(x, y) * frame_pixels)
|
||||
atlases.append(atlas)
|
||||
|
||||
var albedo: Image = atlases[Output.ALBEDO]
|
||||
var normal: Image = atlases[Output.NORMAL]
|
||||
var mask: Image = atlases[Output.MASK]
|
||||
if RenderingServer.get_current_rendering_method() != "gl_compatibility":
|
||||
normal.srgb_to_linear()
|
||||
normal = _fill_transparent(normal, FLAT_NORMAL)
|
||||
_write_alpha(normal, mask)
|
||||
normal.generate_mipmaps()
|
||||
|
||||
albedo = _fill_transparent(albedo, _average_color(albedo))
|
||||
albedo.generate_mipmaps()
|
||||
_preserve_coverage(albedo)
|
||||
|
||||
return {
|
||||
"albedo": albedo,
|
||||
"normal": normal,
|
||||
"frames": frames,
|
||||
"scale": scale,
|
||||
"position_offset": center,
|
||||
}
|
||||
|
||||
|
||||
static func bake(tree: CosmoTreeGen, type: Type) -> MeshInstance3D:
|
||||
var impostor := MeshInstance3D.new()
|
||||
impostor.name = NODE_NAME
|
||||
|
||||
match type:
|
||||
Type.NONE: return null
|
||||
Type.STATIC: impostor.mesh = await _bake_static(tree)
|
||||
Type.OCTAHEDRAL: impostor.mesh = await _bake_octahedral(tree)
|
||||
|
||||
return impostor
|
||||
42
third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/lod_post_import.gd
vendored
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
# Copyright © 2026 CosmonautFrog - MIT License
|
||||
|
||||
@tool
|
||||
extends EditorScenePostImport
|
||||
## glTF loses custom_aabb, without it the LODs don't swap at the same distance.
|
||||
|
||||
|
||||
func _post_import(scene: Node) -> Object:
|
||||
var meshes := scene.get_children().filter(
|
||||
func(child: Node) -> bool:
|
||||
return child is MeshInstance3D
|
||||
)
|
||||
|
||||
var collisions := scene.get_children().filter(
|
||||
func(child: Node) -> bool:
|
||||
return child is StaticBody3D
|
||||
)
|
||||
|
||||
var bounds := AABB()
|
||||
for mesh: MeshInstance3D in meshes:
|
||||
bounds = bounds.merge(mesh.mesh.get_aabb())
|
||||
|
||||
if scene.has_node("Impostor_LOD3"):
|
||||
var r := maxf(
|
||||
maxf(-bounds.position.x, bounds.end.x),
|
||||
maxf(-bounds.position.z, bounds.end.z)
|
||||
)
|
||||
bounds = AABB(
|
||||
Vector3(-r, bounds.position.y, -r),
|
||||
Vector3(2.0 * r, bounds.size.y, 2.0 * r)
|
||||
)
|
||||
|
||||
for mesh: MeshInstance3D in meshes:
|
||||
mesh.custom_aabb = bounds
|
||||
mesh.add_to_group(&"cosmo_tree_mesh", true)
|
||||
|
||||
for col: StaticBody3D in collisions:
|
||||
col.add_to_group(&"cosmo_tree_collision", true)
|
||||
|
||||
scene.add_to_group(&"cosmo_tree", true)
|
||||
|
||||
return scene
|
||||
296
third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/mesh_utils.gd
vendored
Normal file
|
|
@ -0,0 +1,296 @@
|
|||
# Copyright © 2026 CosmonautFrog - MIT License
|
||||
|
||||
extends RefCounted
|
||||
## Shared helpers.
|
||||
|
||||
|
||||
static func _fill_flat(
|
||||
arrays: Array,
|
||||
vertices: PackedVector3Array,
|
||||
indices: PackedInt32Array,
|
||||
uvs := PackedVector2Array(),
|
||||
colors := PackedColorArray(),
|
||||
) -> void:
|
||||
var count := indices.size()
|
||||
var has_uvs := not uvs.is_empty()
|
||||
var has_colors := not colors.is_empty()
|
||||
var flat_vertices := PackedVector3Array()
|
||||
var flat_normals := PackedVector3Array()
|
||||
var flat_uvs := PackedVector2Array()
|
||||
var flat_colors := PackedColorArray()
|
||||
flat_vertices.resize(count)
|
||||
flat_normals.resize(count)
|
||||
if has_uvs:
|
||||
flat_uvs.resize(count)
|
||||
if has_colors:
|
||||
flat_colors.resize(count)
|
||||
|
||||
for t in range(0, count, 3):
|
||||
var a := vertices[indices[t]]
|
||||
var b := vertices[indices[t + 1]]
|
||||
var c := vertices[indices[t + 2]]
|
||||
var normal := (c - a).cross(b - a).normalized()
|
||||
for k in 3:
|
||||
flat_vertices[t + k] = vertices[indices[t + k]]
|
||||
flat_normals[t + k] = normal
|
||||
if has_uvs:
|
||||
flat_uvs[t + k] = uvs[indices[t + k]]
|
||||
if has_colors:
|
||||
flat_colors[t + k] = colors[indices[t + k]]
|
||||
|
||||
arrays[Mesh.ARRAY_VERTEX] = flat_vertices
|
||||
arrays[Mesh.ARRAY_NORMAL] = flat_normals
|
||||
if has_uvs:
|
||||
arrays[Mesh.ARRAY_TEX_UV] = flat_uvs
|
||||
if has_colors:
|
||||
arrays[Mesh.ARRAY_COLOR] = flat_colors
|
||||
|
||||
|
||||
## Returns a copy of the arrays without the vertices no index uses,
|
||||
## otherwise each LOD keeps the whole LOD0 vertex buffer.
|
||||
static func _remove_unused_vertices(arrays: Array) -> Array:
|
||||
var indices: PackedInt32Array = arrays[Mesh.ARRAY_INDEX]
|
||||
var vertex_array: PackedVector3Array = arrays[Mesh.ARRAY_VERTEX]
|
||||
var vertex_count := vertex_array.size()
|
||||
|
||||
var index_map := PackedInt32Array()
|
||||
index_map.resize(vertex_count)
|
||||
index_map.fill(-1)
|
||||
var used := PackedInt32Array()
|
||||
var new_indices := PackedInt32Array()
|
||||
new_indices.resize(indices.size())
|
||||
|
||||
for i in indices.size():
|
||||
var old := indices[i]
|
||||
if index_map[old] == -1:
|
||||
index_map[old] = used.size()
|
||||
used.push_back(old)
|
||||
new_indices[i] = index_map[old]
|
||||
|
||||
var out := []
|
||||
out.resize(Mesh.ARRAY_MAX)
|
||||
out[Mesh.ARRAY_INDEX] = new_indices
|
||||
for attribute: int in [Mesh.ARRAY_VERTEX, Mesh.ARRAY_NORMAL, Mesh.ARRAY_TEX_UV, Mesh.ARRAY_COLOR]:
|
||||
var old_values: Variant = arrays[attribute]
|
||||
if old_values == null:
|
||||
continue
|
||||
@warning_ignore("unsafe_method_access")
|
||||
var new_values: Variant = old_values.duplicate()
|
||||
@warning_ignore("unsafe_method_access")
|
||||
new_values.resize(used.size())
|
||||
for i in used.size():
|
||||
new_values[i] = old_values[used[i]]
|
||||
out[attribute] = new_values
|
||||
|
||||
return out
|
||||
|
||||
|
||||
static func _smooth_normals(vertices: PackedVector3Array, indices: PackedInt32Array) -> PackedVector3Array:
|
||||
var normals := PackedVector3Array()
|
||||
normals.resize(vertices.size())
|
||||
|
||||
for t in range(0, indices.size(), 3):
|
||||
var a := indices[t]
|
||||
var b := indices[t + 1]
|
||||
var c := indices[t + 2]
|
||||
var face := (vertices[c] - vertices[a]).cross(vertices[b] - vertices[a])
|
||||
normals[a] += face
|
||||
normals[b] += face
|
||||
normals[c] += face
|
||||
|
||||
# Weld vertices sharing a position (UV seams) so they get the same normal
|
||||
var welded := {}
|
||||
for i in vertices.size():
|
||||
welded[vertices[i]] = welded.get(vertices[i], Vector3.ZERO) + normals[i]
|
||||
|
||||
for i in normals.size():
|
||||
var normal: Vector3 = welded[vertices[i]]
|
||||
normals[i] = normal.normalized()
|
||||
return normals
|
||||
|
||||
|
||||
static func append_tube(
|
||||
vertices: PackedVector3Array,
|
||||
indices: PackedInt32Array,
|
||||
points: PackedVector3Array,
|
||||
radii: PackedFloat32Array,
|
||||
radial: int,
|
||||
close_end: bool = false,
|
||||
) -> void:
|
||||
var base := vertices.size()
|
||||
var count := points.size()
|
||||
var ring := radial + 1 # extra vertex per ring for the UV seam
|
||||
var tangent := (points[1] - points[0]).normalized()
|
||||
# the UV seam is at angle 0, start it underneath unless the tube is near vertical
|
||||
var normal := tangent.cross(Vector3.RIGHT) if absf(tangent.y) > 0.9 else Vector3.DOWN + tangent * tangent.y
|
||||
normal = normal.normalized()
|
||||
|
||||
for i in count:
|
||||
tangent = (points[mini(i + 1, count - 1)] - points[maxi(i - 1, 0)]).normalized()
|
||||
normal = (normal - tangent * normal.dot(tangent)).normalized()
|
||||
var binormal := normal.cross(tangent)
|
||||
var first := vertices.size()
|
||||
for j in radial:
|
||||
var angle := TAU * j / radial
|
||||
vertices.push_back(points[i] + (normal * cos(angle) + binormal * sin(angle)) * radii[i])
|
||||
vertices.push_back(vertices[first])
|
||||
|
||||
for i in count - 1:
|
||||
for j in radial:
|
||||
var a := base + i * ring + j
|
||||
var b := a + 1
|
||||
var c := a + ring
|
||||
var d := c + 1
|
||||
indices.append_array(PackedInt32Array([d, c, a, d, a, b]))
|
||||
|
||||
# close tube with a cap
|
||||
var tip_radius := radii[count - 1]
|
||||
if close_end and tip_radius > 0.0:
|
||||
var apex := vertices.size()
|
||||
var last := base + (count - 1) * ring
|
||||
vertices.push_back(points[count - 1] + tangent * tip_radius)
|
||||
for j in radial:
|
||||
indices.append_array(PackedInt32Array([apex, last + j, last + j + 1]))
|
||||
|
||||
|
||||
## World space UVs for the tube append_tube added at `first`, `density` texture repeats per meter,
|
||||
## so every tube gets the same texel size. Run it after deforming the tube, it measures the final shape.
|
||||
static func append_tube_uvs(
|
||||
uvs: PackedVector2Array,
|
||||
vertices: PackedVector3Array,
|
||||
first: int,
|
||||
rings: int,
|
||||
radial: int,
|
||||
density: float,
|
||||
offset := Vector2.ZERO,
|
||||
) -> void:
|
||||
var ring := radial + 1
|
||||
var length := 0.0
|
||||
|
||||
for i in rings:
|
||||
var start := first + i * ring
|
||||
# measured on the surface so the flare slope counts, averaged so the columns don't shear
|
||||
if i > 0:
|
||||
var step := 0.0
|
||||
for j in radial:
|
||||
step += vertices[start + j].distance_to(vertices[start + j - ring])
|
||||
length += step / radial
|
||||
|
||||
var perimeter := 0.0
|
||||
for j in radial:
|
||||
perimeter += vertices[start + j].distance_to(vertices[start + j + 1])
|
||||
|
||||
# centered on the top, so where the tube narrows the texture skews at the seam underneath
|
||||
# u and v decrease so the texture is upright and not mirrored seen from outside
|
||||
var arc := perimeter * 0.5
|
||||
for j in ring:
|
||||
if j > 0:
|
||||
arc -= vertices[start + j].distance_to(vertices[start + j - 1])
|
||||
uvs.push_back(Vector2(arc, -length) * density + offset)
|
||||
|
||||
# cap apex
|
||||
var apex := first + rings * ring
|
||||
if apex < vertices.size():
|
||||
var slant := 0.0
|
||||
for j in radial:
|
||||
slant += vertices[apex].distance_to(vertices[apex - ring + j])
|
||||
uvs.push_back(Vector2(0.0, -(length + slant / radial)) * density + offset)
|
||||
|
||||
|
||||
## The albedo texture of a BaseMaterial3D, or the `albedo_texture` uniform of a ShaderMaterial.
|
||||
static func get_albedo_texture(material: Material) -> Texture2D:
|
||||
if material is BaseMaterial3D:
|
||||
return (material as BaseMaterial3D).albedo_texture
|
||||
if material is ShaderMaterial:
|
||||
var texture: Texture2D = (material as ShaderMaterial).get_shader_parameter("albedo_texture")
|
||||
return texture
|
||||
return null
|
||||
|
||||
|
||||
static func build_mesh(
|
||||
vertices: PackedVector3Array,
|
||||
indices: PackedInt32Array,
|
||||
flat_shading: bool,
|
||||
uvs := PackedVector2Array(),
|
||||
colors := PackedColorArray(),
|
||||
) -> ArrayMesh:
|
||||
var arrays := []
|
||||
arrays.resize(Mesh.ARRAY_MAX)
|
||||
if flat_shading:
|
||||
_fill_flat(arrays, vertices, indices, uvs, colors)
|
||||
else:
|
||||
arrays[Mesh.ARRAY_VERTEX] = vertices
|
||||
arrays[Mesh.ARRAY_NORMAL] = _smooth_normals(vertices, indices)
|
||||
arrays[Mesh.ARRAY_INDEX] = indices
|
||||
if not uvs.is_empty():
|
||||
arrays[Mesh.ARRAY_TEX_UV] = uvs
|
||||
if not colors.is_empty():
|
||||
arrays[Mesh.ARRAY_COLOR] = colors
|
||||
|
||||
var mesh := ArrayMesh.new()
|
||||
mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arrays)
|
||||
return mesh
|
||||
|
||||
|
||||
static func combine_meshes(array_meshes: Array[ArrayMesh]) -> ArrayMesh:
|
||||
# could use SurfaceTool but couldn't find out how to maintain separated materials
|
||||
var out := ArrayMesh.new()
|
||||
|
||||
for am: ArrayMesh in array_meshes:
|
||||
for i in range(am.get_surface_count()):
|
||||
out.add_surface_from_arrays(
|
||||
am.surface_get_primitive_type(i),
|
||||
am.surface_get_arrays(i)
|
||||
)
|
||||
var new_idx := out.get_surface_count() - 1
|
||||
out.surface_set_name(new_idx, am.surface_get_name(i))
|
||||
out.surface_set_material(new_idx, am.surface_get_material(i))
|
||||
|
||||
return out
|
||||
|
||||
|
||||
static func count_triangles(mesh: ArrayMesh) -> int:
|
||||
if mesh == null:
|
||||
return 0
|
||||
|
||||
@warning_ignore("integer_division")
|
||||
return mesh.surface_get_array_index_len(0) / 3
|
||||
|
||||
|
||||
static func flatten_mesh(mesh: Mesh) -> ArrayMesh:
|
||||
var src := mesh.surface_get_arrays(0)
|
||||
var vertices: PackedVector3Array = src[Mesh.ARRAY_VERTEX]
|
||||
var indices: PackedInt32Array = src[Mesh.ARRAY_INDEX]
|
||||
var uvs := PackedVector2Array()
|
||||
if src[Mesh.ARRAY_TEX_UV] != null:
|
||||
uvs = src[Mesh.ARRAY_TEX_UV]
|
||||
var colors := PackedColorArray()
|
||||
if src[Mesh.ARRAY_COLOR] != null:
|
||||
colors = src[Mesh.ARRAY_COLOR]
|
||||
var result := build_mesh(vertices, indices, true, uvs, colors)
|
||||
result.surface_set_name(0, (mesh as ArrayMesh).surface_get_name(0))
|
||||
result.surface_set_material(0, mesh.surface_get_material(0))
|
||||
return result
|
||||
|
||||
|
||||
static func simplify(src: ArrayMesh, max_triangles: float) -> ArrayMesh:
|
||||
if count_triangles(src) <= max_triangles:
|
||||
return src
|
||||
|
||||
var arrays := src.surface_get_arrays(0)
|
||||
var importer := ImporterMesh.new()
|
||||
importer.add_surface(Mesh.PRIMITIVE_TRIANGLES, arrays)
|
||||
importer.generate_lods(25.0, 60.0, [])
|
||||
|
||||
for lod in importer.get_surface_lod_count(0):
|
||||
var indices := importer.get_surface_lod_indices(0, lod)
|
||||
arrays[Mesh.ARRAY_INDEX] = indices
|
||||
if indices.size() / 3.0 <= max_triangles:
|
||||
break
|
||||
|
||||
var out := ArrayMesh.new()
|
||||
out.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, _remove_unused_vertices(arrays))
|
||||
out.surface_set_name(0, src.surface_get_name(0))
|
||||
if src.surface_get_material(0) != null:
|
||||
out.surface_set_material(0, src.surface_get_material(0))
|
||||
return out
|
||||
137
third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/settings.gd
vendored
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
# Copyright © 2026 CosmonautFrog - MIT License
|
||||
|
||||
@tool
|
||||
extends RefCounted
|
||||
|
||||
const SETTINGS_PATH: String = "cosmo_tree_gen"
|
||||
|
||||
# generator
|
||||
const LOD1_RATIO: StringName = &"generator/lod1_ratio"
|
||||
const LOD2_RATIO: StringName = &"generator/lod2_ratio"
|
||||
const LOD1_DISTANCE: StringName = &"generator/lod1_distance"
|
||||
const LOD2_DISTANCE: StringName = &"generator/lod2_distance"
|
||||
const LOD_END_DISTANCE: StringName = &"generator/lod_end_distance"
|
||||
|
||||
# export
|
||||
const EXPORT_EXTENSION: StringName = &"export/default_extension"
|
||||
const EXPORT_INCLUDE_COLLISIONS: StringName = &"export/default_include_collisions"
|
||||
const EXPORT_IMAGES: StringName = &"export/default_export_images"
|
||||
const EXPORT_USE_EXTERNAL_MATERIAL: StringName = &"export/default_use_external_material"
|
||||
const EXPORT_IMPOSTOR: StringName = &"export/default_impostor"
|
||||
|
||||
# impostor
|
||||
const IMPOSTOR_DISTANCE: StringName = &"impostor/impostor_distance"
|
||||
const IMPOSTOR_STATIC_RESOLUTION: StringName = &"impostor/static_resolution"
|
||||
const IMPOSTOR_OCTAHEDRAL_FRAMES: StringName = &"impostor/octahedral_frames"
|
||||
const IMPOSTOR_OCTAHEDRAL_RESOLUTION: StringName = &"impostor/octahedral_resolution"
|
||||
const IMPOSTOR_CAST_SHADOW: StringName = &"impostor/cast_shadow"
|
||||
|
||||
const SETTINGS: Dictionary = {
|
||||
LOD1_RATIO: {
|
||||
"value": 0.4,
|
||||
"type": TYPE_FLOAT,
|
||||
"hint": PROPERTY_HINT_RANGE,
|
||||
"hint_string": "0.0,1.0,0.01",
|
||||
},
|
||||
LOD2_RATIO: {
|
||||
"value": 0.15,
|
||||
"type": TYPE_FLOAT,
|
||||
"hint": PROPERTY_HINT_RANGE,
|
||||
"hint_string": "0.0,1.0,0.01",
|
||||
},
|
||||
LOD1_DISTANCE: {
|
||||
"value": 50.0,
|
||||
"type": TYPE_FLOAT,
|
||||
"hint": PROPERTY_HINT_RANGE,
|
||||
"hint_string": "0.0,1000.0,0.1,or_greater,suffix:m",
|
||||
},
|
||||
LOD2_DISTANCE: {
|
||||
"value": 100.0,
|
||||
"type": TYPE_FLOAT,
|
||||
"hint": PROPERTY_HINT_RANGE,
|
||||
"hint_string": "0.0,1000.0,0.1,or_greater,suffix:m",
|
||||
},
|
||||
# 0 keeps the last LOD visible at any distance
|
||||
LOD_END_DISTANCE: {
|
||||
"value": 0.0,
|
||||
"type": TYPE_FLOAT,
|
||||
"hint": PROPERTY_HINT_RANGE,
|
||||
"hint_string": "0.0,1000.0,0.1,or_greater,suffix:m",
|
||||
},
|
||||
EXPORT_EXTENSION: {
|
||||
"value": "glb",
|
||||
"type": TYPE_STRING,
|
||||
"hint": PROPERTY_HINT_ENUM,
|
||||
"hint_string": "glb,gltf",
|
||||
},
|
||||
EXPORT_INCLUDE_COLLISIONS: {
|
||||
"value": true,
|
||||
"type": TYPE_BOOL,
|
||||
},
|
||||
EXPORT_IMAGES: {
|
||||
"value": false,
|
||||
"type": TYPE_BOOL,
|
||||
},
|
||||
EXPORT_USE_EXTERNAL_MATERIAL: {
|
||||
"value": true,
|
||||
"type": TYPE_BOOL,
|
||||
},
|
||||
EXPORT_IMPOSTOR: {
|
||||
"value": 1,
|
||||
"type": TYPE_INT,
|
||||
"hint": PROPERTY_HINT_ENUM,
|
||||
"hint_string": "None,Static,Octahedral",
|
||||
},
|
||||
IMPOSTOR_DISTANCE: {
|
||||
"value": 150.0,
|
||||
"type": TYPE_FLOAT,
|
||||
"hint": PROPERTY_HINT_RANGE,
|
||||
"hint_string": "0.0,1000.0,0.1,or_greater,suffix:m",
|
||||
},
|
||||
IMPOSTOR_STATIC_RESOLUTION: {
|
||||
"value": 512,
|
||||
"type": TYPE_INT,
|
||||
"hint": PROPERTY_HINT_RANGE,
|
||||
"hint_string": "64,2048,64,or_greater,suffix:px",
|
||||
},
|
||||
IMPOSTOR_OCTAHEDRAL_FRAMES: {
|
||||
"value": 12,
|
||||
"type": TYPE_INT,
|
||||
"hint": PROPERTY_HINT_RANGE,
|
||||
"hint_string": "4,32,1",
|
||||
},
|
||||
IMPOSTOR_OCTAHEDRAL_RESOLUTION: {
|
||||
"value": 1024,
|
||||
"type": TYPE_INT,
|
||||
"hint": PROPERTY_HINT_RANGE,
|
||||
"hint_string": "256,4096,64,or_greater,suffix:px",
|
||||
},
|
||||
IMPOSTOR_CAST_SHADOW: {
|
||||
"value": false,
|
||||
"type": TYPE_BOOL,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
static func setup_settings() -> void:
|
||||
for key: String in SETTINGS:
|
||||
var setting_config: Dictionary = SETTINGS[key]
|
||||
var setting_name: String = "%s/%s" % [SETTINGS_PATH, key]
|
||||
var setting_default: Variant = setting_config.get("value")
|
||||
if not ProjectSettings.has_setting(setting_name):
|
||||
ProjectSettings.set_setting(setting_name, setting_default)
|
||||
ProjectSettings.set_initial_value(setting_name, setting_default)
|
||||
ProjectSettings.set_as_basic(setting_name, true)
|
||||
ProjectSettings.add_property_info({
|
||||
"name": setting_name,
|
||||
"type": setting_config.get("type"),
|
||||
"hint": setting_config.get("hint", PROPERTY_HINT_NONE),
|
||||
"hint_string": setting_config.get("hint_string", "")
|
||||
})
|
||||
|
||||
|
||||
static func get_setting(key: String, default: Variant) -> Variant:
|
||||
if ProjectSettings.has_setting("%s/%s" % [SETTINGS_PATH, key]):
|
||||
return ProjectSettings.get_setting("%s/%s" % [SETTINGS_PATH, key])
|
||||
else:
|
||||
return default
|
||||
320
third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/tree_builder.gd
vendored
Normal file
|
|
@ -0,0 +1,320 @@
|
|||
# Copyright © 2026 CosmonautFrog - MIT License
|
||||
|
||||
@tool
|
||||
extends RefCounted
|
||||
## Builds a tree from CosmoTreeGen params, creates meshes and collision shapes.
|
||||
|
||||
enum Part {
|
||||
## Trunk and/or foliage in a single mesh, one surface/material each.
|
||||
COMBINED,
|
||||
TRUNK,
|
||||
FOLIAGE,
|
||||
}
|
||||
|
||||
const Settings := preload("./settings.gd")
|
||||
const Branch := preload("./branch.gd")
|
||||
const FoliageGen := preload("./foliage_gen.gd")
|
||||
const CollisionGen := preload("./collision_gen.gd")
|
||||
const TrunkGen := preload("./trunk_gen.gd")
|
||||
const BranchGen := preload("./branch_gen.gd")
|
||||
const MeshUtils := preload("./mesh_utils.gd")
|
||||
|
||||
const TRUNK_SURFACE_NAME: String = "bark"
|
||||
const FOLIAGE_SURFACE_NAME: String = "foliage"
|
||||
const COLLISION_RADIAL_SEGMENTS: int = 6
|
||||
|
||||
|
||||
## Grows all the branch levels, then meshes them along with the trunk.
|
||||
## Fills `roots` with the trunk roots, they are not part of the returned branches.
|
||||
static func _limb_phase(branch_seed: int) -> float:
|
||||
return float(posmod(hash(branch_seed), 10000)) / 10000.0
|
||||
|
||||
|
||||
static func _generate_branches(
|
||||
tree: CosmoTreeGen,
|
||||
trunks: Array[Branch],
|
||||
roots: Array[Branch],
|
||||
vertices: PackedVector3Array,
|
||||
indices: PackedInt32Array,
|
||||
uvs: PackedVector2Array,
|
||||
colors: PackedColorArray,
|
||||
trunk_radial: int,
|
||||
branch_radial: int,
|
||||
) -> Array[Branch]:
|
||||
var branches: Array[Branch] = []
|
||||
var parents: Array[Branch] = trunks
|
||||
for level in tree.branch_levels:
|
||||
if level == null:
|
||||
continue
|
||||
var children: Array[Branch] = []
|
||||
for parent in parents:
|
||||
children.append_array(BranchGen.grow_branches(parent, level))
|
||||
branches.append_array(children)
|
||||
if children.is_empty():
|
||||
break
|
||||
parents = children
|
||||
|
||||
var has_sub_branches := tree.branch_levels.size() > 1
|
||||
# terminal branches are meshed inside the tube of the branch they continue
|
||||
var params := tree.trunk_params
|
||||
var uv_density := tree.get_uv_density()
|
||||
for trunk in trunks:
|
||||
_append_branch_tube(vertices, indices, uvs, colors, trunk, trunk_radial, params, uv_density, false, has_sub_branches)
|
||||
for branch in branches:
|
||||
if not branch.is_terminal:
|
||||
_append_branch_tube(vertices, indices, uvs, colors, branch, branch_radial, params, uv_density, false, has_sub_branches)
|
||||
|
||||
# roots are not added to `branches`, so they get no foliage
|
||||
if params.roots != null:
|
||||
for trunk in trunks:
|
||||
for root in BranchGen.grow_branches(trunk, params.roots):
|
||||
roots.append(root)
|
||||
_append_branch_tube(vertices, indices, uvs, colors, root, branch_radial, params, uv_density, true, has_sub_branches)
|
||||
|
||||
var max_y := maxf(params.height, 0.5)
|
||||
for v in vertices:
|
||||
max_y = maxf(max_y, v.y)
|
||||
var inv_h := 1.0 / max_y
|
||||
for i in vertices.size():
|
||||
var c := colors[i]
|
||||
colors[i] = Color(c.r, c.g, c.b, clampf(vertices[i].y * inv_h, 0.0, 1.0))
|
||||
|
||||
return branches
|
||||
|
||||
|
||||
## Meshes a branch and its terminal branches as one seamless tube.
|
||||
static func _append_branch_tube(
|
||||
vertices: PackedVector3Array,
|
||||
indices: PackedInt32Array,
|
||||
uvs: PackedVector2Array,
|
||||
colors: PackedColorArray,
|
||||
branch: Branch,
|
||||
radial: int,
|
||||
trunk_params: CosmoTrunkParams,
|
||||
uv_density: float,
|
||||
is_root: bool = false,
|
||||
has_sub_branches: bool = false,
|
||||
) -> void:
|
||||
var first := vertices.size()
|
||||
var ringed: Branch = branch.with_base_rings()
|
||||
var points: PackedVector3Array = ringed.points
|
||||
var radii: PackedFloat32Array = ringed.radii
|
||||
|
||||
if branch.sink_depth > 0.0:
|
||||
points.insert(0, branch.points[0] + Vector3.DOWN * branch.sink_depth)
|
||||
radii.insert(0, branch.radii[0])
|
||||
|
||||
var terminal := branch.terminal
|
||||
while terminal != null:
|
||||
# Its first point is the tip it grows from
|
||||
points.append_array(terminal.points.slice(1))
|
||||
radii.append_array(terminal.radii.slice(1))
|
||||
terminal = terminal.terminal
|
||||
MeshUtils.append_tube(vertices, indices, points, radii, radial, true)
|
||||
if branch.base_rings > 0:
|
||||
TrunkGen.flare_base(vertices, first, branch, trunk_params)
|
||||
|
||||
# after the flare so it doesn't stretch them, offset so the branches don't all start the same
|
||||
var rng := RandomNumberGenerator.new()
|
||||
rng.seed = branch.branch_seed
|
||||
var offset := Vector2(rng.randf(), rng.randf())
|
||||
MeshUtils.append_tube_uvs(uvs, vertices, first, points.size(), radial, uv_density, offset)
|
||||
|
||||
var phase := _limb_phase(branch.branch_seed)
|
||||
var ring_stride := radial + 1
|
||||
var ring_count := points.size()
|
||||
var denom := maxf(1.0, float(ring_count - 1))
|
||||
var tip_color := Color(0.75, 0.25, phase, 1.0)
|
||||
for r in ring_count:
|
||||
var p := float(r) / denom
|
||||
var ao := 0.75
|
||||
var flex := 0.0
|
||||
if is_root:
|
||||
ao = 0.28
|
||||
flex = 0.0
|
||||
elif branch.level == 0:
|
||||
ao = clampf(lerpf(0.32, 0.90, clampf(p * 1.35, 0.0, 1.0)), 0.15, 1.0)
|
||||
var t_flex := clampf((p - 0.06) / 0.94, 0.0, 1.0)
|
||||
flex = 0.25 * (t_flex * t_flex)
|
||||
elif branch.level == 1:
|
||||
ao = clampf(lerpf(0.55, 0.92, p), 0.15, 1.0)
|
||||
flex = lerpf(0.25, 0.48 if has_sub_branches else 0.65, p)
|
||||
else:
|
||||
ao = clampf(lerpf(0.65, 0.95, p), 0.15, 1.0)
|
||||
flex = lerpf(0.48, 0.72, p)
|
||||
var ring_col := Color(ao, flex, phase, 1.0)
|
||||
for j in ring_stride:
|
||||
var v_idx := first + r * ring_stride + j
|
||||
var v_flex := 0.0 if (is_root or (branch.level == 0 and vertices[v_idx].y <= 0.08)) else flex
|
||||
colors.push_back(Color(ao, v_flex, phase, 1.0))
|
||||
tip_color = ring_col
|
||||
while colors.size() < vertices.size():
|
||||
colors.push_back(tip_color)
|
||||
|
||||
|
||||
static func _create_lod(
|
||||
tree: CosmoTreeGen,
|
||||
trunk_mesh: ArrayMesh,
|
||||
foliage_mesh: ArrayMesh,
|
||||
ratio: float,
|
||||
) -> Array[ArrayMesh]:
|
||||
var trunk_tris := MeshUtils.count_triangles(trunk_mesh)
|
||||
var foliage_tris := MeshUtils.count_triangles(foliage_mesh)
|
||||
var budget := (trunk_tris + foliage_tris) * ratio
|
||||
|
||||
var trunk: ArrayMesh
|
||||
if trunk_mesh != null:
|
||||
trunk = MeshUtils.simplify(trunk_mesh, maxf(budget * tree.lod_trunk_share, budget - foliage_tris))
|
||||
|
||||
var foliage: ArrayMesh
|
||||
if foliage_mesh != null:
|
||||
var remaining := budget - MeshUtils.count_triangles(trunk)
|
||||
if tree.foliage_params.type == CosmoFoliageParams.Type.LEAVES:
|
||||
foliage = FoliageGen.create_leaves_lod(tree.foliage_params, foliage_mesh, remaining / foliage_tris)
|
||||
else:
|
||||
foliage = MeshUtils.simplify(foliage_mesh, remaining)
|
||||
|
||||
return [trunk, foliage]
|
||||
|
||||
|
||||
static func build(tree: CosmoTreeGen) -> Result:
|
||||
var result := Result.new()
|
||||
if tree.trunk_params == null:
|
||||
push_warning("CosmoTreeGen: missing 'trunk_params'!")
|
||||
return result
|
||||
|
||||
# Skeleton
|
||||
var trunk_radial: int = TrunkGen.BASE_RADIAL_SEGMENTS * tree.trunk_params.quality
|
||||
var branch_radial: int = maxi(3, trunk_radial - 2)
|
||||
|
||||
var vertices := PackedVector3Array()
|
||||
var indices := PackedInt32Array()
|
||||
var uvs := PackedVector2Array()
|
||||
var colors := PackedColorArray()
|
||||
|
||||
var trunks: Array[Branch] = TrunkGen.generate_trunks(tree.noise_seed, tree.trunk_params)
|
||||
|
||||
var roots: Array[Branch] = []
|
||||
var branches: Array[Branch] = _generate_branches(
|
||||
tree, trunks, roots, vertices, indices, uvs, colors, trunk_radial, branch_radial
|
||||
)
|
||||
|
||||
var tips: Array[Branch] = trunks.duplicate()
|
||||
if not branches.is_empty():
|
||||
var last_level: int = branches.back().level
|
||||
tips.append_array(branches.filter(
|
||||
func(b: Branch) -> bool:
|
||||
return b.level == last_level
|
||||
))
|
||||
|
||||
var tree_height := maxf(tree.trunk_params.height, 0.5)
|
||||
for v in vertices:
|
||||
tree_height = maxf(tree_height, v.y)
|
||||
|
||||
var trunk_mesh: ArrayMesh
|
||||
if tree.create_trunk:
|
||||
trunk_mesh = MeshUtils.build_mesh(vertices, indices, false, uvs, colors)
|
||||
trunk_mesh.surface_set_name(0, TRUNK_SURFACE_NAME)
|
||||
|
||||
# Foliage
|
||||
var foliage_mesh: ArrayMesh
|
||||
var sphere_centers := PackedVector3Array()
|
||||
var sphere_radii := PackedFloat32Array()
|
||||
if tree.foliage_params != null and tree.create_foliage:
|
||||
# TODO: add different types of foliage, E.G.: dead trees, pines, etc...
|
||||
match tree.foliage_params.type:
|
||||
CosmoFoliageParams.Type.NONE: pass
|
||||
CosmoFoliageParams.Type.ICOSPHERES:
|
||||
foliage_mesh = FoliageGen.create_icospheres_mesh(tree, tips, sphere_centers, sphere_radii, tree_height)
|
||||
CosmoFoliageParams.Type.LEAVES:
|
||||
foliage_mesh = FoliageGen.create_leaves_mesh(tree, tips, trunks.size(), sphere_centers, sphere_radii, tree_height)
|
||||
|
||||
if foliage_mesh != null:
|
||||
foliage_mesh.surface_set_name(0, FOLIAGE_SURFACE_NAME)
|
||||
|
||||
# Collision
|
||||
if tree.collision_type != CosmoTreeGen.CollisionType.NONE:
|
||||
var collision_branches: Array[Branch] = trunks.duplicate()
|
||||
collision_branches.append_array(branches)
|
||||
collision_branches.append_array(roots)
|
||||
var max_height := tree.collision_max_height if tree.collision_max_height > 0.0 else INF
|
||||
var shapes := CollisionGen.create_branch_shapes(
|
||||
tree.collision_type, collision_branches, tree.collision_level, max_height, COLLISION_RADIAL_SEGMENTS,
|
||||
tree.trunk_params,
|
||||
)
|
||||
# already in local space
|
||||
for shape in shapes:
|
||||
result.collision.add(shape)
|
||||
|
||||
if tree.foliage_collision_type != CosmoTreeGen.FoliageCollisionType.NONE and foliage_mesh != null:
|
||||
var shapes := CollisionGen.create_foliage_shapes(tree.foliage_collision_type, foliage_mesh, sphere_radii)
|
||||
for i in shapes.size():
|
||||
var origin := Vector3.ZERO
|
||||
if tree.foliage_collision_type == CosmoTreeGen.FoliageCollisionType.SPHERES:
|
||||
origin = sphere_centers[i]
|
||||
result.foliage_collision.add(shapes[i], Transform3D(Basis.IDENTITY, origin))
|
||||
|
||||
# LODs
|
||||
var levels: Array[Array] = [[trunk_mesh, foliage_mesh]]
|
||||
if tree.generate_lod:
|
||||
var lod1_ratio: float = Settings.get_setting(Settings.LOD1_RATIO, 0.4)
|
||||
var lod2_ratio: float = Settings.get_setting(Settings.LOD2_RATIO, 0.15)
|
||||
levels.append(_create_lod(tree, trunk_mesh, foliage_mesh, lod1_ratio))
|
||||
levels.append(_create_lod(tree, trunk_mesh, foliage_mesh, lod2_ratio))
|
||||
|
||||
# Flat shading
|
||||
if tree.flat_shading:
|
||||
for level: Array in levels:
|
||||
var trunk: Mesh = level[0]
|
||||
var foliage: Mesh = level[1]
|
||||
if trunk != null:
|
||||
level[0] = MeshUtils.flatten_mesh(trunk)
|
||||
if foliage != null and tree.foliage_params.type == CosmoFoliageParams.Type.ICOSPHERES:
|
||||
level[1] = MeshUtils.flatten_mesh(foliage)
|
||||
|
||||
# Combine, every level gets a LOD even if empty, so the indices stay the LOD levels
|
||||
for level: Array in levels:
|
||||
var lod := LOD.new()
|
||||
if tree.combine_trunk_and_foliage:
|
||||
var parts: Array[ArrayMesh] = [level[0], level[1]]
|
||||
parts = parts.filter(func(x: ArrayMesh) -> bool: return x != null)
|
||||
if not parts.is_empty():
|
||||
lod.meshes[Part.COMBINED] = MeshUtils.combine_meshes(parts)
|
||||
else:
|
||||
if level[0] != null:
|
||||
lod.meshes[Part.TRUNK] = level[0]
|
||||
if level[1] != null:
|
||||
lod.meshes[Part.FOLIAGE] = level[1]
|
||||
result.lods.append(lod)
|
||||
|
||||
# Bounds
|
||||
for lod in result.lods:
|
||||
for mesh: ArrayMesh in lod.meshes.values():
|
||||
result.bounds = result.bounds.merge(mesh.get_aabb())
|
||||
|
||||
return result
|
||||
|
||||
|
||||
class Collision:
|
||||
var shapes: Array[Shape3D] = []
|
||||
## Transform per shape, local space.
|
||||
var transforms: Array[Transform3D] = []
|
||||
|
||||
func add(shape: Shape3D, transform: Transform3D = Transform3D.IDENTITY) -> void:
|
||||
shapes.append(shape)
|
||||
transforms.append(transform)
|
||||
|
||||
|
||||
class LOD:
|
||||
## Just the built parts, never null meshes.
|
||||
var meshes: Dictionary[Part, ArrayMesh]
|
||||
|
||||
|
||||
class Result:
|
||||
## LOD0 first, its index is the LOD level. 1 LOD, or 3 with generate_lod.
|
||||
var lods: Array[LOD] = []
|
||||
## Bounds of all the LODs, used to swap them at the same distance.
|
||||
var bounds := AABB()
|
||||
## Trunks, roots and branches.
|
||||
var collision := Collision.new()
|
||||
var foliage_collision := Collision.new()
|
||||
80
third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/trunk_gen.gd
vendored
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
# Copyright © 2026 CosmonautFrog - MIT License
|
||||
|
||||
extends RefCounted
|
||||
## Trunk generator
|
||||
## References:
|
||||
## - EZ-Tree author: https://tympanus.net/codrops/2025/01/27/fractals-to-forests-creating-realistic-3d-trees-with-three-js/
|
||||
## - Coding Train / Dan Shiffman: https://www.youtube.com/watch?v=MwLyeEWnMCY
|
||||
## - https://algorithmicbotany.org/
|
||||
## - https://en.wikipedia.org/wiki/L-system
|
||||
|
||||
const Branch := preload("./branch.gd")
|
||||
|
||||
const BASE_RADIAL_SEGMENTS: int = 6
|
||||
const BASE_HEIGHT_SEGMENTS: int = 3
|
||||
const FLARE_RINGS: int = 4
|
||||
|
||||
|
||||
static func generate_trunks(noise_seed: int, params: CosmoTrunkParams) -> Array[Branch]:
|
||||
var rng := RandomNumberGenerator.new()
|
||||
rng.seed = noise_seed
|
||||
var start_angle := rng.randf() * TAU
|
||||
|
||||
var quality := maxi(params.quality, 1)
|
||||
var rings := BASE_HEIGHT_SEGMENTS * quality
|
||||
|
||||
var noise := FastNoiseLite.new()
|
||||
noise.frequency = 0.5
|
||||
|
||||
var trunks: Array[Branch] = []
|
||||
|
||||
for k in params.amount:
|
||||
var trunk := Branch.new()
|
||||
trunk.branch_seed = noise_seed + k
|
||||
noise.seed = trunk.branch_seed
|
||||
var jitter := rng.randf_range(-0.25, 0.25) if k > 0 else 0.0
|
||||
var angle := start_angle + TAU * (k + jitter) / params.amount
|
||||
var base := params.get_base_offset(angle)
|
||||
var lean_vec := params.get_lean_vec(angle)
|
||||
|
||||
for i in rings + 1:
|
||||
var t := float(i) / rings
|
||||
var center := base + Vector3(lean_vec.x * t * t, params.height * t, lean_vec.z * t * t)
|
||||
var w := params.wobble * sin(PI * t)
|
||||
center.x += w * noise.get_noise_1d(t * params.height)
|
||||
center.z += w * noise.get_noise_1d(t * params.height + 100.0)
|
||||
trunk.add_point(center, lerpf(params.radius_bottom, params.radius_top, t))
|
||||
|
||||
trunk.base_rings = FLARE_RINGS if params.flare > 0.0 else 0
|
||||
trunk.sink_depth = params.sink_depth
|
||||
trunks.append(trunk)
|
||||
|
||||
return trunks
|
||||
|
||||
|
||||
static func flare_base(
|
||||
vertices: PackedVector3Array,
|
||||
first: int,
|
||||
trunk: Branch,
|
||||
params: CosmoTrunkParams,
|
||||
) -> void:
|
||||
if params.flare <= 0.0:
|
||||
return
|
||||
|
||||
var noise := FastNoiseLite.new()
|
||||
noise.seed = trunk.branch_seed
|
||||
noise.frequency = 1.0
|
||||
var reach := params.height * params.flare_height
|
||||
var center := trunk.points[0]
|
||||
|
||||
for i in range(first, vertices.size()):
|
||||
var s := minf(1.0 - vertices[i].y / reach, 1.0)
|
||||
if s <= 0.0:
|
||||
continue
|
||||
|
||||
var offset := Vector2(vertices[i].x - center.x, vertices[i].z - center.z)
|
||||
# sampled on a unit circle so it wraps around the trunk without a seam
|
||||
var lobe := noise.get_noise_2dv(offset.normalized())
|
||||
var grow := 1.0 + params.flare * s * s * s * (1.0 + 2.0 * params.flare_lobes * lobe)
|
||||
vertices[i].x = center.x + offset.x * grow
|
||||
vertices[i].z = center.z + offset.y * grow
|
||||