diff --git a/THIRD_PARTY_NOTICES.txt b/THIRD_PARTY_NOTICES.txt index 3e7e1bb..a22e97c 100644 --- a/THIRD_PARTY_NOTICES.txt +++ b/THIRD_PARTY_NOTICES.txt @@ -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 diff --git a/assets/maps/sion/trees/betula_pendula_v0.glb b/assets/maps/sion/trees/betula_pendula_v0.glb new file mode 100644 index 0000000..e341ff5 Binary files /dev/null and b/assets/maps/sion/trees/betula_pendula_v0.glb differ diff --git a/assets/maps/sion/trees/betula_pendula_v0_impostor_albedo.png b/assets/maps/sion/trees/betula_pendula_v0_impostor_albedo.png new file mode 100644 index 0000000..70d509e Binary files /dev/null and b/assets/maps/sion/trees/betula_pendula_v0_impostor_albedo.png differ diff --git a/assets/maps/sion/trees/betula_pendula_v0_impostor_normal.png b/assets/maps/sion/trees/betula_pendula_v0_impostor_normal.png new file mode 100644 index 0000000..3a0e922 Binary files /dev/null and b/assets/maps/sion/trees/betula_pendula_v0_impostor_normal.png differ diff --git a/assets/maps/sion/trees/betula_pendula_v1.glb b/assets/maps/sion/trees/betula_pendula_v1.glb new file mode 100644 index 0000000..b44a132 Binary files /dev/null and b/assets/maps/sion/trees/betula_pendula_v1.glb differ diff --git a/assets/maps/sion/trees/betula_pendula_v1_impostor_albedo.png b/assets/maps/sion/trees/betula_pendula_v1_impostor_albedo.png new file mode 100644 index 0000000..3332a2f Binary files /dev/null and b/assets/maps/sion/trees/betula_pendula_v1_impostor_albedo.png differ diff --git a/assets/maps/sion/trees/betula_pendula_v1_impostor_normal.png b/assets/maps/sion/trees/betula_pendula_v1_impostor_normal.png new file mode 100644 index 0000000..8e914db Binary files /dev/null and b/assets/maps/sion/trees/betula_pendula_v1_impostor_normal.png differ diff --git a/assets/maps/sion/trees/cedrus_v0.glb b/assets/maps/sion/trees/cedrus_v0.glb new file mode 100644 index 0000000..318fd55 Binary files /dev/null and b/assets/maps/sion/trees/cedrus_v0.glb differ diff --git a/assets/maps/sion/trees/cedrus_v0_impostor_albedo.png b/assets/maps/sion/trees/cedrus_v0_impostor_albedo.png new file mode 100644 index 0000000..b8730a2 Binary files /dev/null and b/assets/maps/sion/trees/cedrus_v0_impostor_albedo.png differ diff --git a/assets/maps/sion/trees/cedrus_v0_impostor_normal.png b/assets/maps/sion/trees/cedrus_v0_impostor_normal.png new file mode 100644 index 0000000..f030233 Binary files /dev/null and b/assets/maps/sion/trees/cedrus_v0_impostor_normal.png differ diff --git a/assets/maps/sion/trees/malus_orchard_v0.glb b/assets/maps/sion/trees/malus_orchard_v0.glb new file mode 100644 index 0000000..fe8aede Binary files /dev/null and b/assets/maps/sion/trees/malus_orchard_v0.glb differ diff --git a/assets/maps/sion/trees/malus_orchard_v0_impostor_albedo.png b/assets/maps/sion/trees/malus_orchard_v0_impostor_albedo.png new file mode 100644 index 0000000..823b4af Binary files /dev/null and b/assets/maps/sion/trees/malus_orchard_v0_impostor_albedo.png differ diff --git a/assets/maps/sion/trees/malus_orchard_v0_impostor_normal.png b/assets/maps/sion/trees/malus_orchard_v0_impostor_normal.png new file mode 100644 index 0000000..126ee0e Binary files /dev/null and b/assets/maps/sion/trees/malus_orchard_v0_impostor_normal.png differ diff --git a/assets/maps/sion/trees/malus_orchard_v1.glb b/assets/maps/sion/trees/malus_orchard_v1.glb new file mode 100644 index 0000000..a21febc Binary files /dev/null and b/assets/maps/sion/trees/malus_orchard_v1.glb differ diff --git a/assets/maps/sion/trees/malus_orchard_v1_impostor_albedo.png b/assets/maps/sion/trees/malus_orchard_v1_impostor_albedo.png new file mode 100644 index 0000000..d1296c1 Binary files /dev/null and b/assets/maps/sion/trees/malus_orchard_v1_impostor_albedo.png differ diff --git a/assets/maps/sion/trees/malus_orchard_v1_impostor_normal.png b/assets/maps/sion/trees/malus_orchard_v1_impostor_normal.png new file mode 100644 index 0000000..59e50f8 Binary files /dev/null and b/assets/maps/sion/trees/malus_orchard_v1_impostor_normal.png differ diff --git a/assets/maps/sion/trees/picea_abies_v0.glb b/assets/maps/sion/trees/picea_abies_v0.glb new file mode 100644 index 0000000..9a5fbcc Binary files /dev/null and b/assets/maps/sion/trees/picea_abies_v0.glb differ diff --git a/assets/maps/sion/trees/picea_abies_v0_impostor_albedo.png b/assets/maps/sion/trees/picea_abies_v0_impostor_albedo.png new file mode 100644 index 0000000..acbab20 Binary files /dev/null and b/assets/maps/sion/trees/picea_abies_v0_impostor_albedo.png differ diff --git a/assets/maps/sion/trees/picea_abies_v0_impostor_normal.png b/assets/maps/sion/trees/picea_abies_v0_impostor_normal.png new file mode 100644 index 0000000..6fd0362 Binary files /dev/null and b/assets/maps/sion/trees/picea_abies_v0_impostor_normal.png differ diff --git a/assets/maps/sion/trees/picea_abies_v1.glb b/assets/maps/sion/trees/picea_abies_v1.glb new file mode 100644 index 0000000..edc0b59 Binary files /dev/null and b/assets/maps/sion/trees/picea_abies_v1.glb differ diff --git a/assets/maps/sion/trees/picea_abies_v1_impostor_albedo.png b/assets/maps/sion/trees/picea_abies_v1_impostor_albedo.png new file mode 100644 index 0000000..83e520d Binary files /dev/null and b/assets/maps/sion/trees/picea_abies_v1_impostor_albedo.png differ diff --git a/assets/maps/sion/trees/picea_abies_v1_impostor_normal.png b/assets/maps/sion/trees/picea_abies_v1_impostor_normal.png new file mode 100644 index 0000000..ad97487 Binary files /dev/null and b/assets/maps/sion/trees/picea_abies_v1_impostor_normal.png differ diff --git a/assets/maps/sion/trees/pinus_sylvestris_v0.glb b/assets/maps/sion/trees/pinus_sylvestris_v0.glb new file mode 100644 index 0000000..5f552c4 Binary files /dev/null and b/assets/maps/sion/trees/pinus_sylvestris_v0.glb differ diff --git a/assets/maps/sion/trees/pinus_sylvestris_v0_impostor_albedo.png b/assets/maps/sion/trees/pinus_sylvestris_v0_impostor_albedo.png new file mode 100644 index 0000000..4b5f274 Binary files /dev/null and b/assets/maps/sion/trees/pinus_sylvestris_v0_impostor_albedo.png differ diff --git a/assets/maps/sion/trees/pinus_sylvestris_v0_impostor_normal.png b/assets/maps/sion/trees/pinus_sylvestris_v0_impostor_normal.png new file mode 100644 index 0000000..7735bb4 Binary files /dev/null and b/assets/maps/sion/trees/pinus_sylvestris_v0_impostor_normal.png differ diff --git a/assets/maps/sion/trees/pinus_sylvestris_v1.glb b/assets/maps/sion/trees/pinus_sylvestris_v1.glb new file mode 100644 index 0000000..9d8575b Binary files /dev/null and b/assets/maps/sion/trees/pinus_sylvestris_v1.glb differ diff --git a/assets/maps/sion/trees/pinus_sylvestris_v1_impostor_albedo.png b/assets/maps/sion/trees/pinus_sylvestris_v1_impostor_albedo.png new file mode 100644 index 0000000..6a49627 Binary files /dev/null and b/assets/maps/sion/trees/pinus_sylvestris_v1_impostor_albedo.png differ diff --git a/assets/maps/sion/trees/pinus_sylvestris_v1_impostor_normal.png b/assets/maps/sion/trees/pinus_sylvestris_v1_impostor_normal.png new file mode 100644 index 0000000..6ebf2bf Binary files /dev/null and b/assets/maps/sion/trees/pinus_sylvestris_v1_impostor_normal.png differ diff --git a/assets/maps/sion/trees/platanus_acerifolia_v0.glb b/assets/maps/sion/trees/platanus_acerifolia_v0.glb new file mode 100644 index 0000000..92395d7 Binary files /dev/null and b/assets/maps/sion/trees/platanus_acerifolia_v0.glb differ diff --git a/assets/maps/sion/trees/platanus_acerifolia_v0_impostor_albedo.png b/assets/maps/sion/trees/platanus_acerifolia_v0_impostor_albedo.png new file mode 100644 index 0000000..6f2d79e Binary files /dev/null and b/assets/maps/sion/trees/platanus_acerifolia_v0_impostor_albedo.png differ diff --git a/assets/maps/sion/trees/platanus_acerifolia_v0_impostor_normal.png b/assets/maps/sion/trees/platanus_acerifolia_v0_impostor_normal.png new file mode 100644 index 0000000..6bb72d0 Binary files /dev/null and b/assets/maps/sion/trees/platanus_acerifolia_v0_impostor_normal.png differ diff --git a/assets/maps/sion/trees/platanus_acerifolia_v1.glb b/assets/maps/sion/trees/platanus_acerifolia_v1.glb new file mode 100644 index 0000000..3aa2710 Binary files /dev/null and b/assets/maps/sion/trees/platanus_acerifolia_v1.glb differ diff --git a/assets/maps/sion/trees/platanus_acerifolia_v1_impostor_albedo.png b/assets/maps/sion/trees/platanus_acerifolia_v1_impostor_albedo.png new file mode 100644 index 0000000..df89c1c Binary files /dev/null and b/assets/maps/sion/trees/platanus_acerifolia_v1_impostor_albedo.png differ diff --git a/assets/maps/sion/trees/platanus_acerifolia_v1_impostor_normal.png b/assets/maps/sion/trees/platanus_acerifolia_v1_impostor_normal.png new file mode 100644 index 0000000..a5711d9 Binary files /dev/null and b/assets/maps/sion/trees/platanus_acerifolia_v1_impostor_normal.png differ diff --git a/assets/maps/sion/trees/platanus_monumental_v0.glb b/assets/maps/sion/trees/platanus_monumental_v0.glb new file mode 100644 index 0000000..bc1de84 Binary files /dev/null and b/assets/maps/sion/trees/platanus_monumental_v0.glb differ diff --git a/assets/maps/sion/trees/platanus_monumental_v0_impostor_albedo.png b/assets/maps/sion/trees/platanus_monumental_v0_impostor_albedo.png new file mode 100644 index 0000000..ddc73c1 Binary files /dev/null and b/assets/maps/sion/trees/platanus_monumental_v0_impostor_albedo.png differ diff --git a/assets/maps/sion/trees/platanus_monumental_v0_impostor_normal.png b/assets/maps/sion/trees/platanus_monumental_v0_impostor_normal.png new file mode 100644 index 0000000..cae1a79 Binary files /dev/null and b/assets/maps/sion/trees/platanus_monumental_v0_impostor_normal.png differ diff --git a/assets/maps/sion/trees/populus_nigra_v0.glb b/assets/maps/sion/trees/populus_nigra_v0.glb new file mode 100644 index 0000000..6c26147 Binary files /dev/null and b/assets/maps/sion/trees/populus_nigra_v0.glb differ diff --git a/assets/maps/sion/trees/populus_nigra_v0_impostor_albedo.png b/assets/maps/sion/trees/populus_nigra_v0_impostor_albedo.png new file mode 100644 index 0000000..d5c14b1 Binary files /dev/null and b/assets/maps/sion/trees/populus_nigra_v0_impostor_albedo.png differ diff --git a/assets/maps/sion/trees/populus_nigra_v0_impostor_normal.png b/assets/maps/sion/trees/populus_nigra_v0_impostor_normal.png new file mode 100644 index 0000000..99ceb62 Binary files /dev/null and b/assets/maps/sion/trees/populus_nigra_v0_impostor_normal.png differ diff --git a/assets/maps/sion/trees/populus_nigra_v1.glb b/assets/maps/sion/trees/populus_nigra_v1.glb new file mode 100644 index 0000000..73d6a0d Binary files /dev/null and b/assets/maps/sion/trees/populus_nigra_v1.glb differ diff --git a/assets/maps/sion/trees/populus_nigra_v1_impostor_albedo.png b/assets/maps/sion/trees/populus_nigra_v1_impostor_albedo.png new file mode 100644 index 0000000..365df00 Binary files /dev/null and b/assets/maps/sion/trees/populus_nigra_v1_impostor_albedo.png differ diff --git a/assets/maps/sion/trees/populus_nigra_v1_impostor_normal.png b/assets/maps/sion/trees/populus_nigra_v1_impostor_normal.png new file mode 100644 index 0000000..6948584 Binary files /dev/null and b/assets/maps/sion/trees/populus_nigra_v1_impostor_normal.png differ diff --git a/assets/maps/sion/trees/quercus_pubescens_v0.glb b/assets/maps/sion/trees/quercus_pubescens_v0.glb new file mode 100644 index 0000000..f349f76 Binary files /dev/null and b/assets/maps/sion/trees/quercus_pubescens_v0.glb differ diff --git a/assets/maps/sion/trees/quercus_pubescens_v0_impostor_albedo.png b/assets/maps/sion/trees/quercus_pubescens_v0_impostor_albedo.png new file mode 100644 index 0000000..6164862 Binary files /dev/null and b/assets/maps/sion/trees/quercus_pubescens_v0_impostor_albedo.png differ diff --git a/assets/maps/sion/trees/quercus_pubescens_v0_impostor_normal.png b/assets/maps/sion/trees/quercus_pubescens_v0_impostor_normal.png new file mode 100644 index 0000000..1a515e2 Binary files /dev/null and b/assets/maps/sion/trees/quercus_pubescens_v0_impostor_normal.png differ diff --git a/assets/maps/sion/trees/quercus_pubescens_v1.glb b/assets/maps/sion/trees/quercus_pubescens_v1.glb new file mode 100644 index 0000000..49842e5 Binary files /dev/null and b/assets/maps/sion/trees/quercus_pubescens_v1.glb differ diff --git a/assets/maps/sion/trees/quercus_pubescens_v1_impostor_albedo.png b/assets/maps/sion/trees/quercus_pubescens_v1_impostor_albedo.png new file mode 100644 index 0000000..a298ed6 Binary files /dev/null and b/assets/maps/sion/trees/quercus_pubescens_v1_impostor_albedo.png differ diff --git a/assets/maps/sion/trees/quercus_pubescens_v1_impostor_normal.png b/assets/maps/sion/trees/quercus_pubescens_v1_impostor_normal.png new file mode 100644 index 0000000..ec24cde Binary files /dev/null and b/assets/maps/sion/trees/quercus_pubescens_v1_impostor_normal.png differ diff --git a/assets/maps/sion/trees/sequoiadendron_v0.glb b/assets/maps/sion/trees/sequoiadendron_v0.glb new file mode 100644 index 0000000..7725a1a Binary files /dev/null and b/assets/maps/sion/trees/sequoiadendron_v0.glb differ diff --git a/assets/maps/sion/trees/sequoiadendron_v0_impostor_albedo.png b/assets/maps/sion/trees/sequoiadendron_v0_impostor_albedo.png new file mode 100644 index 0000000..9a8668f Binary files /dev/null and b/assets/maps/sion/trees/sequoiadendron_v0_impostor_albedo.png differ diff --git a/assets/maps/sion/trees/sequoiadendron_v0_impostor_normal.png b/assets/maps/sion/trees/sequoiadendron_v0_impostor_normal.png new file mode 100644 index 0000000..57261e1 Binary files /dev/null and b/assets/maps/sion/trees/sequoiadendron_v0_impostor_normal.png differ diff --git a/assets/maps/sion/trees/textures/bark.png b/assets/maps/sion/trees/textures/bark.png new file mode 100644 index 0000000..1897798 Binary files /dev/null and b/assets/maps/sion/trees/textures/bark.png differ diff --git a/assets/maps/sion/trees/textures/branchlet_birch.png b/assets/maps/sion/trees/textures/branchlet_birch.png new file mode 100644 index 0000000..384144d Binary files /dev/null and b/assets/maps/sion/trees/textures/branchlet_birch.png differ diff --git a/assets/maps/sion/trees/textures/branchlet_broadleaf.png b/assets/maps/sion/trees/textures/branchlet_broadleaf.png new file mode 100644 index 0000000..652fb9a Binary files /dev/null and b/assets/maps/sion/trees/textures/branchlet_broadleaf.png differ diff --git a/assets/maps/sion/trees/textures/branchlet_oak.png b/assets/maps/sion/trees/textures/branchlet_oak.png new file mode 100644 index 0000000..249c9ff Binary files /dev/null and b/assets/maps/sion/trees/textures/branchlet_oak.png differ diff --git a/assets/maps/sion/trees/textures/branchlet_orchard.png b/assets/maps/sion/trees/textures/branchlet_orchard.png new file mode 100644 index 0000000..161c7c2 Binary files /dev/null and b/assets/maps/sion/trees/textures/branchlet_orchard.png differ diff --git a/assets/maps/sion/trees/textures/branchlet_pine.png b/assets/maps/sion/trees/textures/branchlet_pine.png new file mode 100644 index 0000000..87a02f8 Binary files /dev/null and b/assets/maps/sion/trees/textures/branchlet_pine.png differ diff --git a/assets/maps/sion/trees/textures/branchlet_spruce.png b/assets/maps/sion/trees/textures/branchlet_spruce.png new file mode 100644 index 0000000..ad0853d Binary files /dev/null and b/assets/maps/sion/trees/textures/branchlet_spruce.png differ diff --git a/assets/maps/sion/trees/trees_catalog.json b/assets/maps/sion/trees/trees_catalog.json new file mode 100644 index 0000000..630b437 --- /dev/null +++ b/assets/maps/sion/trees/trees_catalog.json @@ -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 +} \ No newline at end of file diff --git a/assets/maps/sion/trees_sion.bin b/assets/maps/sion/trees_sion.bin new file mode 100644 index 0000000..76f40fb Binary files /dev/null and b/assets/maps/sion/trees_sion.bin differ diff --git a/client/ArenaRenderer.cs b/client/ArenaRenderer.cs index e7d6e46..61ebc42 100644 --- a/client/ArenaRenderer.cs +++ b/client/ArenaRenderer.cs @@ -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 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); diff --git a/client/FoliageRenderer.cs b/client/FoliageRenderer.cs new file mode 100644 index 0000000..40a2ea4 --- /dev/null +++ b/client/FoliageRenderer.cs @@ -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; + +/// +/// 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 rtd_flow_field. +/// +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 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 _archetypes = new(17); + private readonly int[,] _archetypeLookup = new int[10, 2]; + private readonly Dictionary _textureCache = new(StringComparer.OrdinalIgnoreCase); + private Shader _leavesShader = null!; + private Shader _barkShader = null!; + private Shader _impostorShader = null!; + + private SionTreeCatalog? _boundCatalog; + private PrecomputedTree[] _precomputed = Array.Empty(); + 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("res://tree_leaves.gdshader") + ?? throw new InvalidOperationException("Missing res://tree_leaves.gdshader"); + _barkShader = GD.Load("res://tree_bark.gdshader") + ?? throw new InvalidOperationException("Missing res://tree_bark.gdshader"); + _impostorShader = GD.Load("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(); + 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(); + } + } +} diff --git a/client/Main.cs b/client/Main.cs index 50be061..ef7f1dd 100644 --- a/client/Main.cs +++ b/client/Main.cs @@ -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; diff --git a/client/ParticlePool.cs b/client/ParticlePool.cs index ca2bce3..6c0c823 100644 --- a/client/ParticlePool.cs +++ b/client/ParticlePool.cs @@ -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(); diff --git a/client/tests/Smoke.cs b/client/tests/Smoke.cs index bde0dc5..136b5fc 100644 --- a/client/tests/Smoke.cs +++ b/client/tests/Smoke.cs @@ -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() diff --git a/client/tree_bark.gdshader b/client/tree_bark.gdshader new file mode 100644 index 0000000..d069aef --- /dev/null +++ b/client/tree_bark.gdshader @@ -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; +} diff --git a/client/tree_impostor.gdshader b/client/tree_impostor.gdshader new file mode 100644 index 0000000..329de6c --- /dev/null +++ b/client/tree_impostor.gdshader @@ -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; +} diff --git a/client/tree_leaves.gdshader b/client/tree_leaves.gdshader new file mode 100644 index 0000000..3046439 --- /dev/null +++ b/client/tree_leaves.gdshader @@ -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; +} diff --git a/src/RustToDust.Core/ArenaScarLedger.cs b/src/RustToDust.Core/ArenaScarLedger.cs index d57d041..f7d79b5 100644 --- a/src/RustToDust.Core/ArenaScarLedger.cs +++ b/src/RustToDust.Core/ArenaScarLedger.cs @@ -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(); diff --git a/src/RustToDust.Core/MatchState.cs b/src/RustToDust.Core/MatchState.cs index 1b1ef5e..026e8f1 100644 --- a/src/RustToDust.Core/MatchState.cs +++ b/src/RustToDust.Core/MatchState.cs @@ -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 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(); } diff --git a/src/RustToDust.Core/SimEvents.cs b/src/RustToDust.Core/SimEvents.cs index ef9fe75..980a2df 100644 --- a/src/RustToDust.Core/SimEvents.cs +++ b/src/RustToDust.Core/SimEvents.cs @@ -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 { diff --git a/src/RustToDust.Core/SionMapLoader.cs b/src/RustToDust.Core/SionMapLoader.cs index 6b01875..30a32e6 100644 --- a/src/RustToDust.Core/SionMapLoader.cs +++ b/src/RustToDust.Core/SionMapLoader.cs @@ -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 Buildings => _buildings; public IReadOnlyList 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; diff --git a/src/RustToDust.Core/SionTreeField.cs b/src/RustToDust.Core/SionTreeField.cs new file mode 100644 index 0000000..996a56a --- /dev/null +++ b/src/RustToDust.Core/SionTreeField.cs @@ -0,0 +1,513 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.IO; +using System.Numerics; + +namespace RustToDust.Core +{ + /// + /// Canonical Sion tree species presets (0..9). Wild beech (Fagus sylvatica) is intentionally excluded. + /// + public enum SionTreeSpecies : byte + { + PinusSylvestris = 0, + QuercusPubescens = 1, + PopulusNigra = 2, + PlatanusAcerifolia = 3, + BetulaPendula = 4, + PiceaAbies = 5, + MalusOrchard = 6, + Sequoiadendron = 7, + Cedrus = 8, + PlatanusMonumental = 9 + } + + /// + /// Packed 2-bit runtime state per tree instance. + /// + 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()); + + public SionTreeCatalog(SionTreePlacement[] trees) + { + _trees = trees ?? throw new ArgumentNullException(nameof(trees)); + var buckets = new List[TileCount]; + for (int i = 0; i < TileCount; i++) + { + buckets[i] = new List(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 Trees => _trees; + public ReadOnlySpan AsSpan() => _trees; + + public ReadOnlySpan GetTileTreeIndices(int tx, int tz) + { + if ((uint)tx >= TileGrid || (uint)tz >= TileGrid) + { + return ReadOnlySpan.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 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); + } + } + + /// + /// Authoritative match-lifetime destruction state for Sion trees (2 bits/tree, ~1.6 KiB). + /// + 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 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 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? 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 trees = _catalog.AsSpan(); + int changed = 0; + + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + ReadOnlySpan 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? 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 trees = _catalog.AsSpan(); + int changed = 0; + + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + ReadOnlySpan 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 outVerts, List outIndices) + { + outVerts.Clear(); + outIndices.Clear(); + + ReadOnlySpan indices = _catalog.GetTileTreeIndices(tx, tz); + if (indices.IsEmpty) + { + return false; + } + + ReadOnlySpan 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); + } + } +} diff --git a/src/RustToDust.Net/RemoteArenaSession.cs b/src/RustToDust.Net/RemoteArenaSession.cs index 4c1236d..f03c074 100644 --- a/src/RustToDust.Net/RemoteArenaSession.cs +++ b/src/RustToDust.Net/RemoteArenaSession.cs @@ -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( diff --git a/src/RustToDust.Net/ServerMatchHost.cs b/src/RustToDust.Net/ServerMatchHost.cs index 4d7674f..e7c0bf0 100644 --- a/src/RustToDust.Net/ServerMatchHost.cs +++ b/src/RustToDust.Net/ServerMatchHost.cs @@ -35,6 +35,7 @@ namespace RustToDust.Net public readonly HashSet SentOrdnanceIds = new(); public readonly HashSet SentTerrainStampIndices = new(); public readonly int[,] SentTileVersions = new int[16, 16]; + public readonly Dictionary SentTreeStates = new(); } private struct EntityPvsTracker @@ -55,6 +56,8 @@ namespace RustToDust.Net private readonly List _hostPendingEvents = new(); private readonly List _terrainStampHistory = new(); private readonly List[,] _tileStampHistory = new List[16, 16]; + private readonly Dictionary _treeChangeHistory = new(); + private readonly HashSet[,] _tileTreeChanges = new HashSet[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(4); + _tileTreeChanges[tx, tz] = new HashSet(); } } @@ -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 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)) diff --git a/src/RustToDust.Ymir/ArenaSession.cs b/src/RustToDust.Ymir/ArenaSession.cs index 1862b8f..7785600 100644 --- a/src/RustToDust.Ymir/ArenaSession.cs +++ b/src/RustToDust.Ymir/ArenaSession.cs @@ -32,6 +32,7 @@ namespace RustToDust.Ymir private readonly bool[,] _contenderPvs = new bool[MatchState.ContenderCount, MatchState.ContenderCount]; private readonly bool[,] _spectatorPvs; private readonly List _stepEvents = new(); + private readonly List _treeEventsScratch = new(16); private readonly List _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 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 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, diff --git a/src/RustToDust.Ymir/Box3DPhysicsTileSync.cs b/src/RustToDust.Ymir/Box3DPhysicsTileSync.cs index c85f5de..4b5f7e8 100644 --- a/src/RustToDust.Ymir/Box3DPhysicsTileSync.cs +++ b/src/RustToDust.Ymir/Box3DPhysicsTileSync.cs @@ -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 _scratchTreeVerts = new(512); + private readonly List _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 needed, + ReadOnlySpan 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 needed, float worldX, float worldZ, int halfTileRadius) { if (!terrain.IsHeightmapMode) diff --git a/src/RustToDust.Ymir/OrdnanceRuntime.cs b/src/RustToDust.Ymir/OrdnanceRuntime.cs index 643ca4c..3841caa 100644 --- a/src/RustToDust.Ymir/OrdnanceRuntime.cs +++ b/src/RustToDust.Ymir/OrdnanceRuntime.cs @@ -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, diff --git a/tests/RustToDust.Tests/HybridBWalkerTests.cs b/tests/RustToDust.Tests/HybridBWalkerTests.cs index 9099c55..1b30814 100644 --- a/tests/RustToDust.Tests/HybridBWalkerTests.cs +++ b/tests/RustToDust.Tests/HybridBWalkerTests.cs @@ -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)) diff --git a/tests/RustToDust.Tests/SionMapTests.cs b/tests/RustToDust.Tests/SionMapTests.cs index 0395045..df3bdc5 100644 --- a/tests/RustToDust.Tests/SionMapTests.cs +++ b/tests/RustToDust.Tests/SionMapTests.cs @@ -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) diff --git a/tests/RustToDust.Tests/SionTreeTests.cs b/tests/RustToDust.Tests/SionTreeTests.cs new file mode 100644 index 0000000..039b3ca --- /dev/null +++ b/tests/RustToDust.Tests/SionTreeTests.cs @@ -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(); + 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(); + // 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)); + } + } +} diff --git a/third_party/cosmo_tree_gen/.editorconfig b/third_party/cosmo_tree_gen/.editorconfig new file mode 100644 index 0000000..f28239b --- /dev/null +++ b/third_party/cosmo_tree_gen/.editorconfig @@ -0,0 +1,4 @@ +root = true + +[*] +charset = utf-8 diff --git a/third_party/cosmo_tree_gen/.gitattributes b/third_party/cosmo_tree_gen/.gitattributes new file mode 100644 index 0000000..30214b9 --- /dev/null +++ b/third_party/cosmo_tree_gen/.gitattributes @@ -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 diff --git a/third_party/cosmo_tree_gen/.gitignore b/third_party/cosmo_tree_gen/.gitignore new file mode 100644 index 0000000..1ed3aa3 --- /dev/null +++ b/third_party/cosmo_tree_gen/.gitignore @@ -0,0 +1,7 @@ +releases/ +test/ +exports/ + +# Godot 4+ specific ignores +.godot/ +/android/ diff --git a/third_party/cosmo_tree_gen/LICENSE.md b/third_party/cosmo_tree_gen/LICENSE.md new file mode 100644 index 0000000..ccc6397 --- /dev/null +++ b/third_party/cosmo_tree_gen/LICENSE.md @@ -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. diff --git a/third_party/cosmo_tree_gen/README.md b/third_party/cosmo_tree_gen/README.md new file mode 100644 index 0000000..c85e418 --- /dev/null +++ b/third_party/cosmo_tree_gen/README.md @@ -0,0 +1,110 @@ +![Cosmo Tree Gen](.github/images/render-logo.png) + +# 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 | +| :------------------------: | :---------------: | +| ![presets](.github/images/example_presets.gif) | ![seed](.github/images/example_lean_wobble_seed.gif) | +| **Live generation** | **Curve editor for fine changes** | +| ![livegen](.github/images/example_leaf_size.gif) | ![curves](.github/images/example_curve.gif) | + +[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 +
+Code, assets and references + +**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) + +
+ +## LICENSE +Released under the [MIT License](LICENSE.md). diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/LICENSE.md b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/LICENSE.md new file mode 100644 index 0000000..ccc6397 --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/LICENSE.md @@ -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. diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/branch.gd b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/branch.gd new file mode 100644 index 0000000..16b492b --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/branch.gd @@ -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 diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/branch_gen.gd b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/branch_gen.gd new file mode 100644 index 0000000..02c9a6b --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/branch_gen.gd @@ -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 diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/collision_gen.gd b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/collision_gen.gd new file mode 100644 index 0000000..7d781d2 --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/collision_gen.gd @@ -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 diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/cosmo_tree_gen.gd b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/cosmo_tree_gen.gd new file mode 100644 index 0000000..3a5f691 --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/cosmo_tree_gen.gd @@ -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) diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/exporter.gd b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/exporter.gd new file mode 100644 index 0000000..ab94bf8 --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/exporter.gd @@ -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 diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/foliage_gen.gd b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/foliage_gen.gd new file mode 100644 index 0000000..9228ab7 --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/foliage_gen.gd @@ -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 diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/impostor_gen.gd b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/impostor_gen.gd new file mode 100644 index 0000000..25f013d --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/impostor_gen.gd @@ -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 diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/lod_post_import.gd b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/lod_post_import.gd new file mode 100644 index 0000000..19e881f --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/lod_post_import.gd @@ -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 diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/mesh_utils.gd b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/mesh_utils.gd new file mode 100644 index 0000000..79859df --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/mesh_utils.gd @@ -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 diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/settings.gd b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/settings.gd new file mode 100644 index 0000000..a0fce49 --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/settings.gd @@ -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 diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/tree_builder.gd b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/tree_builder.gd new file mode 100644 index 0000000..6edfdbd --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/tree_builder.gd @@ -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() diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/trunk_gen.gd b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/trunk_gen.gd new file mode 100644 index 0000000..b4f99cb --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/core/trunk_gen.gd @@ -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 diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/materials/bark.tres b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/materials/bark.tres new file mode 100644 index 0000000..ad63939 --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/materials/bark.tres @@ -0,0 +1,7 @@ +[gd_resource type="StandardMaterial3D" format=3 uid="uid://b7l8vw0qq0s25"] + +[ext_resource type="Texture2D" uid="uid://nf32p1bdtv1w" path="res://addons/cosmo_tree_gen/textures/bark.png" id="1_xwgn2"] + +[resource] +albedo_texture = ExtResource("1_xwgn2") +texture_filter = 0 diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/materials/foliage.tres b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/materials/foliage.tres new file mode 100644 index 0000000..a79dc7d --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/materials/foliage.tres @@ -0,0 +1,8 @@ +[gd_resource type="StandardMaterial3D" format=3 uid="uid://1aem886fag5n"] + +[ext_resource type="Texture2D" uid="uid://bxs6plxpy6inu" path="res://addons/cosmo_tree_gen/textures/foliage.png" id="1_dnet8"] + +[resource] +albedo_texture = ExtResource("1_dnet8") +uv1_triplanar = true +texture_filter = 0 diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/materials/leaves_01.tres b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/materials/leaves_01.tres new file mode 100644 index 0000000..eac19b7 --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/materials/leaves_01.tres @@ -0,0 +1,17 @@ +[gd_resource type="ShaderMaterial" format=3 uid="uid://deodinjmuohgl"] + +[ext_resource type="Shader" uid="uid://bfq8ep8l8jqps" path="res://addons/cosmo_tree_gen/shaders/leaves.gdshader" id="1_leaves"] +[ext_resource type="Texture2D" uid="uid://kyqnw7mku6c7" path="res://addons/cosmo_tree_gen/textures/branchlet_01.png" id="1_xmixh"] + +[resource] +render_priority = 0 +shader = ExtResource("1_leaves") +shader_parameter/albedo = Color(1, 1, 1, 1) +shader_parameter/albedo_texture = ExtResource("1_xmixh") +shader_parameter/alpha_scissor_threshold = 0.5 +shader_parameter/backlight = Color(0.45, 0.5, 0.25, 1) +shader_parameter/ao_light_affect = 0.5 +shader_parameter/wind_direction = Vector3(1, 0, 0.3) +shader_parameter/wind_strength = 0.1 +shader_parameter/wind_speed = 1.0 +shader_parameter/wind_phase_scale = 2.0 diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/materials/leaves_03.tres b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/materials/leaves_03.tres new file mode 100644 index 0000000..a6d2721 --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/materials/leaves_03.tres @@ -0,0 +1,17 @@ +[gd_resource type="ShaderMaterial" format=3 uid="uid://dm5as0s5uoju2"] + +[ext_resource type="Texture2D" uid="uid://ckrflybo5tdwk" path="res://addons/cosmo_tree_gen/textures/branchlet_03.png" id="1_gli6v"] +[ext_resource type="Shader" uid="uid://bfq8ep8l8jqps" path="res://addons/cosmo_tree_gen/shaders/leaves.gdshader" id="1_leaves"] + +[resource] +render_priority = 0 +shader = ExtResource("1_leaves") +shader_parameter/albedo = Color(1, 1, 1, 1) +shader_parameter/albedo_texture = ExtResource("1_gli6v") +shader_parameter/alpha_scissor_threshold = 0.5 +shader_parameter/backlight = Color(0.45, 0.5, 0.25, 1) +shader_parameter/ao_light_affect = 0.5 +shader_parameter/wind_direction = Vector3(1, 0, 0.3) +shader_parameter/wind_strength = 0.1 +shader_parameter/wind_speed = 1.0 +shader_parameter/wind_phase_scale = 2.0 diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/plugin.cfg b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/plugin.cfg new file mode 100644 index 0000000..c2efb47 --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/plugin.cfg @@ -0,0 +1,7 @@ +[plugin] + +name="Cosmo Tree Gen" +description="Procedural tree generator with live editing, presets, LODs, collisions and glb/glTF export." +author="CosmonautFrog" +version="1.1.1" +script="plugin.gd" diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/plugin.gd b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/plugin.gd new file mode 100644 index 0000000..2192837 --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/plugin.gd @@ -0,0 +1,36 @@ +# Copyright © 2026 CosmonautFrog - MIT License + +@tool +extends EditorPlugin + +const Settings := preload("./core/settings.gd") +const TreeGenBar := preload("./ui/tree_gen_bar.gd") +const BAR_SCENE := preload("./ui/tree_gen_bar.tscn") + +var _bar: TreeGenBar + + +func _enter_tree() -> void: + Settings.setup_settings() + _bar = BAR_SCENE.instantiate() + _bar.hide() + add_control_to_container(CONTAINER_SPATIAL_EDITOR_MENU, _bar) + + +func _exit_tree() -> void: + _edit(null) + remove_control_from_container(CONTAINER_SPATIAL_EDITOR_MENU, _bar) + _bar.queue_free() + _bar = null + + +func _handles(object: Object) -> bool: + return object is CosmoTreeGen + + +func _edit(object: Object) -> void: + _bar.tree = object as CosmoTreeGen + + +func _make_visible(visible: bool) -> void: + _bar.visible = visible diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/presets/ash.tres b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/presets/ash.tres new file mode 100644 index 0000000..6b80ccc --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/presets/ash.tres @@ -0,0 +1,87 @@ +[gd_resource type="Resource" script_class="CosmoTreePreset" format=3 uid="uid://dud0uolkbfkt"] + +[ext_resource type="Script" uid="uid://ceh6ii6tlpph4" path="res://addons/cosmo_tree_gen/resources/branch_level.gd" id="1_4oi1l"] +[ext_resource type="Material" uid="uid://deodinjmuohgl" path="res://addons/cosmo_tree_gen/materials/leaves_01.tres" id="2_rc8rs"] +[ext_resource type="Script" uid="uid://1tt4by0vsl04" path="res://addons/cosmo_tree_gen/resources/foliage_params.gd" id="3_rdbt1"] +[ext_resource type="Script" uid="uid://dlp11kr4f76j3" path="res://addons/cosmo_tree_gen/resources/preset.gd" id="4_vg5cv"] +[ext_resource type="Material" uid="uid://b7l8vw0qq0s25" path="res://addons/cosmo_tree_gen/materials/bark.tres" id="5_8lw70"] +[ext_resource type="Script" uid="uid://c0ggn4wsaa746" path="res://addons/cosmo_tree_gen/resources/trunk_params.gd" id="6_iagn2"] + +[sub_resource type="Resource" id="Resource_mj7pe"] +script = ExtResource("1_4oi1l") +count = 7 +terminal = true +start = 0.382 +end = 0.92 +angle = 52.0 +length = 0.5 +radius = 0.65 +gnarl = 0.25 +up_force = 0.2 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_t8a6q"] +script = ExtResource("1_4oi1l") +count = 4 +terminal = true +start = 0.048 +end = 1.0 +angle = 45.0 +length = 0.406 +segments = 2 +gnarl = 0.4 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_5eeob"] +script = ExtResource("1_4oi1l") +count = 3 +terminal = true +start = 0.121 +end = 0.94 +length = 0.487 +segments = 1 +up_force = 0.4 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_qu3ut"] +script = ExtResource("3_rdbt1") +type = 2 +leaf_count = 4 +leaf_tip = true +leaf_size = 0.54 +leaf_size_variance = 0.25 +leaf_start = 0.2 +leaf_angle = 55.0 +metadata/_custom_type_script = "uid://1tt4by0vsl04" + +[sub_resource type="Resource" id="Resource_tdg64"] +script = ExtResource("1_4oi1l") +start = 0.0 +end = 0.03 +angle = 90.0 +length = 0.271 +segments = 5 +gnarl = 1.2 +up_force = -0.8370000000000002 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_fy1p0"] +script = ExtResource("6_iagn2") +height = 5.5 +radius_bottom = 0.28 +radius_top = 0.04 +lean = 0.3 +flare = 0.7 +flare_height = 0.32 +flare_lobes = 1.0 +sink_depth = 0.14 +roots = SubResource("Resource_tdg64") +metadata/_custom_type_script = "uid://c0ggn4wsaa746" + +[resource] +script = ExtResource("4_vg5cv") +trunk_params = SubResource("Resource_fy1p0") +branch_levels = Array[ExtResource("1_4oi1l")]([SubResource("Resource_mj7pe"), SubResource("Resource_t8a6q"), SubResource("Resource_5eeob")]) +foliage_params = SubResource("Resource_qu3ut") +trunk_material = ExtResource("5_8lw70") +foliage_material = ExtResource("2_rc8rs") diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/presets/bush.tres b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/presets/bush.tres new file mode 100644 index 0000000..a28d13d --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/presets/bush.tres @@ -0,0 +1,46 @@ +[gd_resource type="Resource" script_class="CosmoTreePreset" format=3 uid="uid://cqld5e81q5y3w"] + +[ext_resource type="Script" uid="uid://ceh6ii6tlpph4" path="res://addons/cosmo_tree_gen/resources/branch_level.gd" id="1_vfn74"] +[ext_resource type="Material" uid="uid://dm5as0s5uoju2" path="res://addons/cosmo_tree_gen/materials/leaves_03.tres" id="2_3axs3"] +[ext_resource type="Script" uid="uid://1tt4by0vsl04" path="res://addons/cosmo_tree_gen/resources/foliage_params.gd" id="3_stjel"] +[ext_resource type="Script" uid="uid://dlp11kr4f76j3" path="res://addons/cosmo_tree_gen/resources/preset.gd" id="4_n3p2f"] +[ext_resource type="Material" uid="uid://b7l8vw0qq0s25" path="res://addons/cosmo_tree_gen/materials/bark.tres" id="5_xf0ly"] +[ext_resource type="Script" uid="uid://c0ggn4wsaa746" path="res://addons/cosmo_tree_gen/resources/trunk_params.gd" id="6_7jv1x"] + +[sub_resource type="Resource" id="Resource_k1rqu"] +script = ExtResource("1_vfn74") +count = 10 +start = 0.0 +end = 1.0 +angle = 52.844 +length = 0.461 +radius = 1.0 +segments = 1 +gnarl = 0.0 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_wwhtr"] +script = ExtResource("3_stjel") +type = 2 +leaf_count = 14 +leaf_size = 0.76 +leaf_size_variance = 0.322 +leaf_start = 0.0 +leaf_inner_ao = 0.0 + +[sub_resource type="Resource" id="Resource_d1m6b"] +script = ExtResource("6_7jv1x") +height = 0.2 +radius_bottom = 0.04 +radius_top = 0.0 +lean = 0.0 +wobble = 0.0 + +[resource] +script = ExtResource("4_n3p2f") +trunk_params = SubResource("Resource_d1m6b") +branch_levels = Array[ExtResource("1_vfn74")]([SubResource("Resource_k1rqu")]) +foliage_params = SubResource("Resource_wwhtr") +trunk_material = ExtResource("5_xf0ly") +foliage_material = ExtResource("2_3axs3") +create_trunk = false diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/presets/low_poly_bush.tres b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/presets/low_poly_bush.tres new file mode 100644 index 0000000..5216328 --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/presets/low_poly_bush.tres @@ -0,0 +1,44 @@ +[gd_resource type="Resource" script_class="CosmoTreePreset" format=3 uid="uid://ckkd0847sg0q0"] + +[ext_resource type="Script" uid="uid://ceh6ii6tlpph4" path="res://addons/cosmo_tree_gen/resources/branch_level.gd" id="1_2h2pl"] +[ext_resource type="Material" uid="uid://1aem886fag5n" path="res://addons/cosmo_tree_gen/materials/foliage.tres" id="2_x34a3"] +[ext_resource type="Script" uid="uid://1tt4by0vsl04" path="res://addons/cosmo_tree_gen/resources/foliage_params.gd" id="3_p0oq0"] +[ext_resource type="Script" uid="uid://dlp11kr4f76j3" path="res://addons/cosmo_tree_gen/resources/preset.gd" id="4_v4tum"] +[ext_resource type="Material" uid="uid://b7l8vw0qq0s25" path="res://addons/cosmo_tree_gen/materials/bark.tres" id="5_83h8x"] +[ext_resource type="Script" uid="uid://c0ggn4wsaa746" path="res://addons/cosmo_tree_gen/resources/trunk_params.gd" id="6_7iop2"] + +[sub_resource type="Resource" id="Resource_febos"] +script = ExtResource("1_2h2pl") +count = 2 +start = 0.372 +end = 1.0 +angle = 90.0 +length = 1.0 +radius = 1.0 +segments = 1 +gnarl = 0.419 +up_force = 0.31700000000000017 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_usong"] +script = ExtResource("3_p0oq0") +icosphere_radius = 0.49 +icosphere_amplitude = 0.6 + +[sub_resource type="Resource" id="Resource_niwkb"] +script = ExtResource("6_7iop2") +height = 0.4 +radius_bottom = 0.01 +radius_top = 0.0 +lean = 0.0 +wobble = 0.0 + +[resource] +script = ExtResource("4_v4tum") +trunk_params = SubResource("Resource_niwkb") +branch_levels = Array[ExtResource("1_2h2pl")]([SubResource("Resource_febos")]) +foliage_params = SubResource("Resource_usong") +trunk_material = ExtResource("5_83h8x") +foliage_material = ExtResource("2_x34a3") +flat_shading = true +create_trunk = false diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/presets/low_poly_tree.tres b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/presets/low_poly_tree.tres new file mode 100644 index 0000000..2bfbe1a --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/presets/low_poly_tree.tres @@ -0,0 +1,43 @@ +[gd_resource type="Resource" script_class="CosmoTreePreset" format=3 uid="uid://ddhojh1gv28ob"] + +[ext_resource type="Script" uid="uid://ceh6ii6tlpph4" path="res://addons/cosmo_tree_gen/resources/branch_level.gd" id="1_yf14m"] +[ext_resource type="Material" uid="uid://1aem886fag5n" path="res://addons/cosmo_tree_gen/materials/foliage.tres" id="2_3i66d"] +[ext_resource type="Script" uid="uid://1tt4by0vsl04" path="res://addons/cosmo_tree_gen/resources/foliage_params.gd" id="3_qws1h"] +[ext_resource type="Script" uid="uid://dlp11kr4f76j3" path="res://addons/cosmo_tree_gen/resources/preset.gd" id="4_5ww4r"] +[ext_resource type="Material" uid="uid://b7l8vw0qq0s25" path="res://addons/cosmo_tree_gen/materials/bark.tres" id="5_q10pc"] +[ext_resource type="Script" uid="uid://c0ggn4wsaa746" path="res://addons/cosmo_tree_gen/resources/trunk_params.gd" id="6_nxivb"] + +[sub_resource type="Resource" id="Resource_f73r4"] +script = ExtResource("1_yf14m") +count = 5 +start = 0.373 +end = 0.726 +angle = 59.082 +length = 0.235 +radius = 0.8099999999999999 +segments = 2 +gnarl = 0.055 +up_force = 0.18500000000000005 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_hycpn"] +script = ExtResource("3_qws1h") +icosphere_subdivisions = 2 +icosphere_amplitude = 0.42 +icosphere_frequency = 1.92 + +[sub_resource type="Resource" id="Resource_5t1n4"] +script = ExtResource("6_nxivb") +height = 6.0 +radius_bottom = 0.25 +lean = 0.644 +wobble = 0.244 +metadata/_custom_type_script = "uid://c0ggn4wsaa746" + +[resource] +script = ExtResource("4_5ww4r") +trunk_params = SubResource("Resource_5t1n4") +branch_levels = Array[ExtResource("1_yf14m")]([SubResource("Resource_f73r4")]) +foliage_params = SubResource("Resource_hycpn") +trunk_material = ExtResource("5_q10pc") +foliage_material = ExtResource("2_3i66d") diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/resources/branch_level.gd b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/resources/branch_level.gd new file mode 100644 index 0000000..56f2e83 --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/resources/branch_level.gd @@ -0,0 +1,78 @@ +# Copyright © 2026 CosmonautFrog - MIT License + +@tool +class_name CosmoBranchLevel +extends Resource +## A level of branches of a [CosmoTreeGen], grown from every branch of the previous level, +## or from the trunks for the first one. + +## Branches grown from each parent branch, spread around it between [member start] and [member end]. +@export_range(0, 60, 1, "or_greater") var count: int = 6: + set(value): + count = value + emit_changed() +## Grows one more branch from the tip of each parent, with its direction and radius, +## meshed as a single tube with it. [br][br] +## Use it to continue the trunk or the branches past the child branches. It isn't counted in [member count]. +@export var terminal: bool = false: + set(value): + terminal = value + emit_changed() +## Where the branches start along the parent, 0 is its base and 1 its tip. +@export_range(0.0, 1.0) var start: float = 0.4: + set(value): + start = value + emit_changed() +## Where the branches end along the parent, 0 is its base and 1 its tip. +@export_range(0.0, 1.0) var end: float = 0.9: + set(value): + end = value + emit_changed() +## Angle between the branches and their parent, in degrees. 0 grows them along the parent, 90 perpendicular. +@export_range(0.0, 90.0, 0.5, "or_greater") var angle: float = 50.0: + set(value): + angle = value + emit_changed() +## Length of the branches, as a fraction of their parent's length. +@export_range(0.05, 1.0) var length: float = 0.4: + set(value): + length = value + emit_changed() +## Multiplies [member length] by the curve value where each branch grows on the parent (0 base, 1 tip). [br][br] +## For example, a curve going down makes a conical, pine-like shape. Branches where it's 0 aren't grown. +@export var length_curve: Curve: + set(value): + if length_curve != null: + length_curve.changed.disconnect(emit_changed) + length_curve = value + if length_curve != null: + length_curve.changed.connect(emit_changed) + emit_changed() +## Radius of the branches at their base, as a fraction of the parent radius where they grow. [br][br] +## Branches taper to 20% of it at the tip. Terminal branches keep the parent radius instead. +@export_range(0.05, 0.8, 0.05) var radius: float = 0.6: + set(value): + radius = value + emit_changed() +## Segments per branch. More segments make smoother bends with [member gnarl] and [member up_force]. [br][br] +## With Multiple Convex collision, each segment is a collision shape. +@export_range(1, 8) var segments: int = 3: + set(value): + segments = value + emit_changed() +## Random bending of the branches. 0 keeps them straight. +@export_range(0.0, 2.0, 0.01, "or_greater") var gnarl: float = 0.3: + set(value): + gnarl = value + emit_changed() +## Bends the branches up when positive, or down when negative, like a willow. [br][br] +## Broken branches always bend down. See [member broken_chance]. +@export_range(-4.0, 4.0, 0.01, "or_greater", "or_less") var up_force: float = 0.5: + set(value): + up_force = value + emit_changed() +## Chance for each branch to be broken: shorter, bent down, and without child branches or foliage. +@export_range(0.0, 1.0) var broken_chance: float = 0.0: + set(value): + broken_chance = value + emit_changed() diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/resources/foliage_params.gd b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/resources/foliage_params.gd new file mode 100644 index 0000000..1e94d9d --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/resources/foliage_params.gd @@ -0,0 +1,163 @@ +# Copyright © 2026 CosmonautFrog - MIT License + +@tool +class_name CosmoFoliageParams +extends Resource +## Foliage of a [CosmoTreeGen]: icospheres or leaf cards on the branches of the last level. + +const MeshUtils := preload("../core/mesh_utils.gd") + +enum Type { + ## No foliage. + NONE, + ## One noisy icosphere at the tip of each branch of the last level, and at the top of each trunk. + ## Needs a material with UV1 Triplanar. + ICOSPHERES, + ## Textured cards along the branches of the last level. + LEAVES, +} + +## Foliage type. +@export var type: Type = Type.ICOSPHERES: + set(value): + type = value + notify_property_list_changed() + emit_changed() + +#region ICOSPHERES +## How much the branch length scales the icospheres. [br][br] +## 0 gives them all [member icosphere_radius], 1 scales it by the branch length relative to the trunk. +@export_range(0.0, 1.0) var icosphere_length_influence: float = 0.4: + set(value): + icosphere_length_influence = value + emit_changed() +## Radius of the icospheres, in meters, before [member icosphere_length_influence]. +@export_range(0.1, 5.0, 0.01, "suffix:m", "or_greater") var icosphere_radius: float = 1.0: + set(value): + icosphere_radius = value + emit_changed() +## Detail of the icospheres, each level has 4 times the triangles: 20, 80, 320, 1280 and 5120 per icosphere. +@export_range(0, 4, 1, "or_greater") var icosphere_subdivisions: int = 1: + set(value): + icosphere_subdivisions = value + emit_changed() +## How much the noise deforms the icospheres, as a fraction of their radius. 0 keeps them round. +@export_range(0.0, 0.6, 0.01, "or_greater") var icosphere_amplitude: float = 0.4: + set(value): + icosphere_amplitude = value + emit_changed() +## Frequency of the deformation noise. Higher values make more and smaller bumps. +@export_range(0.1, 10.0, 0.1, "or_greater") var icosphere_frequency: float = 1.5: + set(value): + icosphere_frequency = value + emit_changed() +#endregion + + +#region LEAVES +## Leaves per branch, spread from [member leaf_start] to the tip. [br][br] +## With [member leaf_double], each leaf is 2 cards. +@export_range(1, 50, 1, "or_greater") var leaf_count: int = 12: + set(value): + leaf_count = value + emit_changed() +## Adds one more leaf at the tip of each branch, pointing along it. +@export var leaf_tip: bool = false: + set(value): + leaf_tip = value + emit_changed() +## Height of the leaf cards, in meters, before [member leaf_size_variance], [member leaf_size_curve] +## and [member leaf_length_influence]. +@export_range(0.05, 3.0, 0.01, "suffix:m", "or_greater") var leaf_size: float = 0.6: + set(value): + leaf_size = value + emit_changed() +## Width / height of the leaf cards, their height is [member leaf_size]. [br][br] +## 0 takes it from the albedo texture of the foliage material, or square if it has none. +@export_range(0.0, 4.0, 0.01, "or_greater") var leaf_aspect: float = 0.0: + set(value): + leaf_aspect = value + emit_changed() +## Multiplies [member leaf_size] by the curve value where each leaf grows on the branch (0 base, 1 tip). +## Leaves where it's 0 are skipped. +@export var leaf_size_curve: Curve: + set(value): + if leaf_size_curve != null: + leaf_size_curve.changed.disconnect(emit_changed) + leaf_size_curve = value + if leaf_size_curve != null: + leaf_size_curve.changed.connect(emit_changed) + emit_changed() +## How much the branch length scales the leaves. [br][br] +## 0 gives them all the same size, 1 scales them by the branch length relative to the longest branch. +@export_range(0.0, 1.0) var leaf_length_influence: float = 0.0: + set(value): + leaf_length_influence = value + emit_changed() +## Random size variation of each leaf, 0.3 is +-30%. +@export_range(0.0, 0.9) var leaf_size_variance: float = 0.3: + set(value): + leaf_size_variance = value + emit_changed() +## Where the leaves start along the branch, 0 is its base and 1 its tip. +@export_range(0.0, 1.0) var leaf_start: float = 0.3: + set(value): + leaf_start = value + emit_changed() +## Offset applied to each leaf's position relative to its attachment point. +@export var leaf_position_offset: Vector3 = Vector3.ZERO: + set(value): + leaf_position_offset = value + emit_changed() +## Angle between the leaf cards and the branch, in degrees. 0 points them along the branch, 90 perpendicular. +@export_range(0.0, 90.0, 0.05, "degrees") var leaf_angle: float = 40.0: + set(value): + leaf_angle = value + emit_changed() +## How strong leaves are tilted toward the down direction. +## 0 keeps the generated orientation, 1 points them full down. +@export_range(0.0, 1.0) var leaf_gravity: float = 0.0: + set(value): + leaf_gravity = value + emit_changed() +## Adds a second card to each leaf, crossed at 90°, so they don't look flat from the side. +## Doubles the foliage triangles. +@export var leaf_double: bool = true: + set(value): + leaf_double = value + emit_changed() +## Blends the card normals towards a rounded shape around the whole canopy, so it's lit as one volume. +## 0 keeps the flat card normals. +@export_range(0.0, 1.0) var leaf_canopy_normals: float = 0.8: + set(value): + leaf_canopy_normals = value + emit_changed() +## Brightness of the leaves in the center of the canopy, it fades to 1 towards the edges. 1 disables it. [br][br] +## Stored in the vertex color, the included leaves shader uses it as AO. +@export_range(0.0, 1.0) var leaf_inner_ao: float = 0.35: + set(value): + leaf_inner_ao = value + emit_changed() +#endregion + + +func _validate_property(property: Dictionary) -> void: + var prop_name: String = property.name + var is_leaf := prop_name.begins_with("leaf_") + var is_icosphere := prop_name.begins_with("icosphere_") + if ( + (is_leaf and type != Type.LEAVES) + or (is_icosphere and type != Type.ICOSPHERES) + ): + property.usage = PROPERTY_USAGE_NO_EDITOR + + +func get_leaf_aspect(material: Material) -> float: + if leaf_aspect > 0.0: + return leaf_aspect + + var texture := MeshUtils.get_albedo_texture(material) + if texture == null or texture.get_height() == 0: + return 1.0 + + return float(texture.get_width()) / texture.get_height() diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/resources/preset.gd b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/resources/preset.gd new file mode 100644 index 0000000..8c4f3da --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/resources/preset.gd @@ -0,0 +1,43 @@ +# Copyright © 2026 CosmonautFrog - MIT License + +@tool +class_name CosmoTreePreset +extends Resource +## A saved tree type: the parameters and materials of a [CosmoTreeGen]. [br][br] +## The toolbar Preset menu lists every CosmoTreePreset saved as .tres in the project. + +## See [member CosmoTreeGen.trunk_params]. +@export var trunk_params: CosmoTrunkParams +## See [member CosmoTreeGen.branch_levels]. +@export var branch_levels: Array[CosmoBranchLevel] +## See [member CosmoTreeGen.foliage_params]. +@export var foliage_params: CosmoFoliageParams + +## See [member CosmoTreeGen.trunk_material]. +@export var trunk_material: Material +## See [member CosmoTreeGen.foliage_material]. +@export var foliage_material: Material +## See [member CosmoTreeGen.texel_density]. +@export var texel_density: float = 64.0 + +## See [member CosmoTreeGen.combine_trunk_and_foliage]. +@export var combine_trunk_and_foliage: bool = true +## See [member CosmoTreeGen.flat_shading]. +@export var flat_shading: bool = false +## See [member CosmoTreeGen.create_trunk]. +@export var create_trunk: bool = true +## See [member CosmoTreeGen.create_foliage]. +@export var create_foliage: bool = true +## See [member CosmoTreeGen.lod_trunk_share]. +@export_range(0.0, 1.0, 0.01) var lod_trunk_share: float = 0.33 + + +func is_valid() -> bool: + return trunk_params != null + + +func get_errors() -> PackedStringArray: + var errors: PackedStringArray = [] + if trunk_params == null: + errors.append("missing trunk_params") + return errors diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/resources/trunk_params.gd b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/resources/trunk_params.gd new file mode 100644 index 0000000..aff8366 --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/resources/trunk_params.gd @@ -0,0 +1,94 @@ +# Copyright © 2026 CosmonautFrog - MIT License + +@tool +class_name CosmoTrunkParams +extends Resource +## Shape of the trunks of a [CosmoTreeGen], and their roots. + +## Mesh detail of the trunks, branches and roots. [br][br] +## Trunks get 6 × quality sides and 3 × quality height segments, branches and roots 2 sides less. +## Branch segments are set per level, in [member CosmoBranchLevel.segments]. +@export_range(1, 6, 1, "or_greater") var quality: int = 1: + set(value): + quality = value + emit_changed() +## Number of trunks, growing from the same base in a circle. Each one gets its own branches. +@export_range(1, 6, 1, "or_greater") var amount: int = 1: + set(value): + amount = value + emit_changed() +## Distance between the trunk bases, relative to [member radius_bottom]. [br][br] +## 0 grows them all from the same point and 1 makes them touch. Only used with 2 or more trunks. +@export_range(0.0, 4.0, 0.01, "or_greater") var spread: float = 1.0: + set(value): + spread = value + emit_changed() +## Height of the trunks, in meters. [br][br] +## Branch lengths are relative to their parent, so taller trunks also get longer branches. +@export_range(0.1, 25.0, 0.1, "suffix:m", "or_greater") var height: float = 4.5: + set(value): + height = value + emit_changed() +## Radius at the base of the trunks, in meters, before the [member flare]. +@export_range(0.0, 2.0, 0.01, "suffix:m", "or_greater") var radius_bottom: float = 0.35: + set(value): + radius_bottom = value + emit_changed() +## Radius at the top of the trunks, in meters. It goes linearly from [member radius_bottom] to this. +@export_range(0.0, 0.5, 0.01, "suffix:m", "or_greater") var radius_top: float = 0.1: + set(value): + radius_top = value + emit_changed() +## How far the top of the trunks moves sideways, in meters. It bends more towards the top. [br][br] +## The direction comes from the seed. Multiple trunks lean away from each other. +@export_range(0.0, 2.0, 0.01, "suffix:m", "or_greater") var lean: float = 0.6: + set(value): + lean = value + emit_changed() +## Random sideways bending of the trunks, in meters. Strongest in the middle, the base and the top don't move. +@export_range(0.0, 2.0, 0.01, "suffix:m", "or_greater") var wobble: float = 0.15: + set(value): + wobble = value + emit_changed() +## Widens the base of the trunks. [br][br] +## 1 doubles the radius at the ground, 0 disables it. +@export_range(0.0, 3.0, 0.01, "or_greater") var flare: float = 0.0: + set(value): + flare = value + emit_changed() +## How high the flare reaches, as a fraction of [member height]. +@export_range(0.01, 1.0, 0.01) var flare_height: float = 0.15: + set(value): + flare_height = value + emit_changed() +## How uneven the flare is around the trunk. 0 keeps it round, 1 makes strong lobes. +@export_range(0.0, 1.0, 0.01) var flare_lobes: float = 0.6: + set(value): + flare_lobes = value + emit_changed() +## Extends the trunks this many meters underground, so they don't float on slopes. +@export_range(0.0, 2.0, 0.01, "suffix:m", "or_greater") var sink_depth: float = 0.0: + set(value): + sink_depth = value + emit_changed() +## Branch level that grows the roots from each trunk. Roots get no foliage. [br][br] +## Use a low [member CosmoBranchLevel.end], a high angle and a negative +## [member CosmoBranchLevel.up_force] so they spread near the ground, see the Ash preset. +@export var roots: CosmoBranchLevel: + set(value): + if roots != null: + roots.changed.disconnect(emit_changed) + roots = value + if roots != null: + roots.changed.connect(emit_changed) + emit_changed() + + +func get_lean_vec(angle: float) -> Vector3: + return Vector3(cos(angle), 0.0, sin(angle)) * lean + + +func get_base_offset(angle: float) -> Vector3: + if amount < 2: + return Vector3.ZERO + return Vector3(cos(angle), 0.0, sin(angle)) * spread * radius_bottom / sin(PI / amount) diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/shaders/impostor_capture.gdshader b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/shaders/impostor_capture.gdshader new file mode 100644 index 0000000..5d315e4 --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/shaders/impostor_capture.gdshader @@ -0,0 +1,52 @@ +shader_type spatial; +render_mode unshaded, cull_disabled; + +uniform vec4 albedo : source_color = vec4(1.0); +uniform sampler2D albedo_texture : source_color, filter_linear_mipmap, repeat_enable; +uniform float alpha_scissor_threshold = 0.0; +uniform vec3 uv_scale = vec3(1.0); +uniform vec3 uv_offset = vec3(0.0); +uniform bool triplanar = false; +uniform float triplanar_sharpness = 1.0; +uniform float ao_strength = 0.0; +uniform bool is_foliage = false; +uniform vec3 normal_sign = vec3(1.0); +uniform int output = 0; + +varying vec3 local_position; +varying vec3 local_normal; + +vec4 sample_uv(vec2 uv) { + 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)))); + return textureLod(albedo_texture, uv, clamp(mip, 0.0, log2(min(tex_size.x, tex_size.y)) - 3.0)); +} + +vec4 sample_triplanar() { + vec3 w = pow(abs(local_normal), vec3(triplanar_sharpness)); + w /= dot(w, vec3(1.0)); + vec3 p = (local_position * uv_scale + uv_offset) * vec3(1.0, -1.0, 1.0); + return texture(albedo_texture, p.xy) * w.z + + texture(albedo_texture, p.xz) * w.y + + texture(albedo_texture, p.zy * vec2(-1.0, 1.0)) * w.x; +} + +void vertex() { + local_position = VERTEX; + local_normal = NORMAL; +} + +void fragment() { + vec4 tex = triplanar ? sample_triplanar() : sample_uv(UV * uv_scale.xy + uv_offset.xy); + if (albedo.a * tex.a < alpha_scissor_threshold) { + discard; + } + if (output == 2) { + ALBEDO = vec3(is_foliage ? 1.0 : 0.0); + } else if (output == 1) { + ALBEDO = normalize(FRONT_FACING ? NORMAL : -NORMAL) * normal_sign * 0.5 + 0.5; + } else { + ALBEDO = albedo.rgb * tex.rgb * mix(1.0, COLOR.r, ao_strength); + } +} \ No newline at end of file diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/shaders/impostor_octahedral.gdshader b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/shaders/impostor_octahedral.gdshader new file mode 100644 index 0000000..99732fa --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/shaders/impostor_octahedral.gdshader @@ -0,0 +1,169 @@ +/* +Octahedral impostor shader from godot-imposter by Zhang Juntao (Godot 4 port): +https://github.com/zhangjt93/godot-imposter +Based on Godot-Octahedral-Impostors by wojtekpil: +https://github.com/wojtekpil/Godot-Octahedral-Impostors +Modified and optimized for Cosmo Tree Gen, only using hemi octahedron. + +MIT License + +Copyright (c) 2023 Zhang Juntao +Copyright (c) 2020 wojtekpil, K. S. Ernest (iFire) Lee + +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. +*/ + +shader_type spatial; + +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(12.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.5; +uniform bool dither = false; +uniform vec3 backlight : source_color = vec3(0.0); +uniform float roughness : hint_range(0.0, 1.0) = 1.0; +uniform float specular : hint_range(0.0, 1.0) = 0.2; + +const float BAYER_4X4[16] = float[]( + 0.0625, 0.5625, 0.1875, 0.6875, + 0.8125, 0.3125, 0.9375, 0.4375, + 0.25, 0.75, 0.125, 0.625, + 1.0, 0.5, 0.875, 0.375 +); + +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; + +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() { + 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; + + 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; + + ALBEDO = color.rgb; + NORMAL = normalize(normal); + BACKLIGHT = backlight * (tex_a.a * weights.x + tex_b.a * weights.y + tex_c.a * weights.z); + ROUGHNESS = roughness; + SPECULAR = specular; + + if (dither) { + int index = int(FRAGCOORD.x) % 4 + int(FRAGCOORD.y) % 4 * 4; + if (color.a < BAYER_4X4[index] * alpha_scissor_threshold) { + discard; + } + } else { + ALPHA = color.a; + ALPHA_SCISSOR_THRESHOLD = alpha_scissor_threshold; + } +} diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/shaders/impostor_static.gdshader b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/shaders/impostor_static.gdshader new file mode 100644 index 0000000..0a53b74 --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/shaders/impostor_static.gdshader @@ -0,0 +1,37 @@ +shader_type spatial; +render_mode cull_disabled; + +uniform sampler2D albedo_texture : source_color, filter_linear_mipmap, repeat_disable; +uniform sampler2D normal_texture : hint_normal, filter_linear_mipmap, repeat_disable; +uniform float alpha_scissor_threshold : hint_range(0.0, 1.0) = 0.5; +uniform vec3 backlight : source_color = vec3(0.0); +uniform float roughness : hint_range(0.0, 1.0) = 1.0; +uniform float specular : hint_range(0.0, 1.0) = 0.2; + +// copy of what Godot generates for BILLBOARD_FIXED_Y with keep scale +void vertex() { + MODELVIEW_MATRIX = VIEW_MATRIX * mat4( + vec4(normalize(cross(vec3(0.0, 1.0, 0.0), MAIN_CAM_INV_VIEW_MATRIX[2].xyz)), 0.0), + vec4(0.0, 1.0, 0.0, 0.0), + vec4(normalize(cross(MAIN_CAM_INV_VIEW_MATRIX[0].xyz, vec3(0.0, 1.0, 0.0))), 0.0), + MODEL_MATRIX[3]); + MODELVIEW_MATRIX = MODELVIEW_MATRIX * mat4( + vec4(length(MODEL_MATRIX[0].xyz), 0.0, 0.0, 0.0), + vec4(0.0, length(MODEL_MATRIX[1].xyz), 0.0, 0.0), + vec4(0.0, 0.0, length(MODEL_MATRIX[2].xyz), 0.0), + vec4(0.0, 0.0, 0.0, 1.0)); + MODELVIEW_NORMAL_MATRIX = mat3(MODELVIEW_MATRIX); +} + +void fragment() { + vec4 color = texture(albedo_texture, UV); + vec4 normal_mask = texture(normal_texture, UV); + vec3 n = normal_mask.rgb * 2.0 - 1.0; + ALBEDO = color.rgb; + ALPHA = color.a; + ALPHA_SCISSOR_THRESHOLD = alpha_scissor_threshold; + NORMAL = normalize(TANGENT * n.x + BINORMAL * n.y + NORMAL * n.z); + BACKLIGHT = backlight * normal_mask.a; + ROUGHNESS = roughness; + SPECULAR = specular; +} diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/shaders/leaves.gdshader b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/shaders/leaves.gdshader new file mode 100644 index 0000000..ff1cf36 --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/shaders/leaves.gdshader @@ -0,0 +1,44 @@ +// Copyright © 2026 CosmonautFrog - MIT License + +// Two sided leaf cards that keep the CosmoTreeGen canopy normals on both faces. +shader_type spatial; +render_mode cull_disabled; + +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.5; +uniform vec3 backlight : source_color = vec3(0.45, 0.5, 0.25); +uniform float ao_light_affect : hint_range(0.0, 1.0) = 0.5; + +uniform vec3 wind_direction = vec3(1.0, 0.0, 0.3); +uniform float wind_strength : hint_range(0.0, 1.0, 0.01) = 0.1; +uniform float wind_speed : hint_range(0.0, 10.0, 0.01) = 1.0; +uniform float wind_phase_scale : hint_range(0.0, 10.0, 0.01) = 2.0; + +float wind_wave(float t, float phase) { + return 0.5 * sin(t + phase) + 0.3 * sin(2.0 * t + 1.3 * phase) + 0.2 * sin(5.0 * t + 1.5 * phase); +} + +void vertex() { + vec3 world_position = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz; + float phase = dot(world_position, vec3(1.0, 0.7, 1.3)) * wind_phase_scale; + float sway = (1.0 - UV.y) * wind_strength * wind_wave(TIME * wind_speed, phase); + VERTEX += normalize(wind_direction * mat3(MODEL_MATRIX)) * sway; +} + +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 = COLOR.r; + AO_LIGHT_AFFECT = ao_light_affect; + BACKLIGHT = backlight; + ROUGHNESS = 1.0; + SPECULAR = 0.2; +} diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/textures/bark.png b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/textures/bark.png new file mode 100644 index 0000000..eed657e Binary files /dev/null and b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/textures/bark.png differ diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/textures/branchlet_01.png b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/textures/branchlet_01.png new file mode 100644 index 0000000..69ca754 Binary files /dev/null and b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/textures/branchlet_01.png differ diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/textures/branchlet_03.png b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/textures/branchlet_03.png new file mode 100644 index 0000000..cad4e09 Binary files /dev/null and b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/textures/branchlet_03.png differ diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/textures/foliage.png b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/textures/foliage.png new file mode 100644 index 0000000..99d6b12 Binary files /dev/null and b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/textures/foliage.png differ diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/tree.svg b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/tree.svg new file mode 100644 index 0000000..3f8ce95 --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/tree.svg @@ -0,0 +1 @@ + diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/ui/tree_gen_bar.gd b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/ui/tree_gen_bar.gd new file mode 100644 index 0000000..8da3a55 --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/ui/tree_gen_bar.gd @@ -0,0 +1,163 @@ +# Copyright © 2026 CosmonautFrog - MIT License + +@tool +extends HBoxContainer + +const Settings := preload("../core/settings.gd") +const Exporter := preload("../core/exporter.gd") + +var tree: CosmoTreeGen: set = _set_tree + +var _preset_paths := PackedStringArray() + +@onready var _preset_menu: MenuButton = %PresetMenu +@onready var _seed_button: Button = %SeedButton +@onready var _stats_label: Label = %StatsLabel +@onready var _export_button: Button = %ExportButton +@onready var _export_dialog: EditorFileDialog = %ExportDialog +@onready var _preset_dialog: EditorFileDialog = %PresetDialog + + +func _ready() -> void: + ProjectSettings.settings_changed.connect(_on_project_settings_changed) + _on_project_settings_changed() + + var thm := EditorInterface.get_editor_theme() + _preset_menu.icon = thm.get_icon(&"Load", &"EditorIcons") + _seed_button.icon = thm.get_icon(&"RandomNumberGenerator", &"EditorIcons") + _export_button.icon = thm.get_icon(&"Save", &"EditorIcons") + + _preset_menu.about_to_popup.connect(_on_preset_menu_about_to_popup) + _preset_menu.get_popup().index_pressed.connect(_on_preset_menu_index_pressed) + _seed_button.pressed.connect(_on_seed_button_pressed) + _export_button.pressed.connect(_on_export_button_pressed) + _export_dialog.file_selected.connect(_on_export_dialog_file_selected) + _preset_dialog.file_selected.connect(_on_preset_dialog_file_selected) + + +func _set_tree(value: CosmoTreeGen) -> void: + if is_instance_valid(tree): + tree.generated.disconnect(_update_stats) + tree = value + if tree != null: + tree.generated.connect(_update_stats) + _update_stats() + + +func _update_stats() -> void: + var triangles: int = 0 + var surfaces: int = 0 # each surface is a draw call + for mi in tree.get_meshes(0): + var mesh := mi.mesh as ArrayMesh + for i in mesh.get_surface_count(): + var index_len := mesh.surface_get_array_index_len(i) + @warning_ignore("integer_division") + triangles += (index_len if index_len > 0 else mesh.surface_get_array_len(i)) / 3 + surfaces += mesh.get_surface_count() + _stats_label.text = "%d tris - %d draw calls" % [triangles, surfaces] + + +func _find_presets(dir: EditorFileSystemDirectory) -> void: + # TODO: this could be slow on large projects, find another way + # to get all the CosmoTreePresets + for i in dir.get_file_count(): + var path := dir.get_file_path(i) + if dir.get_file_type(i) != &"Resource" or path.get_extension() != "tres": + continue + var file := FileAccess.open(path, FileAccess.READ) + # hacky way of finding if the Resource is CosmoTreePreset + # read just the first line + if file != null and file.get_line().contains('script_class="CosmoTreePreset"'): + _preset_paths.append(path) + for i in dir.get_subdir_count(): + _find_presets(dir.get_subdir(i)) + + +func _apply_preset(path: String) -> void: + var preset := load(path) as CosmoTreePreset + if not preset.is_valid(): + for err in preset.get_errors(): + push_warning("CosmoTreeGen: invalid preset '%s' - %s" % [path, err]) + return + + var undo_redo := EditorInterface.get_editor_undo_redo() + undo_redo.create_action("Apply Tree Preset") + undo_redo.add_do_method(tree, &"apply_preset", preset) + undo_redo.add_undo_method(tree, &"apply_preset", tree.to_preset()) + undo_redo.commit_action() + print("CosmoTreeGen: applied preset '%s'" % path) + + +func _on_project_settings_changed() -> void: + var include_collisions: int = Settings.get_setting(Settings.EXPORT_INCLUDE_COLLISIONS, false) + var export_images: int = Settings.get_setting(Settings.EXPORT_IMAGES, false) + var use_external_material: int = Settings.get_setting(Settings.EXPORT_USE_EXTERNAL_MATERIAL, false) + var impostor: int = Settings.get_setting(Settings.EXPORT_IMPOSTOR, 0) + _export_dialog.set_option_default(0, include_collisions) + _export_dialog.set_option_default(1, export_images) + _export_dialog.set_option_default(2, use_external_material) + _export_dialog.set_option_default(3, impostor) + + +func _on_preset_menu_about_to_popup() -> void: + _preset_paths.clear() + _find_presets(EditorInterface.get_resource_filesystem().get_filesystem()) + + var popup := _preset_menu.get_popup() + popup.clear() + for path: String in _preset_paths: + popup.add_item(path.get_file().get_basename().capitalize()) + var idx := popup.item_count - 1 + popup.set_item_tooltip(idx, path) + popup.set_item_metadata(idx, path) + if not _preset_paths.is_empty(): + popup.add_separator() + popup.add_item("Save Preset…") + + +func _on_preset_menu_index_pressed(index: int) -> void: + var metadata: Variant = _preset_menu.get_popup().get_item_metadata(index) + if metadata is String: + var path: String = metadata + _apply_preset(path) + else: + _preset_dialog.current_file = "%s.tres" % String(tree.name).to_snake_case() + _preset_dialog.popup_file_dialog() + + +func _on_preset_dialog_file_selected(path: String) -> void: + var err := ResourceSaver.save(tree.to_preset(), path) + if err != OK: + push_error( + "CosmoTreeGen: could not save preset to '%s' (%s)" % [path, error_string(err)] + ) + return + + EditorInterface.get_resource_filesystem().update_file(path) + + +func _on_seed_button_pressed() -> void: + var old_seed := tree.noise_seed + tree.set_random_seed() + + var undo_redo := EditorInterface.get_editor_undo_redo() + undo_redo.create_action("Randomize Tree Seed") + undo_redo.add_do_property(tree, &"noise_seed", tree.noise_seed) + undo_redo.add_undo_property(tree, &"noise_seed", old_seed) + undo_redo.commit_action(false) + + +func _on_export_button_pressed() -> void: + var default_extension: String = Settings.get_setting(Settings.EXPORT_EXTENSION, "glb") + _export_dialog.current_file = "%s.%s" % [String(tree.name).to_snake_case(), default_extension] + _export_dialog.popup_file_dialog() + + +func _on_export_dialog_file_selected(path: String) -> void: + var options := _export_dialog.get_selected_options() + var err := await Exporter.export_gltf(path, tree, options) + if err != OK: + push_error( + "CosmoTreeGen: could not export glTF to '%s' (%s)" % [path, error_string(err)] + ) + EditorInterface.get_resource_filesystem().scan() diff --git a/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/ui/tree_gen_bar.tscn b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/ui/tree_gen_bar.tscn new file mode 100644 index 0000000..a45a385 --- /dev/null +++ b/third_party/cosmo_tree_gen/addons/cosmo_tree_gen/ui/tree_gen_bar.tscn @@ -0,0 +1,92 @@ +[gd_scene format=3 uid="uid://dk4w00j460104"] + +[ext_resource type="Script" uid="uid://bareohor40a2f" path="res://addons/cosmo_tree_gen/ui/tree_gen_bar.gd" id="1_psid7"] + +[sub_resource type="DPITexture" id="DPITexture_md707"] +_source = " +" +base_scale = 1.1 +saturation = 2.0 +color_map = { +Color(1, 0.37254903, 0.37254903, 1): Color(1, 0.47, 0.42, 1), +Color(0.37254903, 1, 0.5921569, 1): Color(0.45, 0.95, 0.5, 1), +Color(1, 0.8666667, 0.39607844, 1): Color(0.83, 0.78, 0.62, 1) +} + +[sub_resource type="DPITexture" id="DPITexture_yfefd"] +_source = " +" +base_scale = 1.1 +saturation = 2.0 +color_map = { +Color(1, 0.37254903, 0.37254903, 1): Color(1, 0.47, 0.42, 1), +Color(0.37254903, 1, 0.5921569, 1): Color(0.45, 0.95, 0.5, 1), +Color(1, 0.8666667, 0.39607844, 1): Color(0.83, 0.78, 0.62, 1) +} + +[sub_resource type="DPITexture" id="DPITexture_fcche"] +_source = " +" +base_scale = 1.1 +saturation = 2.0 +color_map = { +Color(1, 0.37254903, 0.37254903, 1): Color(1, 0.47, 0.42, 1), +Color(0.37254903, 1, 0.5921569, 1): Color(0.45, 0.95, 0.5, 1), +Color(1, 0.8666667, 0.39607844, 1): Color(0.83, 0.78, 0.62, 1) +} + +[node name="TreeGenBar" type="HBoxContainer" unique_id=214483086] +script = ExtResource("1_psid7") + +[node name="PresetMenu" type="MenuButton" parent="." unique_id=759787256] +unique_name_in_owner = true +layout_mode = 2 +tooltip_text = "Load a copy of a CosmoTreePreset preset into this tree." +theme_type_variation = &"FlatMenuButton" +text = "Preset" +icon = SubResource("DPITexture_md707") +flat = false + +[node name="SeedButton" type="Button" parent="." unique_id=315177081] +unique_name_in_owner = true +layout_mode = 2 +tooltip_text = "Pick a new random noise_seed." +theme_type_variation = &"FlatButton" +text = "Seed" +icon = SubResource("DPITexture_yfefd") + +[node name="StatsLabel" type="Label" parent="." unique_id=2066327035] +unique_name_in_owner = true +self_modulate = Color(1, 1, 1, 0.6) +layout_mode = 2 +text = "1234 tris - 999 draw calls" + +[node name="ExportButton" type="Button" parent="." unique_id=1971317291] +unique_name_in_owner = true +layout_mode = 2 +tooltip_text = "Export this tree to a .gltf or .glb file." +theme_type_variation = &"FlatButton" +text = "Export glb/glTF" +icon = SubResource("DPITexture_fcche") + +[node name="ExportDialog" type="EditorFileDialog" parent="." unique_id=1151347104] +unique_name_in_owner = true +oversampling_override = 1.0 +title = "Export Tree" +position = Vector2i(0, 36) +filters = PackedStringArray("*.gltf ; glTF", "*.glb ; glTF Binary") +option_count = 4 +option_0/name = "Include Collisions" +option_0/default = 1 +option_1/name = "Export Images" +option_2/name = "Use External Material" +option_2/default = 1 +option_3/name = "Impostor" +option_3/values = PackedStringArray("None", "Static", "Octahedral") +option_3/default = 1 + +[node name="PresetDialog" type="EditorFileDialog" parent="." unique_id=1600897391] +unique_name_in_owner = true +oversampling_override = 1.0 +title = "Save Preset" +filters = PackedStringArray("*.tres ; CosmoTreePreset") diff --git a/third_party/cosmo_tree_gen/demo/batch_generator.gd b/third_party/cosmo_tree_gen/demo/batch_generator.gd new file mode 100644 index 0000000..876a6f8 --- /dev/null +++ b/third_party/cosmo_tree_gen/demo/batch_generator.gd @@ -0,0 +1,138 @@ +# Copyright © 2026 CosmonautFrog - MIT License + +@tool +class_name TreeBatchGenerator +extends Node +## Example of a batch generator based on a preset. +## Usage: be careful when modifying values, avoid negative numbers. +## It's best to multiply by 0.9-1.1 existing ranges instead of adding/subtracting. + +@export var presets: Array[CosmoTreePreset] +@export var amount: int = 1 +@export_dir var export_dir: String +@export var instantiate: bool = false +@export var preview: bool = false +@export var preview_time: float = 1.0 +@export_tool_button("Generate", "Add") var generate_button: Callable = generate + +var _generating: bool = false +var _rng: RandomNumberGenerator + + +func _instantiate(trees: Array[CosmoTreeGen]) -> void: + var pos_x: float = 0.0 + for tree: CosmoTreeGen in trees: + add_child(tree, true) + tree.owner = get_tree().edited_scene_root + tree.position.x = pos_x + tree.rotate_y(randf_range(0, TAU)) + pos_x += 5.0 + + +func generate() -> void: + if _generating: + return + + if presets.is_empty() or presets.has(null): + push_error("TreeBatchGenerator: presets is empty or has empty slots!") + return + + if export_dir.is_empty(): + push_error("TreeBatchGenerator: export_dir is empty!") + return + + _generating = true + var trees: Array[CosmoTreeGen] = [] + + var options: Dictionary = { + "Use External Material": true, + "Include Collisions": true, + } + + _rng = RandomNumberGenerator.new() + + var i: int = 0 + for preset in presets: + for x in amount: + var s := Time.get_ticks_usec() + var tree := CosmoTreeGen.new() + tree.auto_generate = false + tree.set_random_seed() + + # avoid negative values in filepath e.g.: (ash_-1234.glb) + tree.noise_seed = absi(tree.noise_seed) + + _rng.seed = tree.noise_seed + + tree.apply_preset(preset) + + tree.trunk_params.height *= _rng.randf_range(0.8, 1.2) + tree.trunk_params.radius_bottom *= _rng.randf_range(0.9, 1.1) + tree.trunk_params.flare += _rng.randf_range(-0.05, 0.05) + # example: this could potentially end up in negative lean in some presets + #tree.trunk_params.lean += _rng.randf_range(-0.1, 0.1) + # best to use *= randf_range + tree.trunk_params.lean *= _rng.randf_range(0.7, 1.3) + #tree.trunk_params.wobble = _rng.randf_range(1.5, 2.75) + + for level: CosmoBranchLevel in tree.branch_levels: + level.count += _rng.randi_range(-1, 1) + level.start *= _rng.randf_range(0.9, 1.1) + level.end = minf(level.end * _rng.randf_range(0.9, 1.1), 1.0) + level.angle *= _rng.randf_range(0.9, 1.1) + level.length *= _rng.randf_range(0.9, 1.1) + level.radius *= _rng.randf_range(0.9, 1.1) + level.gnarl *= _rng.randf_range(0.9, 1.1) + level.up_force *= _rng.randf_range(0.9, 1.1) + + tree.foliage_params.leaf_count += _rng.randi_range(-3, 3) + tree.foliage_params.leaf_size += _rng.randf_range(-0.05, 0.05) + tree.foliage_params.leaf_start = minf( + tree.foliage_params.leaf_start * _rng.randf_range(0.9, 1.1), 1.0 + ) + tree.foliage_params.leaf_angle *= _rng.randf_range(0.9, 1.1) + + tree.collision_type = CosmoTreeGen.CollisionType.TRIMESH + # trunk collision would cover 25% of the trunk height + tree.collision_max_height = tree.trunk_params.height * 0.25 + #tree.collision_level = 2 + tree.foliage_collision_type = CosmoTreeGen.FoliageCollisionType.HULL + + # you can also change the materials + #tree.trunk_material = preload("res://test/bark_4k.tres") + #tree.foliage_material = preload("res://test/foliage_test.tres") + + tree.generate() + var elapsed := (Time.get_ticks_usec() - s) / 1000.0 + + var preset_name: String = preset.resource_path.get_file().get_basename() + tree.name = preset_name.capitalize() + var out_path: String = "%s/%s_%d.glb" % [export_dir, preset_name, tree.noise_seed] + + var err := await tree.export_gltf(out_path, options) + + if preview: + add_child(tree) + await get_tree().create_timer(preview_time).timeout + remove_child(tree) + + if instantiate: + trees.append(tree) + else: + tree.free() + + i += 1 + var progress: String = "%d/%d" % [i, amount * presets.size()] + + if err != OK: + push_error("[%s] error generating tree: %s" % [progress, error_string(err)]) + continue + + print("[%s] generated %s and saved to: '%s' - took: %.2fms" % [ + progress, preset_name, out_path, elapsed + ]) + + if instantiate: + _instantiate(trees) + + _generating = false diff --git a/third_party/cosmo_tree_gen/demo/batch_generator.tscn b/third_party/cosmo_tree_gen/demo/batch_generator.tscn new file mode 100644 index 0000000..c9feae1 --- /dev/null +++ b/third_party/cosmo_tree_gen/demo/batch_generator.tscn @@ -0,0 +1,15 @@ +[gd_scene format=3 uid="uid://ehely5qeqxua"] + +[ext_resource type="Script" uid="uid://dbmw00fj2h3v6" path="res://demo/batch_generator.gd" id="1_6acij"] +[ext_resource type="Script" uid="uid://dlp11kr4f76j3" path="res://addons/cosmo_tree_gen/resources/preset.gd" id="2_wslh1"] +[ext_resource type="Resource" uid="uid://briv2agm575jt" path="res://demo/extra_presets/pine.tres" id="3_cw7sy"] +[ext_resource type="Resource" uid="uid://dud0uolkbfkt" path="res://addons/cosmo_tree_gen/presets/ash.tres" id="4_0vln7"] + +[node name="BatchGenerator" type="Node" unique_id=631098847] +script = ExtResource("1_6acij") +presets = Array[ExtResource("2_wslh1")]([ExtResource("3_cw7sy"), ExtResource("4_0vln7")]) +amount = 2 +export_dir = "res://exports" +instantiate = true +preview = true +metadata/_custom_type_script = "uid://dbmw00fj2h3v6" diff --git a/third_party/cosmo_tree_gen/demo/demo.tscn b/third_party/cosmo_tree_gen/demo/demo.tscn new file mode 100644 index 0000000..8161a18 --- /dev/null +++ b/third_party/cosmo_tree_gen/demo/demo.tscn @@ -0,0 +1,674 @@ +[gd_scene format=3 uid="uid://c8fxt01sxw6ut"] + +[ext_resource type="Script" uid="uid://thf11ljosiks" path="res://addons/cosmo_tree_gen/core/cosmo_tree_gen.gd" id="1_cycnu"] +[ext_resource type="Script" uid="uid://c0ggn4wsaa746" path="res://addons/cosmo_tree_gen/resources/trunk_params.gd" id="2_u2se3"] +[ext_resource type="Script" uid="uid://ceh6ii6tlpph4" path="res://addons/cosmo_tree_gen/resources/branch_level.gd" id="3_cpj4b"] +[ext_resource type="Script" uid="uid://1tt4by0vsl04" path="res://addons/cosmo_tree_gen/resources/foliage_params.gd" id="4_fxgjp"] +[ext_resource type="Material" uid="uid://b7l8vw0qq0s25" path="res://addons/cosmo_tree_gen/materials/bark.tres" id="5_cpj4b"] +[ext_resource type="Material" uid="uid://1aem886fag5n" path="res://addons/cosmo_tree_gen/materials/foliage.tres" id="7_1ld14"] +[ext_resource type="Material" uid="uid://deodinjmuohgl" path="res://addons/cosmo_tree_gen/materials/leaves_01.tres" id="7_ykvhj"] +[ext_resource type="Material" uid="uid://dm5as0s5uoju2" path="res://addons/cosmo_tree_gen/materials/leaves_03.tres" id="10_fxgjp"] +[ext_resource type="Material" uid="uid://cluv26uchlkcx" path="res://demo/materials/leaves_04.tres" id="11_1rqa4"] +[ext_resource type="Material" uid="uid://bhtq0iyc1n5ch" path="res://demo/materials/leaves_06.tres" id="12_xm42s"] +[ext_resource type="Material" uid="uid://cyy0xvd2uyh5r" path="res://demo/materials/leaves_05.tres" id="13_tdg64"] +[ext_resource type="Material" uid="uid://ud2fyw42vi52" path="res://demo/materials/leaves_07.tres" id="14_nk31j"] +[ext_resource type="Material" uid="uid://cmuj42a78mdm" path="res://demo/materials/leaves_02.tres" id="15_fy1p0"] + +[sub_resource type="ProceduralSkyMaterial" id="ProceduralSkyMaterial_u2se3"] +sky_horizon_color = Color(0.66224277, 0.6717428, 0.6867428, 1) +ground_horizon_color = Color(0.66224277, 0.6717428, 0.6867428, 1) + +[sub_resource type="Sky" id="Sky_yuqv1"] +sky_material = SubResource("ProceduralSkyMaterial_u2se3") + +[sub_resource type="Environment" id="Environment_cpj4b"] +background_mode = 2 +sky = SubResource("Sky_yuqv1") +tonemap_mode = 2 +glow_enabled = true + +[sub_resource type="Gradient" id="Gradient_nwdni"] +colors = PackedColorArray(0, 0.29803923, 0.10980392, 1, 0.13725491, 0.47843137, 0.20392157, 1) + +[sub_resource type="FastNoiseLite" id="FastNoiseLite_cycnu"] +noise_type = 3 +seed = 42 +frequency = 0.2 + +[sub_resource type="NoiseTexture2D" id="NoiseTexture2D_pq1dq"] +width = 64 +height = 64 +generate_mipmaps = false +noise = SubResource("FastNoiseLite_cycnu") +color_ramp = SubResource("Gradient_nwdni") + +[sub_resource type="StandardMaterial3D" id="StandardMaterial3D_u2se3"] +albedo_texture = SubResource("NoiseTexture2D_pq1dq") +uv1_scale = Vector3(6, 6, 6) +texture_filter = 0 + +[sub_resource type="PlaneMesh" id="PlaneMesh_nwdni"] +material = SubResource("StandardMaterial3D_u2se3") +size = Vector2(20, 20) + +[sub_resource type="Resource" id="Resource_5t1n4"] +script = ExtResource("2_u2se3") +height = 6.0 +radius_bottom = 0.25 +lean = 0.644 +wobble = 0.244 +metadata/_custom_type_script = "uid://c0ggn4wsaa746" + +[sub_resource type="Resource" id="Resource_f73r4"] +script = ExtResource("3_cpj4b") +count = 5 +start = 0.373 +end = 0.726 +angle = 59.082 +length = 0.235 +radius = 0.8099999999999999 +segments = 2 +gnarl = 0.055 +up_force = 0.18500000000000005 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_hycpn"] +script = ExtResource("4_fxgjp") +icosphere_subdivisions = 2 +icosphere_amplitude = 0.42 +icosphere_frequency = 1.92 + +[sub_resource type="Resource" id="Resource_niwkb"] +script = ExtResource("2_u2se3") +height = 0.4 +radius_bottom = 0.01 +radius_top = 0.0 +lean = 0.0 +wobble = 0.0 + +[sub_resource type="Resource" id="Resource_febos"] +script = ExtResource("3_cpj4b") +count = 2 +start = 0.372 +end = 1.0 +angle = 90.0 +length = 1.0 +radius = 1.0 +segments = 1 +gnarl = 0.419 +up_force = 0.31700000000000017 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_usong"] +script = ExtResource("4_fxgjp") +icosphere_radius = 0.49 +icosphere_amplitude = 0.6 + +[sub_resource type="Resource" id="Resource_tdg64"] +script = ExtResource("3_cpj4b") +start = 0.0 +end = 0.03 +angle = 90.0 +length = 0.271 +segments = 5 +gnarl = 1.2 +up_force = -0.8370000000000002 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_fy1p0"] +script = ExtResource("2_u2se3") +height = 5.5 +radius_bottom = 0.28 +radius_top = 0.04 +lean = 0.3 +flare = 0.7 +flare_height = 0.32 +flare_lobes = 1.0 +sink_depth = 0.14 +roots = SubResource("Resource_tdg64") +metadata/_custom_type_script = "uid://c0ggn4wsaa746" + +[sub_resource type="Resource" id="Resource_mj7pe"] +script = ExtResource("3_cpj4b") +count = 7 +terminal = true +start = 0.382 +end = 0.92 +angle = 52.0 +length = 0.5 +radius = 0.65 +gnarl = 0.25 +up_force = 0.2 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_t8a6q"] +script = ExtResource("3_cpj4b") +count = 4 +terminal = true +start = 0.048 +end = 1.0 +angle = 45.0 +length = 0.406 +segments = 2 +gnarl = 0.4 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_5eeob"] +script = ExtResource("3_cpj4b") +count = 3 +terminal = true +start = 0.121 +end = 0.94 +length = 0.487 +segments = 1 +up_force = 0.4 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_qu3ut"] +script = ExtResource("4_fxgjp") +type = 2 +leaf_count = 4 +leaf_tip = true +leaf_size = 0.54 +leaf_size_variance = 0.25 +leaf_start = 0.2 +leaf_angle = 55.0 +metadata/_custom_type_script = "uid://1tt4by0vsl04" + +[sub_resource type="Resource" id="Resource_ykvhj"] +script = ExtResource("2_u2se3") +height = 4.0 +radius_bottom = 0.2 +radius_top = 0.01 +lean = 0.473 +wobble = 0.0 + +[sub_resource type="Curve" id="Curve_d1m6b"] +_data = [Vector2(0, 1), 0.0, 0.0, 0, 0, Vector2(0.3698336, 1), 0.0, 0.0, 0, 0, Vector2(1, 0.26500046), 0.0, 0.0, 0, 0] +point_count = 3 + +[sub_resource type="Resource" id="Resource_svvho"] +script = ExtResource("3_cpj4b") +count = 51 +start = 0.421 +end = 1.0 +angle = 90.0 +length = 0.356 +length_curve = SubResource("Curve_d1m6b") +gnarl = 0.676 +up_force = -0.587 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_x31ta"] +script = ExtResource("4_fxgjp") +type = 2 +leaf_size = 0.49 +leaf_length_influence = 0.762 +leaf_start = 0.0 + +[sub_resource type="Resource" id="Resource_d1m6b"] +script = ExtResource("2_u2se3") +height = 0.2 +radius_bottom = 0.04 +radius_top = 0.0 +lean = 0.0 +wobble = 0.0 + +[sub_resource type="Resource" id="Resource_k1rqu"] +script = ExtResource("3_cpj4b") +count = 10 +start = 0.0 +end = 1.0 +angle = 52.844 +length = 0.461 +radius = 1.0 +segments = 1 +gnarl = 0.0 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_wwhtr"] +script = ExtResource("4_fxgjp") +type = 2 +leaf_count = 14 +leaf_size = 0.76 +leaf_size_variance = 0.322 +leaf_start = 0.0 +leaf_inner_ao = 0.0 + +[sub_resource type="Resource" id="Resource_62gnj"] +script = ExtResource("2_u2se3") +quality = 2 +height = 5.5 +radius_bottom = 0.24 +radius_top = 0.03 +lean = 0.2 +wobble = 0.1 +metadata/_custom_type_script = "uid://c0ggn4wsaa746" + +[sub_resource type="Resource" id="Resource_vkopi"] +script = ExtResource("3_cpj4b") +count = 10 +terminal = true +start = 0.3 +end = 0.95 +angle = 55.0 +gnarl = 0.25 +up_force = 0.35 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_qvfii"] +script = ExtResource("3_cpj4b") +count = 4 +terminal = true +start = 0.2 +end = 1.0 +angle = 45.0 +length = 0.5 +segments = 2 +up_force = 0.3 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_8rfdr"] +script = ExtResource("4_fxgjp") +type = 2 +leaf_count = 8 +leaf_tip = true +leaf_size = 1.3 +leaf_size_variance = 0.25 +leaf_start = 0.2 +leaf_inner_ao = 0.4 +metadata/_custom_type_script = "uid://1tt4by0vsl04" + +[sub_resource type="Resource" id="Resource_6ihnu"] +script = ExtResource("2_u2se3") +quality = 2 +height = 4.0 +radius_bottom = 0.18 +radius_top = 0.03 +lean = 0.15 +wobble = 0.2 +metadata/_custom_type_script = "uid://c0ggn4wsaa746" + +[sub_resource type="Resource" id="Resource_mosls"] +script = ExtResource("3_cpj4b") +count = 12 +terminal = true +start = 0.12 +end = 0.95 +angle = 42.0 +length = 0.45 +up_force = 0.4 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_p1aj5"] +script = ExtResource("3_cpj4b") +count = 4 +terminal = true +start = 0.2 +end = 1.0 +angle = 45.0 +length = 0.45 +segments = 2 +up_force = 0.3 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_1d2gs"] +script = ExtResource("4_fxgjp") +type = 2 +leaf_count = 9 +leaf_tip = true +leaf_size = 0.45 +leaf_size_variance = 0.2 +leaf_start = 0.1 +leaf_angle = 35.0 +leaf_canopy_normals = 0.9 +leaf_inner_ao = 0.3 +metadata/_custom_type_script = "uid://1tt4by0vsl04" + +[sub_resource type="Resource" id="Resource_jv588"] +script = ExtResource("2_u2se3") +quality = 2 +height = 8.0 +radius_bottom = 0.25 +radius_top = 0.01 +lean = 0.05 +wobble = 0.05 +metadata/_custom_type_script = "uid://c0ggn4wsaa746" + +[sub_resource type="Curve" id="Curve_fy1p0"] +_data = [Vector2(0, 0.88026786), 0.0, -0.14157727, 0, 0, Vector2(1, 0), -0.55938643, 0.0, 0, 0] +point_count = 2 + +[sub_resource type="Resource" id="Resource_xam2y"] +script = ExtResource("3_cpj4b") +count = 60 +start = 0.156 +end = 0.97 +angle = 88.0 +length = 0.429 +length_curve = SubResource("Curve_fy1p0") +gnarl = 0.1 +up_force = -0.6 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Curve" id="Curve_x31ta"] +_data = [Vector2(0, 1), 0.0, 0.0, 0, 0, Vector2(0.938999, 0.60456264), 0.0, 0.0, 0, 0] +point_count = 2 + +[sub_resource type="Resource" id="Resource_fla3q"] +script = ExtResource("4_fxgjp") +type = 2 +leaf_count = 11 +leaf_tip = true +leaf_size = 1.0 +leaf_size_curve = SubResource("Curve_x31ta") +leaf_length_influence = 0.33 +leaf_size_variance = 0.2 +leaf_start = 0.05 +leaf_angle = 25.0 +leaf_canopy_normals = 0.5 +leaf_inner_ao = 0.5 +metadata/_custom_type_script = "uid://1tt4by0vsl04" + +[sub_resource type="Resource" id="Resource_a0ng0"] +script = ExtResource("2_u2se3") +quality = 2 +height = 3.2 +radius_bottom = 0.2 +radius_top = 0.16 +lean = 0.25 +wobble = 0.1 +metadata/_custom_type_script = "uid://c0ggn4wsaa746" + +[sub_resource type="Resource" id="Resource_7h7tp"] +script = ExtResource("4_fxgjp") +type = 2 +leaf_tip = true +leaf_size = 2.3 +leaf_size_variance = 0.2 +leaf_start = 0.95 +leaf_angle = 62.0 +leaf_canopy_normals = 0.6 +leaf_inner_ao = 0.5 +metadata/_custom_type_script = "uid://1tt4by0vsl04" + +[sub_resource type="Resource" id="Resource_143ej"] +script = ExtResource("2_u2se3") +quality = 2 +height = 3.2 +radius_bottom = 0.4 +radius_top = 0.12 +lean = 0.5 +wobble = 0.3 +sink_depth = 0.12 +metadata/_custom_type_script = "uid://c0ggn4wsaa746" + +[sub_resource type="Resource" id="Resource_u5t42"] +script = ExtResource("3_cpj4b") +count = 7 +terminal = true +start = 0.8 +end = 1.0 +angle = 60.0 +length = 0.95 +radius = 0.703 +up_force = 0.07800000000000029 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_5de16"] +script = ExtResource("3_cpj4b") +count = 3 +terminal = true +start = 0.1 +end = 1.0 +angle = 67.955 +length = 0.8280000000000001 +radius = 0.7999999999999999 +segments = 8 +gnarl = 0.1 +up_force = -3.059 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_h5sl1"] +script = ExtResource("4_fxgjp") +type = 2 +leaf_tip = true +leaf_size = 2.48 +leaf_aspect = 0.3 +leaf_size_variance = 0.2 +leaf_start = 0.0 +leaf_position_offset = Vector3(0, 0.3, 0) +leaf_gravity = 0.9 +leaf_canopy_normals = 0.7 +leaf_inner_ao = 0.4 +metadata/_custom_type_script = "uid://1tt4by0vsl04" + +[sub_resource type="Resource" id="Resource_nk31j"] +script = ExtResource("3_cpj4b") +count = 7 +start = 0.0 +end = 0.02 +angle = 90.0 +length = 0.8 +segments = 5 +gnarl = 0.8 +up_force = -0.796 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_norpd"] +script = ExtResource("2_u2se3") +quality = 2 +height = 3.5 +radius_bottom = 0.45 +lean = 0.4 +wobble = 0.3 +flare = 0.7 +sink_depth = 0.1 +roots = SubResource("Resource_nk31j") +metadata/_custom_type_script = "uid://c0ggn4wsaa746" + +[sub_resource type="Resource" id="Resource_7eb7w"] +script = ExtResource("3_cpj4b") +count = 5 +terminal = true +start = 0.45 +end = 1.0 +angle = 60.0 +length = 0.9 +radius = 0.75 +segments = 5 +gnarl = 0.8 +up_force = 0.2 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_ntps4"] +script = ExtResource("3_cpj4b") +count = 4 +terminal = true +start = 0.2 +end = 1.0 +length = 0.5 +gnarl = 0.8 +up_force = 0.15 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_urb6m"] +script = ExtResource("3_cpj4b") +count = 3 +terminal = true +start = 0.3 +end = 1.0 +length = 0.45 +segments = 2 +gnarl = 0.6 +up_force = 0.3 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_ha3dm"] +script = ExtResource("4_fxgjp") +type = 2 +leaf_count = 4 +leaf_tip = true +leaf_size = 0.75 +leaf_angle = 35.0 +leaf_canopy_normals = 0.4 +leaf_inner_ao = 0.6 +metadata/_custom_type_script = "uid://1tt4by0vsl04" + +[node name="Demo" type="Node3D" unique_id=457106141] + +[node name="WorldEnvironment" type="WorldEnvironment" parent="." unique_id=1552366562] +environment = SubResource("Environment_cpj4b") + +[node name="DirectionalLight3D" type="DirectionalLight3D" parent="." unique_id=869552325] +transform = Transform3D(-0.8660254, -0.43301278, 0.25, 0, 0.49999997, 0.86602545, -0.50000006, 0.75, -0.43301266, 0, 0, 0) +shadow_enabled = true + +[node name="Camera3D" type="Camera3D" parent="." unique_id=2073012112] +transform = Transform3D(1, 0, 0, 0, 0.9961947, 0.08715574, 0, -0.08715574, 0.9961947, 0, 3.94577, 6.249936) + +[node name="Ground" type="MeshInstance3D" parent="." unique_id=364196551] +mesh = SubResource("PlaneMesh_nwdni") + +[node name="Icospheres" type="Node3D" parent="." unique_id=1538727374] + +[node name="LowPolyTree" type="Node3D" parent="Icospheres" unique_id=2106527168] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 6.7686777, 0, 0) +script = ExtResource("1_cycnu") +noise_seed = 1324960724 +trunk_params = SubResource("Resource_5t1n4") +branch_levels = Array[ExtResource("3_cpj4b")]([SubResource("Resource_f73r4")]) +foliage_params = SubResource("Resource_hycpn") +collision_type = 3 +foliage_collision_type = 2 +preview_collision = true +trunk_material = ExtResource("5_cpj4b") +foliage_material = ExtResource("7_1ld14") +metadata/_custom_type_script = "uid://thf11ljosiks" + +[node name="LowPolyBush" type="Node3D" parent="Icospheres" unique_id=1773419636] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 4, 0, 1.6631541) +script = ExtResource("1_cycnu") +trunk_params = SubResource("Resource_niwkb") +branch_levels = Array[ExtResource("3_cpj4b")]([SubResource("Resource_febos")]) +foliage_params = SubResource("Resource_usong") +flat_shading = true +create_trunk = false +collision_type = 3 +foliage_collision_type = 1 +preview_collision = true +trunk_material = ExtResource("5_cpj4b") +foliage_material = ExtResource("7_1ld14") +metadata/_custom_type_script = "uid://thf11ljosiks" + +[node name="CardLeaves" type="Node3D" parent="." unique_id=353850520] + +[node name="Ash" type="Node3D" parent="CardLeaves" unique_id=1925701942] +script = ExtResource("1_cycnu") +noise_seed = 1931204211 +trunk_params = SubResource("Resource_fy1p0") +branch_levels = Array[ExtResource("3_cpj4b")]([SubResource("Resource_mj7pe"), SubResource("Resource_t8a6q"), SubResource("Resource_5eeob")]) +foliage_params = SubResource("Resource_qu3ut") +generate_lod = true +collision_type = 3 +collision_max_height = 2.5 +foliage_collision_type = 1 +preview_collision = true +trunk_material = ExtResource("5_cpj4b") +foliage_material = ExtResource("7_ykvhj") +metadata/_custom_type_script = "uid://thf11ljosiks" + +[node name="Pine" type="Node3D" parent="CardLeaves" unique_id=370071658] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -4, 0, 0) +script = ExtResource("1_cycnu") +noise_seed = 857689528 +trunk_params = SubResource("Resource_ykvhj") +branch_levels = Array[ExtResource("3_cpj4b")]([SubResource("Resource_svvho")]) +foliage_params = SubResource("Resource_x31ta") +preview_collision = true +trunk_material = ExtResource("5_cpj4b") +foliage_material = ExtResource("14_nk31j") +metadata/_custom_type_script = "uid://thf11ljosiks" + +[node name="Bush" type="Node3D" parent="CardLeaves" unique_id=339446749] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -8, -0.1, 0) +script = ExtResource("1_cycnu") +noise_seed = 744334394 +trunk_params = SubResource("Resource_d1m6b") +branch_levels = Array[ExtResource("3_cpj4b")]([SubResource("Resource_k1rqu")]) +foliage_params = SubResource("Resource_wwhtr") +create_trunk = false +preview_collision = true +trunk_material = ExtResource("5_cpj4b") +foliage_material = ExtResource("10_fxgjp") +metadata/_custom_type_script = "uid://thf11ljosiks" + +[node name="Cherry" type="Node3D" parent="CardLeaves" unique_id=1694966617] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 4.1512938, 0, 6.346188) +script = ExtResource("1_cycnu") +noise_seed = -1983353351 +trunk_params = SubResource("Resource_62gnj") +branch_levels = Array[ExtResource("3_cpj4b")]([SubResource("Resource_vkopi"), SubResource("Resource_qvfii")]) +foliage_params = SubResource("Resource_8rfdr") +trunk_material = ExtResource("5_cpj4b") +foliage_material = ExtResource("10_fxgjp") +metadata/_custom_type_script = "uid://thf11ljosiks" + +[node name="Laurel" type="Node3D" parent="CardLeaves" unique_id=1316282636] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -4, 0, 4) +script = ExtResource("1_cycnu") +noise_seed = -2046055894 +trunk_params = SubResource("Resource_6ihnu") +branch_levels = Array[ExtResource("3_cpj4b")]([SubResource("Resource_mosls"), SubResource("Resource_p1aj5")]) +foliage_params = SubResource("Resource_1d2gs") +preview_collision = true +trunk_material = ExtResource("5_cpj4b") +foliage_material = ExtResource("11_1rqa4") +metadata/_custom_type_script = "uid://thf11ljosiks" + +[node name="Spruce" type="Node3D" parent="CardLeaves" unique_id=1237983093] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -8, 0, 6.9584637) +script = ExtResource("1_cycnu") +noise_seed = 2102456159 +trunk_params = SubResource("Resource_jv588") +branch_levels = Array[ExtResource("3_cpj4b")]([SubResource("Resource_xam2y")]) +foliage_params = SubResource("Resource_fla3q") +preview_collision = true +trunk_material = ExtResource("5_cpj4b") +foliage_material = ExtResource("12_xm42s") +metadata/_custom_type_script = "uid://thf11ljosiks" + +[node name="TreeFern" type="Node3D" parent="CardLeaves" unique_id=1844908179] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, -6.6332064) +script = ExtResource("1_cycnu") +noise_seed = -1062421101 +trunk_params = SubResource("Resource_a0ng0") +foliage_params = SubResource("Resource_7h7tp") +preview_collision = true +trunk_material = ExtResource("5_cpj4b") +foliage_material = ExtResource("13_tdg64") +metadata/_custom_type_script = "uid://thf11ljosiks" + +[node name="Willow" type="Node3D" parent="CardLeaves" unique_id=1740680237] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -6.6023374, 0, -6.0391183) +script = ExtResource("1_cycnu") +noise_seed = 1365038018 +trunk_params = SubResource("Resource_143ej") +branch_levels = Array[ExtResource("3_cpj4b")]([SubResource("Resource_u5t42"), SubResource("Resource_5de16")]) +foliage_params = SubResource("Resource_h5sl1") +preview_collision = true +trunk_material = ExtResource("5_cpj4b") +foliage_material = ExtResource("11_1rqa4") +metadata/_custom_type_script = "uid://thf11ljosiks" + +[node name="WinterOak" type="Node3D" parent="CardLeaves" unique_id=345297676] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 4, 0, -4) +script = ExtResource("1_cycnu") +noise_seed = 2135572971 +trunk_params = SubResource("Resource_norpd") +branch_levels = Array[ExtResource("3_cpj4b")]([SubResource("Resource_7eb7w"), SubResource("Resource_ntps4"), SubResource("Resource_urb6m")]) +foliage_params = SubResource("Resource_ha3dm") +preview_collision = true +trunk_material = ExtResource("5_cpj4b") +foliage_material = ExtResource("15_fy1p0") +metadata/_custom_type_script = "uid://thf11ljosiks" diff --git a/third_party/cosmo_tree_gen/demo/extra_presets/cherry.tres b/third_party/cosmo_tree_gen/demo/extra_presets/cherry.tres new file mode 100644 index 0000000..bfb9e74 --- /dev/null +++ b/third_party/cosmo_tree_gen/demo/extra_presets/cherry.tres @@ -0,0 +1,60 @@ +[gd_resource type="Resource" script_class="CosmoTreePreset" format=3 uid="uid://ci6072yv1385a"] + +[ext_resource type="Script" uid="uid://ceh6ii6tlpph4" path="res://addons/cosmo_tree_gen/resources/branch_level.gd" id="1_tgduv"] +[ext_resource type="Material" uid="uid://dm5as0s5uoju2" path="res://addons/cosmo_tree_gen/materials/leaves_03.tres" id="2_82h6u"] +[ext_resource type="Script" uid="uid://1tt4by0vsl04" path="res://addons/cosmo_tree_gen/resources/foliage_params.gd" id="3_1blq4"] +[ext_resource type="Script" uid="uid://dlp11kr4f76j3" path="res://addons/cosmo_tree_gen/resources/preset.gd" id="4_kcckf"] +[ext_resource type="Material" uid="uid://b7l8vw0qq0s25" path="res://addons/cosmo_tree_gen/materials/bark.tres" id="5_g1nna"] +[ext_resource type="Script" uid="uid://c0ggn4wsaa746" path="res://addons/cosmo_tree_gen/resources/trunk_params.gd" id="6_dqbmr"] + +[sub_resource type="Resource" id="Resource_vkopi"] +script = ExtResource("1_tgduv") +count = 10 +terminal = true +start = 0.3 +end = 0.95 +angle = 55.0 +gnarl = 0.25 +up_force = 0.35 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_qvfii"] +script = ExtResource("1_tgduv") +count = 4 +terminal = true +start = 0.2 +end = 1.0 +angle = 45.0 +length = 0.5 +segments = 2 +up_force = 0.3 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_8rfdr"] +script = ExtResource("3_1blq4") +type = 2 +leaf_count = 8 +leaf_tip = true +leaf_size = 1.3 +leaf_size_variance = 0.25 +leaf_start = 0.2 +leaf_inner_ao = 0.4 +metadata/_custom_type_script = "uid://1tt4by0vsl04" + +[sub_resource type="Resource" id="Resource_62gnj"] +script = ExtResource("6_dqbmr") +quality = 2 +height = 5.5 +radius_bottom = 0.24 +radius_top = 0.03 +lean = 0.2 +wobble = 0.1 +metadata/_custom_type_script = "uid://c0ggn4wsaa746" + +[resource] +script = ExtResource("4_kcckf") +trunk_params = SubResource("Resource_62gnj") +branch_levels = Array[ExtResource("1_tgduv")]([SubResource("Resource_vkopi"), SubResource("Resource_qvfii")]) +foliage_params = SubResource("Resource_8rfdr") +trunk_material = ExtResource("5_g1nna") +foliage_material = ExtResource("2_82h6u") diff --git a/third_party/cosmo_tree_gen/demo/extra_presets/laurel.tres b/third_party/cosmo_tree_gen/demo/extra_presets/laurel.tres new file mode 100644 index 0000000..55253ab --- /dev/null +++ b/third_party/cosmo_tree_gen/demo/extra_presets/laurel.tres @@ -0,0 +1,62 @@ +[gd_resource type="Resource" script_class="CosmoTreePreset" format=3 uid="uid://c3fnxoyunycvc"] + +[ext_resource type="Script" uid="uid://ceh6ii6tlpph4" path="res://addons/cosmo_tree_gen/resources/branch_level.gd" id="1_30toe"] +[ext_resource type="Material" uid="uid://cluv26uchlkcx" path="res://demo/materials/leaves_04.tres" id="2_y2177"] +[ext_resource type="Script" uid="uid://1tt4by0vsl04" path="res://addons/cosmo_tree_gen/resources/foliage_params.gd" id="3_rmsyb"] +[ext_resource type="Script" uid="uid://dlp11kr4f76j3" path="res://addons/cosmo_tree_gen/resources/preset.gd" id="4_bvh1h"] +[ext_resource type="Material" uid="uid://b7l8vw0qq0s25" path="res://addons/cosmo_tree_gen/materials/bark.tres" id="5_kcw64"] +[ext_resource type="Script" uid="uid://c0ggn4wsaa746" path="res://addons/cosmo_tree_gen/resources/trunk_params.gd" id="6_321gc"] + +[sub_resource type="Resource" id="Resource_mosls"] +script = ExtResource("1_30toe") +count = 12 +terminal = true +start = 0.12 +end = 0.95 +angle = 42.0 +length = 0.45 +up_force = 0.4 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_p1aj5"] +script = ExtResource("1_30toe") +count = 4 +terminal = true +start = 0.2 +end = 1.0 +angle = 45.0 +length = 0.45 +segments = 2 +up_force = 0.3 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_1d2gs"] +script = ExtResource("3_rmsyb") +type = 2 +leaf_count = 9 +leaf_tip = true +leaf_size = 0.45 +leaf_size_variance = 0.2 +leaf_start = 0.1 +leaf_angle = 35.0 +leaf_canopy_normals = 0.9 +leaf_inner_ao = 0.3 +metadata/_custom_type_script = "uid://1tt4by0vsl04" + +[sub_resource type="Resource" id="Resource_6ihnu"] +script = ExtResource("6_321gc") +quality = 2 +height = 4.0 +radius_bottom = 0.18 +radius_top = 0.03 +lean = 0.15 +wobble = 0.2 +metadata/_custom_type_script = "uid://c0ggn4wsaa746" + +[resource] +script = ExtResource("4_bvh1h") +trunk_params = SubResource("Resource_6ihnu") +branch_levels = Array[ExtResource("1_30toe")]([SubResource("Resource_mosls"), SubResource("Resource_p1aj5")]) +foliage_params = SubResource("Resource_1d2gs") +trunk_material = ExtResource("5_kcw64") +foliage_material = ExtResource("2_y2177") diff --git a/third_party/cosmo_tree_gen/demo/extra_presets/pine.tres b/third_party/cosmo_tree_gen/demo/extra_presets/pine.tres new file mode 100644 index 0000000..e556467 --- /dev/null +++ b/third_party/cosmo_tree_gen/demo/extra_presets/pine.tres @@ -0,0 +1,47 @@ +[gd_resource type="Resource" script_class="CosmoTreePreset" format=3 uid="uid://briv2agm575jt"] + +[ext_resource type="Script" uid="uid://ceh6ii6tlpph4" path="res://addons/cosmo_tree_gen/resources/branch_level.gd" id="1_hnal5"] +[ext_resource type="Material" uid="uid://ud2fyw42vi52" path="res://demo/materials/leaves_07.tres" id="2_0b7mx"] +[ext_resource type="Script" uid="uid://1tt4by0vsl04" path="res://addons/cosmo_tree_gen/resources/foliage_params.gd" id="3_31x05"] +[ext_resource type="Script" uid="uid://dlp11kr4f76j3" path="res://addons/cosmo_tree_gen/resources/preset.gd" id="4_bef8d"] +[ext_resource type="Material" uid="uid://b7l8vw0qq0s25" path="res://addons/cosmo_tree_gen/materials/bark.tres" id="5_ly135"] +[ext_resource type="Script" uid="uid://c0ggn4wsaa746" path="res://addons/cosmo_tree_gen/resources/trunk_params.gd" id="6_gjtky"] + +[sub_resource type="Curve" id="Curve_d1m6b"] +_data = [Vector2(0, 1), 0.0, 0.0, 0, 0, Vector2(0.3698336, 1), 0.0, 0.0, 0, 0, Vector2(1, 0.26500046), 0.0, 0.0, 0, 0] +point_count = 3 + +[sub_resource type="Resource" id="Resource_svvho"] +script = ExtResource("1_hnal5") +count = 51 +start = 0.421 +end = 1.0 +angle = 90.0 +length = 0.356 +length_curve = SubResource("Curve_d1m6b") +gnarl = 0.676 +up_force = -0.587 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_x31ta"] +script = ExtResource("3_31x05") +type = 2 +leaf_size = 0.49 +leaf_length_influence = 0.762 +leaf_start = 0.0 + +[sub_resource type="Resource" id="Resource_ykvhj"] +script = ExtResource("6_gjtky") +height = 4.0 +radius_bottom = 0.2 +radius_top = 0.01 +lean = 0.473 +wobble = 0.0 + +[resource] +script = ExtResource("4_bef8d") +trunk_params = SubResource("Resource_ykvhj") +branch_levels = Array[ExtResource("1_hnal5")]([SubResource("Resource_svvho")]) +foliage_params = SubResource("Resource_x31ta") +trunk_material = ExtResource("5_ly135") +foliage_material = ExtResource("2_0b7mx") diff --git a/third_party/cosmo_tree_gen/demo/extra_presets/spruce.tres b/third_party/cosmo_tree_gen/demo/extra_presets/spruce.tres new file mode 100644 index 0000000..6f68c58 --- /dev/null +++ b/third_party/cosmo_tree_gen/demo/extra_presets/spruce.tres @@ -0,0 +1,61 @@ +[gd_resource type="Resource" script_class="CosmoTreePreset" format=3 uid="uid://bsdok0v1dthfm"] + +[ext_resource type="Script" uid="uid://ceh6ii6tlpph4" path="res://addons/cosmo_tree_gen/resources/branch_level.gd" id="1_rth1g"] +[ext_resource type="Material" uid="uid://bhtq0iyc1n5ch" path="res://demo/materials/leaves_06.tres" id="2_e5fhi"] +[ext_resource type="Script" uid="uid://1tt4by0vsl04" path="res://addons/cosmo_tree_gen/resources/foliage_params.gd" id="3_fo1rj"] +[ext_resource type="Script" uid="uid://dlp11kr4f76j3" path="res://addons/cosmo_tree_gen/resources/preset.gd" id="4_odxqs"] +[ext_resource type="Material" uid="uid://b7l8vw0qq0s25" path="res://addons/cosmo_tree_gen/materials/bark.tres" id="5_uhc02"] +[ext_resource type="Script" uid="uid://c0ggn4wsaa746" path="res://addons/cosmo_tree_gen/resources/trunk_params.gd" id="6_0w06b"] + +[sub_resource type="Curve" id="Curve_fy1p0"] +_data = [Vector2(0, 0.88026786), 0.0, -0.14157727, 0, 0, Vector2(1, 0), -0.55938643, 0.0, 0, 0] +point_count = 2 + +[sub_resource type="Resource" id="Resource_xam2y"] +script = ExtResource("1_rth1g") +count = 60 +start = 0.156 +end = 0.97 +angle = 88.0 +length = 0.429 +length_curve = SubResource("Curve_fy1p0") +gnarl = 0.1 +up_force = -0.6 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Curve" id="Curve_x31ta"] +_data = [Vector2(0, 1), 0.0, 0.0, 0, 0, Vector2(0.938999, 0.60456264), 0.0, 0.0, 0, 0] +point_count = 2 + +[sub_resource type="Resource" id="Resource_fla3q"] +script = ExtResource("3_fo1rj") +type = 2 +leaf_count = 11 +leaf_tip = true +leaf_size = 1.0 +leaf_size_curve = SubResource("Curve_x31ta") +leaf_length_influence = 0.33 +leaf_size_variance = 0.2 +leaf_start = 0.05 +leaf_angle = 25.0 +leaf_canopy_normals = 0.5 +leaf_inner_ao = 0.5 +metadata/_custom_type_script = "uid://1tt4by0vsl04" + +[sub_resource type="Resource" id="Resource_jv588"] +script = ExtResource("6_0w06b") +quality = 2 +height = 8.0 +radius_bottom = 0.25 +radius_top = 0.01 +lean = 0.05 +wobble = 0.05 +metadata/_custom_type_script = "uid://c0ggn4wsaa746" + +[resource] +script = ExtResource("4_odxqs") +trunk_params = SubResource("Resource_jv588") +branch_levels = Array[ExtResource("1_rth1g")]([SubResource("Resource_xam2y")]) +foliage_params = SubResource("Resource_fla3q") +trunk_material = ExtResource("5_uhc02") +foliage_material = ExtResource("2_e5fhi") diff --git a/third_party/cosmo_tree_gen/demo/extra_presets/tree_fern.tres b/third_party/cosmo_tree_gen/demo/extra_presets/tree_fern.tres new file mode 100644 index 0000000..98e337d --- /dev/null +++ b/third_party/cosmo_tree_gen/demo/extra_presets/tree_fern.tres @@ -0,0 +1,37 @@ +[gd_resource type="Resource" script_class="CosmoTreePreset" format=3 uid="uid://h55m7o4jmr4p"] + +[ext_resource type="Script" uid="uid://ceh6ii6tlpph4" path="res://addons/cosmo_tree_gen/resources/branch_level.gd" id="1_4yp87"] +[ext_resource type="Material" uid="uid://cyy0xvd2uyh5r" path="res://demo/materials/leaves_05.tres" id="2_5ux5o"] +[ext_resource type="Script" uid="uid://1tt4by0vsl04" path="res://addons/cosmo_tree_gen/resources/foliage_params.gd" id="3_7jwl1"] +[ext_resource type="Script" uid="uid://dlp11kr4f76j3" path="res://addons/cosmo_tree_gen/resources/preset.gd" id="4_ocb5g"] +[ext_resource type="Material" uid="uid://b7l8vw0qq0s25" path="res://addons/cosmo_tree_gen/materials/bark.tres" id="5_m1lvr"] +[ext_resource type="Script" uid="uid://c0ggn4wsaa746" path="res://addons/cosmo_tree_gen/resources/trunk_params.gd" id="6_22eem"] + +[sub_resource type="Resource" id="Resource_7h7tp"] +script = ExtResource("3_7jwl1") +type = 2 +leaf_tip = true +leaf_size = 2.3 +leaf_size_variance = 0.2 +leaf_start = 0.95 +leaf_angle = 62.0 +leaf_canopy_normals = 0.6 +leaf_inner_ao = 0.5 +metadata/_custom_type_script = "uid://1tt4by0vsl04" + +[sub_resource type="Resource" id="Resource_a0ng0"] +script = ExtResource("6_22eem") +quality = 2 +height = 3.2 +radius_bottom = 0.2 +radius_top = 0.16 +lean = 0.25 +wobble = 0.1 +metadata/_custom_type_script = "uid://c0ggn4wsaa746" + +[resource] +script = ExtResource("4_ocb5g") +trunk_params = SubResource("Resource_a0ng0") +foliage_params = SubResource("Resource_7h7tp") +trunk_material = ExtResource("5_m1lvr") +foliage_material = ExtResource("2_5ux5o") diff --git a/third_party/cosmo_tree_gen/demo/extra_presets/willow.tres b/third_party/cosmo_tree_gen/demo/extra_presets/willow.tres new file mode 100644 index 0000000..b4cdb7c --- /dev/null +++ b/third_party/cosmo_tree_gen/demo/extra_presets/willow.tres @@ -0,0 +1,67 @@ +[gd_resource type="Resource" script_class="CosmoTreePreset" format=3 uid="uid://dwg0ccb88gvo2"] + +[ext_resource type="Script" uid="uid://ceh6ii6tlpph4" path="res://addons/cosmo_tree_gen/resources/branch_level.gd" id="1_ngpsf"] +[ext_resource type="Material" uid="uid://cluv26uchlkcx" path="res://demo/materials/leaves_04.tres" id="2_0me7m"] +[ext_resource type="Script" uid="uid://1tt4by0vsl04" path="res://addons/cosmo_tree_gen/resources/foliage_params.gd" id="3_kkdlt"] +[ext_resource type="Script" uid="uid://dlp11kr4f76j3" path="res://addons/cosmo_tree_gen/resources/preset.gd" id="4_ctvk1"] +[ext_resource type="Material" uid="uid://b7l8vw0qq0s25" path="res://addons/cosmo_tree_gen/materials/bark.tres" id="5_3d3xq"] +[ext_resource type="Script" uid="uid://c0ggn4wsaa746" path="res://addons/cosmo_tree_gen/resources/trunk_params.gd" id="6_sieer"] + +[sub_resource type="Resource" id="Resource_u5t42"] +script = ExtResource("1_ngpsf") +count = 7 +terminal = true +start = 0.8 +end = 1.0 +angle = 60.0 +length = 0.95 +radius = 0.703 +up_force = 0.07800000000000029 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_5de16"] +script = ExtResource("1_ngpsf") +count = 3 +terminal = true +start = 0.1 +end = 1.0 +angle = 67.955 +length = 0.8280000000000001 +radius = 0.7999999999999999 +segments = 8 +gnarl = 0.1 +up_force = -3.059 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_h5sl1"] +script = ExtResource("3_kkdlt") +type = 2 +leaf_tip = true +leaf_size = 2.48 +leaf_aspect = 0.3 +leaf_size_variance = 0.2 +leaf_start = 0.0 +leaf_position_offset = Vector3(0, 0.3, 0) +leaf_gravity = 0.9 +leaf_canopy_normals = 0.7 +leaf_inner_ao = 0.4 +metadata/_custom_type_script = "uid://1tt4by0vsl04" + +[sub_resource type="Resource" id="Resource_143ej"] +script = ExtResource("6_sieer") +quality = 2 +height = 3.2 +radius_bottom = 0.4 +radius_top = 0.12 +lean = 0.5 +wobble = 0.3 +sink_depth = 0.12 +metadata/_custom_type_script = "uid://c0ggn4wsaa746" + +[resource] +script = ExtResource("4_ctvk1") +trunk_params = SubResource("Resource_143ej") +branch_levels = Array[ExtResource("1_ngpsf")]([SubResource("Resource_u5t42"), SubResource("Resource_5de16")]) +foliage_params = SubResource("Resource_h5sl1") +trunk_material = ExtResource("5_3d3xq") +foliage_material = ExtResource("2_0me7m") diff --git a/third_party/cosmo_tree_gen/demo/extra_presets/winter_oak.tres b/third_party/cosmo_tree_gen/demo/extra_presets/winter_oak.tres new file mode 100644 index 0000000..45256c1 --- /dev/null +++ b/third_party/cosmo_tree_gen/demo/extra_presets/winter_oak.tres @@ -0,0 +1,88 @@ +[gd_resource type="Resource" script_class="CosmoTreePreset" format=3 uid="uid://dc1t8ig2eag50"] + +[ext_resource type="Script" uid="uid://ceh6ii6tlpph4" path="res://addons/cosmo_tree_gen/resources/branch_level.gd" id="1_731v0"] +[ext_resource type="Material" uid="uid://cmuj42a78mdm" path="res://demo/materials/leaves_02.tres" id="2_ehocu"] +[ext_resource type="Script" uid="uid://1tt4by0vsl04" path="res://addons/cosmo_tree_gen/resources/foliage_params.gd" id="3_tc2gi"] +[ext_resource type="Script" uid="uid://dlp11kr4f76j3" path="res://addons/cosmo_tree_gen/resources/preset.gd" id="4_u882a"] +[ext_resource type="Material" uid="uid://b7l8vw0qq0s25" path="res://addons/cosmo_tree_gen/materials/bark.tres" id="5_opp8c"] +[ext_resource type="Script" uid="uid://c0ggn4wsaa746" path="res://addons/cosmo_tree_gen/resources/trunk_params.gd" id="6_6do0e"] + +[sub_resource type="Resource" id="Resource_7eb7w"] +script = ExtResource("1_731v0") +count = 5 +terminal = true +start = 0.45 +end = 1.0 +angle = 60.0 +length = 0.9 +radius = 0.75 +segments = 5 +gnarl = 0.8 +up_force = 0.2 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_ntps4"] +script = ExtResource("1_731v0") +count = 4 +terminal = true +start = 0.2 +end = 1.0 +length = 0.5 +gnarl = 0.8 +up_force = 0.15 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_urb6m"] +script = ExtResource("1_731v0") +count = 3 +terminal = true +start = 0.3 +end = 1.0 +length = 0.45 +segments = 2 +gnarl = 0.6 +up_force = 0.3 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_ha3dm"] +script = ExtResource("3_tc2gi") +type = 2 +leaf_count = 4 +leaf_tip = true +leaf_size = 0.75 +leaf_angle = 35.0 +leaf_canopy_normals = 0.4 +leaf_inner_ao = 0.6 +metadata/_custom_type_script = "uid://1tt4by0vsl04" + +[sub_resource type="Resource" id="Resource_nk31j"] +script = ExtResource("1_731v0") +count = 7 +start = 0.0 +end = 0.02 +angle = 90.0 +length = 0.8 +segments = 5 +gnarl = 0.8 +up_force = -0.796 +metadata/_custom_type_script = "uid://ceh6ii6tlpph4" + +[sub_resource type="Resource" id="Resource_norpd"] +script = ExtResource("6_6do0e") +quality = 2 +height = 3.5 +radius_bottom = 0.45 +lean = 0.4 +wobble = 0.3 +flare = 0.7 +sink_depth = 0.1 +roots = SubResource("Resource_nk31j") +metadata/_custom_type_script = "uid://c0ggn4wsaa746" + +[resource] +script = ExtResource("4_u882a") +trunk_params = SubResource("Resource_norpd") +branch_levels = Array[ExtResource("1_731v0")]([SubResource("Resource_7eb7w"), SubResource("Resource_ntps4"), SubResource("Resource_urb6m")]) +foliage_params = SubResource("Resource_ha3dm") +trunk_material = ExtResource("5_opp8c") +foliage_material = ExtResource("2_ehocu") diff --git a/third_party/cosmo_tree_gen/demo/materials/leaves_02.tres b/third_party/cosmo_tree_gen/demo/materials/leaves_02.tres new file mode 100644 index 0000000..dbbaec2 --- /dev/null +++ b/third_party/cosmo_tree_gen/demo/materials/leaves_02.tres @@ -0,0 +1,17 @@ +[gd_resource type="ShaderMaterial" format=3 uid="uid://cmuj42a78mdm"] + +[ext_resource type="Texture2D" uid="uid://36cfifubhvvp" path="res://demo/textures/branchlet_02.png" id="1_2m2ct"] +[ext_resource type="Shader" uid="uid://bfq8ep8l8jqps" path="res://addons/cosmo_tree_gen/shaders/leaves.gdshader" id="1_leaves"] + +[resource] +render_priority = 0 +shader = ExtResource("1_leaves") +shader_parameter/albedo = Color(1, 1, 1, 1) +shader_parameter/albedo_texture = ExtResource("1_2m2ct") +shader_parameter/alpha_scissor_threshold = 0.5 +shader_parameter/backlight = Color(0.45, 0.5, 0.25, 1) +shader_parameter/ao_light_affect = 0.5 +shader_parameter/wind_direction = Vector3(1, 0, 0.3) +shader_parameter/wind_strength = 0.1 +shader_parameter/wind_speed = 1.0 +shader_parameter/wind_phase_scale = 2.0 diff --git a/third_party/cosmo_tree_gen/demo/materials/leaves_04.tres b/third_party/cosmo_tree_gen/demo/materials/leaves_04.tres new file mode 100644 index 0000000..6449c38 --- /dev/null +++ b/third_party/cosmo_tree_gen/demo/materials/leaves_04.tres @@ -0,0 +1,17 @@ +[gd_resource type="ShaderMaterial" format=3 uid="uid://cluv26uchlkcx"] + +[ext_resource type="Shader" uid="uid://bfq8ep8l8jqps" path="res://addons/cosmo_tree_gen/shaders/leaves.gdshader" id="1_leaves"] +[ext_resource type="Texture2D" uid="uid://b445t0j8oyb58" path="res://demo/textures/branchlet_04.png" id="1_lme5h"] + +[resource] +render_priority = 0 +shader = ExtResource("1_leaves") +shader_parameter/albedo = Color(1, 1, 1, 1) +shader_parameter/albedo_texture = ExtResource("1_lme5h") +shader_parameter/alpha_scissor_threshold = 0.5 +shader_parameter/backlight = Color(0.45, 0.5, 0.25, 1) +shader_parameter/ao_light_affect = 0.5 +shader_parameter/wind_direction = Vector3(1, 0, 0.3) +shader_parameter/wind_strength = 0.1 +shader_parameter/wind_speed = 1.0 +shader_parameter/wind_phase_scale = 2.0 diff --git a/third_party/cosmo_tree_gen/demo/materials/leaves_05.tres b/third_party/cosmo_tree_gen/demo/materials/leaves_05.tres new file mode 100644 index 0000000..b765e1c --- /dev/null +++ b/third_party/cosmo_tree_gen/demo/materials/leaves_05.tres @@ -0,0 +1,17 @@ +[gd_resource type="ShaderMaterial" format=3 uid="uid://cyy0xvd2uyh5r"] + +[ext_resource type="Texture2D" uid="uid://umkfokbv06cq" path="res://demo/textures/branchlet_05.png" id="1_ep1kh"] +[ext_resource type="Shader" uid="uid://bfq8ep8l8jqps" path="res://addons/cosmo_tree_gen/shaders/leaves.gdshader" id="1_leaves"] + +[resource] +render_priority = 0 +shader = ExtResource("1_leaves") +shader_parameter/albedo = Color(1, 1, 1, 1) +shader_parameter/albedo_texture = ExtResource("1_ep1kh") +shader_parameter/alpha_scissor_threshold = 0.5 +shader_parameter/backlight = Color(0.45, 0.5, 0.25, 1) +shader_parameter/ao_light_affect = 0.5 +shader_parameter/wind_direction = Vector3(1, 0, 0.3) +shader_parameter/wind_strength = 0.1 +shader_parameter/wind_speed = 1.0 +shader_parameter/wind_phase_scale = 2.0 diff --git a/third_party/cosmo_tree_gen/demo/materials/leaves_06.tres b/third_party/cosmo_tree_gen/demo/materials/leaves_06.tres new file mode 100644 index 0000000..ace0275 --- /dev/null +++ b/third_party/cosmo_tree_gen/demo/materials/leaves_06.tres @@ -0,0 +1,17 @@ +[gd_resource type="ShaderMaterial" format=3 uid="uid://bhtq0iyc1n5ch"] + +[ext_resource type="Shader" uid="uid://bfq8ep8l8jqps" path="res://addons/cosmo_tree_gen/shaders/leaves.gdshader" id="1_leaves"] +[ext_resource type="Texture2D" uid="uid://bjygtvpu04yly" path="res://demo/textures/branchlet_06.png" id="1_pj0uu"] + +[resource] +render_priority = 0 +shader = ExtResource("1_leaves") +shader_parameter/albedo = Color(1, 1, 1, 1) +shader_parameter/albedo_texture = ExtResource("1_pj0uu") +shader_parameter/alpha_scissor_threshold = 0.5 +shader_parameter/backlight = Color(0.45, 0.5, 0.25, 1) +shader_parameter/ao_light_affect = 0.5 +shader_parameter/wind_direction = Vector3(1, 0, 0.3) +shader_parameter/wind_strength = 0.1 +shader_parameter/wind_speed = 1.0 +shader_parameter/wind_phase_scale = 2.0 diff --git a/third_party/cosmo_tree_gen/demo/materials/leaves_07.tres b/third_party/cosmo_tree_gen/demo/materials/leaves_07.tres new file mode 100644 index 0000000..530ad62 --- /dev/null +++ b/third_party/cosmo_tree_gen/demo/materials/leaves_07.tres @@ -0,0 +1,17 @@ +[gd_resource type="ShaderMaterial" format=3 uid="uid://ud2fyw42vi52"] + +[ext_resource type="Texture2D" uid="uid://bfi4necapptje" path="res://demo/textures/branchlet_07.png" id="1_ec16d"] +[ext_resource type="Shader" uid="uid://bfq8ep8l8jqps" path="res://addons/cosmo_tree_gen/shaders/leaves.gdshader" id="1_leaves"] + +[resource] +render_priority = 0 +shader = ExtResource("1_leaves") +shader_parameter/albedo = Color(1, 1, 1, 1) +shader_parameter/albedo_texture = ExtResource("1_ec16d") +shader_parameter/alpha_scissor_threshold = 0.4 +shader_parameter/backlight = Color(0.45, 0.5, 0.25, 1) +shader_parameter/ao_light_affect = 0.5 +shader_parameter/wind_direction = Vector3(1, 0, 0.3) +shader_parameter/wind_strength = 0.1 +shader_parameter/wind_speed = 1.0 +shader_parameter/wind_phase_scale = 2.0 diff --git a/third_party/cosmo_tree_gen/demo/textures/branchlet_02.png b/third_party/cosmo_tree_gen/demo/textures/branchlet_02.png new file mode 100644 index 0000000..ead7685 Binary files /dev/null and b/third_party/cosmo_tree_gen/demo/textures/branchlet_02.png differ diff --git a/third_party/cosmo_tree_gen/demo/textures/branchlet_04.png b/third_party/cosmo_tree_gen/demo/textures/branchlet_04.png new file mode 100644 index 0000000..7e846d1 Binary files /dev/null and b/third_party/cosmo_tree_gen/demo/textures/branchlet_04.png differ diff --git a/third_party/cosmo_tree_gen/demo/textures/branchlet_05.png b/third_party/cosmo_tree_gen/demo/textures/branchlet_05.png new file mode 100644 index 0000000..8bd0312 Binary files /dev/null and b/third_party/cosmo_tree_gen/demo/textures/branchlet_05.png differ diff --git a/third_party/cosmo_tree_gen/demo/textures/branchlet_06.png b/third_party/cosmo_tree_gen/demo/textures/branchlet_06.png new file mode 100644 index 0000000..8703a84 Binary files /dev/null and b/third_party/cosmo_tree_gen/demo/textures/branchlet_06.png differ diff --git a/third_party/cosmo_tree_gen/demo/textures/branchlet_07.png b/third_party/cosmo_tree_gen/demo/textures/branchlet_07.png new file mode 100644 index 0000000..702b27e Binary files /dev/null and b/third_party/cosmo_tree_gen/demo/textures/branchlet_07.png differ diff --git a/third_party/cosmo_tree_gen/docs/batch_generation.md b/third_party/cosmo_tree_gen/docs/batch_generation.md new file mode 100644 index 0000000..9f9a65d --- /dev/null +++ b/third_party/cosmo_tree_gen/docs/batch_generation.md @@ -0,0 +1,144 @@ +# Batch generation + +`demo/batch_generator.tscn` generates tens of trees with a single click: each one gets a random seed +and small variations of its preset (height, lean, branch angles...) and is saved as `_.glb`. + +## Using the demo batch generator +1. Open `demo/batch_generator.tscn` and select the `BatchGenerator` node. +1. Add the presets you want to `presets`. It already has `pine.tres` and `ash.tres`. +1. Set `amount`, the number of trees per preset. With 2 presets and an `amount` of 10, you get 20 trees. +1. Choose the folder in `export_dir`. It must exist, otherwise the export fails. +1. Click `Generate` in the inspector. +1. The Output panel prints the progress, the path and the generation time of each tree. + +The trees are exported one by one, and each export waits for Godot to import the file, so big batches take a while. +The file name is the preset file name plus the seed, e.g. `ash.tres` makes `ash_1234.glb`, with `Ash` as the root node. + +### Parameters +| Parameter | Default | Description | +| --------- | ------- | ----------- | +| `presets` | Empty | Presets to generate trees from. Each preset gets `amount` trees. It can't have empty slots. | +| `amount` | `1` | Number of trees per preset. | +| `export_dir` | Empty | Folder where the trees are saved. It must exist. | +| `instantiate` | `false` | Adds the generated `CosmoTreeGen` nodes to the scene when the batch ends, in a row 5 m apart and with a random rotation. Save the scene to keep them. | +| `preview` | `false` | Shows each tree in the scene for `preview_time` seconds after exporting it. It makes the batch slower. | +| `preview_time` | `1.0 s` | How long each tree is shown with `preview`. | +| *Generate* | | Button. Starts the batch. It does nothing if a batch is already running. | + +Note: the instantiated trees are `CosmoTreeGen` nodes, not the exported files. Use the `.glb` files in your game, see [Getting Started](getting_started.md#next-steps). +Intantiating trees may be useful for fine tuning the ones you didn't like, bad seeds, etc... and re-exported again. + +## Using it in your project +1. Copy `demo/batch_generator.gd` to your project. +1. Add a `TreeBatchGenerator` node (Ctrl+A) to any scene, or attach the script to a `Node`. +1. Change the script to your needs: variations, collisions, materials... + +## Writing your own batch script +The minimum is: create a `CosmoTreeGen`, apply a preset, generate it, export it and free it. + +```gdscript +@tool +extends Node + +@export var preset: CosmoTreePreset +@export var amount: int = 10 +@export_dir var export_dir: String +@export_tool_button("Generate", "Add") var generate_button: Callable = generate + + +func generate() -> void: + for i in amount: + var tree := CosmoTreeGen.new() + tree.auto_generate = false + tree.noise_seed = i + tree.apply_preset(preset) + tree.generate() + + tree.name = "MyTree" + var path: String = "%s/my_tree_%d.glb" % [export_dir, i] + var err := await tree.export_gltf(path, {"Use External Material": true}) + if err != OK: + push_error("error exporting %s: %s" % [path, error_string(err)]) + + tree.free() +``` + +- The script must be `@tool`, `export_gltf()` only works in the editor. Outside the editor it returns `ERR_UNAVAILABLE`. +- `apply_preset()` copies the preset, so you can change the parameters of the tree without changing the preset file. +- A tree created with `CosmoTreeGen.new()` isn't built until you call `generate()`. Call it once, after all your changes. +- Turn off `auto_generate`, so the tree is only built when you call `generate()`. Otherwise, if the tree is in the scene, every parameter change rebuilds it. +- `name` is the name of the root node in the exported scene. +- `export_gltf()` must be awaited. The options use the same names as in the export window, see [Exporting from scripts](exporting.md#exporting-from-scripts). +- `free()` the tree when you're done. It's not in the scene, so nothing else will free it. + +### Random seeds +`set_random_seed()` sets a random `noise_seed`, but it can be negative. Use `absi()` to avoid file names like `ash_-1234.glb`: + +```gdscript +tree.set_random_seed() +tree.noise_seed = absi(tree.noise_seed) +``` + +## Adding variations +The seed only changes the random values of the tree, the parameters are the same for every tree of a preset. +To get more different trees, change the parameters after `apply_preset()` and before `generate()`: + +```gdscript +tree.apply_preset(preset) + +var rng := RandomNumberGenerator.new() +rng.seed = tree.noise_seed + +tree.trunk_params.height *= rng.randf_range(0.8, 1.2) +tree.trunk_params.radius_bottom *= rng.randf_range(0.9, 1.1) +tree.trunk_params.lean *= rng.randf_range(0.7, 1.3) + +for level: CosmoBranchLevel in tree.branch_levels: + level.angle *= rng.randf_range(0.9, 1.1) + level.length *= rng.randf_range(0.9, 1.1) + level.end = minf(level.end * rng.randf_range(0.9, 1.1), 1.0) + +tree.foliage_params.leaf_angle *= rng.randf_range(0.9, 1.1) + +tree.generate() +``` + +Some tips: +- Use a `RandomNumberGenerator` with the tree seed instead of `randf()`. The same preset and seed always make the same tree, so with the file name (`ash_1234.glb`) you can make that tree again. + Note: if you change the variations in your script, the same seed will make a different tree. +- Multiply instead of adding. `*= rng.randf_range(0.9, 1.1)` keeps the value close to the preset one and never changes its sign. + Adding can end in negative values, e.g. a `lean` of `0.05` plus `-0.1`. +- Parameters from 0 to 1, like `start`, `end` or `leaf_start`, can go over 1 when multiplied. Cap them with `minf(value, 1.0)`. +- Be careful with integers like `count` or `leaf_count`: adding `randi_range(-3, 3)` to a small value can go below the minimum. + +## Collisions, LODs, impostor and materials +Presets don't save `generate_lod` or the collision parameters, so set them in your script. +You can also give the whole batch your own materials: + +```gdscript +tree.apply_preset(preset) + +tree.generate_lod = true +tree.collision_type = CosmoTreeGen.CollisionType.TRIMESH +tree.collision_max_height = tree.trunk_params.height * 0.25 +tree.foliage_collision_type = CosmoTreeGen.FoliageCollisionType.HULL + +tree.trunk_material = preload("res://materials/my_bark.tres") +tree.foliage_material = preload("res://materials/my_leaves.tres") + +tree.generate() + +var options: Dictionary = { + "Include Collisions": true, + "Use External Material": true, + "Impostor": 1, +} +var err := await tree.export_gltf(path, options) +``` + +- Set the materials after `apply_preset()`, it replaces them with the preset ones. +- `collision_max_height` is in meters. If the height changes between trees, use a fraction of `trunk_params.height`, after the variations. +- Collisions are only exported with `"Include Collisions": true`. +- The LOD distances and ratios are the same for the whole batch, they come from the [settings](settings.md). +- The impostor is only baked with `"Impostor": 1` (Static) or `2` (Octahedral). Each tree gets its own `_impostor.res`, + and its export takes around 0.1-0.2s longer with Static, and around 0.6s with Octahedral. diff --git a/third_party/cosmo_tree_gen/docs/exporting.md b/third_party/cosmo_tree_gen/docs/exporting.md new file mode 100644 index 0000000..ef862cf --- /dev/null +++ b/third_party/cosmo_tree_gen/docs/exporting.md @@ -0,0 +1,115 @@ +# Exporting + +Trees can be exported as `glb` or `glTF`, with LODs, impostor and collisions. + +## How to export +1. Select a `CosmoTreeGen` node. +1. Click `Export glb/glTF` in the toolbar. +1. Choose the folder and the file name, by default it's the node name in snake_case. + The extension can be `.glb` or `.gltf`, the default one can be changed in the [settings](settings.md). +1. Check the export options you want and save. + +The tree will appear in the FileSystem already imported. Now you can use it as is or as `New Inherited Scene`. + +## Export options +The default value of each option can be changed in the [settings](settings.md). + +- *Include Collisions*: Exports the trunk and foliage collisions. Default on. + Only works if `collision_type` and/or `foliage_collision_type` are set, otherwise there's nothing to export. +- *Export Images*: Exports the textures inside the glTF. Default off. + Note: if both "Export Images" and "Use External Material" are off, the tree will be imported without textures. +- *Use External Material*: The imported tree uses your material files (`.tres`) + instead of a copy stored in the glTF. Default on. + This is recommended, glTF can't store shaders, so without it the leaves lose the wind sway shader. + Also, any change to your materials will apply to all the exported trees. + Note: only materials saved as their own file are linked, built-in materials are exported as usual. +- *Impostor*: Bakes a billboard of the tree and adds it as the last LOD. Default *Static*. + - *None*: No impostor will be generated. + - *Static*: A quad that turns around its vertical axis to face the camera, with one view of the tree captured from the front. + - *Octahedral*: A quad that faces the camera from any angle and blends between views of the tree captured from the side to straight above (144 with the default settings). + It looks right from every side and from above, but uses more memory, see the [settings](settings.md#cosmo-tree-gen--impostor). + + Its material is saved next to the glTF as `_impostor.res`, and it's always linked as an external material, + even with "Use External Material" off. + +## What's exported +The exported scene has the same nodes as the `CosmoTreeGen` node, and the root node takes its name. + +- *CosmoTree*: Trunk and foliage combined in one mesh. + If `combine_trunk_and_foliage` is off, there are two meshes instead: *Trunk* and *Foliage*. +- *_LOD0*, *_LOD1*, *_LOD2*: If `generate_lod` is on, each mesh has one of these suffixes. +- *Impostor_LOD3*: If "Impostor" isn't None, the impostor is generated during the export. +- *Collision* and *FoliageCollision*: If "Include Collisions" is on. + +## LODs and impostor +If `generate_lod` or *Impostor* isn't None, the exporter also changes the `.import` file of the tree: +- Sets the visibility ranges of each LOD and the impostor, using the distances from the [settings](settings.md#example-with-the-default-settings). + With an impostor, the last LOD (LOD2, or the tree itself if it has no LODs) ends at `impostor_distance`. +- Sets the `cast_shadow` of the impostor from the settings. +- Disables Godot's automatic LOD generation (`meshes/generate_lods`), because it breaks the leaf cards. Don't turn it back on. +- Adds an import script (`lod_post_import.gd`) that restores the `custom_aabb` of the LODs, so they all swap at the same distance. + With an impostor, the box is wider, so the billboard isn't cut at the screen edges when it turns. + It also adds the groups `cosmo_tree` (root), `cosmo_tree_mesh` (meshes) and `cosmo_tree_collision` (collisions). + +Note: if you change the LOD or impostor settings, you need to export the tree again. +Note: the impostor is baked on every export. With *Use External Material*, changes to your materials reach the exported LODs, but not the impostor: it keeps what it was baked with until you export again. + +### Impostor types +These gifs show the difference between the *Static* and *Octahedral* impostors. + +*Static* is a single picture of the tree on a quad that turns around its vertical axis to face the camera. +It looks right from the side, but from above you see the card edge-on, so it doesn't work for games with a top-down or high camera. + +![Static Impostor GIF](../.github/images/example_static_impostor.gif) + +*Octahedral* uses the same quad, but bakes 144 views of the tree into an atlas and blends the 3 closest to the camera angle, +so it holds up from any angle above the ground. Each view has less resolution than the *Static* texture (84 px vs 512 px with the default settings), +but it's barely noticeable from a distance. + +![Octahedral Impostor GIF](../.github/images/example_octahedral_impostor.gif) + +**Which one to choose?** + +Use *Static* if the camera stays close to the ground, like in first or third person games, +or if you need to save memory: with the default settings its texture has about 5 times fewer pixels than the *Octahedral* atlas. + +Use *Octahedral* if the camera goes up or orbits around the trees, like in strategy, +flight or city-builder games. It looks right from any angle above the ground, and with `cast_shadow` on, its shadow also follows the shape of the tree. + +Side to side comparison. + +![Impostor Comparison GIF](../.github/images/impostor_comparison.gif) + +## Exporting from scripts +Trees can also be exported from a `@tool` script with `export_gltf()`. The options use the same names as in the export window: + +```gdscript +var tree := CosmoTreeGen.new() +tree.apply_preset(preload("res://addons/cosmo_tree_gen/presets/ash.tres")) +tree.generate() + +var options: Dictionary = { + "Include Collisions": true, + "Use External Material": true, + "Impostor": 2, +} +var err := await tree.export_gltf("res://trees/ash.glb", options) +``` + +- If you create the tree from code, call `generate()` before exporting. +- `"Impostor"` takes the index of the option: `0` None, `1` Static, `2` Octahedral. +- Missing options are off, the default values from the settings are only used by the export window. +- It only works in the editor. + +See `demo/batch_generator.gd` for a full example. + +Note: the impostor material uses `impostor_static.gdshader` or `impostor_octahedral.gdshader` from `addons/cosmo_tree_gen/shaders/`, copy them or keep the addon in your project. + +## Known issues / Limitations +- *Export Images*: The textures are saved without a name (`.png`). +- *Impostor*: It has no wind. +- *Impostor* - *Static*: It's a single view of the tree, captured from the front (+Z). + It looks the same from every side, and like a thin card when seen from above. +- *Impostor* - *Octahedral*: With `cast_shadow` on, its shadow on the ground follows the shape of the tree, + but the impostor also shadows itself and part of the canopy turns dark. +- *Impostor*: Exporting again with *None* doesn't delete the old `_impostor.res`. diff --git a/third_party/cosmo_tree_gen/docs/getting_started.md b/third_party/cosmo_tree_gen/docs/getting_started.md new file mode 100644 index 0000000..6bc9882 --- /dev/null +++ b/third_party/cosmo_tree_gen/docs/getting_started.md @@ -0,0 +1,39 @@ +# Getting Started + +## Requirements +Godot 4.6+ is required. Developed in 4.6.2. + +## Installation +Copy `addons/cosmo_tree_gen/` to your project and activate the plugin, `Project > Project Settings > Plugins`. +It must be in `res://addons/cosmo_tree_gen/`, otherwise Godot won't find the plugin. +Once activated, some extra settings will be added to `Project Settings > General > Cosmo Tree Gen`. [More info about settings](settings.md) + +## My first tree in 5 minutes +1. Create a new 3D scene or use an existing one. +1. Add a new `CosmoTreeGen` node (Ctrl+A). +1. Once the node is added, you will see a toolbar above the 3D viewport when that node is selected. +1. Click on `Preset > Ash` to load the included "Ash" preset. +1. Tweak the `trunk_params`, `branch_levels` and `foliage_params` in the inspector. + For example, change `trunk_params.height` to increase the height of the trunk(s). + [More info about what parameters do](parameters.md). +1. Click on `Seed` until you find a tree you like. +1. Optionally, change bark and foliage materials under `Materials`, the addon includes materials, but you can (and should) use yours. + Note that if you're using icosphere foliage, you should use a material with UV1 Triplanar activated. Otherwise it will look bad. + The included `foliage.tres` already has UV1 Triplanar activated. + Leaf cards take the shape of the foliage albedo texture (if `leaf_aspect` is 0), and the bark texture size depends on `texel_density`. +1. You can save the modified params as a new custom preset: `Preset > Save Preset`. +1. Optionally, enable `generate_lod` for LODs and set `collision_type` and/or `foliage_collision_type` for collisions. + If none of them are set, "Include Collisions" won't export anything. [More info about LODs](settings.md) +1. Once you're happy with your tree, click `Export glb/glTF`. +1. A save window will pop up, there are four extra options there: "Include Collisions", "Export Images", "Use External Material" and "Impostor". [More info about export options](exporting.md) +1. Save it to the desired folder, and that's all. + The tree will appear in the FileSystem already imported. Now you can use the `glb/glTF` as is or as `New Inherited Scene`. + If it has LODs or an impostor, they will swap automatically with the distance. + +## Next steps +- You don't need to export the tree, the `CosmoTreeGen` node can be used as is for quick prototyping. +However, this isn't recommended for production, because the tree is generated every time the scene is loaded, which can slow down loading. +Also, if you have multiple instances of the same tree with the same seed, their meshes won't be shared, resulting in duplicate draw calls. +- Check the `demo` folder, there are 7 more presets in `demo/extra_presets`. +- Generate tens of trees at once with `demo/batch_generator.tscn`. Copy `batch_generator.gd` to your project and change it to your needs. +- Read more about [parameters](parameters.md), [settings](settings.md) and [exporting](exporting.md). diff --git a/third_party/cosmo_tree_gen/docs/parameters.md b/third_party/cosmo_tree_gen/docs/parameters.md new file mode 100644 index 0000000..c71d407 --- /dev/null +++ b/third_party/cosmo_tree_gen/docs/parameters.md @@ -0,0 +1,169 @@ +# Parameters + +All the parameters of the `CosmoTreeGen` node and its resources. +The same descriptions are in the inspector, hover a parameter to see them. + +## How a tree is built +1. **Trunks**: `trunk_params` makes one or more trunks, growing from the same base. They can have roots. +1. **Branches**: each `CosmoBranchLevel` in `branch_levels` grows branches from every branch of the previous level. The first level grows from the trunks. +1. **Foliage**: `foliage_params` puts icospheres or leaf cards on the branches of the last level, or on the trunks if there are no branch levels. + +Branches are relative to their parent: `length` and `radius` are fractions of the parent ones, and `start`, `end` and the curves go from 0 (base of the parent) to 1 (its tip). +So taller trunks also get longer branches. + +Every change rebuilds the tree, unless `auto_generate` is off. + +## CosmoTreeGen +| Parameter | Default | Description | +| --------- | ------- | ----------- | +| *Generate tree* | | Button. Rebuilds the meshes, collisions and LODs from the current parameters. Use it when `auto_generate` is off, or after changing the [settings](settings.md). | +| `auto_generate` | `true` | Rebuilds the tree every time a parameter changes. Turn it off for heavy trees and use *Generate tree*. | +| `noise_seed` | `42` | Seed of all the random values. The same seed and parameters always make the same tree. The `Seed` button in the toolbar sets a random one. | + +### Tree Parameters +| Parameter | Default | Description | +| --------- | ------- | ----------- | +| `trunk_params` | | Shape of the trunks and their roots. See [CosmoTrunkParams](#cosmotrunkparams). | +| `branch_levels` | Empty | Branch levels, from the trunk out. The first level grows from the trunks, the second from the first level branches, and so on. See [CosmoBranchLevel](#cosmobranchlevel). | +| `foliage_params` | | Foliage type and shape. It grows on the branches of the last level, or on the trunks if there are none. See [CosmoFoliageParams](#cosmofoliageparams). | + +### Meshes +| Parameter | Default | Description | +| --------- | ------- | ----------- | +| `generate_lod` | `false` | Generates 3 LODs (`_LOD0`, `_LOD1` and `_LOD2`) that swap with the distance. Their triangle ratios and distances are in `Project Settings > Cosmo Tree Gen > Generator`, see [Settings](settings.md). | +| `lod_trunk_share` | `0.33` | Share of each LOD triangle budget kept for the trunk, the foliage gets the rest. Raise it to keep more trunk detail, lower it to keep more leaves. Only used with `generate_lod`. See [How the triangle budget works](settings.md#how-the-triangle-budget-works). | +| `combine_trunk_and_foliage` | `true` | Puts the trunk and the foliage in a single mesh, one surface each. 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). | +| `flat_shading` | `false` | One normal per face for a low-poly/PSX look, on the trunk, branches, roots and icospheres. Leaf cards aren't affected. | +| `create_trunk` | `true` | Builds the trunk, branches and roots mesh. When off, the branches are still generated, so the foliage and the collisions don't change. | +| `create_foliage` | `true` | Builds the foliage mesh. When off, there's no foliage collision either. | + +### Collision +| Parameter | Default | Description | +| --------- | ------- | ----------- | +| `collision_type` | `None` | Type of collision to generate for the trunk, roots and branches. See the types below. | +| `collision_level` | `0` | Maximum level of branches to create collisions for. Level 0 generates collisions just for the trunk/s and level 1 for trunks, roots and first level of branches. | +| `collision_max_height` | `0 m` | Cuts the trunk, root and branch collisions at this height, in local space. Branches starting above it get no collision. 0 means no limit. | +| `foliage_collision_type` | `None` | Type of collision to generate for the foliage. See the types below. | +| `preview_collision` | `false` | Draws the collision shapes on top of the tree. Editor only, never exported. | +| `collision_layer` | `1` | Physics layers of the generated StaticBody3Ds, trunk and foliage. | +| `collision_mask` | `1` | Physics layers scanned by the generated StaticBody3Ds, trunk and foliage. | + +The collisions are `StaticBody3D` child nodes: `Collision` for the trunk, roots and branches, and `FoliageCollision` for the foliage. + +`collision_type`: + +| Type | Description | +| ---- | ----------- | +| `None` | Do not generate collision shapes. | +| `Simple Convex` | One convex collision shape per branch, up to `collision_level`. Curved branches get a looser fit. | +| `Multiple Convex` | One convex collision shape per branch segment, up to `collision_level`. More precise than Simple Convex, it's solid so pushes out bodies. Uses more memory than Trimesh. | +| `Trimesh` | A single trimesh collision shape, using branch levels up to `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. | + +`foliage_collision_type`: + +| Type | Description | +| ---- | ----------- | +| `None` | Do not generate collision shapes for foliage. | +| `Hull` | One convex collision shape around the whole canopy. | +| `Spheres` | One `SphereShape3D` per branch tip. | + +### Materials +| Parameter | Default | Description | +| --------- | ------- | ----------- | +| `trunk_material` | Empty | Material of the trunk, branches and roots. The width of its albedo texture (the `albedo_texture` uniform on a ShaderMaterial) and `texel_density` set the bark UV scale. | +| `foliage_material` | Empty | Material of the leaf cards or the icospheres. Leaf cards take the shape of its albedo texture (the `albedo_texture` uniform on a ShaderMaterial), see `leaf_aspect`. Icospheres have no UVs, they need a material with UV1 Triplanar. The included leaves shader adds wind sway and uses `leaf_inner_ao`. | +| `texel_density` | `64 px/m` | Bark texture pixels per meter, the same on trunks, branches and roots. The texture repeats every `texture width / texel_density` meters, e.g. a 1024 px texture with 64 px/m repeats every 16 m. Without an albedo texture, 128 px is used. | + +The addon includes some materials in `addons/cosmo_tree_gen/materials`: `bark.tres` for the trunk, `leaves_01.tres` and `leaves_03.tres` for leaf cards, and `foliage.tres` for icospheres (it already has UV1 Triplanar). + +## CosmoTrunkParams +Shape of the trunks of a `CosmoTreeGen`, and their roots. + +| Parameter | Default | Description | +| --------- | ------- | ----------- | +| `quality` | `1` | Mesh detail of the trunks, branches and roots. Trunks get 6 × quality sides and 3 × quality height segments, branches and roots 2 sides less. Branch segments are set per level, in `CosmoBranchLevel.segments`. | +| `amount` | `1` | Number of trunks, growing from the same base in a circle. Each one gets its own branches. | +| `spread` | `1.0` | Distance between the trunk bases, relative to `radius_bottom`. 0 grows them all from the same point and 1 makes them touch. Only used with 2 or more trunks. | +| `height` | `4.5 m` | Height of the trunks. Branch lengths are relative to their parent, so taller trunks also get longer branches. | +| `radius_bottom` | `0.35 m` | Radius at the base of the trunks, before the `flare`. | +| `radius_top` | `0.1 m` | Radius at the top of the trunks. It goes linearly from `radius_bottom` to this. | +| `lean` | `0.6 m` | How far the top of the trunks moves sideways. It bends more towards the top. The direction comes from the seed. Multiple trunks lean away from each other. | +| `wobble` | `0.15 m` | Random sideways bending of the trunks. Strongest in the middle, the base and the top don't move. | +| `flare` | `0.0` | Widens the base of the trunks. 1 doubles the radius at the ground, 0 disables it. | +| `flare_height` | `0.15` | How high the flare reaches, as a fraction of `height`. | +| `flare_lobes` | `0.6` | How uneven the flare is around the trunk. 0 keeps it round, 1 makes strong lobes. | +| `sink_depth` | `0 m` | Extends the trunks this many meters underground, so they don't float on slopes. | +| `roots` | Empty | Branch level that grows the roots from each trunk. Roots get no foliage. Use a low `end`, a high `angle` and a negative `up_force` so they spread near the ground, see the Ash preset. It's a [CosmoBranchLevel](#cosmobranchlevel). | + +## CosmoBranchLevel +A level of branches of a `CosmoTreeGen`, grown from every branch of the previous level, or from the trunks for the first one. +It's also used for the `roots` of [CosmoTrunkParams](#cosmotrunkparams). + +| Parameter | Default | Description | +| --------- | ------- | ----------- | +| `count` | `6` | Branches grown from each parent branch, spread around it between `start` and `end`. | +| `terminal` | `false` | Grows one more branch from the tip of each parent, with its direction and radius, meshed as a single tube with it. Use it to continue the trunk or the branches past the child branches. It isn't counted in `count`. | +| `start` | `0.4` | Where the branches start along the parent, 0 is its base and 1 its tip. | +| `end` | `0.9` | Where the branches end along the parent, 0 is its base and 1 its tip. | +| `angle` | `50°` | Angle between the branches and their parent. 0 grows them along the parent, 90 perpendicular. | +| `length` | `0.4` | Length of the branches, as a fraction of their parent's length. | +| `length_curve` | Empty | Multiplies `length` by the curve value where each branch grows on the parent (0 base, 1 tip). For example, a curve going down makes a conical, pine-like shape. Branches where it's 0 aren't grown. | +| `radius` | `0.6` | Radius of the branches at their base, as a fraction of the parent radius where they grow. Branches taper to 20% of it at the tip. Terminal branches keep the parent radius instead. | +| `segments` | `3` | Segments per branch. More segments make smoother bends with `gnarl` and `up_force`. With Multiple Convex collision, each segment is a collision shape. | +| `gnarl` | `0.3` | Random bending of the branches. 0 keeps them straight. | +| `up_force` | `0.5` | Bends the branches up when positive, or down when negative, like a willow. Broken branches always bend down, see `broken_chance`. | +| `broken_chance` | `0.0` | Chance for each branch to be broken: shorter, bent down, and without child branches or foliage. | + +## CosmoFoliageParams +Foliage of a `CosmoTreeGen`: icospheres or leaf cards on the branches of the last level. +Only the parameters of the selected `type` are shown in the inspector. + +| Parameter | Default | Description | +| --------- | ------- | ----------- | +| `type` | `Icospheres` | Foliage type. See the types below. | + +| Type | Description | +| ---- | ----------- | +| `None` | No foliage. | +| `Icospheres` | One noisy icosphere at the tip of each branch of the last level, and at the top of each trunk. Needs a material with UV1 Triplanar. | +| `Leaves` | Textured cards along the branches of the last level. | + +### Icospheres +| Parameter | Default | Description | +| --------- | ------- | ----------- | +| `icosphere_length_influence` | `0.4` | How much the branch length scales the icospheres. 0 gives them all `icosphere_radius`, 1 scales it by the branch length relative to the trunk. | +| `icosphere_radius` | `1.0 m` | Radius of the icospheres, before `icosphere_length_influence`. | +| `icosphere_subdivisions` | `1` | Detail of the icospheres, each level has 4 times the triangles: 20, 80, 320, 1280 and 5120 per icosphere. | +| `icosphere_amplitude` | `0.4` | How much the noise deforms the icospheres, as a fraction of their radius. 0 keeps them round. | +| `icosphere_frequency` | `1.5` | Frequency of the deformation noise. Higher values make more and smaller bumps. | + +### Leaves +| Parameter | Default | Description | +| --------- | ------- | ----------- | +| `leaf_count` | `12` | Leaves per branch, spread from `leaf_start` to the tip. With `leaf_double`, each leaf is 2 cards. | +| `leaf_tip` | `false` | Adds one more leaf at the tip of each branch, pointing along it. | +| `leaf_size` | `0.6 m` | Height of the leaf cards, before `leaf_size_variance`, `leaf_size_curve` and `leaf_length_influence`. | +| `leaf_aspect` | `0.0` | Width / height of the leaf cards, their height is `leaf_size`. 0 takes it from the albedo texture of the foliage material, or square if it has none. | +| `leaf_size_curve` | Empty | Multiplies `leaf_size` by the curve value where each leaf grows on the branch (0 base, 1 tip). Leaves where it's 0 are skipped. | +| `leaf_length_influence` | `0.0` | How much the branch length scales the leaves. 0 gives them all the same size, 1 scales them by the branch length relative to the longest branch. | +| `leaf_size_variance` | `0.3` | Random size variation of each leaf, 0.3 is ±30%. | +| `leaf_start` | `0.3` | Where the leaves start along the branch, 0 is its base and 1 its tip. | +| `leaf_position_offset` | `Vector3.ZERO` | Offset applied to each leaf's position relative to its attachment point. | +| `leaf_angle` | `40°` | Angle between the leaf cards and the branch. 0 points them along the branch, 90 perpendicular. | +| `leaf_gravity` | `0.0` | How strong leaves are tilted toward the down direction. | +| `leaf_double` | `true` | Adds a second card to each leaf, crossed at 90°, so they don't look flat from the side. Doubles the foliage triangles. | +| `leaf_canopy_normals` | `0.8` | Blends the card normals towards a rounded shape around the whole canopy, so it's lit as one volume. 0 keeps the flat card normals. | +| `leaf_inner_ao` | `0.35` | Brightness of the leaves in the center of the canopy, it fades to 1 towards the edges. 1 disables it. Stored in the vertex color, the included leaves shader uses it as AO. | + +## CosmoTreePreset +A saved tree type: the parameters and materials of a `CosmoTreeGen`. +The toolbar `Preset` menu lists every `CosmoTreePreset` saved as `.tres` in the project, and `Preset > Save Preset` saves the current tree as a new one. + +A preset saves: +- `trunk_params`, `branch_levels` and `foliage_params`. +- `trunk_material`, `foliage_material` and `texel_density`. +- `combine_trunk_and_foliage`, `flat_shading`, `create_trunk`, `create_foliage` and `lod_trunk_share`. + +The rest stays as it is on the node when you load a preset: `noise_seed`, `auto_generate`, `generate_lod`, and the collision parameters. + +Loading a preset copies its parameters, so editing the tree doesn't change the preset file. Use `Preset > Save Preset` to keep the changes. diff --git a/third_party/cosmo_tree_gen/docs/settings.md b/third_party/cosmo_tree_gen/docs/settings.md new file mode 100644 index 0000000..ec3f73b --- /dev/null +++ b/third_party/cosmo_tree_gen/docs/settings.md @@ -0,0 +1,75 @@ +# Settings + +There are a few options to customize the addon behaviour. +They're on `Project Settings > General > Cosmo Tree Gen`. + +## Cosmo Tree Gen > Generator +These settings control the automatic LODs and apply to every tree in the project. +They only have an effect on trees with `generate_lod` enabled, except `lod_end_distance`, +which also applies to trees exported with an impostor. + +Trees don't update by themselves when you change a setting: press **Generate tree** on each +`CosmoTreeGen` node to apply it. Trees you already exported need to be exported again. + +| Setting | Default | Description | +| ------- | ------- | ----------- | +| `lod1_ratio` | `0.4` | Triangle budget for LOD1, as a fraction of LOD0's triangles (trunk + foliage). | +| `lod2_ratio` | `0.15` | Triangle budget for LOD2, as a fraction of LOD0's triangles. | +| `lod1_distance` | `50 m` | Distance at which LOD0 switches to LOD1. | +| `lod2_distance` | `100 m` | Distance at which LOD1 switches to LOD2. | +| `lod_end_distance` | `0 m` | Distance at which the last LOD stops being drawn: the impostor if the tree was exported with one, otherwise LOD2. `0` keeps it visible at any distance. | + +### How the triangle budget works +Each LOD gets a budget of `LOD0 triangles × ratio`. The trunk takes its share first, and the +foliage gets what's left. For example, for LOD1 with the default settings: + +1. **Budget**: a tree with 3,500 trunk triangles and 6,500 foliage triangles has 10,000 in total, so LOD1 gets 10,000 × 0.4 = 4,000. +1. **Trunk**: it's simplified to `budget × lod_trunk_share`. With the default share of 0.33, that's 4,000 * 0.33 = 1,300 triangles. +1. **Foliage**: it gets the remaining ~2,700 triangles. + - Leaf cards aren't simplified. Some cards are dropped and the remaining ones are scaled up, so the canopy keeps its size and shape. + - Icospheres are simplified like the trunk. + +`lod_trunk_share` is set per tree on the `CosmoTreeGen` node and is saved in presets. +Raise it to keep more trunk detail, lower it to keep more leaves. + +If the foliage needs less than what's left, the trunk keeps the rest of the budget. +A tree without foliage spends the whole budget on the trunk. + +### Example with the default settings +- LOD0: Will be visible from 0 to 50 meters. +- LOD1: Will be visible from 50 to 100 meters. +- LOD2: Will be visible from 100 meters to infinity, or to 150 meters if the tree is exported with an impostor. +- Impostor: Will be visible from 150 meters to infinity. + +Note: This addon sets the `custom_aabb` of each LOD so the transition between them is as seamless as possible. +It uses a Post Import script on the exported trees to achieve it: `lod_post_import.gd`. + +See [Visibility ranges (HLOD)](https://docs.godotengine.org/en/stable/tutorials/3d/visibility_ranges.html) for more info amout how LOD works. + +## Cosmo Tree Gen > Export + +These are the starting values of the export dialog. You can still change them on each export. +See [Exporting](exporting.md) for what each option does. + +| Setting | Default | Description | +| ------- | ------- | ----------- | +| `default_extension` | `glb` | File extension suggested in the export dialog: `glb` or `gltf`. | +| `default_include_collisions` | `true` | Starting value of *Include Collisions*. | +| `default_export_images` | `false` | Starting value of *Export Images*. | +| `default_use_external_material` | `true` | Starting value of *Use External Material*. | +| `default_impostor` | `Static` | Starting value of *Impostor*: None, Static or Octahedral. | + +## Cosmo Tree Gen > Impostor + +Used when a tree is exported with *Impostor* set to *Static* or *Octahedral*. The changes apply the next time you export the tree. + +| Setting | Default | Description | +| ------- | ------- | ----------- | +| `impostor_distance` | `150.0` | Distance at which the last LOD switches to the impostor: LOD2, or the tree itself if it has no LODs. With LODs it must be greater than `lod2_distance`, otherwise the export prints a warning. | +| `static_resolution` | `512` | *Static*: Longest side of the textures, the other side follows the tree proportions. Halving it uses about 4 times less memory. | +| `octahedral_frames` | `12` | *Octahedral*: Views per side of the atlas, 12 * 12 = 144 views. More views make the change between angles smoother, but each view gets fewer pixels. | +| `octahedral_resolution` | `1024` | *Octahedral*: Size of the atlas. Each view gets `octahedral_resolution / octahedral_frames` pixels, 84 px with the default values. Halving it uses about 4 times less memory. | +| `cast_shadow` | `false` | Whether the impostor casts shadows. Off by default: the *Static* shadow turns when the camera moves, and the *Octahedral* one also darkens the impostor itself. | + +Note: `DirectionalLight3D` only draws shadows up to its `directional_shadow_max_distance` (100 m by default), so with the default `impostor_distance` the impostor shadow won't show even with `cast_shadow` on. +Note: with the default values, a *Static* impostor uses about 0.5 MB of video memory and an *Octahedral* one about 2.7 MB diff --git a/third_party/cosmo_tree_gen/project.godot b/third_party/cosmo_tree_gen/project.godot new file mode 100644 index 0000000..c036d39 --- /dev/null +++ b/third_party/cosmo_tree_gen/project.godot @@ -0,0 +1,39 @@ +; Engine configuration file. +; It's best edited using the editor UI and not directly, +; since the parameters that go here are not all obvious. +; +; Format: +; [section] ; section goes between [] +; param=value ; assign values to parameters + +config_version=5 + +[application] + +config/name="CosmoTreeGen" +config/version="1.0" +config/tags=PackedStringArray("addons") +run/main_scene="uid://c8fxt01sxw6ut" +config/features=PackedStringArray("4.6", "Forward Plus") +config/icon="uid://da0ltcru2oqfw" + +[debug] + +gdscript/warnings/directory_rules={} +gdscript/warnings/untyped_declaration=1 +gdscript/warnings/unsafe_property_access=1 +gdscript/warnings/unsafe_method_access=1 +gdscript/warnings/unsafe_cast=1 +gdscript/warnings/unsafe_call_argument=1 + +[editor_plugins] + +enabled=PackedStringArray("res://addons/cosmo_tree_gen/plugin.cfg") + +[physics] + +3d/physics_engine="Jolt Physics" + +[rendering] + +rendering_device/driver.windows="d3d12" diff --git a/tools/maps/sion/arbres_remarquables_sion.json b/tools/maps/sion/arbres_remarquables_sion.json new file mode 100644 index 0000000..e905a22 --- /dev/null +++ b/tools/maps/sion/arbres_remarquables_sion.json @@ -0,0 +1 @@ +{"displayFieldName":"numero","fieldAliases":{"objectid":"objectid","numero":"N° du sujet","nom_latin":"Nom latin","nom_francais":"Nom français","lieu":"Lieu-dit","parcelle":"Parcelle","date_releve":"Date du relevé","fiche":"Fiche"},"geometryType":"esriGeometryPoint","spatialReference":{"wkid":2056,"latestWkid":2056},"fields":[{"name":"objectid","type":"esriFieldTypeOID","alias":"objectid"},{"name":"numero","type":"esriFieldTypeString","alias":"N° du sujet","length":255},{"name":"nom_latin","type":"esriFieldTypeString","alias":"Nom latin","length":255},{"name":"nom_francais","type":"esriFieldTypeString","alias":"Nom français","length":255},{"name":"lieu","type":"esriFieldTypeString","alias":"Lieu-dit","length":255},{"name":"parcelle","type":"esriFieldTypeInteger","alias":"Parcelle"},{"name":"date_releve","type":"esriFieldTypeDate","alias":"Date du relevé","length":8},{"name":"fiche","type":"esriFieldTypeString","alias":"Fiche","length":255}],"features":[{"attributes":{"objectid":20,"numero":"17.2","nom_latin":"Cedrus libani 'Atlantica'","nom_francais":"Cèdre de l'Atlas","lieu":"Cimetière Saint-François","parcelle":1350,"date_releve":1507068000000,"fiche":"https://www.sion.ch/_docn/5302336/Arbre-remarquable-Cimetiere_de_Saint-Fran%C3%A7ois-Cedrus_libani_%27Atlantica%27.pdf"},"geometry":{"x":2593779.008200001,"y":1120633.6816999987}},{"attributes":{"objectid":25,"numero":"1.6","nom_latin":"Aesculus hippocastanum","nom_francais":"Marronnier commun, d'inde ou blanc","lieu":"Planta d'en Haut","parcelle":1340,"date_releve":1505772000000,"fiche":"https://www.sion.ch/_docn/5302630/Arbre-remarquable-Planta_d%27En_Haut-Aesculus_hippocastanum.pdf"},"geometry":{"x":2593619.7613999993,"y":1120373.0298999995}},{"attributes":{"objectid":26,"numero":"15","nom_latin":"Pinus nigra","nom_francais":"Pin noir d'Autriche","lieu":"Planta d'en Haut","parcelle":12426,"date_releve":1507068000000,"fiche":"https://www.sion.ch/_docn/5302633/Arbre-remarquable-Planta_d%27En_Haut-Pinus_nigra.pdf"},"geometry":{"x":2593452.2952999994,"y":1120378.320700001}},{"attributes":{"objectid":27,"numero":"13","nom_latin":"Abies pinsapo","nom_francais":"Sapin d'Andalousie ou d'Espagne","lieu":"Pratifori","parcelle":581,"date_releve":1506463200000,"fiche":"https://www.sion.ch/_docn/5302645/Arbre-remarquable-Pratifori-Abies_pinsapo.pdf"},"geometry":{"x":2593527.1237000003,"y":1119965.3511000015}},{"attributes":{"objectid":11,"numero":"7","nom_latin":"Fagus sylvatica 'Atropurpurea'","nom_francais":"Hêtre pourpre","lieu":"Les Potences","parcelle":9521,"date_releve":1505772000000,"fiche":null},"geometry":{"x":2592438.3225999996,"y":1119419.5344000012}},{"attributes":{"objectid":17,"numero":"16","nom_latin":"Cedrus libani","nom_francais":"Cèdre du Liban","lieu":"Cimetière Saint-François","parcelle":1350,"date_releve":1507068000000,"fiche":"https://www.sion.ch/_docn/5302339/Arbre-remarquable-Cimetiere_de_Saint-Fran%C3%A7ois-Cedrus_libani.pdf"},"geometry":{"x":2593817.1143000014,"y":1120625.3636999987}},{"attributes":{"objectid":33,"numero":"3.1","nom_latin":"Taxus baccata","nom_francais":"If commun","lieu":"Planta d'en Haut","parcelle":1340,"date_releve":1505772000000,"fiche":"https://www.sion.ch/_docn/5302642/Arbre-remarquable-Planta_d%27En_Haut-Taxus_baccata.pdf"},"geometry":{"x":2593611.5203000009,"y":1120392.363499999}},{"attributes":{"objectid":31,"numero":"1.7","nom_latin":"Aesculus hippocastanum","nom_francais":"Marronnier commun, d'inde ou blanc","lieu":"Planta d'en Haut","parcelle":1340,"date_releve":1505772000000,"fiche":"https://www.sion.ch/_docn/5302630/Arbre-remarquable-Planta_d%27En_Haut-Aesculus_hippocastanum.pdf"},"geometry":{"x":2593610.5117000006,"y":1120377.4272999987}},{"attributes":{"objectid":34,"numero":"11","nom_latin":"Sequoiadendron gigantum","nom_francais":"Séquoia géant","lieu":"Planta d'en Haut","parcelle":553,"date_releve":1506463200000,"fiche":"https://www.sion.ch/_docn/5302618/Arbre-remarquable-Planta_d%E2%80%99En_Haut-Sequoiadendron.pdf"},"geometry":{"x":2593636.1374000013,"y":1120075.4019999988}},{"attributes":{"objectid":12,"numero":"12","nom_latin":"Cedrus libani","nom_francais":"Cèdre du Liban","lieu":"Pratifori","parcelle":281,"date_releve":-55611708808000,"fiche":"https://www.sion.ch/_docn/5302651/Arbre-remarquable-Pratifori-Cedrus_libani.pdf"},"geometry":{"x":2593522.9419,"y":1119968.4164000005}},{"attributes":{"objectid":10,"numero":"4","nom_latin":"Platanus x acerifolia","nom_francais":"Platane commun ou à feuilles d'Erable","lieu":"En Ville","parcelle":14182,"date_releve":1505772000000,"fiche":"https://www.sion.ch/_docn/5302348/Arbre-remarquable-En_ville-Platanus_x_acerifolia.pdf"},"geometry":{"x":2593778.4908000007,"y":1120085.4532000013}},{"attributes":{"objectid":18,"numero":"1.3","nom_latin":"Aesculus hippocastanum","nom_francais":"Marronnier commun, d'inde ou blanc","lieu":"Planta d'en Haut","parcelle":1340,"date_releve":1505772000000,"fiche":"https://www.sion.ch/_docn/5302630/Arbre-remarquable-Planta_d%27En_Haut-Aesculus_hippocastanum.pdf"},"geometry":{"x":2593640.8282000013,"y":1120388.3839000016}},{"attributes":{"objectid":2,"numero":"9","nom_latin":"Sequoiadendron gigantum","nom_francais":"Séquoia géant","lieu":"Les Mayens de Salins","parcelle":2798,"date_releve":1506463200000,"fiche":"https://www.sion.ch/_docn/5302609/Arbre-remarquable-Mayens_de_Salins-Sequoiadendron_giganteum.pdf"},"geometry":{"x":2594025.9844000004,"y":1116633.9781000018}},{"attributes":{"objectid":15,"numero":"2.1","nom_latin":"Taxus baccata 'Fastigiata'","nom_francais":"If fastigé","lieu":"Planta d'en Haut","parcelle":1340,"date_releve":1505772000000,"fiche":"https://www.sion.ch/_docn/5302636/Arbre-remarquable-Planta_d%27En_Haut-Taxus_baccata_%27Fastigiata%27.pdf"},"geometry":{"x":2593620.6642000005,"y":1120387.3601999991}},{"attributes":{"objectid":13,"numero":"1.4","nom_latin":"Aesculus hippocastanum","nom_francais":"Marronnier commun, d'inde ou blanc","lieu":"Planta d'en Haut","parcelle":1340,"date_releve":1505772000000,"fiche":"https://www.sion.ch/_docn/5302630/Arbre-remarquable-Planta_d%27En_Haut-Aesculus_hippocastanum.pdf"},"geometry":{"x":2593634.5868999995,"y":1120378.6024000011}},{"attributes":{"objectid":21,"numero":"17.5","nom_latin":"Cedrus libani 'Atlantica'","nom_francais":"Cèdre de l'Atlas","lieu":"Cimetière Saint-François","parcelle":1350,"date_releve":1507068000000,"fiche":"https://www.sion.ch/_docn/5302336/Arbre-remarquable-Cimetiere_de_Saint-Fran%C3%A7ois-Cedrus_libani_%27Atlantica%27.pdf"},"geometry":{"x":2593781.625500001,"y":1120615.6878000014}},{"attributes":{"objectid":5,"numero":"6","nom_latin":"Quercus robur","nom_francais":"Chêne pédonculé, blanc ou commun","lieu":"Grand-Champsec","parcelle":2105,"date_releve":1505772000000,"fiche":"https://www.sion.ch/_docn/5302354/Arbre-remarquable-Grand-Champsec-Quercus_robur.pdf"},"geometry":{"x":2595339.2437000014,"y":1120467.3346999995}},{"attributes":{"objectid":19,"numero":"17.4","nom_latin":"Cedrus libani 'Atlantica'","nom_francais":"Cèdre de l'Atlas","lieu":"Cimetière Saint-François","parcelle":1350,"date_releve":1507068000000,"fiche":"https://www.sion.ch/_docn/5302336/Arbre-remarquable-Cimetiere_de_Saint-Fran%C3%A7ois-Cedrus_libani_%27Atlantica%27.pdf"},"geometry":{"x":2593776.0637999997,"y":1120614.7718000002}},{"attributes":{"objectid":32,"numero":"1.5","nom_latin":"Aesculus hippocastanum","nom_francais":"Marronnier commun, d'inde ou blanc","lieu":"Planta d'en Haut","parcelle":1340,"date_releve":1505772000000,"fiche":"https://www.sion.ch/_docn/5302630/Arbre-remarquable-Planta_d%27En_Haut-Aesculus_hippocastanum.pdf"},"geometry":{"x":2593623.4512000009,"y":1120364.3867000006}},{"attributes":{"objectid":24,"numero":"17.1","nom_latin":"Cedrus libani 'Atlantica'","nom_francais":"Cèdre de l'Atlas","lieu":"Cimetière Saint-François","parcelle":1350,"date_releve":1507068000000,"fiche":"https://www.sion.ch/_docn/5302336/Arbre-remarquable-Cimetiere_de_Saint-Fran%C3%A7ois-Cedrus_libani_%27Atlantica%27.pdf"},"geometry":{"x":2593769.6513999999,"y":1120631.4569999985}},{"attributes":{"objectid":8,"numero":"18","nom_latin":"Cupressus arizonica 'Glauca'","nom_francais":"Cyprès bleu de l'Arizona","lieu":"Chanterie","parcelle":5616,"date_releve":1507068000000,"fiche":"https://www.sion.ch/_docn/5302330/Arbre-remarquable-Chanterie-Cupressus_arizonica_%27Glauca%27.pdf"},"geometry":{"x":2593499.6667999998,"y":1120549.4202000014}},{"attributes":{"objectid":28,"numero":"1.9","nom_latin":"Aesculus hippocastanum","nom_francais":"Marronnier commun, d'inde ou blanc","lieu":"Planta d'en Haut","parcelle":1340,"date_releve":1505772000000,"fiche":"https://www.sion.ch/_docn/5302630/Arbre-remarquable-Planta_d%27En_Haut-Aesculus_hippocastanum.pdf"},"geometry":{"x":2593596.4096999988,"y":1120390.9732999988}},{"attributes":{"objectid":30,"numero":"1.2","nom_latin":"Aesculus hippocastanum","nom_francais":"Marronnier commun, d'inde ou blanc","lieu":"Planta d'en Haut","parcelle":1340,"date_releve":1505772000000,"fiche":"https://www.sion.ch/_docn/5302630/Arbre-remarquable-Planta_d%27En_Haut-Aesculus_hippocastanum.pdf"},"geometry":{"x":2593644.2895000018,"y":1120399.0912999995}},{"attributes":{"objectid":6,"numero":"10","nom_latin":"Cedrus libani 'Glauca'","nom_francais":"Cèdre bleu","lieu":"Planta d'en Haut","parcelle":553,"date_releve":1506463200000,"fiche":"https://www.sion.ch/_docn/5302615/Arbre-remarquable-Planta_d%E2%80%99En_Haut-Cedrus_libani_%27Glauca%27.pdf"},"geometry":{"x":2593632.5835000016,"y":1120097.8313000016}},{"attributes":{"objectid":29,"numero":"17.3","nom_latin":"Cedrus libani 'Atlantica'","nom_francais":"Cèdre de l'Atlas","lieu":"Cimetière Saint-François","parcelle":1350,"date_releve":1507068000000,"fiche":"https://www.sion.ch/_docn/5302336/Arbre-remarquable-Cimetiere_de_Saint-Fran%C3%A7ois-Cedrus_libani_%27Atlantica%27.pdf"},"geometry":{"x":2593772.2686999999,"y":1120619.8101000004}},{"attributes":{"objectid":16,"numero":"1.8","nom_latin":"Aesculus hippocastanum","nom_francais":"Marronnier commun, d'inde ou blanc","lieu":"Planta d'en Haut","parcelle":1340,"date_releve":1505772000000,"fiche":"https://www.sion.ch/_docn/5302630/Arbre-remarquable-Planta_d%27En_Haut-Aesculus_hippocastanum.pdf"},"geometry":{"x":2593602.8288999982,"y":1120383.1893999986}},{"attributes":{"objectid":4,"numero":"14","nom_latin":"Taxus baccata","nom_francais":"If commun","lieu":"Jardin en ville","parcelle":141,"date_releve":1506463200000,"fiche":"https://www.sion.ch/_docn/5302357/Arbre-remarquable-Jardin_en_ville-Taxus_baccata.pdf"},"geometry":{"x":2593917.9043999985,"y":1120089.2928999998}},{"attributes":{"objectid":23,"numero":"2.2","nom_latin":"Taxus baccata 'Fastigiata'","nom_francais":"If fastigé","lieu":"Planta d'en Haut","parcelle":1340,"date_releve":1505772000000,"fiche":"https://www.sion.ch/_docn/5302636/Arbre-remarquable-Planta_d%27En_Haut-Taxus_baccata_%27Fastigiata%27.pdf"},"geometry":{"x":2593625.7824999988,"y":1120389.4880000018}},{"attributes":{"objectid":1,"numero":"19","nom_latin":"Quercus robur","nom_francais":"Chêne pédonculé, blanc ou commun","lieu":"Grand-Champsec","parcelle":2105,"date_releve":1507068000000,"fiche":"https://www.sion.ch/_docn/5302342/Arbre-remarquable3-Grand-Champsec-Quercus_robur.pdf"},"geometry":{"x":2595421.7751000002,"y":1119661.0141999982}},{"attributes":{"objectid":22,"numero":"3.3","nom_latin":"Taxus baccata","nom_francais":"If commun","lieu":"Planta d'en Haut","parcelle":1340,"date_releve":1505772000000,"fiche":"https://www.sion.ch/_docn/5302642/Arbre-remarquable-Planta_d%27En_Haut-Taxus_baccata.pdf"},"geometry":{"x":2593629.4631000012,"y":1120399.7820999995}},{"attributes":{"objectid":3,"numero":"8","nom_latin":"Pinus strobus","nom_francais":"Pin blanc","lieu":"Les Mayens de Salins","parcelle":2798,"date_releve":1506463200000,"fiche":"https://www.sion.ch/_docn/5302582/Arbre-remarquable-Mayens_de_Salins-Pinus_strobus.pdf"},"geometry":{"x":2594012.9039000012,"y":1116683.5850999989}},{"attributes":{"objectid":14,"numero":"1.1","nom_latin":"Aesculus hippocastanum","nom_francais":"Marronnier commun, d'inde ou blanc","lieu":"Planta d'en Haut","parcelle":1340,"date_releve":1505772000000,"fiche":"https://www.sion.ch/_docn/5302630/Arbre-remarquable-Planta_d%27En_Haut-Aesculus_hippocastanum.pdf"},"geometry":{"x":2593644.5806999989,"y":1120406.1110000014}},{"attributes":{"objectid":35,"numero":"1.0","nom_latin":"Aesculus hippocastanum","nom_francais":"Marronnier commun, d'inde ou blanc","lieu":"Planta d'en Haut","parcelle":1340,"date_releve":1505772000000,"fiche":"https://www.sion.ch/_docn/5302630/Arbre-remarquable-Planta_d%27En_Haut-Aesculus_hippocastanum.pdf"},"geometry":{"x":2593641.4105000012,"y":1120414.4893000014}},{"attributes":{"objectid":9,"numero":"20","nom_latin":"Quercus robur","nom_francais":"Chêne pédonculé, blanc ou commun","lieu":"Grand-Champsec","parcelle":2105,"date_releve":1507068000000,"fiche":"https://www.sion.ch/_docn/5302318/Arbre-remarquable2-Grand-Champsec-Quercus_robur.pdf"},"geometry":{"x":2595412.8865999989,"y":1119639.9816000015}},{"attributes":{"objectid":7,"numero":"5","nom_latin":"Betula pendula","nom_francais":"Bouleau verruqueux, blanc ou d'Europe","lieu":"Grand-Champsec","parcelle":1726,"date_releve":1505772000000,"fiche":"https://www.sion.ch/_docn/5302351/Arbre-remarquable-Grand-Champsec-Betula_pendula.pdf"},"geometry":{"x":2594920.2652000003,"y":1119806.3742000014}}]} \ No newline at end of file diff --git a/tools/maps/sion/bake_sion_trees.py b/tools/maps/sion/bake_sion_trees.py new file mode 100644 index 0000000..50a277d --- /dev/null +++ b/tools/maps/sion/bake_sion_trees.py @@ -0,0 +1,657 @@ +#!/usr/bin/env python3 +""" +Offline Swisstopo + Ville de Sion ecological tree placement baker for RustToDust. +Consumes: + - Ville de Sion REST cadastre/arbres_remarquables/MapServer/0 (cached JSON) + - Swisstopo TLM_EINZELBAUM + TLM_BODENBEDECKUNG (Wald/Gebueschwald/Gehoelz) + TLM_NUTZUNGSAREAL (Obstanlage) + - WSL/BAFU 0.5 m LiDAR NFI VHM (ch.bafu.landesforstinventar-vegetationshoehenmodell_lidar_2022, COG HTTP range crop) + - WSL/BAFU 10 m waldmischungsgrad + BAFU uferbestockung (COG HTTP range crop) + - assets/maps/sion/heightmap_05m.u16z, buildings_manifest.json, terrain_surface_mask.png, metadata.json + +Exports: + - assets/maps/sion/trees_sion.bin (RDTR v1 binary, <= 6,500 instances, 0 wild beech) +""" + +from __future__ import annotations + +import argparse +import hashlib +import io +import json +import math +import os +import struct +import subprocess +import urllib.request +import zipfile +import zlib +from pathlib import Path + +import imagecodecs +import numpy as np +import pyogrio.raw +from scipy.ndimage import map_coordinates, maximum_filter +from shapely import box as shp_box, wkb as shp_wkb +from shapely.geometry import Point +from shapely.strtree import STRtree +import tifffile + +ARENA_SIZE_M = 3072.0 +HALF_EXTENT_M = 1536.0 +TILE_GRID = 16 +TILE_SIZE_M = ARENA_SIZE_M / TILE_GRID # 192.0m +MAX_TREES = 6500 + +# Canonical species IDs matching RustToDust.Core.SionTreeSpecies (0..9, 0 wild beech!) +SP_PINUS_SYLVESTRIS = 0 +SP_QUERCUS_PUBESCENS = 1 +SP_POPULUS_NIGRA = 2 +SP_PLATANUS_ACERIFOLIA = 3 +SP_BETULA_PENDULA = 4 +SP_PICEA_ABIES = 5 +SP_MALUS_ORCHARD = 6 +SP_SEQUOIADENDRON = 7 +SP_CEDRUS = 8 +SP_PLATANUS_MONUMENTAL = 9 + +SPECIES_NAMES = { + 0: "PinusSylvestris", + 1: "QuercusPubescens", + 2: "PopulusNigra", + 3: "PlatanusAcerifolia", + 4: "BetulaPendula", + 5: "PiceaAbies", + 6: "MalusOrchard", + 7: "Sequoiadendron", + 8: "Cedrus", + 9: "PlatanusMonumental", +} + +TLM_ZIP_URL = "https://data.geo.admin.ch/ch.swisstopo.swisstlm3d/swisstlm3d_2026-02/swisstlm3d_2026-02_2056_5728.gdb.zip" +VHM_2022_URL = "https://data.geo.admin.ch/ch.bafu.landesforstinventar-vegetationshoehenmodell_lidar/landesforstinventar-vegetationshoehenmodell_lidar_2022/landesforstinventar-vegetationshoehenmodell_lidar_2022_2056.tif" +WALDMISCH_URL = "https://data.geo.admin.ch/ch.bafu.landesforstinventar-waldmischungsgrad/landesforstinventar-waldmischungsgrad/landesforstinventar-waldmischungsgrad_2056.tif" +UFER_URL = "https://data.geo.admin.ch/ch.bafu.gewaesser-uferbestockung_vegetation/gewaesser-uferbestockung_vegetation/gewaesser-uferbestockung_vegetation_2056.tif" +ARBRES_URL = "https://arcgis.sion.ch/server/rest/services/cadastre/arbres_remarquables/MapServer/0/query?where=1%3D1&outFields=*&returnGeometry=true&outSR=2056&f=json" + + +class HttpRangeFile(io.RawIOBase): + def __init__(self, url: str) -> None: + self.url = url + req = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "RustToDust-TreeBaker/1.0"}) + with urllib.request.urlopen(req, timeout=20) as r: + self.length = int(r.headers["Content-Length"]) + self.pos = 0 + + def readable(self) -> bool: + return True + + def seekable(self) -> bool: + return True + + def seek(self, offset: int, whence: int = io.SEEK_SET) -> int: + if whence == io.SEEK_SET: + self.pos = offset + elif whence == io.SEEK_CUR: + self.pos += offset + elif whence == io.SEEK_END: + self.pos = self.length + offset + return self.pos + + def tell(self) -> int: + return self.pos + + def read(self, size: int = -1) -> bytes: + if size is None or size < 0: + size = self.length - self.pos + if size <= 0 or self.pos >= self.length: + return b"" + end = min(self.length - 1, self.pos + size - 1) + req = urllib.request.Request( + self.url, + headers={"Range": f"bytes={self.pos}-{end}", "User-Agent": "RustToDust-TreeBaker/1.0"}, + ) + with urllib.request.urlopen(req, timeout=30) as r: + data = r.read() + self.pos += len(data) + return data + + +def read_cog_window( + url: str, + cache_npz: Path, + e0: float, + n0: float, + e1: float, + n1: float, + fill_val: float = 0.0, +) -> tuple[np.ndarray, float, float, float, float]: + """Read & cache an LV95 bbox crop from a nationwide COG GeoTIFF via HTTP range requests.""" + if cache_npz.exists(): + d = np.load(cache_npz) + return d["arr"], float(d["ox"]), float(d["ny"]), float(d["sx"]), float(d["sy"]) + + print(f" [COG crop] {url.split('/')[-1]} -> {cache_npz.name}") + f = HttpRangeFile(url) + with tifffile.TiffFile(f) as tf: + p = tf.pages[0] + scale = p.tags["ModelPixelScaleTag"].value + tie = p.tags["ModelTiepointTag"].value + ox, oy = float(tie[3]), float(tie[4]) + sx, sy = float(scale[0]), float(scale[1]) + tw, th = int(p.tilewidth), int(p.tilelength) + img_h, img_w = int(p.shape[0]), int(p.shape[1]) + + c0 = max(0, int(math.floor((e0 - ox) / sx))) + c1 = min(img_w - 1, int(math.ceil((e1 - ox) / sx))) + r0 = max(0, int(math.floor((oy - n1) / sy))) + r1 = min(img_h - 1, int(math.ceil((oy - n0) / sy))) + + out_h = r1 - r0 + 1 + out_w = c1 - c0 + 1 + arr = np.full((out_h, out_w), fill_val, dtype=np.float32) + + tiles_across = (img_w + tw - 1) // tw + tr0, tr1 = r0 // th, r1 // th + tc0, tc1 = c0 // tw, c1 // tw + + offsets = p.dataoffsets + bytecounts = p.databytecounts + + for tr in range(tr0, tr1 + 1): + for tc in range(tc0, tc1 + 1): + idx = tr * tiles_across + tc + bc = int(bytecounts[idx]) + bo = int(offsets[idx]) + if bc <= 0 or bo <= 0: + continue + f.seek(bo) + raw = f.read(bc) + decoded = np.squeeze(np.asarray(p.decode(raw, idx)[0])) + if decoded.ndim != 2: + decoded = decoded.reshape((th, tw)) + tile_r0 = tr * th + tile_c0 = tc * tw + ir0 = max(r0, tile_r0) + ir1 = min(r1 + 1, tile_r0 + decoded.shape[0]) + ic0 = max(c0, tile_c0) + ic1 = min(c1 + 1, tile_c0 + decoded.shape[1]) + patch = decoded[ir0 - tile_r0 : ir1 - tile_r0, ic0 - tile_c0 : ic1 - tile_c0].astype(np.float32) + # Replace NaN / huge nodata sentinels with fill_val + bad = ~np.isfinite(patch) | (patch < -100.0) | (patch > 5000.0) + if np.any(bad): + patch = np.where(bad, fill_val, patch) + arr[ir0 - r0 : ir1 - r0, ic0 - c0 : ic1 - c0] = patch + + crop_ox = ox + c0 * sx + crop_ny = oy - r0 * sy + cache_npz.parent.mkdir(parents=True, exist_ok=True) + np.savez_compressed(cache_npz, arr=arr, ox=crop_ox, ny=crop_ny, sx=sx, sy=sy) + return arr, crop_ox, crop_ny, sx, sy + + +def ensure_tlm_gdb(cache_dir: Path) -> Path: + gdb_dir = cache_dir / "swissTLM3D_2026_LV95_LN02.gdb" + if gdb_dir.exists(): + return gdb_dir + zip_path = cache_dir / "swisstlm3d_2026-02_2056_5728.gdb.zip" + if not zip_path.exists(): + print(f" [TLM download] {TLM_ZIP_URL}") + subprocess.run(["curl", "-fsSL", "-o", str(zip_path), TLM_ZIP_URL], check=True) + print(" [TLM extract] swissTLM3D_2026_LV95_LN02.gdb...") + with zipfile.ZipFile(zip_path) as zf: + for info in zf.infolist(): + rel = info.filename.replace("\\", "/") + if rel.endswith("/"): + continue + target = cache_dir / rel + target.parent.mkdir(parents=True, exist_ok=True) + with zf.open(info) as src, open(target, "wb") as dst: + dst.write(src.read()) + return gdb_dir + + +def load_heightmap_u16z(path: Path) -> tuple[np.ndarray, int]: + raw_file = path.read_bytes() + magic, ver, grid_res, min_y, scale, raw_bytes = struct.unpack("<4sIIffI", raw_file[:24]) + assert magic == b"RDHM" and ver == 2, f"Bad RDHM header in {path}" + decompressed = zlib.decompress(raw_file[24:]) + assert len(decompressed) == raw_bytes + zz = np.frombuffer(decompressed, dtype="> 1) ^ -(zz & 1)).astype(np.int16).astype(np.int32) + q = np.empty((grid_res, grid_res), dtype=np.uint16) + for r in range(grid_res): + pred = int(q[r - 1, 0]) if r > 0 else 0 + row = q[r] + drow = diff[r] + for c in range(grid_res): + pred = (pred + int(drow[c])) & 0xFFFF + row[c] = pred + hm = min_y + q.astype(np.float32) * scale + return hm, grid_res + + +def sample_bilinear(grid: np.ndarray, wx: float, wz: float) -> float: + res = grid.shape[0] + fx = np.clip((wx + HALF_EXTENT_M) / ARENA_SIZE_M * (res - 1), 0.0, res - 1.0001) + fz = np.clip((wz + HALF_EXTENT_M) / ARENA_SIZE_M * (res - 1), 0.0, res - 1.0001) + ix = int(fx) + iz = int(fz) + tx = fx - ix + tz = fz - iz + h00 = float(grid[iz, ix]) + h10 = float(grid[iz, ix + 1]) + h01 = float(grid[iz + 1, ix]) + h11 = float(grid[iz + 1, ix + 1]) + return (h00 * (1 - tx) + h10 * tx) * (1 - tz) + (h01 * (1 - tx) + h11 * tx) * tz + + +def sample_cog(arr: np.ndarray, ox: float, ny: float, sx: float, sy: float, e: float, n: float) -> float: + col = int(round((e - ox) / sx)) + row = int(round((ny - n) / sy)) + if 0 <= row < arr.shape[0] and 0 <= col < arr.shape[1]: + return float(arr[row, col]) + return 0.0 + + +def sample_cog_max(arr: np.ndarray, ox: float, ny: float, sx: float, sy: float, e: float, n: float, rad_px: int = 4) -> float: + col = int(round((e - ox) / sx)) + row = int(round((ny - n) / sy)) + r0 = max(0, row - rad_px) + r1 = min(arr.shape[0], row + rad_px + 1) + c0 = max(0, col - rad_px) + c1 = min(arr.shape[1], col + rad_px + 1) + if r0 >= r1 or c0 >= c1: + return 0.0 + return float(arr[r0:r1, c0:c1].max()) + + +def load_arbres_remarquables(cache_dir: Path, script_dir: Path) -> list[dict]: + repo_json = script_dir / "arbres_remarquables_sion.json" + cache_json = cache_dir / "arbres_remarquables.json" + if repo_json.exists(): + data = json.loads(repo_json.read_text(encoding="utf-8")) + elif cache_json.exists(): + data = json.loads(cache_json.read_text(encoding="utf-8")) + else: + req = urllib.request.Request(ARBRES_URL, headers={"User-Agent": "RustToDust-TreeBaker/1.0"}) + with urllib.request.urlopen(req, timeout=20) as r: + raw = r.read() + cache_json.write_bytes(raw) + data = json.loads(raw) + return data.get("features", []) + + +def map_remarkable_species(nom_latin: str) -> tuple[int, float, float]: + """Map Ville de Sion arbres_remarquables Latin name -> (speciesId, minHeightM, trunkRadiusM). Never beech.""" + low = nom_latin.lower() + if "sequoiadendron" in low: + return SP_SEQUOIADENDRON, 28.0, 0.88 + if "cedrus" in low: + return SP_CEDRUS, 20.0, 0.68 + if "platanus" in low: + return SP_PLATANUS_MONUMENTAL, 22.0, 0.72 + if "aesculus" in low: + return SP_PLATANUS_MONUMENTAL, 17.5, 0.56 + if "pinus" in low: + return SP_PINUS_SYLVESTRIS, 17.0, 0.44 + if "quercus" in low: + return SP_QUERCUS_PUBESCENS, 15.0, 0.48 + if "betula" in low: + return SP_BETULA_PENDULA, 13.5, 0.28 + if "abies" in low or "taxus" in low or "picea" in low: + return SP_PICEA_ABIES, 12.0, 0.36 + return SP_PLATANUS_ACERIFOLIA, 16.0, 0.45 + + +def morton2d(x: int, y: int) -> int: + def part1by1(n: int) -> int: + n &= 0xFFFF + n = (n | (n << 8)) & 0x00FF00FF + n = (n | (n << 4)) & 0x0F0F0F0F + n = (n | (n << 2)) & 0x33333333 + n = (n | (n << 1)) & 0x55555555 + return n + return part1by1(x) | (part1by1(y) << 1) + + +def deterministic_rng(e: float, n: float) -> float: + h = hashlib.blake2b(f"{e:.2f},{n:.2f}".encode(), digest_size=4).digest() + return int.from_bytes(h, "little") / 4294967296.0 + + +def classify_species( + wx: float, + wz: float, + e: float, + n: float, + ground_y: float, + slope: float, + conifer_pct: float, + is_riparian: bool, + is_orchard: bool, + rock_mask: float, + u: float, +) -> tuple[int, float]: + """Assign authentic Sion species (NO wild beech!) and realistic trunk radius.""" + if is_orchard: + return SP_MALUS_ORCHARD, 0.14 + 0.06 * u + + if is_riparian: + if u < 0.68: + return SP_POPULUS_NIGRA, 0.32 + 0.14 * u + return SP_BETULA_PENDULA, 0.18 + 0.08 * u + + # Dry rocky hills (Valere, Tourbillon, south-facing limestone slopes) + in_valere_tourbillon = (-350.0 <= wx <= 550.0) and (-450.0 <= wz <= 250.0) and ground_y > 22.0 + if in_valere_tourbillon or rock_mask > 0.30 or (slope > 0.24 and ground_y < 110.0): + if conifer_pct >= 55.0 or (u < 0.44 and ground_y > 35.0): + return SP_PINUS_SYLVESTRIS, 0.28 + 0.12 * u + return SP_QUERCUS_PUBESCENS, 0.26 + 0.14 * u + + # Higher slopes / ravines -> PinusSylvestris + PiceaAbies + if ground_y > 90.0 or conifer_pct >= 55.0: + if conifer_pct >= 72.0 or (ground_y > 125.0 and u < 0.62): + return SP_PICEA_ABIES, 0.27 + 0.13 * u + return SP_PINUS_SYLVESTRIS, 0.28 + 0.12 * u + + # Valley floor / urban parks & avenues (Planta, Old Town, Vissigen, Ronquoz) + if ground_y < 18.0: + if u < 0.46: + return SP_PLATANUS_ACERIFOLIA, 0.32 + 0.14 * u + if u < 0.76: + return SP_POPULUS_NIGRA, 0.29 + 0.12 * u + if u < 0.92: + return SP_BETULA_PENDULA, 0.17 + 0.08 * u + return SP_PINUS_SYLVESTRIS, 0.28 + 0.08 * u + + # Mid-slopes / vineyards & hedgerows + if u < 0.45: + return SP_QUERCUS_PUBESCENS, 0.26 + 0.12 * u + if u < 0.78: + return SP_PINUS_SYLVESTRIS, 0.28 + 0.11 * u + return SP_BETULA_PENDULA, 0.17 + 0.08 * u + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--cache-dir", type=Path, default=Path.home() / "nibu-ci" / "sion-cache") + parser.add_argument("--sion-dir", type=Path, default=Path(__file__).resolve().parents[3] / "assets" / "maps" / "sion") + args = parser.parse_args() + + script_dir = Path(__file__).resolve().parent + sion_dir: Path = args.sion_dir + cache_dir: Path = args.cache_dir + cache_dir.mkdir(parents=True, exist_ok=True) + + meta = json.loads((sion_dir / "metadata.json").read_text(encoding="utf-8")) + cE = float(meta["centerE"]) + cN = float(meta["centerN"]) + e0, e1 = cE - HALF_EXTENT_M, cE + HALF_EXTENT_M + n0, n1 = cN - HALF_EXTENT_M, cN + HALF_EXTENT_M + bbox = (e0, n0, e1, n1) + + print("[TreeBaker] Loading heightmap_05m.u16z, buildings_manifest.json & terrain_surface_mask.png...") + hm, hm_res = load_heightmap_u16z(sion_dir / "heightmap_05m.u16z") + grad_z, grad_x = np.gradient(hm, 0.5) + slope_grid = np.hypot(grad_x, grad_z).astype(np.float32) + + mask_rgba = imagecodecs.png_decode((sion_dir / "terrain_surface_mask.png").read_bytes()).astype(np.float32) / 255.0 + rock_grid = mask_rgba[..., 0] + asphalt_grid = mask_rgba[..., 2] + water_grid = mask_rgba[..., 3] + + bldg_data = json.loads((sion_dir / "buildings_manifest.json").read_text(encoding="utf-8")) + bldg_boxes = [] + bldg_boxes_padded = [] + for b in bldg_data["buildings"]: + cx, _, cz = b["center"] + hx, _, hz = b["size"][0] * 0.5, b["size"][1] * 0.5, b["size"][2] * 0.5 + bldg_boxes.append(shp_box(cx - hx, cz - hz, cx + hx, cz + hz)) + bldg_boxes_padded.append(shp_box(cx - hx - 1.2, cz - hz - 1.2, cx + hx + 1.2, cz + hz + 1.2)) + bldg_tree = STRtree(bldg_boxes) + bldg_pad_tree = STRtree(bldg_boxes_padded) + + def is_blocked_xz(wx: float, wz: float, pad: bool = True) -> bool: + if abs(wx) >= HALF_EXTENT_M - 3.0 or abs(wz) >= HALF_EXTENT_M - 3.0: + return True + if sample_bilinear(water_grid, wx, wz) >= 0.40: + return True + pt = Point(wx, wz) + tree = bldg_pad_tree if pad else bldg_tree + hits = tree.query(pt, predicate="intersects") + return len(hits) > 0 + + print("[TreeBaker] Fetching/caching Swisstopo COGs (VHM 2022, waldmischungsgrad, uferbestockung)...") + vhm_arr, vhm_ox, vhm_ny, vhm_sx, vhm_sy = read_cog_window(VHM_2022_URL, cache_dir / "sion_vhm_2022.npz", e0, n0, e1, n1, 0.0) + wmg_arr, wmg_ox, wmg_ny, wmg_sx, wmg_sy = read_cog_window(WALDMISCH_URL, cache_dir / "sion_waldmisch.npz", e0, n0, e1, n1, 50.0) + ufer_arr, ufer_ox, ufer_ny, ufer_sx, ufer_sy = read_cog_window(UFER_URL, cache_dir / "sion_ufer.npz", e0, n0, e1, n1, 0.0) + + print("[TreeBaker] Reading swissTLM3D TLM_EINZELBAUM, TLM_BODENBEDECKUNG & TLM_NUTZUNGSAREAL...") + gdb_path = ensure_tlm_gdb(cache_dir) + _, _, ein_geoms, _ = pyogrio.raw.read(str(gdb_path), layer="TLM_EINZELBAUM", bbox=bbox) + + bb_meta, _, bb_geoms, bb_fields = pyogrio.raw.read(str(gdb_path), layer="TLM_BODENBEDECKUNG", bbox=bbox) + bb_obj_idx = list(bb_meta["fields"]).index("OBJEKTART") + forest_polys = [] + water_polys = [] + for g_bytes, obj in zip(bb_geoms, bb_fields[bb_obj_idx]): + if obj in (12, 13, 6, 14): # Wald, Wald offen, Gebueschwald, Gehoelz + forest_polys.append(shp_wkb.loads(g_bytes)) + elif obj in (1, 2): # Stehendes / Fliessgewaesser + water_polys.append(shp_wkb.loads(g_bytes)) + forest_tree = STRtree(forest_polys) if forest_polys else None + tlm_water_tree = STRtree(water_polys) if water_polys else None + + na_meta, _, na_geoms, na_fields = pyogrio.raw.read(str(gdb_path), layer="TLM_NUTZUNGSAREAL", bbox=bbox) + na_obj_idx = list(na_meta["fields"]).index("OBJEKTART") + orchard_polys = [] + for g_bytes, obj in zip(na_geoms, na_fields[na_obj_idx]): + if obj == 15: # Obstanlage + orchard_polys.append(shp_wkb.loads(g_bytes)) + orchard_tree = STRtree(orchard_polys) if orchard_polys else None + + def is_in_tlm_water(e: float, n: float) -> bool: + if tlm_water_tree is None: + return False + return len(tlm_water_tree.query(Point(e, n), predicate="intersects")) > 0 + + def is_in_orchard(e: float, n: float) -> bool: + if orchard_tree is None: + return False + return len(orchard_tree.query(Point(e, n), predicate="intersects")) > 0 + + placed: list[dict] = [] + # Spatial hash grid (cell = 8m) for fast min-spacing deduplication + cell_m = 8.0 + grid_buckets: dict[tuple[int, int], list[tuple[float, float]]] = {} + + def too_close(wx: float, wz: float, min_dist: float) -> bool: + cx = int(math.floor(wx / cell_m)) + cz = int(math.floor(wz / cell_m)) + r_cells = int(math.ceil(min_dist / cell_m)) + md2 = min_dist * min_dist + for dz in range(-r_cells, r_cells + 1): + for dx in range(-r_cells, r_cells + 1): + pts = grid_buckets.get((cx + dx, cz + dz)) + if not pts: + continue + for px, pz in pts: + if (px - wx) ** 2 + (pz - wz) ** 2 < md2: + return True + return False + + def add_tree(wx: float, wz: float, height_m: float, radius_m: float, species: int, variant: int, yaw: float) -> None: + tx = max(0, min(TILE_GRID - 1, int(math.floor((wx + HALF_EXTENT_M) / TILE_SIZE_M)))) + tz = max(0, min(TILE_GRID - 1, int(math.floor((wz + HALF_EXTENT_M) / TILE_SIZE_M)))) + y = sample_bilinear(hm, wx, wz) + placed.append({ + "tx": tx, + "tz": tz, + "x": wx, + "y": y, + "z": wz, + "yaw": yaw, + "height": height_m, + "radius": radius_m, + "species": species, + "variant": variant, + }) + cx = int(math.floor(wx / cell_m)) + cz = int(math.floor(wz / cell_m)) + grid_buckets.setdefault((cx, cz), []).append((wx, wz)) + + # 1. Ville de Sion Arbres Remarquables (exact coordinates!) + arbres = load_arbres_remarquables(cache_dir, script_dir) + remark_count = 0 + for feat in arbres: + geom = feat.get("geometry") or {} + attrs = feat.get("attributes") or {} + e = float(geom.get("x", 0.0)) + n = float(geom.get("y", 0.0)) + if not (e0 + 4.0 <= e <= e1 - 4.0 and n0 + 4.0 <= n <= n1 - 4.0): + continue + wx = e - cE + wz = cN - n + if is_blocked_xz(wx, wz, pad=False) or is_in_tlm_water(e, n): + continue + sp, min_h, rad = map_remarkable_species(str(attrs.get("nom_latin", ""))) + vhm_h = sample_cog_max(vhm_arr, vhm_ox, vhm_ny, vhm_sx, vhm_sy, e, n, rad_px=5) + h = max(min_h, min(36.0, vhm_h if vhm_h >= 4.5 else min_h)) + u = deterministic_rng(e, n) + add_tree(wx, wz, h, rad, sp, 0, u * math.tau) + remark_count += 1 + print(f" Placed {remark_count} Ville de Sion arbres remarquables inside arena") + + # 2. TLM_EINZELBAUM (isolated, avenue & hedgerow trees >= 5m) + ein_candidates: list[tuple[float, float, float, float, float]] = [] + for g_bytes in ein_geoms: + pt = shp_wkb.loads(g_bytes) + e, n = float(pt.x), float(pt.y) + if not (e0 + 4.0 <= e <= e1 - 4.0 and n0 + 4.0 <= n <= n1 - 4.0): + continue + wx = e - cE + wz = cN - n + if is_blocked_xz(wx, wz, pad=True) or is_in_tlm_water(e, n): + continue + vhm_h = sample_cog_max(vhm_arr, vhm_ox, vhm_ny, vhm_sx, vhm_sy, e, n, rad_px=4) + ein_candidates.append((e, n, wx, wz, vhm_h)) + + # Prioritize orchard trees and dominant canopy heights deterministically across the valley + ein_candidates.sort(key=lambda item: (0 if is_in_orchard(item[0], item[1]) else 1, -item[4], item[0], item[1])) + ein_count = 0 + ein_cap = 3800 + for e, n, wx, wz, vhm_h in ein_candidates: + if len(placed) >= MAX_TREES or ein_count >= ein_cap: + break + if too_close(wx, wz, 9.5): + continue + u = deterministic_rng(e, n) + ground_y = sample_bilinear(hm, wx, wz) + slope = sample_bilinear(slope_grid, wx, wz) + rock = sample_bilinear(rock_grid, wx, wz) + conifer = sample_cog(wmg_arr, wmg_ox, wmg_ny, wmg_sx, wmg_sy, e, n) + ufer = sample_cog(ufer_arr, ufer_ox, ufer_ny, ufer_sx, ufer_sy, e, n) + is_rip = (1.0 <= ufer <= 105.0) and ((int(round(ufer)) % 100) == 1) + is_orch = is_in_orchard(e, n) + sp, rad = classify_species(wx, wz, e, n, ground_y, slope, conifer, is_rip, is_orch, rock, u) + h = vhm_h if 4.5 <= vhm_h <= 32.0 else (5.5 + 1.8 * u if sp == SP_MALUS_ORCHARD else 10.5 + 8.0 * u) + if sp == SP_MALUS_ORCHARD: + h = min(h, 7.5) + var = 0 if ((int(round(e * 10)) + int(round(n * 10))) & 1) == 0 else 1 + add_tree(wx, wz, h, rad, sp, var, u * math.tau) + ein_count += 1 + print(f" Placed {ein_count} TLM_EINZELBAUM trees (from {len(ein_candidates)} valid points)") + + # 3. 0.5 m LiDAR NFI VHM canopy maxima inside TLM_BODENBEDECKUNG forest & uferbestockung + # Find local maxima on the 0.5m VHM grid (window 15 px = 7.5m spacing) + vhm_clean = np.where((vhm_arr >= 4.5) & (vhm_arr <= 38.0), vhm_arr, 0.0) + local_max = maximum_filter(vhm_clean, size=15) + peaks = np.argwhere((vhm_clean >= 4.5) & (vhm_clean == local_max)) + # Sort peaks by height descending so dominant canopy tops win budget up to MAX_TREES + peak_heights = vhm_clean[peaks[:, 0], peaks[:, 1]] + order = np.argsort(-peak_heights) + + forest_count = 0 + for idx in order: + if len(placed) >= MAX_TREES: + break + r, c = int(peaks[idx, 0]), int(peaks[idx, 1]) + h = float(peak_heights[idx]) + e = vhm_ox + c * vhm_sx + n = vhm_ny - r * vhm_sy + if not (e0 + 4.0 <= e <= e1 - 4.0 and n0 + 4.0 <= n <= n1 - 4.0): + continue + wx = e - cE + wz = cN - n + if too_close(wx, wz, 8.0): + continue + if is_blocked_xz(wx, wz, pad=True) or is_in_tlm_water(e, n): + continue + if sample_bilinear(asphalt_grid, wx, wz) >= 0.55: + continue + + ufer = sample_cog(ufer_arr, ufer_ox, ufer_ny, ufer_sx, ufer_sy, e, n) + in_forest = forest_tree is not None and len(forest_tree.query(Point(e, n), predicate="intersects")) > 0 + is_rip = (1.0 <= ufer <= 105.0) and ((int(round(ufer)) % 100) == 1) + is_orch = is_in_orchard(e, n) + if not in_forest and not is_rip and not is_orch: + continue + + u = deterministic_rng(e, n) + ground_y = sample_bilinear(hm, wx, wz) + slope = sample_bilinear(slope_grid, wx, wz) + rock = sample_bilinear(rock_grid, wx, wz) + conifer = sample_cog(wmg_arr, wmg_ox, wmg_ny, wmg_sx, wmg_sy, e, n) + sp, rad = classify_species(wx, wz, e, n, ground_y, slope, conifer, is_rip and not in_forest, is_orch, rock, u) + var = 0 if ((int(round(e * 10)) + int(round(n * 10))) & 1) == 0 else 1 + add_tree(wx, wz, h, rad, sp, var, u * math.tau) + forest_count += 1 + + print(f" Placed {forest_count} VHM LiDAR canopy maxima trees (total={len(placed)})") + + # Sort deterministically by (Tx, Tz, MortonIdx) + placed.sort(key=lambda t: ( + t["tx"], + t["tz"], + morton2d( + max(0, min(65535, int((t["x"] + HALF_EXTENT_M) / ARENA_SIZE_M * 65535))), + max(0, min(65535, int((t["z"] + HALF_EXTENT_M) / ARENA_SIZE_M * 65535))), + ), + t["x"], + t["z"], + )) + + assert len(placed) <= MAX_TREES, f"Exceeded {MAX_TREES}: {len(placed)}" + assert all(0 <= t["species"] <= 9 for t in placed), "Invalid species ID" + + # Pack RDTR v1 binary + header = struct.pack("<4sIII", b"RDTR", 1, len(placed), 0) + chunks = [header] + sp_counts = [0] * 10 + for tree_id, t in enumerate(placed): + sp_counts[t["species"]] += 1 + chunks.append(struct.pack( + ".glb containing Intact_LOD0, Intact_LOD1, Intact_LOD2, SnappedStump, CharredSkeleton +# - _impostor_albedo.png + _impostor_normal.png (6x6 octahedral atlas) +# - textures/bark.png + branchlet_*.png +# - trees_catalog.json +extends SceneTree + +const CosmoTree := preload("res://addons/cosmo_tree_gen/core/cosmo_tree_gen.gd") +const TreeBuilder := preload("res://addons/cosmo_tree_gen/core/tree_builder.gd") +const MeshUtils := preload("res://addons/cosmo_tree_gen/core/mesh_utils.gd") +const ImpostorGen := preload("res://addons/cosmo_tree_gen/core/impostor_gen.gd") + +const IMPOSTOR_FRAMES: int = 6 +const IMPOSTOR_RES: int = 384 # 6x6 cells of 64x64 px + +var _repo_root: String +var _out_dir: String +var _tex_dir: String +var _bark_tex: Texture2D +var _leaf_textures: Dictionary = {} + + +func _initialize() -> void: + if DisplayServer.get_name() != "headless": + DisplayServer.window_set_flag(DisplayServer.WINDOW_FLAG_NO_FOCUS, true) + DisplayServer.window_set_flag(DisplayServer.WINDOW_FLAG_BORDERLESS, true) + DisplayServer.window_set_position(Vector2i(-4000, -4000)) + call_deferred("_run_async") + + +func _run_async() -> void: + var cosmo_root := ProjectSettings.globalize_path("res://").simplify_path() + _repo_root = cosmo_root.path_join("../..").simplify_path() + _out_dir = _repo_root.path_join("assets/maps/sion/trees") + _tex_dir = _out_dir.path_join("textures") + DirAccess.make_dir_recursive_absolute(_tex_dir) + + _copy_shared_textures() + _bark_tex = _load_png_texture(_tex_dir.path_join("bark.png")) + for key in ["broadleaf", "oak", "orchard", "birch", "spruce", "pine"]: + _leaf_textures[key] = _load_png_texture(_tex_dir.path_join("branchlet_%s.png" % key)) + + var specs := _build_species_specs() + var catalog_entries: Array = [] + var can_capture_impostors := DisplayServer.get_name() != "headless" + var skip_impostors := "--skip-impostors" in OS.get_cmdline_user_args() + if skip_impostors: + can_capture_impostors = false + + var total_glb_bytes := 0 + for spec in specs: + var slug: String = spec["slug"] + var entry := await _bake_archetype(spec, can_capture_impostors) + catalog_entries.append(entry) + var glb_path := _out_dir.path_join(slug + ".glb") + var f := FileAccess.open(glb_path, FileAccess.READ) + if f != null: + total_glb_bytes += f.get_length() + f.close() + + var catalog := { + "version": 1, + "impostorFrames": IMPOSTOR_FRAMES, + "impostorResolution": IMPOSTOR_RES, + "beechPresent": false, + "archetypes": catalog_entries, + } + var json_file := FileAccess.open(_out_dir.path_join("trees_catalog.json"), FileAccess.WRITE) + json_file.store_string(JSON.stringify(catalog, " ")) + json_file.close() + + print("SION_TREES_BAKED count=%d glb_bytes=%d impostors_gpu=%s dir=%s" % [ + catalog_entries.size(), total_glb_bytes, str(can_capture_impostors), _out_dir + ]) + quit(0) + + +func _copy_shared_textures() -> void: + var copies := { + "res://addons/cosmo_tree_gen/textures/bark.png": "bark.png", + "res://addons/cosmo_tree_gen/textures/branchlet_01.png": "branchlet_broadleaf.png", + "res://demo/textures/branchlet_02.png": "branchlet_oak.png", + "res://addons/cosmo_tree_gen/textures/branchlet_03.png": "branchlet_orchard.png", + "res://demo/textures/branchlet_04.png": "branchlet_birch.png", + "res://demo/textures/branchlet_06.png": "branchlet_spruce.png", + "res://demo/textures/branchlet_07.png": "branchlet_pine.png", + } + for src_res: String in copies: + var src_abs := ProjectSettings.globalize_path(src_res) + var dst_abs := _tex_dir.path_join(copies[src_res]) + var img := Image.load_from_file(src_abs) + if img == null: + push_error("Failed to load texture: %s" % src_abs) + quit(2) + return + img.save_png(dst_abs) + + +func _load_png_texture(abs_path: String) -> ImageTexture: + var img := Image.load_from_file(abs_path) + return ImageTexture.create_from_image(img) + + +func _make_bark_mat(tint: Color) -> StandardMaterial3D: + var mat := StandardMaterial3D.new() + mat.albedo_texture = _bark_tex + mat.albedo_color = tint + mat.roughness = 0.92 + return mat + + +func _make_leaf_mat(tex_key: String, tint: Color, backlight: Color) -> ShaderMaterial: + var mat := ShaderMaterial.new() + mat.shader = preload("res://addons/cosmo_tree_gen/shaders/leaves.gdshader") + mat.set_shader_parameter("albedo", tint) + mat.set_shader_parameter("albedo_texture", _leaf_textures[tex_key]) + mat.set_shader_parameter("alpha_scissor_threshold", 0.45) + mat.set_shader_parameter("backlight", backlight) + mat.set_shader_parameter("ao_light_affect", 0.55) + return mat + + +func _make_curve(points: Array) -> Curve: + var c := Curve.new() + for pt: Vector2 in points: + c.add_point(pt) + return c + + +func _branch_level( + count: int, + start: float, + end: float, + angle: float, + length: float, + radius: float, + segments: int, + gnarl: float, + up_force: float, + terminal: bool = false, + broken: float = 0.0, + curve: Curve = null, +) -> CosmoBranchLevel: + var lvl := CosmoBranchLevel.new() + lvl.count = count + lvl.start = start + lvl.end = end + lvl.angle = angle + lvl.length = length + lvl.radius = radius + lvl.segments = segments + lvl.gnarl = gnarl + lvl.up_force = up_force + lvl.terminal = terminal + lvl.broken_chance = broken + lvl.length_curve = curve + return lvl + + +func _build_species_specs() -> Array[Dictionary]: + # Canonical species IDs match RustToDust.Core.SionTreeSpecies (0..9, 0 wild beech). + var specs: Array[Dictionary] = [] + + # 0: PinusSylvestris (Scots Pine - Valere / dry rocky slopes) + for v in 2: + var t := CosmoTrunkParams.new() + t.quality = 1 + t.height = 16.5 if v == 0 else 14.0 + t.radius_bottom = 0.34 if v == 0 else 0.29 + t.radius_top = 0.04 + t.lean = 0.55 if v == 0 else 0.85 + t.wobble = 0.22 + t.flare = 0.35 + t.sink_depth = 0.35 + var b0 := _branch_level(9 if v == 0 else 8, 0.52, 0.98, 72.0, 0.34, 0.55, 2, 0.38, 0.15, true, 0.12, + _make_curve([Vector2(0.0, 1.0), Vector2(0.45, 0.90), Vector2(1.0, 0.35)])) + var b1 := _branch_level(3, 0.40, 1.0, 48.0, 0.42, 0.55, 2, 0.32, 0.12, false, 0.05) + var f := CosmoFoliageParams.new() + f.type = CosmoFoliageParams.Type.LEAVES + f.leaf_count = 7 + f.leaf_tip = true + f.leaf_size = 1.35 + f.leaf_length_influence = 0.35 + f.leaf_start = 0.10 + f.leaf_angle = 35.0 + f.leaf_double = true + f.leaf_canopy_normals = 0.65 + f.leaf_inner_ao = 0.40 + specs.append({ + "speciesId": 0, "speciesName": "PinusSylvestris", "variant": v, + "slug": "pinus_sylvestris_v%d" % v, "seed": 1100 + v * 37, + "trunk": t, "levels": [b0, b1], "foliage": f, + "leafTex": "pine", "barkTint": Color(0.76, 0.54, 0.40), "leafTint": Color(0.56, 0.68, 0.44), + "backlight": Color(0.32, 0.42, 0.18), "stumpH": 2.2 + v * 0.3, + }) + + # 1: QuercusPubescens (Downy Oak - Valere / Tourbillon limestone cliffs) + for v in 2: + var t := CosmoTrunkParams.new() + t.quality = 1 + t.height = 10.5 if v == 0 else 9.0 + t.radius_bottom = 0.36 if v == 0 else 0.30 + t.radius_top = 0.06 + t.lean = 0.65 if v == 0 else 0.95 + t.wobble = 0.32 + t.flare = 0.55 + t.sink_depth = 0.35 + var b0 := _branch_level(7 if v == 0 else 6, 0.28, 0.92, 54.0, 0.48, 0.62, 2, 0.58, 0.30, true, 0.08) + var b1 := _branch_level(3, 0.30, 0.98, 46.0, 0.44, 0.58, 2, 0.45, 0.18, false, 0.0) + var f := CosmoFoliageParams.new() + f.type = CosmoFoliageParams.Type.LEAVES + f.leaf_count = 8 + f.leaf_tip = true + f.leaf_size = 1.25 + f.leaf_length_influence = 0.30 + f.leaf_start = 0.05 + f.leaf_angle = 38.0 + f.leaf_double = true + f.leaf_canopy_normals = 0.70 + f.leaf_inner_ao = 0.38 + specs.append({ + "speciesId": 1, "speciesName": "QuercusPubescens", "variant": v, + "slug": "quercus_pubescens_v%d" % v, "seed": 2200 + v * 41, + "trunk": t, "levels": [b0, b1], "foliage": f, + "leafTex": "oak", "barkTint": Color(0.56, 0.50, 0.44), "leafTint": Color(0.62, 0.70, 0.40), + "backlight": Color(0.38, 0.46, 0.20), "stumpH": 1.9 + v * 0.4, + }) + + # 2: PopulusNigra (Black Poplar - Rhone levees & valley floor) + for v in 2: + var t := CosmoTrunkParams.new() + t.quality = 1 + t.height = 19.5 if v == 0 else 17.0 + t.radius_bottom = 0.38 if v == 0 else 0.33 + t.radius_top = 0.04 + t.lean = 0.28 if v == 0 else 0.45 + t.wobble = 0.14 + t.flare = 0.40 + t.sink_depth = 0.35 + var b0 := _branch_level(11 if v == 0 else 9, 0.24, 0.95, 28.0, 0.32, 0.48, 2, 0.22, 0.85, true, 0.0, + _make_curve([Vector2(0.0, 0.65), Vector2(0.5, 1.0), Vector2(1.0, 0.35)])) + var b1 := _branch_level(3, 0.25, 0.98, 28.0, 0.38, 0.55, 2, 0.22, 0.50, false, 0.0) + var f := CosmoFoliageParams.new() + f.type = CosmoFoliageParams.Type.LEAVES + f.leaf_count = 7 + f.leaf_tip = true + f.leaf_size = 1.25 + f.leaf_length_influence = 0.25 + f.leaf_start = 0.05 + f.leaf_angle = 32.0 + f.leaf_double = true + f.leaf_canopy_normals = 0.60 + f.leaf_inner_ao = 0.42 + specs.append({ + "speciesId": 2, "speciesName": "PopulusNigra", "variant": v, + "slug": "populus_nigra_v%d" % v, "seed": 3300 + v * 53, + "trunk": t, "levels": [b0, b1], "foliage": f, + "leafTex": "broadleaf", "barkTint": Color(0.68, 0.65, 0.58), "leafTint": Color(0.66, 0.78, 0.46), + "backlight": Color(0.45, 0.55, 0.25), "stumpH": 2.4 + v * 0.3, + }) + + # 3: PlatanusAcerifolia (London Plane - urban avenues & parks) + for v in 2: + var t := CosmoTrunkParams.new() + t.quality = 1 + t.height = 17.0 if v == 0 else 15.0 + t.radius_bottom = 0.42 if v == 0 else 0.36 + t.radius_top = 0.06 + t.lean = 0.35 + t.wobble = 0.18 + t.flare = 0.45 + t.sink_depth = 0.35 + var b0 := _branch_level(8, 0.30, 0.92, 48.0, 0.44, 0.60, 2, 0.30, 0.40, true, 0.02) + var b1 := _branch_level(3, 0.25, 0.96, 44.0, 0.42, 0.58, 2, 0.28, 0.18, false, 0.0) + var f := CosmoFoliageParams.new() + f.type = CosmoFoliageParams.Type.LEAVES + f.leaf_count = 8 + f.leaf_tip = true + f.leaf_size = 1.45 + f.leaf_length_influence = 0.30 + f.leaf_start = 0.05 + f.leaf_angle = 40.0 + f.leaf_double = true + f.leaf_canopy_normals = 0.72 + f.leaf_inner_ao = 0.42 + specs.append({ + "speciesId": 3, "speciesName": "PlatanusAcerifolia", "variant": v, + "slug": "platanus_acerifolia_v%d" % v, "seed": 4400 + v * 61, + "trunk": t, "levels": [b0, b1], "foliage": f, + "leafTex": "broadleaf", "barkTint": Color(0.76, 0.72, 0.62), "leafTint": Color(0.64, 0.76, 0.42), + "backlight": Color(0.45, 0.52, 0.24), "stumpH": 2.3 + v * 0.4, + }) + + # 4: BetulaPendula (Silver Birch - slender white trunk, weeping crown) + for v in 2: + var t := CosmoTrunkParams.new() + t.quality = 1 + t.height = 13.5 if v == 0 else 11.5 + t.radius_bottom = 0.21 if v == 0 else 0.18 + t.radius_top = 0.025 + t.lean = 0.50 if v == 0 else 0.75 + t.wobble = 0.25 + t.flare = 0.25 + t.sink_depth = 0.30 + var b0 := _branch_level(9, 0.34, 0.96, 46.0, 0.34, 0.48, 2, 0.32, -0.35, true, 0.0) + var b1 := _branch_level(3, 0.25, 0.98, 42.0, 0.40, 0.52, 2, 0.25, -0.65, false, 0.0) + var f := CosmoFoliageParams.new() + f.type = CosmoFoliageParams.Type.LEAVES + f.leaf_count = 7 + f.leaf_tip = true + f.leaf_size = 1.02 + f.leaf_length_influence = 0.25 + f.leaf_start = 0.05 + f.leaf_angle = 45.0 + f.leaf_gravity = 0.45 + f.leaf_double = true + f.leaf_canopy_normals = 0.55 + f.leaf_inner_ao = 0.50 + specs.append({ + "speciesId": 4, "speciesName": "BetulaPendula", "variant": v, + "slug": "betula_pendula_v%d" % v, "seed": 5500 + v * 67, + "trunk": t, "levels": [b0, b1], "foliage": f, + "leafTex": "birch", "barkTint": Color(0.92, 0.90, 0.86), "leafTint": Color(0.70, 0.82, 0.46), + "backlight": Color(0.48, 0.56, 0.26), "stumpH": 1.8 + v * 0.3, + }) + + # 5: PiceaAbies (Norway Spruce - ravines / higher slopes) + for v in 2: + var t := CosmoTrunkParams.new() + t.quality = 1 + t.height = 20.5 if v == 0 else 17.5 + t.radius_bottom = 0.32 if v == 0 else 0.27 + t.radius_top = 0.02 + t.lean = 0.14 + t.wobble = 0.08 + t.flare = 0.35 + t.sink_depth = 0.35 + var b0 := _branch_level(26 if v == 0 else 22, 0.16, 0.97, 86.0, 0.30, 0.48, 2, 0.12, -0.55, false, 0.0, + _make_curve([Vector2(0.0, 0.95), Vector2(0.55, 0.55), Vector2(1.0, 0.08)])) + var f := CosmoFoliageParams.new() + f.type = CosmoFoliageParams.Type.LEAVES + f.leaf_count = 8 + f.leaf_tip = true + f.leaf_size = 1.45 + f.leaf_length_influence = 0.35 + f.leaf_start = 0.05 + f.leaf_angle = 26.0 + f.leaf_double = true + f.leaf_canopy_normals = 0.55 + f.leaf_inner_ao = 0.42 + specs.append({ + "speciesId": 5, "speciesName": "PiceaAbies", "variant": v, + "slug": "picea_abies_v%d" % v, "seed": 6600 + v * 71, + "trunk": t, "levels": [b0], "foliage": f, + "leafTex": "spruce", "barkTint": Color(0.54, 0.42, 0.34), "leafTint": Color(0.42, 0.56, 0.36), + "backlight": Color(0.24, 0.34, 0.16), "stumpH": 2.0 + v * 0.4, + }) + + # 6: MalusOrchard (Orchard Apple / Apricot - valley orchards) + for v in 2: + var t := CosmoTrunkParams.new() + t.quality = 1 + t.height = 5.2 if v == 0 else 4.6 + t.radius_bottom = 0.18 if v == 0 else 0.15 + t.radius_top = 0.04 + t.lean = 0.35 + t.wobble = 0.16 + t.flare = 0.25 + t.sink_depth = 0.25 + var b0 := _branch_level(6, 0.32, 0.90, 56.0, 0.48, 0.58, 2, 0.40, 0.22, true, 0.0) + var b1 := _branch_level(3, 0.25, 0.96, 48.0, 0.44, 0.56, 2, 0.32, 0.15, false, 0.0) + var f := CosmoFoliageParams.new() + f.type = CosmoFoliageParams.Type.LEAVES + f.leaf_count = 7 + f.leaf_tip = true + f.leaf_size = 0.85 + f.leaf_length_influence = 0.25 + f.leaf_start = 0.08 + f.leaf_angle = 40.0 + f.leaf_double = true + f.leaf_canopy_normals = 0.72 + f.leaf_inner_ao = 0.45 + specs.append({ + "speciesId": 6, "speciesName": "MalusOrchard", "variant": v, + "slug": "malus_orchard_v%d" % v, "seed": 7700 + v * 79, + "trunk": t, "levels": [b0, b1], "foliage": f, + "leafTex": "orchard", "barkTint": Color(0.62, 0.54, 0.46), "leafTint": Color(0.68, 0.78, 0.44), + "backlight": Color(0.45, 0.52, 0.24), "stumpH": 1.6 + v * 0.2, + }) + + # 7: Sequoiadendron (Arbre Remarquable - Planta d'en Haut Giant Sequoia) + var seq_t := CosmoTrunkParams.new() + seq_t.quality = 1 + seq_t.height = 29.0 + seq_t.radius_bottom = 0.88 + seq_t.radius_top = 0.06 + seq_t.lean = 0.15 + seq_t.wobble = 0.08 + seq_t.flare = 0.75 + seq_t.flare_height = 0.18 + seq_t.sink_depth = 0.50 + var seq_b0 := _branch_level(28, 0.20, 0.96, 82.0, 0.24, 0.42, 2, 0.18, -0.35, false, 0.0, + _make_curve([Vector2(0.0, 1.0), Vector2(0.55, 0.65), Vector2(1.0, 0.10)])) + var seq_f := CosmoFoliageParams.new() + seq_f.type = CosmoFoliageParams.Type.LEAVES + seq_f.leaf_count = 8 + seq_f.leaf_tip = true + seq_f.leaf_size = 1.95 + seq_f.leaf_length_influence = 0.35 + seq_f.leaf_start = 0.08 + seq_f.leaf_angle = 28.0 + seq_f.leaf_double = true + seq_f.leaf_canopy_normals = 0.60 + seq_f.leaf_inner_ao = 0.38 + specs.append({ + "speciesId": 7, "speciesName": "Sequoiadendron", "variant": 0, + "slug": "sequoiadendron_v0", "seed": 8801, + "trunk": seq_t, "levels": [seq_b0], "foliage": seq_f, + "leafTex": "spruce", "barkTint": Color(0.72, 0.42, 0.30), "leafTint": Color(0.46, 0.60, 0.38), + "backlight": Color(0.28, 0.38, 0.18), "stumpH": 2.8, + }) + + # 8: Cedrus (Arbre Remarquable - Cimetiere Saint-Francois / Pratifori Lebanon Cedar) + var ced_t := CosmoTrunkParams.new() + ced_t.quality = 1 + ced_t.height = 20.0 + ced_t.radius_bottom = 0.68 + ced_t.radius_top = 0.12 + ced_t.lean = 0.30 + ced_t.wobble = 0.18 + ced_t.flare = 0.60 + ced_t.sink_depth = 0.45 + var ced_b0 := _branch_level(10, 0.32, 0.96, 84.0, 0.44, 0.55, 2, 0.25, 0.08, true, 0.0, + _make_curve([Vector2(0.0, 1.0), Vector2(0.6, 0.88), Vector2(1.0, 0.45)])) + var ced_b1 := _branch_level(3, 0.25, 0.98, 65.0, 0.38, 0.50, 2, 0.20, 0.05, false, 0.0) + var ced_f := CosmoFoliageParams.new() + ced_f.type = CosmoFoliageParams.Type.LEAVES + ced_f.leaf_count = 8 + ced_f.leaf_tip = true + ced_f.leaf_size = 1.80 + ced_f.leaf_length_influence = 0.30 + ced_f.leaf_start = 0.08 + ced_f.leaf_angle = 20.0 + ced_f.leaf_double = true + ced_f.leaf_canopy_normals = 0.68 + ced_f.leaf_inner_ao = 0.36 + specs.append({ + "speciesId": 8, "speciesName": "Cedrus", "variant": 0, + "slug": "cedrus_v0", "seed": 8901, + "trunk": ced_t, "levels": [ced_b0, ced_b1], "foliage": ced_f, + "leafTex": "spruce", "barkTint": Color(0.58, 0.52, 0.46), "leafTint": Color(0.48, 0.64, 0.46), + "backlight": Color(0.30, 0.42, 0.24), "stumpH": 2.6, + }) + + # 9: PlatanusMonumental (Arbre Remarquable - En Ville / Planta Monumental Plane) + var pm_t := CosmoTrunkParams.new() + pm_t.quality = 1 + pm_t.height = 22.0 + pm_t.radius_bottom = 0.72 + pm_t.radius_top = 0.14 + pm_t.lean = 0.40 + pm_t.wobble = 0.24 + pm_t.flare = 0.65 + pm_t.sink_depth = 0.45 + var pm_b0 := _branch_level(9, 0.28, 0.92, 52.0, 0.48, 0.62, 2, 0.35, 0.36, true, 0.0) + var pm_b1 := _branch_level(3, 0.25, 0.96, 46.0, 0.42, 0.58, 2, 0.30, 0.16, false, 0.0) + var pm_f := CosmoFoliageParams.new() + pm_f.type = CosmoFoliageParams.Type.LEAVES + pm_f.leaf_count = 8 + pm_f.leaf_tip = true + pm_f.leaf_size = 1.85 + pm_f.leaf_length_influence = 0.30 + pm_f.leaf_start = 0.05 + pm_f.leaf_angle = 40.0 + pm_f.leaf_double = true + pm_f.leaf_canopy_normals = 0.74 + pm_f.leaf_inner_ao = 0.40 + specs.append({ + "speciesId": 9, "speciesName": "PlatanusMonumental", "variant": 0, + "slug": "platanus_monumental_v0", "seed": 9001, + "trunk": pm_t, "levels": [pm_b0, pm_b1], "foliage": pm_f, + "leafTex": "broadleaf", "barkTint": Color(0.78, 0.74, 0.64), "leafTint": Color(0.64, 0.76, 0.42), + "backlight": Color(0.45, 0.52, 0.24), "stumpH": 2.7, + }) + + return specs + + +func _configure_tree(tree: CosmoTree, spec: Dictionary, generate_lod: bool, create_foliage: bool) -> void: + tree.auto_generate = false + tree.noise_seed = spec["seed"] + tree.trunk_params = (spec["trunk"] as CosmoTrunkParams).duplicate(true) + var lvls: Array[CosmoBranchLevel] = [] + for l: CosmoBranchLevel in spec["levels"]: + lvls.append(l.duplicate(true)) + tree.branch_levels = lvls + tree.foliage_params = (spec["foliage"] as CosmoFoliageParams).duplicate(true) + tree.generate_lod = generate_lod + tree.combine_trunk_and_foliage = true + tree.create_trunk = true + tree.create_foliage = create_foliage + tree.lod_trunk_share = 0.34 + tree.texel_density = 64.0 + tree.trunk_material = _make_bark_mat(spec["barkTint"]) + tree.foliage_material = _make_leaf_mat(spec["leafTex"], spec["leafTint"], spec["backlight"]) + + +func _build_snapped_stump_mesh(spec: Dictionary) -> ArrayMesh: + var stump_h: float = spec["stumpH"] + var src_trunk: CosmoTrunkParams = spec["trunk"] + var t_ratio := clampf(stump_h / maxf(src_trunk.height, 1.0), 0.08, 0.65) + var stump_params := src_trunk.duplicate(true) as CosmoTrunkParams + stump_params.height = stump_h + stump_params.radius_top = lerpf(src_trunk.radius_bottom, src_trunk.radius_top, t_ratio) * 0.94 + stump_params.lean = src_trunk.lean * t_ratio * 0.45 + stump_params.wobble = src_trunk.wobble * 0.35 + stump_params.quality = 1 + stump_params.flare_height = clampf(src_trunk.flare_height / t_ratio, 0.20, 0.85) + + var rng := RandomNumberGenerator.new() + rng.seed = int(spec["seed"]) + 991 + + var radial := 8 + var rings := 5 + var sink := stump_params.sink_depth + var vertices := PackedVector3Array() + var indices := PackedInt32Array() + var uvs := PackedVector2Array() + var colors := PackedColorArray() + + var ring_stride := radial + 1 + var phase := float(posmod(hash(int(spec["seed"])), 10000)) / 10000.0 + var lean_dir := Vector3(cos(phase * TAU), 0.0, sin(phase * TAU)) * stump_params.lean + + for r in rings + 1: + var p := float(r) / rings + var y := -sink if r == 0 else lerpf(0.0, stump_h, p) + var base_rad := lerpf(stump_params.radius_bottom, stump_params.radius_top, p) + if r <= 2: + base_rad *= 1.0 + stump_params.flare * pow(1.0 - p * 1.4, 2.0) * 0.45 + var center := Vector3(lean_dir.x * p * p, y, lean_dir.z * p * p) + for j in radial: + var ang := TAU * float(j) / radial + var splinter := 0.0 + if r == rings: + # Jagged artillery-sheared splinters at top rim + splinter = rng.randf_range(-0.18, 0.32) if (j % 2 == 0) else rng.randf_range(-0.28, 0.08) + var pt := center + Vector3(cos(ang) * base_rad, splinter, sin(ang) * base_rad) + vertices.push_back(pt) + uvs.push_back(Vector2(float(j) / radial, y * 0.5)) + var ao := clampf(lerpf(0.30, 0.72, p), 0.15, 1.0) + colors.push_back(Color(ao, 0.0, phase, clampf(maxf(y, 0.0) / stump_h, 0.0, 1.0))) + # Seam vertex + vertices.push_back(vertices[vertices.size() - radial]) + uvs.push_back(Vector2(1.0, y * 0.5)) + colors.push_back(colors[colors.size() - radial]) + + for r in rings: + for j in radial: + var a := r * ring_stride + j + var b := a + 1 + var c := a + ring_stride + var d := c + 1 + indices.append_array(PackedInt32Array([d, c, a, d, a, b])) + + # Jagged inner apex cap + var apex_idx := vertices.size() + vertices.push_back(Vector3(lean_dir.x, stump_h - 0.18, lean_dir.z)) + uvs.push_back(Vector2(0.5, stump_h * 0.5)) + colors.push_back(Color(0.22, 0.0, phase, 0.95)) + var top_ring := rings * ring_stride + for j in radial: + indices.append_array(PackedInt32Array([apex_idx, top_ring + j, top_ring + j + 1])) + + var mesh := MeshUtils.build_mesh(vertices, indices, false, uvs, colors) + mesh.surface_set_name(0, TreeBuilder.TRUNK_SURFACE_NAME) + return mesh + + +func _darken_charred_mesh(src: ArrayMesh) -> ArrayMesh: + var out := ArrayMesh.new() + for s in src.get_surface_count(): + var arrays := src.surface_get_arrays(s) + var colors: PackedColorArray = arrays[Mesh.ARRAY_COLOR] + if not colors.is_empty(): + for i in colors.size(): + var c := colors[i] + colors[i] = Color(clampf(c.r * 0.35, 0.15, 0.45), c.g * 0.65, c.b, c.a) + arrays[Mesh.ARRAY_COLOR] = colors + out.add_surface_from_arrays(src.surface_get_primitive_type(s), arrays) + out.surface_set_name(s, src.surface_get_name(s)) + return out + + +func _verify_mesh_colors(mesh: ArrayMesh, label: String) -> void: + var has_flex := false + for s in mesh.get_surface_count(): + var arrays := mesh.surface_get_arrays(s) + var colors: PackedColorArray = arrays[Mesh.ARRAY_COLOR] + if colors.is_empty(): + push_error("Missing ARRAY_COLOR on %s surface %d" % [label, s]) + quit(3) + return + for c in colors: + if c.g > 0.05: + has_flex = true + break + if not has_flex and not label.ends_with("SnappedStump"): + push_error("Zero flex gradient on %s" % label) + quit(4) + + +func _bake_archetype(spec: Dictionary, capture_impostors: bool) -> Dictionary: + var slug: String = spec["slug"] + + var intact_tree := CosmoTree.new() + _configure_tree(intact_tree, spec, true, true) + get_root().add_child(intact_tree) + intact_tree.generate() + + var lod0 := intact_tree.get_meshes(0)[0].mesh as ArrayMesh + var lod1 := intact_tree.get_meshes(1)[0].mesh as ArrayMesh + var lod2 := intact_tree.get_meshes(2)[0].mesh as ArrayMesh + _verify_mesh_colors(lod0, slug + "_LOD0") + _verify_mesh_colors(lod1, slug + "_LOD1") + _verify_mesh_colors(lod2, slug + "_LOD2") + + var bounds := lod0.get_aabb() + var canon_h := maxf(bounds.end.y, (spec["trunk"] as CosmoTrunkParams).height) + var canon_r := (spec["trunk"] as CosmoTrunkParams).radius_bottom + + var imp_scale := canon_h * 0.65 + var imp_offset_y := canon_h * 0.5 + if capture_impostors: + var imp := await ImpostorGen.bake_octahedral_images(intact_tree, IMPOSTOR_FRAMES, IMPOSTOR_RES) + var alb_img: Image = imp["albedo"] + var nrm_img: Image = imp["normal"] + alb_img.save_png(_out_dir.path_join(slug + "_impostor_albedo.png")) + nrm_img.save_png(_out_dir.path_join(slug + "_impostor_normal.png")) + imp_scale = float(imp["scale"]) + imp_offset_y = float((imp["position_offset"] as Vector3).y) + + intact_tree.queue_free() + + # Charred skeleton: leafless, broken limbs, darkened COLOR.r + var charred_spec := spec.duplicate(false) + var charred_levels: Array[CosmoBranchLevel] = [] + for l: CosmoBranchLevel in spec["levels"]: + var cl := l.duplicate(true) as CosmoBranchLevel + cl.broken_chance = maxf(cl.broken_chance, 0.35) + charred_levels.append(cl) + charred_spec["levels"] = charred_levels + var charred_tree := CosmoTree.new() + _configure_tree(charred_tree, charred_spec, true, false) + get_root().add_child(charred_tree) + charred_tree.generate() + var charred_lod := _darken_charred_mesh(charred_tree.get_meshes(2)[0].mesh as ArrayMesh) + _verify_mesh_colors(charred_lod, slug + "_CharredSkeleton") + charred_tree.queue_free() + + var stump_mesh := _build_snapped_stump_mesh(spec) + _verify_mesh_colors(stump_mesh, slug + "_SnappedStump") + + # Export single GLB containing all 5 named MeshInstance3D states (no embedded textures) + var export_root := Node3D.new() + export_root.name = slug + var states := { + "Intact_LOD0": lod0, + "Intact_LOD1": lod1, + "Intact_LOD2": lod2, + "SnappedStump": stump_mesh, + "CharredSkeleton": charred_lod, + } + for node_name: String in states: + var mi := MeshInstance3D.new() + mi.name = node_name + mi.mesh = states[node_name] + export_root.add_child(mi) + mi.owner = export_root + + var doc := GLTFDocument.new() + doc.set_image_format("None") + var state := GLTFState.new() + var glb_path := _out_dir.path_join(slug + ".glb") + var err := doc.append_from_scene(export_root, state) + if err == OK: + err = doc.write_to_filesystem(state, glb_path) + export_root.free() + if err != OK: + push_error("GLTF export failed for %s: %s" % [slug, error_string(err)]) + quit(5) + + var bark_c: Color = spec["barkTint"] + var leaf_c: Color = spec["leafTint"] + return { + "speciesId": int(spec["speciesId"]), + "speciesName": String(spec["speciesName"]), + "variant": int(spec["variant"]), + "slug": slug, + "glb": slug + ".glb", + "leafTexture": "textures/branchlet_%s.png" % spec["leafTex"], + "barkTexture": "textures/bark.png", + "barkTint": [bark_c.r, bark_c.g, bark_c.b], + "leafTint": [leaf_c.r, leaf_c.g, leaf_c.b], + "canonicalHeightM": snappedf(canon_h, 0.01), + "canonicalRadiusM": snappedf(canon_r, 0.001), + "impostorAlbedo": slug + "_impostor_albedo.png", + "impostorNormal": slug + "_impostor_normal.png", + "impostorFrames": IMPOSTOR_FRAMES, + "impostorScale": snappedf(imp_scale, 0.01), + "impostorOffsetY": snappedf(imp_offset_y, 0.01), + "lod0Tris": MeshUtils.count_triangles(lod0), + "lod1Tris": MeshUtils.count_triangles(lod1), + "lod2Tris": MeshUtils.count_triangles(lod2), + }