diff --git a/.gitignore b/.gitignore index 4642f47..61bea65 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,10 @@ __pycache__/ /out/ /scratch/ +/dist/ bin/ obj/ +artifacts/ +build/ .godot/ .vs/ diff --git a/RustToDust.slnx b/RustToDust.slnx index cf1fca2..e78085c 100644 --- a/RustToDust.slnx +++ b/RustToDust.slnx @@ -2,6 +2,7 @@ + diff --git a/THIRD_PARTY_NOTICES.txt b/THIRD_PARTY_NOTICES.txt new file mode 100644 index 0000000..a22e97c --- /dev/null +++ b/THIRD_PARTY_NOTICES.txt @@ -0,0 +1,20 @@ +THIRD-PARTY SOFTWARE NOTICES AND INFORMATION + +This product incorporates or bundles the following third-party software and +font assets under their respective licenses: + +1. Monaspace Krypton (Krypton.ttf — Monaspace Krypton Var.ttf v1.400) + Copyright (c) 2023, GitHub (https://github.com/githubnext/monaspace) + Reserved Font Names: 'Monaspace', 'Argon', 'Neon', 'Xenon', 'Radon', 'Krypton' + License: SIL Open Font License, Version 1.1 + Full license text: assets/fonts/OFL-1.1.txt + +2. HarfBuzz (15.2.0) — shaping and hb-gpu shader/curve encoder (rtd_hbgpu) + 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/fonts/HARFBUZZ-COPYING.txt b/assets/fonts/HARFBUZZ-COPYING.txt new file mode 100644 index 0000000..1dd917e --- /dev/null +++ b/assets/fonts/HARFBUZZ-COPYING.txt @@ -0,0 +1,42 @@ +HarfBuzz is licensed under the so-called "Old MIT" license. Details follow. +For parts of HarfBuzz that are licensed under different licenses see individual +files names COPYING in subdirectories where applicable. + +Copyright © 2010-2022 Google, Inc. +Copyright © 2015-2020 Ebrahim Byagowi +Copyright © 2019,2020 Facebook, Inc. +Copyright © 2012,2015 Mozilla Foundation +Copyright © 2011 Codethink Limited +Copyright © 2008,2010 Nokia Corporation and/or its subsidiary(-ies) +Copyright © 2009 Keith Stribley +Copyright © 2011 Martin Hosken and SIL International +Copyright © 2007 Chris Wilson +Copyright © 2005,2006,2020,2021,2022,2023 Behdad Esfahbod +Copyright © 2004,2007,2008,2009,2010,2013,2021,2022,2023 Red Hat, Inc. +Copyright © 1998-2005 David Turner and Werner Lemberg +Copyright © 2016 Igalia S.L. +Copyright © 2022 Matthias Clasen +Copyright © 2018,2021 Khaled Hosny +Copyright © 2018,2019,2020 Adobe, Inc +Copyright © 2013-2015 Alexei Podtelezhnikov + +For full copyright notices consult the individual files in the package. + + +Permission is hereby granted, without written agreement and without +license or royalty fees, to use, copy, modify, and distribute this +software and its documentation for any purpose, provided that the +above copyright notice and the following two paragraphs appear in +all copies of this software. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR +DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN +IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGE. + +THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, +BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS +ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO +PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. diff --git a/assets/fonts/Krypton.ttf b/assets/fonts/Krypton.ttf new file mode 100644 index 0000000..821c61e Binary files /dev/null and b/assets/fonts/Krypton.ttf differ diff --git a/assets/fonts/OFL-1.1.txt b/assets/fonts/OFL-1.1.txt new file mode 100644 index 0000000..0ad8d06 --- /dev/null +++ b/assets/fonts/OFL-1.1.txt @@ -0,0 +1,94 @@ +Copyright (c) 2023, GitHub (https://github.com/githubnext/monaspace) +with Reserved Font Names 'Monaspace', 'Argon', 'Neon', 'Xenon', 'Radon', 'Krypton'. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSIONS & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to remain +under this license does not apply to any document created using the fonts +or their derivatives. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/maps/sion/heightmap.f32 b/assets/maps/sion/heightmap.f32 deleted file mode 100644 index 7b83982..0000000 Binary files a/assets/maps/sion/heightmap.f32 and /dev/null differ diff --git a/assets/maps/sion/heightmap_05m.u16z b/assets/maps/sion/heightmap_05m.u16z new file mode 100644 index 0000000..3c2dd63 Binary files /dev/null and b/assets/maps/sion/heightmap_05m.u16z differ diff --git a/assets/maps/sion/metadata.json b/assets/maps/sion/metadata.json index f2f22af..ac7c1c7 100644 --- a/assets/maps/sion/metadata.json +++ b/assets/maps/sion/metadata.json @@ -2,7 +2,7 @@ "name": "Sion, Valais, Switzerland", "attribution": "Federal Office of Topography swisstopo", "sources": [ - "ch.swisstopo.swissalti3d (2m DTM, Open Government Data)", + "ch.swisstopo.swissalti3d (0.5m DTM, Open Government Data)", "ch.swisstopo.swissbuildings3d_3_0 (LOD2 3D Buildings, Open Government Data)" ], "stacItems": [ @@ -27,24 +27,33 @@ "swissbuildings3d_3_0_2020_1306-21", "swissbuildings3d_3_0_2020_1306-23" ], + "demAssetHash": "a0dae3310058004e43a071290b3972ae4e0919e0958be5ec56320ea1a204c5de", "crs": "EPSG:2056", "originE": 2592614.0, "originN": 1118514.0, "centerE": 2594150.0, "centerN": 1120050.0, "baseElevationM": 483.41, - "minY": -5.863, - "maxY": 304.92, - "reliefM": 310.783, + "minY": -5.885, + "maxY": 304.957, + "reliefM": 310.841, "sizeMeters": 3072.0, - "tileGrid": 6, - "tileSizeMeters": 512.0, - "gridRes": 1025, - "cellSizeMeters": 3.0, - "heightmapFormat": "float32_le_row_major", + "tileGrid": 16, + "tileSizeMeters": 192.0, + "buildingTileGrid": 6, + "buildingTileSizeMeters": 512.0, + "gridRes": 6145, + "cellSizeMeters": 0.5, + "heightmapFile": "heightmap_05m.u16z", + "heightmapFormat": "rdhm_v2_u16_zigzag_zlib", + "heightmapMinY": -5.884674072265625, + "heightmapScale": 0.004743136931210756, "surfaceTexture": "terrain_surface.png", - "surfaceTextureSize": 2048, + "surfaceTextureSize": 4096, "surfaceTextureFormat": "png_rgb_north_to_south_west_to_east", + "surfaceMaskTexture": "terrain_surface_mask.png", + "surfaceMaskTextureSize": 2048, + "surfaceMaskFormat": "png_rgba_rock_grass_asphalt_water", "collisionFormat": { "magic": "RCOL", "version": 1, diff --git a/assets/maps/sion/terrain_surface.png b/assets/maps/sion/terrain_surface.png index e240d47..88ec3f2 100644 Binary files a/assets/maps/sion/terrain_surface.png and b/assets/maps/sion/terrain_surface.png differ diff --git a/assets/maps/sion/terrain_surface_mask.png b/assets/maps/sion/terrain_surface_mask.png new file mode 100644 index 0000000..eeac085 Binary files /dev/null and b/assets/maps/sion/terrain_surface_mask.png differ 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 2bee722..4dbce55 100644 --- a/client/ArenaRenderer.cs +++ b/client/ArenaRenderer.cs @@ -24,9 +24,7 @@ public partial class ArenaRenderer : Node3D public required VehicleVisualInstance Visual; public MeshInstance3D? HaloMesh; public StandardMaterial3D? HaloMat; - public MeshInstance3D? LaserMesh; public SpectatorStance? LastHaloStance; - public bool LastLaserVisible; public float RigDtAccum; public int RigSkipFrames; } @@ -70,7 +68,7 @@ public partial class ArenaRenderer : Node3D } private const int MaxVfxBeams = 512; - private const int MaxVfxSpheres = 512; + private const int MaxVfxSpheres = 64; private const int MaxVfxRings = 128; private VehicleAssetCache _assetCache = null!; @@ -80,6 +78,8 @@ public partial class ArenaRenderer : Node3D private PomDecalPool _pomDecals = null!; private DebrisSystem _debris = null!; private ParticlePool _particles = null!; + private readonly VolumetricEmitterPool _volumetrics = new(); + private GpuSparksSystem _gpuSparks = null!; private MeshInstance3D _safeRingMesh = null!; private ImmediateMesh _safeRingImm = null!; @@ -89,8 +89,9 @@ public partial class ArenaRenderer : Node3D private MultiMesh _dropPillarMm = null!; private MultiMeshInstance3D _dropPillarMmi = null!; - // Pooled weapon VFX MultiMeshes (beams/tracers, explosive detonation cores, shockwave rings) + // Pooled weapon VFX MultiMeshes (analytic volumetric capsule beams, optional spheres, shockwave rings) private ShaderMaterial _vfxMat = null!; + private ShaderMaterial _vfxBeamMat = null!; private MultiMesh _vfxBeamMm = null!; private MultiMeshInstance3D _vfxBeamMmi = null!; private MultiMesh _vfxSphereMm = null!; @@ -99,8 +100,9 @@ public partial class ArenaRenderer : Node3D private MultiMeshInstance3D _vfxRingMmi = null!; private readonly List _transientVfx = new(128); private readonly ClientOrdnanceMirror _ordnanceMirror = new(); - private readonly List<(Transform3D Xf, Color Col)> _mirrorSpheres = new(64); + private readonly List<(Transform3D Xf, Color Col)> _mirrorSpheres = new(32); private readonly List<(Transform3D Xf, Color Col)> _mirrorRings = new(128); + private readonly List _mirrorBeams = new(64); private int _activeBeamCount; // Continuous emitter rate limiters (keyed by (IsContender, EntityId)) @@ -120,12 +122,15 @@ 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; public VehicleAssetCache AssetCache => _assetCache; public DebrisSystem Debris => _debris; public ParticlePool Particles => _particles; + public VolumetricEmitterPool Volumetrics => _volumetrics; + public GpuSparksSystem GpuSparks => _gpuSparks; internal MultiMeshPartPool PartPool => _partPool; internal PomDecalPool PomDecals => _pomDecals; internal ClientOrdnanceMirror OrdnanceMirror => _ordnanceMirror; @@ -167,12 +172,15 @@ public partial class ArenaRenderer : Node3D _pomDecals = new PomDecalPool { Name = "PomDecals" }; _debris = new DebrisSystem { Name = "Debris" }; _particles = new ParticlePool { Name = "ParticlePool" }; + _gpuSparks = new GpuSparksSystem { Name = "GpuSparks" }; + _particles.BindTargets(_volumetrics, _gpuSparks); AddChild(_staticGroup); AddChild(_actorsGroup); AddChild(_partPool); AddChild(_pomDecals); AddChild(_debris); AddChild(_particles); + AddChild(_gpuSparks); _coverMat = new StandardMaterial3D { AlbedoColor = CoverRust, Roughness = 0.88f, Metallic = 0.25f }; _bermMat = new StandardMaterial3D { AlbedoColor = BermDark, Roughness = 0.94f, Metallic = 0.1f }; @@ -229,9 +237,14 @@ public partial class ArenaRenderer : Node3D }; _vfxMat = new ShaderMaterial { Shader = vfxShader }; + Shader beamShader = GD.Load("res://volumetric_capsule_beam.gdshader") + ?? throw new InvalidOperationException("Failed to load res://volumetric_capsule_beam.gdshader"); + _vfxBeamMat = new ShaderMaterial { Shader = beamShader }; + _vfxBeamMm = new MultiMesh { TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, + UseColors = true, UseCustomData = true, Mesh = new BoxMesh { Size = Vector3.One }, InstanceCount = MaxVfxBeams, @@ -241,7 +254,7 @@ public partial class ArenaRenderer : Node3D { Name = "VfxBeams", Multimesh = _vfxBeamMm, - MaterialOverride = _vfxMat, + MaterialOverride = _vfxBeamMat, CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 450f, 3200f)), PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, @@ -357,17 +370,19 @@ public partial class ArenaRenderer : Node3D SyncOrbitalPods(session, alpha, hasCam, camPos); _mirrorSpheres.Clear(); _mirrorRings.Clear(); + _mirrorBeams.Clear(); _ordnanceMirror.StepAndSubmit( dt, session, _assetCache, _partPool, _particles, + _volumetrics, state.Terrain, hasCam, camPos, (xf, col) => _mirrorRings.Add((xf, col)), - (xf, col) => _mirrorSpheres.Add((xf, col))); + beam => _mirrorBeams.Add(beam)); _debris.Step(dt, state.Terrain); _debris.SubmitToPool(_partPool); _partPool.EndFrame(); @@ -397,6 +412,7 @@ public partial class ArenaRenderer : Node3D _assetCache, _debris, _particles, + _volumetrics, hasCam, camPos, spec => AddTransient(new TransientVfx @@ -422,8 +438,68 @@ 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) => @@ -513,10 +589,13 @@ public partial class ArenaRenderer : Node3D _pomDecals.ClearAll(); _debris.ClearAll(); _particles.ClearAll(); + _volumetrics.ClearAll(); + _gpuSparks.ClearAll(); _transientVfx.Clear(); _ordnanceMirror.Clear(); _mirrorSpheres.Clear(); _mirrorRings.Clear(); + _mirrorBeams.Clear(); _tireDustNextTime.Clear(); _thermalVentNextTime.Clear(); _damageSmokeNextTime.Clear(); @@ -712,10 +791,6 @@ public partial class ArenaRenderer : Node3D hiddenVis.Visual.SyncDamageAndHeat(s.Grid, _debris, Vector3.Zero); } hiddenVis.Visual.Root.Visible = false; - if (hiddenVis.LaserMesh is not null) - { - hiddenVis.LaserMesh.Visible = false; - } } continue; } @@ -837,42 +912,6 @@ public partial class ArenaRenderer : Node3D vis.HaloMat.EmissionEnergyMultiplier = pulse; } } - - // Lock-on laser beam when Cleared or Provoked - if (vis.LaserMesh is not null) - { - if (s.Stance != SpectatorStance.Neutral && s.HasTargetLos && target is { Alive: true } && - (target.Id == session.LocalContenderId || session.IsContenderVisible(target.Id))) - { - Vector3 start = specPos + new Vector3(0f, s.Grid.Spec.HalfHeight * 0.7f, 0f); - var (targetPos, _, _) = session.GetInterpolatedContenderPose(target.Id, alpha); - Vector3 end = new Vector3(targetPos.X, targetPos.Y + target.Grid.Spec.HalfHeight * 0.3f, targetPos.Z); - float dist = start.DistanceTo(end); - if (dist > 0.5f) - { - if (!vis.LastLaserVisible) - { - vis.LastLaserVisible = true; - vis.LaserMesh.Visible = true; - } - vis.LaserMesh.GlobalPosition = (start + end) * 0.5f; - Vector3 dir = (end - start).Normalized(); - Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.99f ? Vector3.Right : Vector3.Up; - vis.LaserMesh.LookAt(end, up); - vis.LaserMesh.Scale = new Vector3(1f, 1f, dist); - } - else if (vis.LastLaserVisible) - { - vis.LastLaserVisible = false; - vis.LaserMesh.Visible = false; - } - } - else if (vis.LastLaserVisible) - { - vis.LastLaserVisible = false; - vis.LaserMesh.Visible = false; - } - } } } @@ -894,30 +933,11 @@ public partial class ArenaRenderer : Node3D }; instance.Root.AddChild(halo); - var laserMat = new StandardMaterial3D - { - AlbedoColor = new Color(2.2f, 0.24f, 0.20f, 0.85f), - EmissionEnabled = true, - Emission = new Color(1f, 0.12f, 0.1f), - EmissionEnergyMultiplier = 2.2f, - ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded, - Transparency = BaseMaterial3D.TransparencyEnum.Alpha - }; - var laser = new MeshInstance3D - { - Mesh = new BoxMesh { Size = new Vector3(0.08f, 0.08f, 1.0f) }, - MaterialOverride = laserMat, - Visible = false, - CastShadow = GeometryInstance3D.ShadowCastingSetting.Off - }; - _actorsGroup.AddChild(laser); - return new ActorVisual { Visual = instance, HaloMesh = halo, - HaloMat = haloMat, - LaserMesh = laser + HaloMat = haloMat }; } @@ -1261,7 +1281,7 @@ public partial class ArenaRenderer : Node3D lifetime: petalLife); } - // Touchdown retro shockwave ring + brief detonation core + // Touchdown retro shockwave ring (fireball & radial dust handled by VolumetricEmitterPool + GpuSparksSystem) Vector3 upRef = MathF.Abs(normal.Y) > 0.92f ? Vector3.Forward : Vector3.Up; Vector3 right = upRef.Cross(normal).Normalized(); Vector3 fwd = normal.Cross(right).Normalized(); @@ -1279,19 +1299,6 @@ public partial class ArenaRenderer : Node3D Age = 0f, Lifetime = isContender ? 0.42f : 0.30f }); - AddTransient(new TransientVfx - { - Shape = VfxShape.Sphere, - Position = pos + normal * 0.65f, - Velocity = normal * 1.8f, - BaseRotation = Basis.Identity, - StartScale = Vector3.One * (isContender ? 1.2f : 0.7f), - EndScale = Vector3.One * (isContender ? 4.4f : 2.6f), - ColorStart = new Color(3.8f, 2.2f, 0.65f, 0.90f), - ColorEnd = new Color(0.85f, 0.25f, 0.06f, 0.0f), - Age = 0f, - Lifetime = isContender ? 0.28f : 0.20f - }); } } @@ -1304,90 +1311,69 @@ public partial class ArenaRenderer : Node3D var t = tracers[i]; Vector3 start = new(t.StartX, t.StartY, t.StartZ); Vector3 end = new(t.EndX, t.EndY, t.EndZ); - Vector3 delta = end - start; - float dist = delta.Length(); - if (dist < 0.1f) + if (start.DistanceSquaredTo(end) < 0.01f) { continue; } - Vector3 dir = delta / dist; - Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.95f ? Vector3.Right : Vector3.Up; - Basis lookBasis = Basis.LookingAt(dir, up); - Vector3 mid = (start + end) * 0.5f; - switch (t.WeaponClass) { case WeaponVisualClass.KineticLight: { bool isPd = string.Equals(t.WeaponId, "pd_flak", StringComparison.Ordinal); Color col = isPd - ? new Color(2.8f, 1.35f, 0.35f, 0.94f) - : new Color(2.6f, 2.35f, 1.15f, 0.92f); - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(isPd ? 0.09f : 0.06f, isPd ? 0.09f : 0.06f, dist), col); + ? new Color(3.2f, 1.55f, 0.42f, 0.94f) + : new Color(3.0f, 2.55f, 1.25f, 0.92f); + SubmitCapsuleBeam(ref beamIdx, start, end, isPd ? 0.075f : 0.055f, col, coreSharpness: 3.0f, coreRadiusFrac: 0.36f, tailFade: 1.0f); break; } case WeaponVisualClass.Autocannon: - { - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.20f, 0.20f, dist), new Color(2.5f, 0.85f, 0.14f, 0.72f)); - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.08f, 0.08f, dist), new Color(3.6f, 2.7f, 1.3f, 0.98f)); + SubmitCapsuleBeam(ref beamIdx, start, end, 0.14f, new Color(3.4f, 1.35f, 0.28f, 0.96f), coreSharpness: 2.8f, coreRadiusFrac: 0.36f, tailFade: 1.0f); break; - } case WeaponVisualClass.Explosive: { bool isRecoilless = string.Equals(t.WeaponId, "recoilless", StringComparison.Ordinal); - float w = isRecoilless ? 0.22f : 0.12f; - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(w, w, dist), new Color(3.2f, 1.25f, 0.25f, 0.96f)); + SubmitCapsuleBeam(ref beamIdx, start, end, isRecoilless ? 0.17f : 0.10f, new Color(3.6f, 1.45f, 0.32f, 0.96f), coreSharpness: 2.6f, coreRadiusFrac: 0.34f, tailFade: 1.0f); break; } case WeaponVisualClass.ThermalBeam: { bool isLance = string.Equals(t.WeaponId, "gilded_lance", StringComparison.Ordinal); - float outerW = isLance ? 0.34f : 0.20f; - float coreW = isLance ? 0.13f : 0.08f; - Color outerCol = isLance - ? new Color(2.8f, 1.95f, 0.45f, 0.62f) - : new Color(0.45f, 2.35f, 2.95f, 0.65f); - Color coreCol = isLance - ? new Color(1.6f, 3.6f, 3.8f, 0.98f) - : new Color(2.4f, 3.4f, 3.8f, 0.98f); - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(outerW, outerW, dist), outerCol); - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(coreW, coreW, dist), coreCol); + float outerR = isLance ? 0.24f : 0.15f; + Color beamCol = isLance + ? new Color(3.4f, 2.35f, 0.55f, 0.96f) + : new Color(0.55f, 2.80f, 3.60f, 0.96f); + SubmitCapsuleBeam(ref beamIdx, start, end, outerR, beamCol, coreSharpness: 3.2f, coreRadiusFrac: 0.38f, tailFade: 0.0f, pulsePhase: 12f); break; } case WeaponVisualClass.GaussRail: - { - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.30f, 0.30f, dist), new Color(0.25f, 1.85f, 3.4f, 0.68f)); - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.10f, 0.10f, dist), new Color(2.2f, 3.6f, 4.0f, 0.98f)); + SubmitCapsuleBeam(ref beamIdx, start, end, 0.22f, new Color(0.42f, 2.45f, 3.80f, 0.98f), coreSharpness: 3.6f, coreRadiusFrac: 0.34f, tailFade: 0.0f, pulsePhase: 18f); break; - } case WeaponVisualClass.PlasmaPpc: - { - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.36f, 0.36f, dist), new Color(0.18f, 2.25f, 2.65f, 0.65f)); - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.14f, 0.14f, dist), new Color(1.2f, 3.5f, 3.8f, 0.98f)); + SubmitCapsuleBeam(ref beamIdx, start, end, 0.25f, new Color(0.28f, 2.85f, 3.40f, 0.96f), coreSharpness: 2.6f, coreRadiusFrac: 0.40f, tailFade: 0.0f, pulsePhase: 14f); break; - } case WeaponVisualClass.RocketSalvo: - { - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.22f, 0.22f, dist), new Color(3.2f, 1.45f, 0.30f, 0.92f)); + SubmitCapsuleBeam(ref beamIdx, start, end, 0.16f, new Color(3.6f, 1.65f, 0.38f, 0.94f), coreSharpness: 2.6f, coreRadiusFrac: 0.36f, tailFade: 1.0f); break; - } case WeaponVisualClass.SwarmSmart: - { - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.16f, 0.16f, dist), new Color(1.4f, 2.8f, 0.45f, 0.85f)); - EmitBeam(ref beamIdx, lookBasis, mid, new Vector3(0.07f, 0.07f, dist), new Color(2.0f, 0.95f, 3.2f, 0.96f)); + SubmitCapsuleBeam(ref beamIdx, start, end, 0.12f, new Color(1.65f, 3.20f, 0.58f, 0.95f), coreSharpness: 2.8f, coreRadiusFrac: 0.36f, tailFade: 1.0f); break; - } } } + for (int i = 0; i < _mirrorBeams.Count; i++) + { + var b = _mirrorBeams[i]; + SubmitCapsuleBeam(ref beamIdx, b.Start, b.End, b.Radius, b.HdrTint, b.CoreSharpness, b.CoreRadiusFrac, b.TailFade); + } + _activeBeamCount = beamIdx; _vfxBeamMm.VisibleInstanceCount = beamIdx; _vfxBeamMmi.Visible = beamIdx > 0; @@ -1426,7 +1412,6 @@ public partial class ArenaRenderer : Node3D normal = normal.Normalized(); bool isRecoilless = string.Equals(ev.WeaponId, "recoilless", StringComparison.Ordinal); - float detSize = isRecoilless || wClass == WeaponVisualClass.RocketSalvo ? 3.2f : 1.9f; float ringSize = isRecoilless || wClass == WeaponVisualClass.RocketSalvo ? 6.2f : 3.4f; Color coreStart = wClass switch { @@ -1440,19 +1425,6 @@ public partial class ArenaRenderer : Node3D WeaponVisualClass.SwarmSmart => new Color(0.55f, 0.25f, 0.85f, 0f), _ => new Color(0.85f, 0.28f, 0.08f, 0f) }; - AddTransient(new TransientVfx - { - Shape = VfxShape.Sphere, - Position = pos + normal * 0.25f, - Velocity = normal * 1.4f, - BaseRotation = Basis.Identity, - StartScale = Vector3.One * 0.5f, - EndScale = Vector3.One * detSize, - ColorStart = coreStart, - ColorEnd = coreEnd, - Age = 0f, - Lifetime = isRecoilless ? 0.28f : 0.22f - }); Vector3 upRef = MathF.Abs(normal.Y) > 0.92f ? Vector3.Forward : Vector3.Up; Vector3 right = upRef.Cross(normal).Normalized(); @@ -1694,14 +1666,34 @@ public partial class ArenaRenderer : Node3D return fallbackPos + new Vector3(0f, halfHeight * 0.7f, 0f); } - private void EmitBeam(ref int beamIdx, Basis lookBasis, Vector3 mid, Vector3 scale, Color color) + private void SubmitCapsuleBeam( + ref int beamIdx, + Vector3 start, + Vector3 end, + float outerRadius, + Color hdrTint, + float coreSharpness, + float coreRadiusFrac, + float tailFade, + float pulsePhase = 0f) { if (beamIdx >= MaxVfxBeams) { return; } + + Vector3 delta = end - start; + float len = delta.Length(); + Vector3 dir = len > 0.01f ? delta / len : Vector3.Forward; + Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.95f ? Vector3.Right : Vector3.Up; + Basis lookBasis = Basis.LookingAt(dir, up); + Vector3 mid = (start + end) * 0.5f; + float r = MathF.Max(0.01f, outerRadius); + Vector3 scale = new(2f * r, 2f * r, len + 2f * r); + _vfxBeamMm.SetInstanceTransform(beamIdx, new Transform3D(lookBasis * Basis.FromScale(scale), mid)); - _vfxBeamMm.SetInstanceCustomData(beamIdx, color); + _vfxBeamMm.SetInstanceColor(beamIdx, hdrTint); + _vfxBeamMm.SetInstanceCustomData(beamIdx, new Color(coreSharpness, coreRadiusFrac, tailFade, pulsePhase)); beamIdx++; } diff --git a/client/AtmosphereLutBaker.cs b/client/AtmosphereLutBaker.cs index 312f0c7..5d18af7 100644 --- a/client/AtmosphereLutBaker.cs +++ b/client/AtmosphereLutBaker.cs @@ -90,12 +90,12 @@ public static class AtmosphereLutBaker MieScattering: new Vector3(3.2e-6f, 3.2e-6f, 3.2e-6f), MieG: 0.78f, SolarIrradiance: 17.5f, - CalibratedSunEnergy: 1.28f, + CalibratedSunEnergy: 2.85f, FogMaxLengthMeters: 460f, VolumetricFogDensity: 0.0008f, VolumetricFogDetailSpread: 2.4f, VolumetricFogAnisotropy: 0.62f, - VolumetricFogEmissionEnergy: 0.18f, + VolumetricFogEmissionEnergy: 0f, ValleyVolumeSize: new Vector3(3100f, 110f, 3100f), ValleyVolumePosition: new Vector3(0f, 20f, 0f), ValleyVolumeDensity: 0.0038f, @@ -108,7 +108,7 @@ public static class AtmosphereLutBaker DepthFogAerialPerspective: 0.88f, DepthFogSunScatter: 0.45f, ShadowMaxDistance: 320f, - AmbientLightEnergy: 0.48f, + AmbientLightEnergy: 0.0f, SunDiscIntensity: 8.5f, MieAureoleStrength: 0.24f) : new AtmospherePreset( @@ -120,12 +120,12 @@ public static class AtmosphereLutBaker MieScattering: new Vector3(10.5e-6f, 8.8e-6f, 6.6e-6f), MieG: 0.74f, SolarIrradiance: 16.0f, - CalibratedSunEnergy: 1.42f, + CalibratedSunEnergy: 2.55f, FogMaxLengthMeters: 380f, VolumetricFogDensity: 0.0012f, VolumetricFogDetailSpread: 2.2f, VolumetricFogAnisotropy: 0.68f, - VolumetricFogEmissionEnergy: 0.22f, + VolumetricFogEmissionEnergy: 0f, ValleyVolumeSize: new Vector3(1600f, 56f, 1600f), ValleyVolumePosition: new Vector3(0f, 2f, 0f), ValleyVolumeDensity: 0.0052f, @@ -138,7 +138,7 @@ public static class AtmosphereLutBaker DepthFogAerialPerspective: 0.22f, DepthFogSunScatter: 0.65f, ShadowMaxDistance: 280f, - AmbientLightEnergy: 0.55f, + AmbientLightEnergy: 0.0f, SunDiscIntensity: 8.0f, MieAureoleStrength: 0.30f); diff --git a/client/AtmosphereSystem.cs b/client/AtmosphereSystem.cs index 80b953d..17bda3b 100644 --- a/client/AtmosphereSystem.cs +++ b/client/AtmosphereSystem.cs @@ -21,6 +21,11 @@ public partial class AtmosphereSystem : Node private CanvasLayer _filmGrainLayer = null!; private ColorRect _filmGrainRect = null!; private ShaderMaterial _filmGrainMat = null!; + private Texture3Drd? _flowTexRd; + private ImageTexture3D? _dummyFlowTex; + private VolumetricCompositorEffect? _volumetricEffect; + private Compositor? _compositor; + private VolumetricEmitterPool _emitterPool = new(); private bool _initialized; public WorldEnvironment WorldEnvironment => _worldEnv; @@ -29,6 +34,8 @@ public partial class AtmosphereSystem : Node public FogVolume ValleyFogVolume => _valleyFog; public CanvasLayer FilmGrainLayer => _filmGrainLayer; public AtmosphereLutBaker.BakedAtmosphere? CurrentBaked { get; private set; } + public VolumetricCompositorEffect? VolumetricEffect => _volumetricEffect; + public VolumetricEmitterPool EmitterPool => _emitterPool; public override void _Ready() { @@ -58,14 +65,24 @@ public partial class AtmosphereSystem : Node { BackgroundMode = Godot.Environment.BGMode.Sky, Sky = _sky, - AmbientLightSource = Godot.Environment.AmbientSource.Sky, - AmbientLightEnergy = 0.48f, + AmbientLightSource = Godot.Environment.AmbientSource.Disabled, + AmbientLightEnergy = 0.0f, + + // Option 1 (Low-Gamma): SDFGI multi-bounce + occlusion with zero flat ambient + SdfgiEnabled = true, + SdfgiUseOcclusion = true, + SdfgiReadSkyLight = true, + SdfgiBounceFeedback = 0.60f, + SdfgiCascades = 3, + SdfgiMinCellSize = 0.8f, + SdfgiYScale = Godot.Environment.SdfgiyScale.Scale75Percent, + SdfgiEnergy = 0.85f, // AgX tonemapping preserves orange/amber combat hues while rolling off HDR emitters smoothly TonemapMode = Godot.Environment.ToneMapper.Agx, TonemapAgxWhite = 6.0f, - TonemapAgxContrast = 1.22f, - TonemapExposure = 1.0f, + TonemapAgxContrast = 1.50f, + TonemapExposure = 0.84f, // Normalized additive bloom strictly above GlowHdrThreshold=1.0 (zero diffuse screen smear) GlowEnabled = true, @@ -100,7 +117,7 @@ public partial class AtmosphereSystem : Node VolumetricFogEnabled = true, VolumetricFogTemporalReprojectionEnabled = true, VolumetricFogTemporalReprojectionAmount = 0.88f, - VolumetricFogAmbientInject = 0.25f, + VolumetricFogAmbientInject = 0.0f, VolumetricFogSkyAffect = 0.10f, // Tier 2: Far aerial perspective (340/400m .. horizon peaks) @@ -122,6 +139,38 @@ public partial class AtmosphereSystem : Node Name = "WorldEnv", Environment = _env }; + + Vector3 defaultInvExtent = new( + 1f / (VolumetricCompositorEffect.FlowDimX * VolumetricCompositorEffect.FlowVoxelSizeMeters), + 1f / (VolumetricCompositorEffect.FlowDimY * VolumetricCompositorEffect.FlowVoxelSizeMeters), + 1f / (VolumetricCompositorEffect.FlowDimZ * VolumetricCompositorEffect.FlowVoxelSizeMeters)); + RegisterGlobalParamIfMissing("rtd_flow_origin", RenderingServer.GlobalShaderParameterType.Vec3, Vector3.Zero); + RegisterGlobalParamIfMissing("rtd_flow_inv_extent", RenderingServer.GlobalShaderParameterType.Vec3, defaultInvExtent); + + if (RenderingServer.GetRenderingDevice() is not null) + { + RenderingServer.GISetUseHalfResolution(true); + RenderingServer.EnvironmentSetSdfgiRayCount(RenderingServer.EnvironmentSdfgiRayCount.Count4); + RenderingServer.EnvironmentSetSdfgiFramesToConverge(RenderingServer.EnvironmentSdfgiFramesToConverge.In10Frames); + RenderingServer.EnvironmentSetSdfgiFramesToUpdateLight(RenderingServer.EnvironmentSdfgiFramesToUpdateLight.In8Frames); + _flowTexRd = new Texture3Drd(); + RegisterGlobalParamIfMissing("rtd_flow_field", RenderingServer.GlobalShaderParameterType.Sampler3D, _flowTexRd); + _volumetricEffect = new VolumetricCompositorEffect(_flowTexRd, _emitterPool); + _compositor = new Compositor + { + CompositorEffects = new Godot.Collections.Array { _volumetricEffect } + }; + _worldEnv.Compositor = _compositor; + } + else + { + var dummyImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgbah); + dummyImg.SetPixel(0, 0, new Color(0f, 0f, 0f, 0f)); + _dummyFlowTex = new ImageTexture3D(); + _dummyFlowTex.Create(Image.Format.Rgbah, 1, 1, 1, false, new Godot.Collections.Array { dummyImg }); + RegisterGlobalParamIfMissing("rtd_flow_field", RenderingServer.GlobalShaderParameterType.Sampler3D, _dummyFlowTex); + } + AddChild(_worldEnv); _sun = new DirectionalLight3D @@ -161,6 +210,7 @@ public partial class AtmosphereSystem : Node ?? throw new InvalidOperationException("Failed to load res://film_grain.gdshader"); _filmGrainMat = new ShaderMaterial { Shader = grainShader }; _filmGrainMat.SetShaderParameter("grain_strength", 0.018f); + _filmGrainMat.SetShaderParameter("post_gamma", 1.32f); _filmGrainLayer = new CanvasLayer { @@ -214,9 +264,9 @@ public partial class AtmosphereSystem : Node _env.VolumetricFogDensity = preset.VolumetricFogDensity; _env.VolumetricFogDetailSpread = preset.VolumetricFogDetailSpread; _env.VolumetricFogAnisotropy = preset.VolumetricFogAnisotropy; - _env.VolumetricFogEmissionEnergy = preset.VolumetricFogEmissionEnergy; + _env.VolumetricFogEmissionEnergy = 0f; _env.VolumetricFogAlbedo = haze; - _env.VolumetricFogEmission = new Color(haze.R * 0.45f, haze.G * 0.45f, haze.B * 0.45f, 1.0f); + _env.VolumetricFogEmission = Colors.Black; _valleyFog.Size = preset.ValleyVolumeSize; _valleyFog.Position = preset.ValleyVolumePosition; @@ -224,7 +274,7 @@ public partial class AtmosphereSystem : Node _valleyFogMat.HeightFalloff = preset.ValleyVolumeHeightFalloff; _valleyFogMat.EdgeFade = preset.ValleyVolumeEdgeFade; _valleyFogMat.Albedo = haze; - _valleyFogMat.Emission = new Color(haze.R * 0.35f, haze.G * 0.35f, haze.B * 0.35f, 1.0f); + _valleyFogMat.Emission = Colors.Black; _env.FogLightColor = haze; _env.FogDepthBegin = preset.DepthFogBegin; @@ -233,5 +283,106 @@ public partial class AtmosphereSystem : Node _env.FogDensity = preset.DepthFogDensity; _env.FogAerialPerspective = preset.DepthFogAerialPerspective; _env.FogSunScatter = preset.DepthFogSunScatter; + + if (_volumetricEffect is not null) + { + Color ambCol = new( + MathF.Max(0.10f, haze.R * 0.55f), + MathF.Max(0.12f, haze.G * 0.55f), + MathF.Max(0.14f, haze.B * 0.58f)); + _volumetricEffect.SetAtmosphere( + baked.SunDirection, + baked.SunLightEnergy, + baked.SunLightColor, + ambCol, + extinctionScale: mapKind == ArenaMapKind.Sion ? 0.95f : 0.85f); + } + } + + public void BindEmitterPool(VolumetricEmitterPool pool) + { + _emitterPool = pool ?? throw new ArgumentNullException(nameof(pool)); + _volumetricEffect?.SetEmitterPool(pool); + } + + public void ApplyGraphicsSettings(GraphicsSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + EnsureInitialized(); + + _volumetricEffect?.ApplyGraphicsSettings(settings); + + SdfgiSettingsConfig sdfgi = GraphicsSettings.GetSdfgiConfig(settings.SdfgiQuality); + _env.SdfgiEnabled = sdfgi.Enabled; + if (sdfgi.Enabled) + { + _env.SdfgiMinCellSize = sdfgi.MinCellSize; + _env.SdfgiCascades = sdfgi.Cascades; + } + + if (RenderingServer.GetRenderingDevice() is not null) + { + RenderingServer.GISetUseHalfResolution(sdfgi.HalfResolution); + RenderingServer.EnvironmentSetSdfgiRayCount( + sdfgi.RayCount >= 8 + ? RenderingServer.EnvironmentSdfgiRayCount.Count8 + : RenderingServer.EnvironmentSdfgiRayCount.Count4); + } + } + + public override void _ExitTree() + { + if (_worldEnv is not null && GodotObject.IsInstanceValid(_worldEnv)) + { + _worldEnv.Compositor = null; + } + if (_flowTexRd is not null) + { + _flowTexRd.TextureRdRid = new Rid(); + } + if (AreFlowGlobalsRegistered && RenderingServer.Singleton is not null) + { + _dummyFlowTex ??= CreateDummyFlowTexture(); + RenderingServer.GlobalShaderParameterSet("rtd_flow_field", _dummyFlowTex); + } + if (_volumetricEffect is not null) + { + _volumetricEffect.Enabled = false; + if (RenderingServer.GetRenderingDevice() is not null) + { + RenderingServer.CallOnRenderThread(Callable.From(_volumetricEffect.DisposeRdResources)); + RenderingServer.ForceSync(); + } + } + } + + private static ImageTexture3D CreateDummyFlowTexture() + { + var dummyImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgbah); + dummyImg.SetPixel(0, 0, new Color(0f, 0f, 0f, 0f)); + var tex = new ImageTexture3D(); + tex.Create(Image.Format.Rgbah, 1, 1, 1, false, new Godot.Collections.Array { dummyImg }); + return tex; + } + + private static readonly System.Collections.Generic.HashSet RegisteredGlobals = new(); + public static bool AreFlowGlobalsRegistered => + RegisteredGlobals.Contains("rtd_flow_field") && + RegisteredGlobals.Contains("rtd_flow_origin") && + RegisteredGlobals.Contains("rtd_flow_inv_extent"); + + private static void RegisterGlobalParamIfMissing( + StringName name, + RenderingServer.GlobalShaderParameterType type, + Variant defaultValue) + { + string key = name.ToString(); + if (RegisteredGlobals.Contains(key)) + { + RenderingServer.GlobalShaderParameterSet(name, defaultValue); + return; + } + RegisteredGlobals.Add(key); + RenderingServer.GlobalShaderParameterAdd(name, type, defaultValue); } } diff --git a/client/CameraJuiceState.cs b/client/CameraJuiceState.cs index 87accae..2e3ac8a 100644 --- a/client/CameraJuiceState.cs +++ b/client/CameraJuiceState.cs @@ -17,11 +17,15 @@ namespace RustToDust.Client; public sealed class CameraJuiceState { public const float BaseFovDeg = 58.0f; + public const float DropFreefallFovDeg = 82.0f; + public const float DropRetroFovDeg = 76.0f; private const float ZeroEpsilon = 1e-4f; private const float TraumaDecayPerSec = 1.95f; private const float RecoilDecayRate = 14.0f; private const float FootstepDecayRate = 16.0f; private const float FovBlendRate = 6.0f; + private const float DropFovBlendInRate = 5.0f; + private const float DropFovBlendOutRate = 3.8f; private float _time; @@ -236,7 +240,7 @@ public sealed class CameraJuiceState } } - public void Update(float dt, float localSpeedMps, bool isVtol) + public void Update(float dt, float localSpeedMps, bool isVtol, bool isInDropPod = false, OrbitalPodPhase podPhase = OrbitalPodPhase.Freefall) { float stepDt = float.IsFinite(dt) && dt > 0f ? Math.Clamp(dt, 0f, 0.1f) : 0f; if (stepDt > 0f) @@ -258,15 +262,28 @@ public sealed class CameraJuiceState } float speed = float.IsFinite(localSpeedMps) ? MathF.Max(0f, localSpeedMps) : 0f; - float speedStart = isVtol ? 14f : 12f; - float speedFull = isVtol ? 46f : 36f; - float targetFovOffset = speed > speedStart - ? Math.Clamp((speed - speedStart) / (speedFull - speedStart), 0f, 1f) * (isVtol ? 4.8f : 3.4f) - : 0f; + float targetFovOffset; + float blendRate; + if (isInDropPod) + { + targetFovOffset = podPhase == OrbitalPodPhase.RetroBurn + ? (DropRetroFovDeg - BaseFovDeg) + : (DropFreefallFovDeg - BaseFovDeg) + Math.Clamp(speed / 62f, 0f, 2.0f); + blendRate = DropFovBlendInRate; + } + else + { + float speedStart = isVtol ? 14f : 12f; + float speedFull = isVtol ? 46f : 36f; + targetFovOffset = speed > speedStart + ? Math.Clamp((speed - speedStart) / (speedFull - speedStart), 0f, 1f) * (isVtol ? 4.8f : 3.4f) + : 0f; + blendRate = FovOffsetDeg > targetFovOffset + 0.5f ? DropFovBlendOutRate : FovBlendRate; + } if (stepDt > 0f) { - float blend = 1f - MathF.Exp(-FovBlendRate * stepDt); + float blend = 1f - MathF.Exp(-blendRate * stepDt); FovOffsetDeg += (targetFovOffset - FovOffsetDeg) * blend; if (MathF.Abs(FovOffsetDeg) < 0.002f && targetFovOffset == 0f) { diff --git a/client/ClientAssets.cs b/client/ClientAssets.cs new file mode 100644 index 0000000..8898259 --- /dev/null +++ b/client/ClientAssets.cs @@ -0,0 +1,42 @@ +using System; +using System.IO; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +internal static class ClientAssets +{ + private static bool _registered; + + internal static void EnsureAssetsRootRegistered() + { + if (_registered) + { + return; + } + _registered = true; + + if (OS.HasFeature("template")) + { + string exeAssets = Path.Combine(OS.GetExecutablePath().GetBaseDir(), "assets"); + if (Directory.Exists(exeAssets)) + { + AssetPathResolver.RegisterAssetsRoot(exeAssets); + return; + } + } + + string baseAssets = Path.Combine(AppContext.BaseDirectory, "assets"); + if (Directory.Exists(baseAssets)) + { + AssetPathResolver.RegisterAssetsRoot(baseAssets); + } + } + + internal static string LocateAssetsDirectory() + { + EnsureAssetsRootRegistered(); + return AssetPathResolver.LocateAssetsRoot(); + } +} diff --git a/client/ClientOrdnanceMirror.cs b/client/ClientOrdnanceMirror.cs index 57304c9..1330924 100644 --- a/client/ClientOrdnanceMirror.cs +++ b/client/ClientOrdnanceMirror.cs @@ -27,6 +27,15 @@ public sealed class ClientOrdnanceMirror Color ColorEnd, float Lifetime); + public readonly record struct ActiveBeamSpec( + Vector3 Start, + Vector3 End, + float Radius, + Color HdrTint, + float CoreSharpness, + float CoreRadiusFrac, + float TailFade); + private struct MirroredSlot { public bool Active; @@ -39,6 +48,7 @@ public sealed class ClientOrdnanceMirror public Color Color; public float ManufacturerRoleIndex; public Vector3 Pos; + public Vector3 TailPos; public Vector3 Vel; public Vector3 AnchorPos; public int TargetEntityId; @@ -82,6 +92,7 @@ public sealed class ClientOrdnanceMirror VehicleAssetCache cache, DebrisSystem debris, ParticlePool particles, + VolumetricEmitterPool volumetrics, bool hasCam, Vector3 camPos, Action emitTransient) @@ -186,16 +197,10 @@ public sealed class ClientOrdnanceMirror RemoveById(ev.OrdnanceId); float splashR = def is not null && def.SplashRadius > 0.5f ? def.SplashRadius : 4.2f; particles.EmitOrdnanceBurst(pos, col, sparkCount: 6, radiusScale: Math.Clamp(splashR / 4.5f, 0.7f, 1.6f), camPos, hasCam); - emitTransient(new TransientVfxSpec( - IsSphere: true, - Position: pos + Vector3.Up * 0.2f, - Velocity: Vector3.Up * 1.2f, - Rotation: Basis.Identity, - StartScale: Vector3.One * 0.55f, - EndScale: Vector3.One * Math.Clamp(splashR * 0.75f, 1.8f, 4.8f), - ColorStart: new Color(col.R * 3.2f, col.G * 3.2f, col.B * 3.2f, 0.92f), - ColorEnd: new Color(col.R * 0.8f, col.G * 0.3f, col.B * 0.2f, 0f), - Lifetime: 0.26f)); + if (!hasCam || pos.DistanceSquaredTo(camPos) <= 280f * 280f) + { + volumetrics.EmitOrdnanceDetonation(pos, col, splashR); + } emitTransient(new TransientVfxSpec( IsSphere: false, Position: pos + Vector3.Up * 0.16f, @@ -227,11 +232,12 @@ public sealed class ClientOrdnanceMirror VehicleAssetCache cache, MultiMeshPartPool partPool, ParticlePool particles, + VolumetricEmitterPool volumetrics, TerrainField terrain, bool hasCam, Vector3 camPos, Action submitActiveRing, - Action submitActiveSphere) + Action submitActiveBeam) { if (_activeCount == 0) { @@ -273,6 +279,8 @@ public sealed class ClientOrdnanceMirror } AdvanceSlotKinematics(ref s, def, state, terrain, stepDt); + float tailLerp = 1f - MathF.Exp(-stepDt * 18f); + s.TailPos = s.TailPos.Lerp(s.Pos, tailLerp); } if (hasCam && s.Pos.DistanceSquaredTo(camPos) > 340f * 340f) @@ -293,9 +301,6 @@ public sealed class ClientOrdnanceMirror Transform3D ringXf = new(Basis.FromScale(new Vector3(radius * 2f * pulse, 0.35f, radius * 2f * pulse)), poolPos); submitActiveRing(ringXf, new Color(s.Color.R * 2.6f, s.Color.G * 2.6f, s.Color.B * 2.6f, 0.78f)); - Transform3D discXf = new(Basis.FromScale(new Vector3(radius * 1.4f * pulse, 0.14f, radius * 1.4f * pulse)), poolPos - new Vector3(0f, 0.04f, 0f)); - submitActiveSphere(discXf, new Color(s.Color.R * 2.1f, s.Color.G * 2.1f, s.Color.B * 2.1f, 0.42f)); - if (stepDt > 0f) { s.EmberTimer += stepDt; @@ -303,6 +308,10 @@ public sealed class ClientOrdnanceMirror { s.EmberTimer = 0f; particles.EmitThermalPoolEmber(poolPos, radius, s.Color, camPos, hasCam); + if (!hasCam || poolPos.DistanceSquaredTo(camPos) <= 220f * 220f) + { + volumetrics.EmitThermalPoolPlume(poolPos, radius, s.Color); + } } } continue; @@ -349,10 +358,13 @@ public sealed class ClientOrdnanceMirror if (stepDt > 0f) { s.TrailTimer += stepDt; - if (s.TrailTimer >= 0.055f) + if (s.TrailTimer >= 0.075f) { s.TrailTimer = 0f; - particles.EmitOrdnanceTrail(s.Pos, s.Vel, s.Color, isRocket: def?.Motion != OrdnanceMotion.LoiterOrbit, camPos, hasCam); + if (!hasCam || s.Pos.DistanceSquaredTo(camPos) <= 240f * 240f) + { + volumetrics.EmitOrdnanceTrailCapsule(s.TailPos, s.Pos, s.Vel, s.Color, isRocket: def?.Motion != OrdnanceMotion.LoiterOrbit); + } } } continue; @@ -382,19 +394,30 @@ public sealed class ClientOrdnanceMirror def?.Motion is OrdnanceMotion.RocketBoosted or OrdnanceMotion.HomingMissile; partPool.Submit(projMesh, in projXf, new Color(0f, isRocket ? 0.65f : 0.25f, s.ManufacturerRoleIndex, 1f), wantsShadow: false); - if (isRocket) - { - Transform3D thrusterXf = new(Basis.FromScale(Vector3.One * 0.42f), s.Pos - dir * 0.22f); - submitActiveSphere(thrusterXf, new Color(s.Color.R * 3.2f, s.Color.G * 3.2f, s.Color.B * 3.2f, 0.90f)); - } + // Connected [TailPos, Pos] volumetric capsule streak + Vector3 tailStart = s.Pos.DistanceSquaredTo(s.TailPos) > 0.04f ? s.TailPos : s.Pos - dir * 1.4f; + Color beamCol = isRocket + ? new Color(s.Color.R * 3.4f, s.Color.G * 2.4f, s.Color.B * 1.4f, 0.94f) + : new Color(s.Color.R * 3.0f, s.Color.G * 3.0f, s.Color.B * 3.0f, 0.92f); + submitActiveBeam(new ActiveBeamSpec( + Start: tailStart, + End: s.Pos - dir * 0.16f, + Radius: isRocket ? 0.24f : 0.15f, + HdrTint: beamCol, + CoreSharpness: 2.8f, + CoreRadiusFrac: 0.36f, + TailFade: 1.0f)); if (stepDt > 0f) { s.TrailTimer += stepDt; - if (s.TrailTimer >= (isRocket ? 0.035f : 0.055f)) + if (s.TrailTimer >= (isRocket ? 0.055f : 0.075f)) { s.TrailTimer = 0f; - particles.EmitOrdnanceTrail(s.Pos - dir * 0.18f, s.Vel, s.Color, isRocket, camPos, hasCam); + if (!hasCam || s.Pos.DistanceSquaredTo(camPos) <= 240f * 240f) + { + volumetrics.EmitOrdnanceTrailCapsule(s.TailPos, s.Pos - dir * 0.18f, s.Vel, s.Color, isRocket); + } } } } @@ -565,6 +588,7 @@ public sealed class ClientOrdnanceMirror Color = col, ManufacturerRoleIndex = mfgRole, Pos = pos, + TailPos = pos, Vel = vel, AnchorPos = pos, TargetEntityId = ev.TargetEntityId, diff --git a/client/FoliageRenderer.cs b/client/FoliageRenderer.cs new file mode 100644 index 0000000..c66be47 --- /dev/null +++ b/client/FoliageRenderer.cs @@ -0,0 +1,698 @@ +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 = 28f; + public const float Lod1MaxDistanceM = 76f; + public const float Lod2MaxDistanceM = 230f; + public const float ImpostorMaxDistanceM = 1450f; + public const float StumpMaxDistanceM = 230f; + private const float RebuildMoveThresholdSq = 8.0f * 8.0f; + private const float RebuildTurnCosThreshold = 0.866f; // ~30 degrees + private const float FrustumCullMinDistSq = 48.0f * 48.0f; + private const float FrustumRearConeCosSq = 0.35f * 0.35f; // cull rear ~139 deg cone behind camera + + 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; + public BucketState? BucketLod2; + public BucketState? BucketImpostor; + public BucketState? BucketStump; + public BucketState? BucketCharred; + public int CanonicalArchIdx; + } + + 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 Transform3D WorldXformCanon; + 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 Vector2 _lastCamFwdXz = new(0f, 1f); + private bool _lastCamConeActive; + 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); + _lastCamFwdXz = new Vector2(0f, 1f); + _lastCamConeActive = false; + } + + 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; + Vector2 camFwdXz = new(0f, 1f); + bool useCamCone = false; + var cam = GetViewport()?.GetCamera3D(); + if (cam is not null) + { + Vector3 fwd = -cam.GlobalTransform.Basis.Z; + if (MathF.Abs(fwd.Y) <= 0.50f) + { + float lenSq = fwd.X * fwd.X + fwd.Z * fwd.Z; + if (lenSq > 1e-4f) + { + float inv = 1f / MathF.Sqrt(lenSq); + camFwdXz = new Vector2(fwd.X * inv, fwd.Z * inv); + useCamCone = true; + } + } + } + + bool movedFar = !_lastCamPos.IsFinite() || _lastCamPos.DistanceSquaredTo(camPos) >= RebuildMoveThresholdSq; + bool coneToggled = useCamCone != _lastCamConeActive; + bool turnedFar = useCamCone && (_lastCamFwdXz.X * camFwdXz.X + _lastCamFwdXz.Y * camFwdXz.Y) < RebuildTurnCosThreshold; + if (!movedFar && !coneToggled && !turnedFar && curVer == _lastRenderVersion) + { + return; + } + + _lastCamPos = camPos; + _lastCamConeActive = useCamCone; + if (useCamCone) + { + _lastCamFwdXz = camFwdXz; + } + _lastRenderVersion = curVer; + RebuildBuckets(destruction, camPos, useCamCone ? camFwdXz : null); + } + + 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, visibilityEndM: Lod0MaxDistanceM + 8f); + if (variant == 0) + { + arch.BucketLod1 = CreateBucket($"{slug}_LOD1", arch.Lod1, castShadows: true, visibilityEndM: Lod1MaxDistanceM + 10f); + arch.BucketLod2 = CreateBucket($"{slug}_LOD2", arch.Lod2, castShadows: false, visibilityEndM: Lod2MaxDistanceM + 12f); + arch.BucketImpostor = CreateBucket($"{slug}_Impostor", arch.ImpostorQuad, castShadows: false, visibilityEndM: ImpostorMaxDistanceM + 20f); + arch.BucketStump = CreateBucket($"{slug}_Stump", arch.SnappedStump, castShadows: false, visibilityEndM: StumpMaxDistanceM + 10f); + arch.BucketCharred = CreateBucket($"{slug}_Charred", arch.CharredSkeleton, castShadows: true, visibilityEndM: Lod2MaxDistanceM + 12f); + } + + int idx = _archetypes.Count; + _archetypes.Add(arch); + if ((uint)speciesId < 10 && (uint)variant < 2) + { + _archetypeLookup[speciesId, variant] = idx; + } + } + + for (int a = 0; a < _archetypes.Count; a++) + { + var arch = _archetypes[a]; + int canon = _archetypeLookup[Math.Clamp(arch.SpeciesId, 0, 9), 0]; + arch.CanonicalArchIdx = canon >= 0 ? canon : a; + } + + _assetsLoaded = _archetypes.Count > 0; + } + + private BucketState CreateBucket(string name, Mesh mesh, bool castShadows, float visibilityEndM) + { + 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, + VisibilityRangeEnd = visibilityEndM, + VisibilityRangeFadeMode = GeometryInstance3D.VisibilityRangeFadeModeEnum.Disabled, + 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]; + var canonArch = _archetypes[arch.CanonicalArchIdx]; + Basis yawBasis = Basis.FromEuler(new Vector3(0f, t.Yaw, 0f)); + float scaleY = Math.Clamp(t.HeightM / arch.CanonicalHeightM, 0.35f, 2.2f); + float canonScaleY = Math.Clamp(t.HeightM / canonArch.CanonicalHeightM, 0.35f, 2.2f); + Basis rot = yawBasis.Scaled(new Vector3(scaleY, scaleY, scaleY)); + Basis canonRot = ReferenceEquals(arch, canonArch) + ? rot + : yawBasis.Scaled(new Vector3(canonScaleY, canonScaleY, canonScaleY)); + 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), + WorldXformCanon = new Transform3D(canonRot, pos), + Position = pos, + CustomDataBase = new Color(0f, phase, t.HeightM, 1f) + }; + } + + Invalidate(); + } + + private void RebuildBuckets(SionTreeDestructionState? destruction, Vector3 camPos, Vector2? camFwdXz) + { + 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; + bool cullCone = camFwdXz.HasValue; + Vector2 fwd = camFwdXz ?? default; + + 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; + } + if (cullCone && dSq > FrustumCullMinDistSq) + { + float dot = dx * fwd.X + dz * fwd.Y; + if (dot < 0f && dot * dot > FrustumRearConeCosSq * dSq) + { + continue; + } + } + + SionTreeState st = destruction is not null + ? destruction.GetState((ushort)i) + : SionTreeState.Intact; + + var arch = _archetypes[pt.ArchetypeIdx]; + var canonArch = _archetypes[arch.CanonicalArchIdx]; + if (st == SionTreeState.Snapped) + { + if (dSq <= stumpSq && canonArch.BucketStump is not null) + { + canonArch.BucketStump.Indices.Add(i); + } + } + else if (st == SionTreeState.Charred) + { + if (dSq <= lod2Sq && canonArch.BucketCharred is not null) + { + canonArch.BucketCharred.Indices.Add(i); + } + else if (canonArch.BucketImpostor is not null) + { + canonArch.BucketImpostor.Indices.Add(i); + } + } + else + { + if (dSq <= lod0Sq) + { + arch.BucketLod0.Indices.Add(i); + } + else if (dSq <= lod1Sq && canonArch.BucketLod1 is not null) + { + canonArch.BucketLod1.Indices.Add(i); + } + else if (dSq <= lod2Sq && canonArch.BucketLod2 is not null) + { + canonArch.BucketLod2.Indices.Add(i); + } + else if (canonArch.BucketImpostor is not null) + { + canonArch.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, useCanonXform: false); + if (arch.BucketLod1 is not null) c1 += CommitBucket(arch.BucketLod1, destruction, forceCharred: false, useCanonXform: true); + if (arch.BucketLod2 is not null) c2 += CommitBucket(arch.BucketLod2, destruction, forceCharred: false, useCanonXform: true); + if (arch.BucketImpostor is not null) cImp += CommitBucket(arch.BucketImpostor, destruction, forceCharred: false, useCanonXform: true); + if (arch.BucketStump is not null) cStump += CommitBucket(arch.BucketStump, destruction, forceCharred: false, useCanonXform: true); + if (arch.BucketCharred is not null) cChar += CommitBucket(arch.BucketCharred, destruction, forceCharred: true, useCanonXform: true); + } + + VisibleLod0Count = c0; + VisibleLod1Count = c1; + VisibleLod2Count = c2; + VisibleImpostorCount = cImp; + VisibleStumpCount = cStump; + VisibleCharredCount = cChar; + } + + private int CommitBucket(BucketState bucket, SionTreeDestructionState? destruction, bool forceCharred, bool useCanonXform) + { + 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; + + float minX = float.PositiveInfinity, minY = float.PositiveInfinity, minZ = float.PositiveInfinity; + float maxX = float.NegativeInfinity, maxY = float.NegativeInfinity, maxZ = float.NegativeInfinity; + + for (int k = 0; k < count; k++) + { + int treeIdx = bucket.Indices[k]; + ref readonly var pt = ref _precomputed[treeIdx]; + bucket.MultiMesh.SetInstanceTransform(k, useCanonXform ? pt.WorldXformCanon : pt.WorldXform); + + Vector3 p = pt.Position; + if (p.X < minX) minX = p.X; + if (p.Y < minY) minY = p.Y; + if (p.Z < minZ) minZ = p.Z; + if (p.X > maxX) maxX = p.X; + if (p.Y > maxY) maxY = p.Y; + if (p.Z > maxZ) maxZ = p.Z; + + 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); + } + + var tightAabb = new Aabb( + new Vector3(minX - 14f, minY - 2f, minZ - 14f), + new Vector3((maxX - minX) + 28f, (maxY - minY) + 42f, (maxZ - minZ) + 28f)); + bucket.MultiMesh.CustomAabb = tightAabb; + bucket.Instance.CustomAabb = tightAabb; + + 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/GpuSparksSystem.cs b/client/GpuSparksSystem.cs new file mode 100644 index 0000000..10cea16 --- /dev/null +++ b/client/GpuSparksSystem.cs @@ -0,0 +1,214 @@ +using System; +using Godot; + +namespace RustToDust.Client; + +/// +/// Flow-coupled GPU particle system (, 65,536 capacity) driven by +/// the global rtd_flow_field + Tri3D curl streams for +/// stochastic opaque HDR sparks, buoyant embers, flow-entrained dust motes, and muzzle starbursts. +/// +public partial class GpuSparksSystem : Node3D +{ + public const int Capacity = 65536; + + public const int TypeVelocitySpark = 0; + public const int TypeBuoyantEmber = 1; + public const int TypeDustMote = 2; + public const int TypeMuzzleStarburst = 3; + + private const uint EmitFlagsAll = (uint)( + GpuParticles3D.EmitFlags.Position | + GpuParticles3D.EmitFlags.Velocity | + GpuParticles3D.EmitFlags.Color | + GpuParticles3D.EmitFlags.Custom); + + private GpuParticles3D _particles = null!; + private ShaderMaterial _processMat = null!; + private ShaderMaterial _drawMat = null!; + private bool _initialized; + private uint _rng = 0x9E3779B9u; + + public int TotalEmittedCount { get; private set; } + public GpuParticles3D ParticlesNode => _particles; + + public override void _Ready() + { + EnsureInitialized(); + } + + public void EnsureInitialized() + { + if (_initialized) + { + return; + } + _initialized = true; + + Shader processShader = GD.Load("res://gpu_sparks_process.gdshader") + ?? throw new InvalidOperationException("Failed to load res://gpu_sparks_process.gdshader"); + Shader drawShader = GD.Load("res://gpu_sparks_draw.gdshader") + ?? throw new InvalidOperationException("Failed to load res://gpu_sparks_draw.gdshader"); + + _processMat = new ShaderMaterial { Shader = processShader }; + _drawMat = new ShaderMaterial { Shader = drawShader }; + + var quad = new QuadMesh + { + Size = Vector2.One, + Material = _drawMat + }; + + _particles = new GpuParticles3D + { + Name = "GpuSparks3D", + Amount = Capacity, + LocalCoords = false, + Emitting = true, + AmountRatio = 0.0f, // Keep GPU process active with zero automatic spawns + Lifetime = 2.5f, + FixedFps = 0, + Explosiveness = 0.0f, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, + VisibilityAabb = new Aabb(new Vector3(-1800f, -200f, -1800f), new Vector3(3600f, 2200f, 3600f)), + PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, + ProcessMaterial = _processMat, + DrawPass1 = quad + }; + AddChild(_particles); + } + + public void ClearAll() + { + EnsureInitialized(); + TotalEmittedCount = 0; + _particles.Restart(); + _particles.Emitting = true; + _particles.AmountRatio = 0.0f; + } + + public void Prewarm(Vector3 nearPos) + { + EnsureInitialized(); + EmitRaw(nearPos + new Vector3(0f, -20f, 0f), Vector3.Up * 0.1f, new Color(1f, 1f, 1f, 0.01f), 0.02f, 0.05f, TypeVelocitySpark, 1.0f); + TotalEmittedCount = 0; + } + + public void EmitMuzzleStarburst(Vector3 pos, Color hdrColor, float sizeM, float lifetimeSec) + { + EnsureInitialized(); + EmitRaw(pos, Vector3.Zero, hdrColor, Math.Clamp(sizeM, 0.25f, 0.90f), Math.Clamp(lifetimeSec, 0.05f, 0.14f), TypeMuzzleStarburst, 0f); + } + + public void EmitSparkBurst(Vector3 pos, Vector3 normal, int count, Color hdrColor, float speed, float widthM = 0.026f) + { + EnsureInitialized(); + Vector3 n = normal.LengthSquared() > 1e-4f ? normal.Normalized() : Vector3.Up; + for (int i = 0; i < count; i++) + { + Vector3 rand = new(NextSigned(), MathF.Abs(NextSigned()) + 0.28f, NextSigned()); + Vector3 dir = (n * 0.65f + rand).Normalized(); + float spd = speed * (0.55f + 0.85f * NextFloat()); + float life = 0.24f + 0.34f * NextFloat(); + Vector3 spawnPos = pos + new Vector3(NextSigned() * 0.14f, NextFloat() * 0.12f, NextSigned() * 0.14f); + EmitRaw(spawnPos, dir * spd, hdrColor, widthM, life, TypeVelocitySpark, 0.85f); + } + } + + public void EmitEmberBurst(Vector3 pos, int count, Color hdrColor, float spreadSpeed, float widthM = 0.030f) + { + EnsureInitialized(); + for (int i = 0; i < count; i++) + { + Vector3 vel = new(NextSigned() * spreadSpeed, 2.5f + NextFloat() * 5.5f, NextSigned() * spreadSpeed); + float life = 0.90f + NextFloat() * 1.25f; + EmitRaw(pos + new Vector3(NextSigned() * 0.7f, NextFloat() * 0.6f, NextSigned() * 0.7f), vel, hdrColor, widthM, life, TypeBuoyantEmber, 1.5f); + } + } + + public void EmitDustMotes(Vector3 pos, Vector3 normal, int count, Color dustColor, float speed, float widthM = 0.065f) + { + EnsureInitialized(); + Vector3 n = normal.LengthSquared() > 1e-4f ? normal.Normalized() : Vector3.Up; + for (int i = 0; i < count; i++) + { + float ang = NextFloat() * MathF.Tau; + float spd = speed * (0.55f + 0.70f * NextFloat()); + Vector3 vel = new Vector3(MathF.Cos(ang) * spd, 0.8f + NextFloat() * 1.4f, MathF.Sin(ang) * spd) + n * (0.4f * spd); + float life = 0.45f + NextFloat() * 0.45f; + EmitRaw(pos + new Vector3(NextSigned() * 0.35f, 0.08f, NextSigned() * 0.35f), vel, dustColor, widthM, life, TypeDustMote, 3.6f); + } + } + + public void EmitThermalPoolEmber(Vector3 pos, float radius, Color accentCol) + { + EnsureInitialized(); + float ang = NextFloat() * MathF.Tau; + float r = MathF.Sqrt(NextFloat()) * MathF.Max(0.5f, radius * 0.85f); + Vector3 p = pos + new Vector3(MathF.Cos(ang) * r, 0.18f, MathF.Sin(ang) * r); + Vector3 vel = new(NextSigned() * 0.7f, 2.0f + NextFloat() * 1.8f, NextSigned() * 0.7f); + Color hdr = new(accentCol.R * 3.8f, accentCol.G * 3.8f, accentCol.B * 3.8f, 0.95f); + EmitRaw(p, vel, hdr, 0.055f, 0.65f + NextFloat() * 0.45f, TypeBuoyantEmber, 1.4f); + } + + public void EmitPodRetroSparksAndDust(Vector3 podBasePos, float agl, Color groundTint, bool isContender) + { + EnsureInitialized(); + float scale = isContender ? 1.2f : 0.85f; + Color sparkHdr = new(4.8f, 2.6f, 0.65f, 0.98f); + int sparkCount = isContender ? 14 : 8; + for (int i = 0; i < sparkCount; i++) + { + Vector3 vel = new(NextSigned() * 7.5f, -(11f + NextFloat() * 7f), NextSigned() * 7.5f); + EmitRaw(podBasePos + new Vector3(NextSigned() * 0.7f, 0.1f, NextSigned() * 0.7f), vel, sparkHdr, 0.028f * scale, 0.24f + NextFloat() * 0.16f, TypeVelocitySpark, 1.2f); + } + + if (agl < 60f) + { + float washT = Math.Clamp(1f - agl / 60f, 0.2f, 1f); + Vector3 groundPos = podBasePos - new Vector3(0f, MathF.Max(0f, agl), 0f) + new Vector3(0f, 0.22f, 0f); + Color dustCol = new(groundTint.R * 1.1f, groundTint.G * 1.1f, groundTint.B * 1.1f, 0.78f * washT); + int moteCount = isContender ? 24 : 14; + for (int d = 0; d < moteCount; d++) + { + float ang = NextFloat() * MathF.Tau; + float spd = (7.5f + NextFloat() * 8.5f) * washT * scale; + Vector3 vel = new(MathF.Cos(ang) * spd, 1.0f + NextFloat() * 1.6f, MathF.Sin(ang) * spd); + EmitRaw(groundPos + new Vector3(MathF.Cos(ang) * 0.9f, 0f, MathF.Sin(ang) * 0.9f), vel, dustCol, 0.055f * scale, 0.55f + NextFloat() * 0.30f, TypeDustMote, 3.4f); + } + } + } + + public void EmitPodTouchdownSparksAndDust(Vector3 pos, Vector3 normal, Color groundTint, bool isContender) + { + EnsureInitialized(); + float scale = isContender ? 1.3f : 0.95f; + EmitSparkBurst(pos + normal * 0.45f, normal, isContender ? 160 : 90, new Color(5.2f, 2.8f, 0.70f, 0.98f), 19f * scale, 0.028f); + EmitEmberBurst(pos + normal * 0.45f, isContender ? 85 : 48, new Color(4.0f, 1.6f, 0.35f, 0.95f), 7.5f * scale, 0.032f); + EmitDustMotes(pos + normal * 0.25f, normal, isContender ? 75 : 45, groundTint with { A = 0.82f }, 10f * scale, 0.058f); + } + + private void EmitRaw(Vector3 pos, Vector3 vel, Color hdrColor, float widthM, float lifetimeSec, int type, float drag) + { + float packedTypeAndDrag = type + Math.Clamp(drag, 0f, 19.9f) * 0.05f; + _particles.EmitParticle( + new Transform3D(Basis.Identity, pos), + vel, + hdrColor, + new Color(widthM, 0f, lifetimeSec, packedTypeAndDrag), + EmitFlagsAll); + TotalEmittedCount++; + } + + private float NextFloat() + { + uint x = _rng; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + _rng = x; + return (x & 0x00FFFFFFu) / 16777216f; + } + + private float NextSigned() => NextFloat() * 2f - 1f; +} diff --git a/client/GraphicsSettings.cs b/client/GraphicsSettings.cs new file mode 100644 index 0000000..e8e4e60 --- /dev/null +++ b/client/GraphicsSettings.cs @@ -0,0 +1,270 @@ +using System; +using System.IO; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RustToDust.Client; + +public enum VfxResolutionScale +{ + Half = 0, + ThreeQuarter = 1, + Full = 2 +} + +public enum VolumetricSamples +{ + Low = 0, + Medium = 1, + High = 2, + Ultra = 3 +} + +public enum SdfgiQuality +{ + Off = 0, + Balanced = 1, + High = 2 +} + +public readonly record struct SdfgiSettingsConfig( + bool Enabled, + float MinCellSize, + int Cascades, + bool HalfResolution, + int RayCount); + +public sealed record GraphicsSettingsData +{ + [JsonPropertyName("vfxResolutionScale")] + public VfxResolutionScale VfxResolution { get; init; } = VfxResolutionScale.Half; + + [JsonPropertyName("volumetricSamples")] + public VolumetricSamples VolumetricSamples { get; init; } = VolumetricSamples.Medium; + + [JsonPropertyName("sdfgiQuality")] + public SdfgiQuality SdfgiQuality { get; init; } = SdfgiQuality.Balanced; + + [JsonPropertyName("borderlessFullscreen")] + public bool BorderlessFullscreen { get; init; } = true; +} + +/// +/// Single persisted authority for live graphics and display settings (user://graphics_settings.json). +/// Pure .NET so unit tests and headless runs share the exact same schema, defaults, and event flow. +/// +public sealed class GraphicsSettings +{ + public const string DefaultFileName = "graphics_settings.json"; + + private static readonly JsonSerializerOptions JsonOptions = new() + { + WriteIndented = true, + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter() } + }; + + private readonly string? _storagePath; + + public GraphicsSettings(string? storagePath = null) + { + _storagePath = string.IsNullOrWhiteSpace(storagePath) ? null : storagePath; + ResetFieldsToDefaults(); + } + + public VfxResolutionScale VfxResolution { get; private set; } + public VolumetricSamples VolumetricSamples { get; private set; } + public SdfgiQuality SdfgiQuality { get; private set; } + public bool BorderlessFullscreen { get; private set; } + + public string? StoragePath => _storagePath; + + public event Action? Changed; + + public GraphicsSettingsData ToData() => new() + { + VfxResolution = VfxResolution, + VolumetricSamples = VolumetricSamples, + SdfgiQuality = SdfgiQuality, + BorderlessFullscreen = BorderlessFullscreen + }; + + public static GraphicsSettings Load(string? storagePath) + { + var settings = new GraphicsSettings(storagePath); + if (string.IsNullOrWhiteSpace(storagePath)) + { + return settings; + } + + try + { + if (File.Exists(storagePath)) + { + string json = File.ReadAllText(storagePath); + settings.LoadFromJson(json); + } + } + catch + { + settings.ResetFieldsToDefaults(); + } + return settings; + } + + public bool LoadFromJson(string? json) + { + if (string.IsNullOrWhiteSpace(json)) + { + ResetFieldsToDefaults(); + return false; + } + + try + { + var parsed = JsonSerializer.Deserialize(json, JsonOptions); + if (parsed is null) + { + ResetFieldsToDefaults(); + return false; + } + + VfxResolution = Enum.IsDefined(parsed.VfxResolution) + ? parsed.VfxResolution + : VfxResolutionScale.Half; + VolumetricSamples = Enum.IsDefined(parsed.VolumetricSamples) + ? parsed.VolumetricSamples + : VolumetricSamples.Medium; + SdfgiQuality = Enum.IsDefined(parsed.SdfgiQuality) + ? parsed.SdfgiQuality + : SdfgiQuality.Balanced; + BorderlessFullscreen = parsed.BorderlessFullscreen; + return true; + } + catch + { + ResetFieldsToDefaults(); + return false; + } + } + + public string ToJson() => JsonSerializer.Serialize(ToData(), JsonOptions); + + public bool Save() + { + if (string.IsNullOrWhiteSpace(_storagePath)) + { + return false; + } + + try + { + string? dir = Path.GetDirectoryName(_storagePath); + if (!string.IsNullOrEmpty(dir)) + { + Directory.CreateDirectory(dir); + } + string json = ToJson(); + string tempPath = _storagePath + ".tmp"; + File.WriteAllText(tempPath, json); + File.Move(tempPath, _storagePath, overwrite: true); + return true; + } + catch + { + return false; + } + } + + public void Apply( + VfxResolutionScale vfxResolution, + VolumetricSamples volumetricSamples, + SdfgiQuality sdfgiQuality, + bool borderlessFullscreen, + bool persist = true, + bool forcePersist = false) + { + VfxResolutionScale safeRes = Enum.IsDefined(vfxResolution) ? vfxResolution : VfxResolutionScale.Half; + VolumetricSamples safeSamples = Enum.IsDefined(volumetricSamples) ? volumetricSamples : VolumetricSamples.Medium; + SdfgiQuality safeSdfgi = Enum.IsDefined(sdfgiQuality) ? sdfgiQuality : SdfgiQuality.Balanced; + + bool changed = VfxResolution != safeRes + || VolumetricSamples != safeSamples + || SdfgiQuality != safeSdfgi + || BorderlessFullscreen != borderlessFullscreen; + + if (!changed) + { + if (persist && forcePersist) + { + Save(); + } + return; + } + + VfxResolution = safeRes; + VolumetricSamples = safeSamples; + SdfgiQuality = safeSdfgi; + BorderlessFullscreen = borderlessFullscreen; + + if (persist) + { + Save(); + } + Changed?.Invoke(this); + } + + public void SetVfxResolution(VfxResolutionScale value, bool persist = true) => + Apply(value, VolumetricSamples, SdfgiQuality, BorderlessFullscreen, persist); + + public void SetVolumetricSamples(VolumetricSamples value, bool persist = true) => + Apply(VfxResolution, value, SdfgiQuality, BorderlessFullscreen, persist); + + public void SetSdfgiQuality(SdfgiQuality value, bool persist = true) => + Apply(VfxResolution, VolumetricSamples, value, BorderlessFullscreen, persist); + + public void SetBorderlessFullscreen(bool value, bool persist = true) => + Apply(VfxResolution, VolumetricSamples, SdfgiQuality, value, persist); + + public void ResetToDefaults(bool persist = true) => + Apply( + VfxResolutionScale.Half, + VolumetricSamples.Medium, + SdfgiQuality.Balanced, + borderlessFullscreen: true, + persist: persist, + forcePersist: persist); + + public static float GetResolutionScaleFactor(VfxResolutionScale scale) => scale switch + { + VfxResolutionScale.Half => 0.50f, + VfxResolutionScale.ThreeQuarter => 0.75f, + VfxResolutionScale.Full => 1.00f, + _ => 0.50f + }; + + public static (int MaxSteps, int MaxIter) GetVolumetricStepBudget(VolumetricSamples samples) => samples switch + { + VolumetricSamples.Low => (8, 12), + VolumetricSamples.Medium => (10, 15), + VolumetricSamples.High => (16, 24), + VolumetricSamples.Ultra => (24, 36), + _ => (10, 15) + }; + + public static SdfgiSettingsConfig GetSdfgiConfig(SdfgiQuality quality) => quality switch + { + SdfgiQuality.Off => new SdfgiSettingsConfig(false, 0.8f, 3, true, 4), + SdfgiQuality.Balanced => new SdfgiSettingsConfig(true, 0.8f, 3, true, 4), + SdfgiQuality.High => new SdfgiSettingsConfig(true, 0.4f, 4, false, 8), + _ => new SdfgiSettingsConfig(true, 0.8f, 3, true, 4) + }; + + private void ResetFieldsToDefaults() + { + VfxResolution = VfxResolutionScale.Half; + VolumetricSamples = VolumetricSamples.Medium; + SdfgiQuality = SdfgiQuality.Balanced; + BorderlessFullscreen = true; + } +} diff --git a/client/HbGpuCanvas.cs b/client/HbGpuCanvas.cs new file mode 100644 index 0000000..a647c75 --- /dev/null +++ b/client/HbGpuCanvas.cs @@ -0,0 +1,1099 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using Godot; +using RustToDust.HbGpu; + +namespace RustToDust.Client; + +/// +/// Single-draw-call HarfBuzz 15.2.0 hb-gpu GLSL renderer on Godot 4.7 Forward+ Vulkan RenderingDevice. +/// Safe in --headless / null-RD mode: preserves CPU shaping/layout without allocating RD resources. +/// +public partial class HbGpuCanvas : Control +{ + public const byte DefaultFontId = 0; + private const int PushConstantBytes = 80; // mat4 (64) + vec2 viewport (8) + vec2 logicalSize (8) + private const int AtlasTexWidth = 1024; + private const int AtlasTexHeight = 256; // 1024 * 256 = 262,144 == HbGpuAtlasAllocator.TotalTexels + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + private struct PushConstants + { + // Column-major mat4 for GLSL: col 0, col 1, col 2, col 3 + public float C0R0, C0R1, C0R2, C0R3; + public float C1R0, C1R1, C1R2, C1R3; + public float C2R0, C2R1, C2R2, C2R3; + public float C3R0, C3R1, C3R2, C3R3; + public float ViewportX, ViewportY; + public float LogicalW, LogicalH; + } + + private readonly HbGpuFontCache _fontCache = new(); + private readonly HbGpuAtlasAllocator _atlas = new(); + private readonly HbGpuBlobCache _blobCache; + private readonly HbGpuCommandWriter _writer = new(); + + private readonly object _syncLock = new(); + private readonly HbGpuQuadInstance[] _stagedQuads = new HbGpuQuadInstance[HbGpuCommandWriter.MaxQuads]; + private readonly byte[] _stagedAtlasMirror = new byte[HbGpuAtlasAllocator.TotalBytes]; + private bool _stagedAtlasDirty; + private int _stagedQuadCount; + private float _stagedLogicalW = 1280f; + private float _stagedLogicalH = 720f; + private int _stagedPhysW = 1280; + private int _stagedPhysH = 720; + private bool _hasStagedFrame; + + private TextureRect? _outputRect; + private Texture2Drd? _outputTexRd; + private HbGpuVulkanBackend? _backend; + private Callable _renderCallable; + private Callable _disposeCallable; + private bool _disposed; + + public bool ProfilingEnabled { get; set; } + public double LastHbGpuMs => _backend?.LastHbGpuMs ?? 0.0; + public int LastDrawCallCount => _backend?.LastDrawCallCount ?? 0; + public int LastQuadCount { get; private set; } + public bool IsVulkanActive => RenderingServer.GetRenderingDevice() is not null; + + public HbGpuFontCache Fonts => _fontCache; + public HbGpuBlobCache Blobs => _blobCache; + public HbGpuCommandWriter Writer => _writer; + + public HbGpuCanvas() + { + _blobCache = new HbGpuBlobCache(_atlas); + MouseFilter = MouseFilterEnum.Ignore; + } + + public override void _Ready() + { + SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect); + MouseFilter = MouseFilterEnum.Ignore; + + LoadDefaultKryptonFont(); + + if (RenderingServer.GetRenderingDevice() is not null) + { + _outputTexRd = new Texture2Drd(); + _outputRect = new TextureRect + { + Name = "HbGpuOutput", + MouseFilter = MouseFilterEnum.Ignore, + ExpandMode = TextureRect.ExpandModeEnum.IgnoreSize, + StretchMode = TextureRect.StretchModeEnum.Scale, + Texture = _outputTexRd, + Material = new CanvasItemMaterial + { + BlendMode = CanvasItemMaterial.BlendModeEnum.PremultAlpha + } + }; + AddChild(_outputRect); + _outputRect.SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect); + + _backend = new HbGpuVulkanBackend(_outputTexRd); + _renderCallable = Callable.From(RenderOnRenderThread); + _disposeCallable = Callable.From(DisposeOnRenderThread); + } + } + + private void LoadDefaultKryptonFont() + { + if (_fontCache.TryGetMetrics(DefaultFontId, out _)) + { + return; + } + + string path = ResolveKryptonPath(); + _fontCache.RegisterFontFromFile(DefaultFontId, path); + } + + public static string ResolveKryptonPath() + { + ClientAssets.EnsureAssetsRootRegistered(); + string[] candidates = + { + Path.Combine(ClientAssets.LocateAssetsDirectory(), "fonts", "Krypton.ttf"), + Path.GetFullPath(Path.Combine(ProjectSettings.GlobalizePath("res://"), "..", "assets", "fonts", "Krypton.ttf")), + Path.Combine(AppContext.BaseDirectory, "assets", "fonts", "Krypton.ttf") + }; + + foreach (string c in candidates) + { + if (File.Exists(c)) + { + return c; + } + } + + throw new FileNotFoundException("Could not locate assets/fonts/Krypton.ttf."); + } + + public void BeginFrame() + { + _blobCache.EnsureBudgetOrReset(); + _writer.BeginFrame(); + } + + public float DrawText( + ReadOnlySpan text, + float x, + float baselineY, + float fontSizePx, + Color color, + float wght = 200f, + float wdth = 100f, + float slnt = 0f, + HbGpuFeatureFlags features = HbGpuFeatureFlags.Default, + bool stemDarken = true, + uint clipMinPacked = 0, + uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + return _writer.DrawTextUtf16( + text, x, baselineY, fontSizePx, + color.R, color.G, color.B, color.A, + _fontCache, _blobCache, + DefaultFontId, wght, wdth, slnt, + features, stemDarken, clipMinPacked, clipMaxPacked); + } + + public float MeasureTextWidth( + ReadOnlySpan text, + float fontSizePx, + float wght = 200f, + float wdth = 100f, + float slnt = 0f, + HbGpuFeatureFlags features = HbGpuFeatureFlags.Default) + { + return _writer.MeasureTextWidth(text, fontSizePx, _fontCache, DefaultFontId, wght, wdth, slnt, features); + } + + public void DrawRectFilled(float x, float y, float w, float h, Color color, + uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + CachedBlob blob = HbGpuVectorShapes.GetUnitFilledRect(_blobCache); + float cx = x + w * 0.5f; + float cy = y + h * 0.5f; + _writer.DrawBlob( + blob, cx, cy, + w * 0.001f, 0f, 0f, -h * 0.001f, + 0f, 0f, + color.R, color.G, color.B, color.A, + stemDarken: false, clipMinPacked, clipMaxPacked, + extraFlags: HbGpuQuadInstance.FlagSolidRect); + } + + public void DrawLineSegment(float x0, float y0, float x1, float y1, float thicknessPx, Color color, + uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + float dx = x1 - x0; + float dy = y1 - y0; + float len = MathF.Sqrt(dx * dx + dy * dy); + if (len < 1e-4f || thicknessPx <= 0f) + { + return; + } + + CachedBlob blob = HbGpuVectorShapes.GetUnitFilledRect(_blobCache); + float cos = dx / len; + float sin = dy / len; + float sx = len * 0.001f; + float sy = thicknessPx * 0.001f; + float cx = (x0 + x1) * 0.5f; + float cy = (y0 + y1) * 0.5f; + // Rotate unit rect (X along segment, Y perpendicular) in Y-down screen coords + _writer.DrawBlob( + blob, cx, cy, + cos * sx, -sin * sy, + sin * sx, cos * sy, + 0f, 0f, + color.R, color.G, color.B, color.A, + stemDarken: false, clipMinPacked, clipMaxPacked, + extraFlags: HbGpuQuadInstance.FlagSolidRect); + } + + public void DrawCircleFilled(float cx, float cy, float radiusPx, Color color, + uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + CachedBlob blob = HbGpuVectorShapes.GetUnitFilledCircle(_blobCache); + float s = radiusPx * 0.002f; + _writer.DrawBlob( + blob, cx, cy, + s, 0f, 0f, -s, + 0f, 0f, + color.R, color.G, color.B, color.A, + stemDarken: false, clipMinPacked, clipMaxPacked); + } + + public void DrawCircleRing(float cx, float cy, float radiusPx, float strokePx, Color color, + uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + if (radiusPx <= 0f || strokePx <= 0f) + { + return; + } + + ushort strokeUnits = (ushort)Math.Clamp((int)MathF.Round(strokePx / radiusPx * 500f), 2, 480); + CachedBlob blob = HbGpuVectorShapes.GetUnitRingStroke(_blobCache, strokeUnits); + float s = radiusPx * 0.002f; + _writer.DrawBlob( + blob, cx, cy, + s, 0f, 0f, -s, + 0f, 0f, + color.R, color.G, color.B, color.A, + stemDarken: false, clipMinPacked, clipMaxPacked); + } + + public void DrawTargetBracketCorner(float cornerX, float cornerY, float armPx, float thicknessPx, int quadrant, Color color) + { + if (armPx <= 0f || thicknessPx <= 0f) + { + return; + } + + ushort thickUnits = (ushort)Math.Clamp((int)MathF.Round(thicknessPx / armPx * 1000f), 10, 450); + CachedBlob blob = HbGpuVectorShapes.GetTargetBracketCorner(_blobCache, thickUnits); + float s = armPx * 0.001f; + // Design space: corner at (0,0), X in [0..1000], Y in [-1000..0] (so -emY points down in screen if m11 = -s -> +s). + // Rotate per quadrant: 0=top-left (+X,+Y), 1=top-right (-X,+Y), 2=bottom-right (-X,-Y), 3=bottom-left (+X,-Y) + float sx = (quadrant == 1 || quadrant == 2) ? -s : s; + float sy = (quadrant == 2 || quadrant == 3) ? s : -s; + _writer.DrawBlob( + blob, cornerX, cornerY, + sx, 0f, 0f, sy, + 0f, 0f, + color.R, color.G, color.B, color.A); + } + + public void DrawDirectionalArrow(float cx, float cy, float sizePx, float angleRad, Color color) + { + CachedBlob blob = HbGpuVectorShapes.GetDirectionalArrow(_blobCache); + float s = sizePx * 0.001f; + float cos = MathF.Cos(angleRad); + float sin = MathF.Sin(angleRad); + // Angle 0 points right (+X) in screen space; design arrow points +Y, so rotate by angleRad - PI/2 with Y flip + // Design (0, +500) -> screen (+cos, +sin) * sizePx * 0.5 + _writer.DrawBlob( + blob, cx, cy, + -sin * s, cos * s, + cos * s, sin * s, + 0f, 0f, + color.R, color.G, color.B, color.A); + } + + public void DrawChevron(float cx, float cy, float sizePx, float angleRad, Color color) + { + CachedBlob blob = HbGpuVectorShapes.GetChevronTriangle(_blobCache); + float s = sizePx * 0.001f; + float cos = MathF.Cos(angleRad); + float sin = MathF.Sin(angleRad); + _writer.DrawBlob( + blob, cx, cy, + -sin * s, cos * s, + cos * s, sin * s, + 0f, 0f, + color.R, color.G, color.B, color.A); + } + + public void DrawDiamond(float cx, float cy, float radiusPx, Color color, + uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + CachedBlob blob = HbGpuVectorShapes.GetDiamondBlip(_blobCache); + float s = radiusPx * 0.002f; + _writer.DrawBlob( + blob, cx, cy, + s, 0f, 0f, -s, + 0f, 0f, + color.R, color.G, color.B, color.A, + stemDarken: false, clipMinPacked, clipMaxPacked); + } + + public void DrawRectOutline(float x, float y, float w, float h, float thicknessPx, Color color, + uint clipMinPacked = 0, uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + if (w <= 0f || h <= 0f || thicknessPx <= 0f) + { + return; + } + float t = thicknessPx; + DrawRectFilled(x, y, w, t, color, clipMinPacked, clipMaxPacked); + DrawRectFilled(x, y + h - t, w, t, color, clipMinPacked, clipMaxPacked); + DrawRectFilled(x, y + t, t, MathF.Max(0f, h - 2f * t), color, clipMinPacked, clipMaxPacked); + DrawRectFilled(x + w - t, y + t, t, MathF.Max(0f, h - 2f * t), color, clipMinPacked, clipMaxPacked); + } + + public void DrawPanelFrame(Rect2 rect, Color bgCol, Color borderCol, Color accentCol, + float cornerLen = 12f, float borderPx = 1.5f, bool drawBg = true) + { + float x = rect.Position.X; + float y = rect.Position.Y; + float w = rect.Size.X; + float h = rect.Size.Y; + if (w < 2f || h < 2f) + { + return; + } + if (drawBg) + { + DrawRectFilled(x, y, w, h, bgCol); + } + DrawRectOutline(x, y, w, h, borderPx, borderCol); + + float arm = MathF.Min(cornerLen, MathF.Min(w, h) * 0.4f); + float cThick = MathF.Max(borderPx + 0.5f, 2.0f); + DrawTargetBracketCorner(x, y, arm, cThick, 0, accentCol); + DrawTargetBracketCorner(x + w, y, arm, cThick, 1, accentCol); + DrawTargetBracketCorner(x + w, y + h, arm, cThick, 2, accentCol); + DrawTargetBracketCorner(x, y + h, arm, cThick, 3, accentCol); + } + + public void DrawArcStrokeStatic( + float cx, + float cy, + float radiusPx, + float strokePx, + float startRadScreen, + float endRadScreen, + float rotationRadScreen, + VectorBlobKey key, + Color color) + { + if (radiusPx <= 0f || strokePx <= 0f) + { + return; + } + + float halfThickDesign = Math.Clamp(strokePx / radiusPx * 250f, 2f, 200f); + CachedBlob blob = HbGpuVectorShapes.GetStaticArcStroke( + _blobCache, key, -endRadScreen, -startRadScreen, 500f, halfThickDesign); + float s = radiusPx * 0.002f; + if (MathF.Abs(rotationRadScreen) < 1e-5f) + { + _writer.DrawBlob( + blob, cx, cy, + s, 0f, 0f, -s, + 0f, 0f, + color.R, color.G, color.B, color.A); + } + else + { + // Rotate Y-up design space clockwise by rotationRadScreen in Y-down screen space: + // Screen X = s * (cos*ex + sin*ey), Screen Y = s * (sin*ex - cos*ey) + float cos = MathF.Cos(rotationRadScreen); + float sin = MathF.Sin(rotationRadScreen); + _writer.DrawBlob( + blob, cx, cy, + cos * s, sin * s, + sin * s, -cos * s, + 0f, 0f, + color.R, color.G, color.B, color.A); + } + } + + public void DrawArcStrokeDynamic(float cx, float cy, float radiusPx, float strokePx, float startRadScreen, float endRadScreen, Color color) + { + if (radiusPx <= 0f || strokePx <= 0f) + { + return; + } + + float halfThickDesign = Math.Clamp(strokePx / radiusPx * 250f, 2f, 200f); + // Screen Y-down angles -> design Y-up angles (negate angles so screen clockwise matches -design angle) + CachedBlob blob = HbGpuVectorShapes.EncodeArcStrokeDynamic(_blobCache, -endRadScreen, -startRadScreen, 500f, halfThickDesign); + float s = radiusPx * 0.002f; + _writer.DrawBlob( + blob, cx, cy, + s, 0f, 0f, -s, + 0f, 0f, + color.R, color.G, color.B, color.A); + } + + public void EndFrameAndSubmit() + { + LastQuadCount = _writer.QuadCount; + + if (_backend is null || _disposed) + { + _atlas.ClearPending(); + return; + } + + ComputeViewportSizes(out float logicalW, out float logicalH, out int physW, out int physH); + + lock (_syncLock) + { + int count = _writer.QuadCount; + if (count > 0) + { + Array.Copy(_writer.RawBuffer, 0, _stagedQuads, 0, count); + } + if (_atlas.PendingChunkCount > 0) + { + _atlas.DrainToMirror(_stagedAtlasMirror); + _stagedAtlasDirty = true; + } + _stagedQuadCount = count; + _stagedLogicalW = logicalW; + _stagedLogicalH = logicalH; + _stagedPhysW = physW; + _stagedPhysH = physH; + _hasStagedFrame = true; + _backend.ProfilingEnabled = ProfilingEnabled; + } + + RenderingServer.CallOnRenderThread(_renderCallable); + } + + private void ComputeViewportSizes(out float logicalW, out float logicalH, out int physW, out int physH) + { + Viewport? vp = GetViewport(); + if (vp is null) + { + logicalW = MathF.Max(2f, Size.X); + logicalH = MathF.Max(2f, Size.Y); + physW = Math.Max(2, Mathf.RoundToInt(logicalW)); + physH = Math.Max(2, Mathf.RoundToInt(logicalH)); + return; + } + + Vector2 vis = vp.GetVisibleRect().Size; + if (vis.X < 2f || vis.Y < 2f) + { + vis = Size; + } + + logicalW = MathF.Max(2f, vis.X); + logicalH = MathF.Max(2f, vis.Y); + + if (vp is SubViewport sv) + { + physW = Math.Max(2, sv.Size.X); + physH = Math.Max(2, sv.Size.Y); + } + else + { + Vector2 stretchScale = vp.GetStretchTransform().Scale; + physW = Math.Max(2, Mathf.RoundToInt(logicalW * stretchScale.X)); + physH = Math.Max(2, Mathf.RoundToInt(logicalH * stretchScale.Y)); + } + } + + private void RenderOnRenderThread() + { + if (_backend is null || _disposed) + { + return; + } + + lock (_syncLock) + { + if (!_hasStagedFrame) + { + return; + } + _hasStagedFrame = false; + bool atlasDirty = _stagedAtlasDirty; + _stagedAtlasDirty = false; + _backend.RenderFrame( + _stagedQuads, + _stagedQuadCount, + _stagedAtlasMirror, + atlasDirty, + _stagedLogicalW, + _stagedLogicalH, + _stagedPhysW, + _stagedPhysH); + } + } + + private void DisposeOnRenderThread() + { + _backend?.DisposeRdResources(); + } + + /// + /// Synchronously reads back the current offscreen RGBA8 render target from RenderingDevice. + /// Intended strictly for verification probes/tests. + /// + public bool TryReadbackRgba8(out byte[] data, out int width, out int height) + { + byte[]? captured = null; + int w = 0, h = 0; + + if (_backend is null || RenderingServer.GetRenderingDevice() is null) + { + data = Array.Empty(); + width = 0; + height = 0; + return false; + } + + RenderingServer.CallOnRenderThread(Callable.From(() => + { + _backend.TryReadbackOnRenderThread(out captured, out w, out h); + })); + RenderingServer.ForceSync(); + + if (captured is null || w <= 0 || h <= 0) + { + data = Array.Empty(); + width = 0; + height = 0; + return false; + } + + data = captured; + width = w; + height = h; + return true; + } + + public override void _ExitTree() + { + ReleaseResources(disposing: true); + } + + protected override void Dispose(bool disposing) + { + ReleaseResources(disposing); + base.Dispose(disposing); + } + + private void ReleaseResources(bool disposing) + { + if (_disposed) + { + return; + } + _disposed = true; + + if (disposing) + { + if (_outputTexRd is not null) + { + _outputTexRd.TextureRdRid = new Rid(); + } + + if (_backend is not null && RenderingServer.GetRenderingDevice() is not null) + { + RenderingServer.CallOnRenderThread(_disposeCallable); + RenderingServer.ForceSync(); + } + } + + _fontCache.Dispose(); + } + + private sealed class HbGpuVulkanBackend + { + private readonly Texture2Drd _outputTexRd; + + private readonly byte[] _quadUploadBytes = new byte[HbGpuCommandWriter.MaxQuads * 80]; + private readonly byte[] _pushConstantBytes = new byte[PushConstantBytes]; + private static readonly Color[] ClearColors = { new Color(0f, 0f, 0f, 0f) }; + + private RenderingDevice? _rd; + private bool _initialized; + private bool _failed; + + private Rid _shaderRid; + private Rid _pipelineRid; + private Rid _nearestSamplerRid; + private Rid _atlasTexRid; + private Rid _quadSsboRid; + private Rid _uniformSetRid; + private Rid _colorTexRid; + private Rid _framebufferRid; + private int _fbWidth; + private int _fbHeight; + + private ulong _frameIndex; + private ulong _lastSampledTimestampFrame = ulong.MaxValue; + + public bool ProfilingEnabled { get; set; } + public double LastHbGpuMs { get; private set; } + public int LastDrawCallCount { get; private set; } + + public HbGpuVulkanBackend(Texture2Drd outputTexRd) + { + _outputTexRd = outputTexRd; + } + + public void RenderFrame( + HbGpuQuadInstance[] quads, + int quadCount, + byte[] atlasMirrorBytes, + bool atlasDirty, + float logicalW, + float logicalH, + int physW, + int physH) + { + if (_failed) + { + return; + } + + RenderingDevice? rd = RenderingServer.GetRenderingDevice(); + if (rd is null) + { + return; + } + + if (!_initialized) + { + if (!TryInitialize(rd, atlasMirrorBytes, physW, physH)) + { + _failed = true; + return; + } + } + else + { + if (atlasDirty) + { + rd.TextureUpdate(_atlasTexRid, 0, atlasMirrorBytes); + } + if (physW != _fbWidth || physH != _fbHeight) + { + RecreateRenderTarget(rd, physW, physH); + } + } + + _rd = rd; + _frameIndex++; + + // Upload quad instances into SSBO + if (quadCount > 0) + { + uint byteLen = (uint)(quadCount * 80); + ReadOnlySpan srcBytes = MemoryMarshal.AsBytes(quads.AsSpan(0, quadCount)); + srcBytes.CopyTo(_quadUploadBytes); + rd.BufferUpdate(_quadSsboRid, 0, byteLen, _quadUploadBytes); + } + + bool captureTs = ProfilingEnabled && rd.GetCapturedTimestampsCount() < 180; + if (ProfilingEnabled) + { + SamplePreviousTimestamps(rd); + } + if (captureTs) + { + rd.CaptureTimestamp("HbGpu_Start"); + } + + long dl = rd.DrawListBegin(_framebufferRid, RenderingDevice.DrawFlags.ClearColorAll, ClearColors); + if (quadCount > 0) + { + var pc = new PushConstants + { + C0R0 = 2.0f / logicalW, + C1R1 = 2.0f / logicalH, + C2R2 = 1.0f, + C3R0 = -1.0f, + C3R1 = -1.0f, + C3R3 = 1.0f, + ViewportX = physW, + ViewportY = physH, + LogicalW = logicalW, + LogicalH = logicalH + }; + MemoryMarshal.Write(_pushConstantBytes, in pc); + + rd.DrawListBindRenderPipeline(dl, _pipelineRid); + rd.DrawListBindUniformSet(dl, _uniformSetRid, 0); + rd.DrawListSetPushConstant(dl, _pushConstantBytes, PushConstantBytes); + rd.DrawListDraw(dl, useIndices: false, instances: (uint)quadCount, proceduralVertexCount: 6u); + LastDrawCallCount = 1; + } + else + { + LastDrawCallCount = 0; + } + rd.DrawListEnd(); + + if (captureTs) + { + rd.CaptureTimestamp("HbGpu_End"); + } + } + + private void CreateAtlasAndUniformSet(RenderingDevice rd, byte[] initialAtlasBytes) + { + var nearestState = new RDSamplerState + { + MinFilter = RenderingDevice.SamplerFilter.Nearest, + MagFilter = RenderingDevice.SamplerFilter.Nearest, + RepeatU = RenderingDevice.SamplerRepeatMode.ClampToEdge, + RepeatV = RenderingDevice.SamplerRepeatMode.ClampToEdge, + RepeatW = RenderingDevice.SamplerRepeatMode.ClampToEdge + }; + _nearestSamplerRid = rd.SamplerCreate(nearestState); + + var atlasFmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type2D, + Format = RenderingDevice.DataFormat.R16G16B16A16Sint, + Width = AtlasTexWidth, + Height = AtlasTexHeight, + Depth = 1, + ArrayLayers = 1, + Mipmaps = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.SamplingBit + | RenderingDevice.TextureUsageBits.CanUpdateBit + }; + _atlasTexRid = rd.TextureCreate( + atlasFmt, + new RDTextureView(), + new Godot.Collections.Array { initialAtlasBytes }); + + var u0 = new RDUniform + { + UniformType = RenderingDevice.UniformType.SamplerWithTexture, + Binding = 0 + }; + u0.AddId(_nearestSamplerRid); + u0.AddId(_atlasTexRid); + + var u1 = new RDUniform + { + UniformType = RenderingDevice.UniformType.StorageBuffer, + Binding = 1 + }; + u1.AddId(_quadSsboRid); + + _uniformSetRid = rd.UniformSetCreate(new Godot.Collections.Array { u0, u1 }, _shaderRid, 0); + } + + private void SamplePreviousTimestamps(RenderingDevice rd) + { + uint count = rd.GetCapturedTimestampsCount(); + if (count == 0) + { + return; + } + + ulong tsFrame = rd.GetCapturedTimestampsFrame(); + if (tsFrame == _lastSampledTimestampFrame) + { + return; + } + _lastSampledTimestampFrame = tsFrame; + + ulong tStart = 0, tEnd = 0; + for (uint i = 0; i < count; i++) + { + string name = rd.GetCapturedTimestampName(i); + if (name == "HbGpu_Start") + { + tStart = rd.GetCapturedTimestampGpuTime(i); + } + else if (name == "HbGpu_End") + { + tEnd = rd.GetCapturedTimestampGpuTime(i); + } + } + + if (tStart > 0 && tEnd >= tStart) + { + LastHbGpuMs = (tEnd - tStart) / 1_000_000.0; + } + } + + private bool TryInitialize(RenderingDevice rd, byte[] initialAtlasBytes, int physW, int physH) + { + _rd = rd; + + string vertSrc = BuildVertexShaderSource(); + string fragSrc = BuildFragmentShaderSource(); + + using var rdSrc = new RDShaderSource + { + Language = RenderingDevice.ShaderLanguage.Glsl, + SourceVertex = vertSrc, + SourceFragment = fragSrc + }; + + using RDShaderSpirV spirv = rd.ShaderCompileSpirVFromSource(rdSrc, allowCache: true); + if (!string.IsNullOrEmpty(spirv.CompileErrorVertex)) + { + GD.PrintErr($"HbGpuCanvas vertex SPIR-V error: {spirv.CompileErrorVertex}"); + return false; + } + if (!string.IsNullOrEmpty(spirv.CompileErrorFragment)) + { + GD.PrintErr($"HbGpuCanvas fragment SPIR-V error: {spirv.CompileErrorFragment}"); + return false; + } + + _shaderRid = rd.ShaderCreateFromSpirV(spirv, "HbGpuCanvas"); + if (!_shaderRid.IsValid) + { + GD.PrintErr("HbGpuCanvas: ShaderCreateFromSpirV failed."); + return false; + } + + _quadSsboRid = rd.StorageBufferCreate((uint)(HbGpuCommandWriter.MaxQuads * 80)); + CreateAtlasAndUniformSet(rd, initialAtlasBytes); + + RecreateRenderTarget(rd, physW, physH); + + long fbFormat = rd.FramebufferGetFormat(_framebufferRid); + + var rasterState = new RDPipelineRasterizationState + { + CullMode = RenderingDevice.PolygonCullMode.Disabled + }; + var msState = new RDPipelineMultisampleState + { + SampleCount = RenderingDevice.TextureSamples.Samples1 + }; + var dsState = new RDPipelineDepthStencilState(); + var blendAttachment = new RDPipelineColorBlendStateAttachment + { + EnableBlend = true, + SrcColorBlendFactor = RenderingDevice.BlendFactor.One, + DstColorBlendFactor = RenderingDevice.BlendFactor.OneMinusSrcAlpha, + ColorBlendOp = RenderingDevice.BlendOperation.Add, + SrcAlphaBlendFactor = RenderingDevice.BlendFactor.One, + DstAlphaBlendFactor = RenderingDevice.BlendFactor.OneMinusSrcAlpha, + AlphaBlendOp = RenderingDevice.BlendOperation.Add + }; + var blendState = new RDPipelineColorBlendState(); + blendState.Attachments.Add(blendAttachment); + + _pipelineRid = rd.RenderPipelineCreate( + _shaderRid, + fbFormat, + RenderingDevice.InvalidFormatId, + RenderingDevice.RenderPrimitive.Triangles, + rasterState, + msState, + dsState, + blendState); + + if (!_pipelineRid.IsValid) + { + GD.PrintErr("HbGpuCanvas: RenderPipelineCreate failed."); + return false; + } + + _initialized = true; + return true; + } + + private void RecreateRenderTarget(RenderingDevice rd, int physW, int physH) + { + if (_framebufferRid.IsValid) + { + rd.FreeRid(_framebufferRid); + _framebufferRid = new Rid(); + } + if (_colorTexRid.IsValid) + { + _outputTexRd.TextureRdRid = new Rid(); + rd.FreeRid(_colorTexRid); + _colorTexRid = new Rid(); + } + + var fmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type2D, + Format = RenderingDevice.DataFormat.R8G8B8A8Unorm, + Width = (uint)physW, + Height = (uint)physH, + Depth = 1, + ArrayLayers = 1, + Mipmaps = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.ColorAttachmentBit + | RenderingDevice.TextureUsageBits.SamplingBit + | RenderingDevice.TextureUsageBits.CanCopyFromBit + }; + _colorTexRid = rd.TextureCreate(fmt, new RDTextureView()); + _framebufferRid = rd.FramebufferCreate(new Godot.Collections.Array { _colorTexRid }); + _fbWidth = physW; + _fbHeight = physH; + _outputTexRd.TextureRdRid = _colorTexRid; + } + + public void TryReadbackOnRenderThread(out byte[]? data, out int width, out int height) + { + if (_rd is null || !_initialized || !_colorTexRid.IsValid) + { + data = null; + width = 0; + height = 0; + return; + } + + data = _rd.TextureGetData(_colorTexRid, 0); + width = _fbWidth; + height = _fbHeight; + } + + public void DisposeRdResources() + { + if (_rd is null) + { + return; + } + + _outputTexRd.TextureRdRid = new Rid(); + + if (_framebufferRid.IsValid) { _rd.FreeRid(_framebufferRid); _framebufferRid = new Rid(); } + if (_colorTexRid.IsValid) { _rd.FreeRid(_colorTexRid); _colorTexRid = new Rid(); } + if (_uniformSetRid.IsValid) { _rd.FreeRid(_uniformSetRid); _uniformSetRid = new Rid(); } + if (_quadSsboRid.IsValid) { _rd.FreeRid(_quadSsboRid); _quadSsboRid = new Rid(); } + if (_atlasTexRid.IsValid) { _rd.FreeRid(_atlasTexRid); _atlasTexRid = new Rid(); } + if (_nearestSamplerRid.IsValid) { _rd.FreeRid(_nearestSamplerRid); _nearestSamplerRid = new Rid(); } + if (_pipelineRid.IsValid) { _rd.FreeRid(_pipelineRid); _pipelineRid = new Rid(); } + if (_shaderRid.IsValid) { _rd.FreeRid(_shaderRid); _shaderRid = new Rid(); } + + _initialized = false; + _rd = null; + } + + private static string BuildVertexShaderSource() + { + string sharedVert = HbGpuNative.GetShaderSource(HbGpuShaderStage.Vertex, HbGpuShaderKind.Shared); + return $@"#version 450 +{sharedVert} + +struct QuadInstance {{ + vec4 em_box; + vec4 pos_anchor; + vec4 xform; + vec4 color; + uvec4 meta; +}}; + +layout(set = 0, binding = 1, std430) readonly buffer Quads {{ + QuadInstance quads[]; +}}; + +layout(push_constant, std430) uniform Push {{ + mat4 u_mvp; + vec2 u_viewport; + vec2 u_logicalSize; +}} pc; + +layout(location = 0) out vec2 v_em; +layout(location = 1) out vec4 v_color; +layout(location = 2) flat out uint v_blob_loc; +layout(location = 3) flat out uint v_flags; +layout(location = 4) flat out uvec2 v_clip_packed; + +void main() {{ + QuadInstance q = quads[gl_InstanceIndex]; + const uint idxMap[6] = uint[6](0u, 1u, 2u, 0u, 2u, 3u); + uint c = idxMap[gl_VertexIndex]; + vec2 uv = vec2((c == 1u || c == 2u) ? 1.0 : 0.0, (c >= 2u) ? 1.0 : 0.0); + vec2 em = mix(q.em_box.xy, q.em_box.zw, uv); + vec2 emSgn = uv * 2.0 - 1.0; + + vec2 dEm = em - q.pos_anchor.xy; + float m00 = q.xform.x; + float m01 = q.xform.y; + float m10 = q.xform.z; + float m11 = q.xform.w; + vec2 pos = q.pos_anchor.zw + vec2(m00 * dEm.x + m01 * dEm.y, m10 * dEm.x + m11 * dEm.y); + + vec2 ax = vec2(m00, m10); + vec2 ay = vec2(m01, m11); + float lx = length(ax); + float ly = length(ay); + vec2 axisX = lx > 1e-8 ? ax / lx : vec2(1.0, 0.0); + vec2 axisY = ly > 1e-8 ? ay / ly : vec2(0.0, 1.0); + vec2 normal = axisX * emSgn.x + axisY * emSgn.y; + + float det = m00 * m11 - m01 * m10; + float invDet = abs(det) > 1e-12 ? (1.0 / det) : 0.0; + vec4 jac = vec4(m11, -m01, -m10, m00) * invDet; + + hb_gpu_dilate(pos, em, normal, jac, pc.u_mvp, pc.u_viewport); + + gl_Position = pc.u_mvp * vec4(pos, 0.0, 1.0); + v_em = em; + v_color = q.color; + v_blob_loc = q.meta.x; + v_flags = q.meta.y; + v_clip_packed = q.meta.zw; +}} +"; + } + + private static string BuildFragmentShaderSource() + { + string sharedFrag = HbGpuNative.GetShaderSource(HbGpuShaderStage.Fragment, HbGpuShaderKind.Shared); + string drawFrag = HbGpuNative.GetShaderSource(HbGpuShaderStage.Fragment, HbGpuShaderKind.Draw); + const string oldAtlasDecl = "uniform highp isampler2D hb_gpu_atlas;"; + const string oldWidthDecl = "uniform int hb_gpu_atlas_width;"; + if (!sharedFrag.Contains(oldAtlasDecl, StringComparison.Ordinal) || + !sharedFrag.Contains(oldWidthDecl, StringComparison.Ordinal)) + { + throw new InvalidOperationException("Unexpected hb-gpu-fragment.glsl HB_GPU_ATLAS_2D uniform layout."); + } + sharedFrag = sharedFrag + .Replace(oldAtlasDecl, "layout(set = 0, binding = 0) uniform highp isampler2D hb_gpu_atlas;", StringComparison.Ordinal) + .Replace(oldWidthDecl, $"const int hb_gpu_atlas_width = {AtlasTexWidth};", StringComparison.Ordinal); + + return $@"#version 450 +#define HB_GPU_ATLAS_2D +{sharedFrag} +{drawFrag} + +layout(push_constant, std430) uniform Push {{ + mat4 u_mvp; + vec2 u_viewport; + vec2 u_logicalSize; +}} pc; + +layout(location = 0) in vec2 v_em; +layout(location = 1) in vec4 v_color; +layout(location = 2) flat in uint v_blob_loc; +layout(location = 3) flat in uint v_flags; +layout(location = 4) flat in uvec2 v_clip_packed; + +layout(location = 0) out vec4 frag_color; + +void main() {{ + vec2 dx = dFdx(v_em); + vec2 dy = dFdy(v_em); + vec2 em_px = vec2(length(vec2(dx.x, dy.x)), length(vec2(dx.y, dy.y))); + vec2 pixelsPerEm = 1.0 / max(em_px, vec2(1e-6)); + float cov; + + if ((v_flags & 2u) != 0u) {{ + vec2 edgeDist = (500.0 - abs(v_em)) * pixelsPerEm; + cov = clamp(min(edgeDist.x, edgeDist.y) + 0.5, 0.0, 1.0); + }} else {{ + cov = _hb_gpu_slug(v_em, pixelsPerEm, v_blob_loc); + if ((v_flags & 1u) != 0u) {{ + float ppem = hb_gpu_ppem(v_em, v_blob_loc); + if (cov > 0.0 && cov < 1.0) {{ + float brightness = dot(v_color.rgb, vec3(1.0 / 3.0)); + cov = hb_gpu_stem_darken(cov, brightness, ppem); + }} + }} + }} + + if (v_clip_packed.y != 0xFFFFFFFFu) {{ + vec2 logicalPos = gl_FragCoord.xy * (pc.u_logicalSize / pc.u_viewport); + vec2 cMin = vec2(float(v_clip_packed.x & 0xFFFFu), float(v_clip_packed.x >> 16u)); + vec2 cMax = vec2(float(v_clip_packed.y & 0xFFFFu), float(v_clip_packed.y >> 16u)); + if (logicalPos.x < cMin.x || logicalPos.y < cMin.y || logicalPos.x > cMax.x || logicalPos.y > cMax.y) {{ + cov = 0.0; + }} + }} + + float a = clamp(v_color.a * cov, 0.0, 1.0); + frag_color = vec4(v_color.rgb * a, a); +}} +"; + } + } +} diff --git a/client/Hud.cs b/client/Hud.cs index 40d4312..41acd41 100644 --- a/client/Hud.cs +++ b/client/Hud.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Globalization; using Godot; using RustToDust.Core; +using RustToDust.HbGpu; namespace RustToDust.Client; @@ -15,130 +16,273 @@ public enum HitMarkerKind } /// -/// Rust to Dust industrial HUD: -/// - Top-Left: Chassis badge (DORSAL/CORONAL), Core HP, Speed, Contenders Alive, Safe Circle status, Pickup prompt. +/// Rust to Dust industrial HUD rendered in a single Vulkan draw call via : +/// - Top-Left: Chassis badge (DORSAL/CORONAL), Core HP bar, Speed/Alt/Alive/Kills, Safe Circle, Detection, Wave, Net, Prompt. /// - Top-Right: Tactical Radar (Safe Circle, RadarSignature-scaled Spectator Wall, lock lines, contenders, salvage). /// - Bottom-Left: Live clickable Aetheria Hardpoint & Heat Schematic + Cargo Salvage Rack (Tab expands Garage details). -/// - Bottom-Center: Imperial Broadcast Chyron (Weksa commentary). +/// - Bottom-Right: Imperial Broadcast Chyron (Weksa commentary). +/// - Center & 3D World: Crosshair + heat arc + incoming/outgoing hit feedback + squad chevrons + target boxes + offscreen arrows. /// public partial class Hud : CanvasLayer { - private static readonly Color BgDark = Color.FromHtml("#131613"); + private static readonly Color BgDark = new(0.075f, 0.086f, 0.075f, 0.88f); private static readonly Color BgInner = Color.FromHtml("#1b1f1b"); + private static readonly Color BgRowHover = new(0.16f, 0.20f, 0.16f, 0.92f); private static readonly Color BorderCol = Color.FromHtml("#3e4638"); private static readonly Color OliveCol = Color.FromHtml("#9bb06a"); private static readonly Color OrangeCol = Color.FromHtml("#e08a4a"); private static readonly Color TextLight = Color.FromHtml("#e4dfd2"); private static readonly Color TextMuted = Color.FromHtml("#989487"); private static readonly Color CyanCol = Color.FromHtml("#44d9e8"); + private static readonly Color AlliedCol = Color.FromHtml("#52e3a8"); private static readonly Color GoldCol = Color.FromHtml("#e6b838"); private static readonly Color RedCol = Color.FromHtml("#d93829"); + private static readonly Color PatronColor = Color.FromHtml("#4ba8a5"); + private static readonly Color ShadowCol = new(0.04f, 0.05f, 0.04f, 0.88f); + + private const float HitArcDuration = 0.65f; + private const float BorderPad = 36f; + private const float PanelAvoidPad = 18f; + private const float OffscreenHostileMaxDistance = 220f; + private const int MaxOffscreenHostileArrows = 6; + private const int MaxCargoHitRects = 16; + + private struct IncomingHitArc + { + public float SourceX; + public float SourceZ; + public WeaponVisualClass WeaponClass; + public float Age; + } + + private readonly struct OffscreenMarker + { + public readonly System.Numerics.Vector3 CamLocal; + public readonly float Distance; + public readonly Color Color; + public readonly bool IsLockedOnLocal; + + public OffscreenMarker(System.Numerics.Vector3 camLocal, float distance, Color color, bool isLockedOnLocal) + { + CamLocal = camLocal; + Distance = distance; + Color = color; + IsLockedOnLocal = isLockedOnLocal; + } + } private readonly Func _getSession; private readonly Action _onEquipCargo; private readonly Func _getCameraYaw; + private readonly Func? _projectWorld; - private Label _chassisHeader = null!; - private Label _planeBadge = null!; - private ProgressBar _coreHpBar = null!; - private Label _coreHpLabel = null!; - private Label _statsLabel = null!; - private Label _safeLabel = null!; - private Label _detectionLabel = null!; - private Label _waveLabel = null!; - private Label _netStatusLabel = null!; - private Label _promptLabel = null!; - private Label _controlsHint = null!; - - private RadarWidget _radar = null!; - private Label _radarTitle = null!; - private Label _mapAttribLabel = null!; private ColorRect _vignetteRect = null!; private ShaderMaterial _vignetteMat = null!; - private CrosshairOverlay _crosshair = null!; - private float _damagePulse; - private float _lowCoreRatio; - private float _overheatPulse; - private float _vignetteTime; + private ColorRect _bottomLeftBg = null!; private InventoryGridControl _schematic = null!; - private Label _hoverLabel = null!; - private VBoxContainer _cargoList = null!; - private Label _cargoHeader = null!; - private Label _garageDetails = null!; - private ChromePanel _topLeftPanel = null!; - private ChromePanel _topRightPanel = null!; - private ChromePanel _bottomLeftPanel = null!; - private ChromePanel _chyronPanel = null!; + private HbGpuCanvas _hbCanvas = null!; - private ChromePanel _netPanel = null!; + // Interactive [F9] multiplayer input panel (kept on Godot Controls until Thing 2 Cut 14c) + private PanelContainer _netPanel = null!; private Label _netModeBadge = null!; private Label _netPanelStatus = null!; private LineEdit _callsignEdit = null!; private LineEdit _endpointEdit = null!; private string? _uiNetError; - private VBoxContainer _chyronBox = null!; - private readonly Label[] _chyronLabels = new Label[3]; - private BroadcastFeed? _lastBroadcastFeed; - private long _lastChyronVersion = -1; - private ChromePanel _outcomeBanner = null!; - private Label _outcomeLabel = null!; + // Layout rects (logical pixels) + private Rect2 _topLeftRect; + private Rect2 _topRightRect; + private Rect2 _bottomLeftRect; + private Rect2 _schematicRect; + private Rect2 _chyronRect; + private Rect2 _outcomeRect; + private bool _outcomeVisible; + private Vector2 _lastViewportSize = new(1280f, 720f); + // Cargo click hitboxes (zero Button allocations) + private readonly Rect2[] _cargoRowRects = new Rect2[MaxCargoHitRects]; + private readonly Rect2[] _cargoFitRects = new Rect2[MaxCargoHitRects]; + private int _cargoHitCount; + private ChassisGrid? _lastCargoGrid; private int _selectedCargoIndex = -1; - private int _lastCargoHash = -1; private bool _garageExpanded; private Vector2I? _lastHoveredCell; + // Vignette & combat feedback + private float _damagePulse; + private float _lowCoreRatio; + private float _overheatPulse; + private float _vignetteTime; + private readonly IncomingHitArc[] _incomingArcs = new IncomingHitArc[8]; + private int _incomingArcCount; + private HitMarkerKind _hitMarkerKind; + private float _hitMarkerRemaining; + private float _hitMarkerDuration; + private MatchState? _lastCrosshairState; + + // Zero-GC scratch & change-detected text caches + private readonly char[] _scratch = new char[512]; + private readonly List _offscreenHostiles = new(16); + private static readonly Comparison OffscreenSortComparison = static (a, b) => + { + int lockCmp = b.IsLockedOnLocal.CompareTo(a.IsLockedOnLocal); + return lockCmp != 0 ? lockCmp : a.Distance.CompareTo(b.Distance); + }; + + private readonly List _promptLines = new(3); + private string _cachedPromptText = string.Empty; + private int _lastPromptKey = int.MinValue; + private bool _lastPromptPod; + private int _lastPodAglRounded = int.MinValue; + private int _lastPodHorizRounded = int.MinValue; + private int _lastPodVertRounded = int.MinValue; + private bool _lastPodBurn; + + private readonly List _hoverLines = new(3); + private string _cachedHoverText = "HOVER CELL FOR TELEMETRY"; + private Color _cachedHoverColor = TextMuted; + + private readonly List _garageLines = new(24); + private string _cachedGarageDetails = string.Empty; + private int _lastGarageHash = int.MinValue; + + private BroadcastFeed? _lastBroadcastFeed; + private long _lastChyronVersion = -1; + private readonly string[] _chyronDisplayLines = new string[3]; + private readonly bool[] _chyronIsLatest = new bool[3]; + private readonly List _chyronWrapScratch = new(8); + private int _chyronLineCount; + + private readonly List _hintLines = new(2); + private int _lastHintMode = -1; + + private IClientArenaSession? _latestSession; + private string? _cachedChassisName; + private string _cachedChassisUpper = "CHASSIS"; + private bool _inputBlocked; + private bool _dirtyEmit; + private bool _emittedThisFrame; + public event Action? JoinRequested; public event Action? HostRequested; public event Action? SoloRequested; public event Action? NetworkPanelToggled; - public Hud(Func getSession, Action onEquipCargo, Func? getCameraYaw = null) + public Hud( + Func getSession, + Action onEquipCargo, + Func? getCameraYaw = null, + Func? projectWorld = null) { _getSession = getSession; _onEquipCargo = onEquipCargo; _getCameraYaw = getCameraYaw ?? (() => 0f); + _projectWorld = projectWorld; Layer = 10; } + public HbGpuCanvas HbCanvas => _hbCanvas; public bool GarageExpanded => _garageExpanded; public bool NetworkPanelOpen => _netPanel.Visible; public bool IsUiTextInputFocused => _netPanel.Visible && (_callsignEdit.HasFocus() || _endpointEdit.HasFocus()); public InventoryGridControl Schematic => _schematic; - internal int ActiveHitArcCount => _crosshair.ActiveHitArcCount; - internal bool HasActiveHitMarker => _crosshair.HasActiveHitMarker; - internal HitMarkerKind ActiveHitMarkerKind => _crosshair.ActiveHitMarkerKind; + internal int ActiveHitArcCount => _incomingArcCount; + internal bool HasActiveHitMarker => _hitMarkerRemaining > 0f && _hitMarkerKind != HitMarkerKind.None; + internal HitMarkerKind ActiveHitMarkerKind => HasActiveHitMarker ? _hitMarkerKind : HitMarkerKind.None; internal bool IsVignetteVisible => _vignetteRect is not null && _vignetteRect.Visible; - internal void PushTestHitArc(float sourceX, float sourceZ, WeaponVisualClass weaponClass) => - _crosshair.PushTestHitArc(sourceX, sourceZ, weaponClass); + internal Rect2 BottomLeftPanelRect => _bottomLeftRect; + internal Rect2 ChyronPanelRect => _chyronRect; + internal string HoverLabelText => _cachedHoverText; + internal string PromptLabelText => _cachedPromptText; + internal string GarageDetailsText => _cachedGarageDetails; + + internal void PushTestHitArc(float sourceX, float sourceZ, WeaponVisualClass weaponClass) + { + if (_incomingArcCount >= _incomingArcs.Length) + { + for (int i = 1; i < _incomingArcs.Length; i++) + { + _incomingArcs[i - 1] = _incomingArcs[i]; + } + _incomingArcCount = _incomingArcs.Length - 1; + } + _incomingArcs[_incomingArcCount++] = new IncomingHitArc + { + SourceX = sourceX, + SourceZ = sourceZ, + WeaponClass = weaponClass, + Age = 0f + }; + _dirtyEmit = true; + } + internal void ResetFeedback() { _damagePulse = 0f; _lowCoreRatio = 0f; _overheatPulse = 0f; _vignetteTime = 0f; + _incomingArcCount = 0; + _hitMarkerKind = HitMarkerKind.None; + _hitMarkerRemaining = 0f; + _hitMarkerDuration = 0f; if (_vignetteRect is not null) { _vignetteRect.Visible = false; } - _crosshair?.ResetFeedback(); + _dirtyEmit = true; } - internal Rect2 BottomLeftPanelRect => _bottomLeftPanel.GetGlobalRect(); - internal Rect2 ChyronPanelRect => _chyronPanel.GetGlobalRect(); - internal string HoverLabelText => _hoverLabel.Text; - internal string PromptLabelText => _promptLabel.Text; - internal string GarageDetailsText => _garageDetails.Text; + internal void SimulateCellHover(Vector2I? cell, HardpointSpec? hp) => OnSchematicHoverChanged(cell, hp); - public IEnumerable GetChromeMaterials() + public override void _Ready() { - yield return _topLeftPanel.ChromeMaterial; - yield return _topRightPanel.ChromeMaterial; - yield return _bottomLeftPanel.ChromeMaterial; - yield return _chyronPanel.ChromeMaterial; - yield return _outcomeBanner.ChromeMaterial; - yield return _netPanel.ChromeMaterial; + Shader vigShader = GD.Load("res://hud_vignette.gdshader") + ?? throw new InvalidOperationException("Failed to load res://hud_vignette.gdshader"); + _vignetteMat = new ShaderMaterial { Shader = vigShader }; + _vignetteRect = new ColorRect + { + Name = "HudVignette", + Material = _vignetteMat, + MouseFilter = Control.MouseFilterEnum.Ignore, + Visible = false + }; + _vignetteRect.SetAnchorsPreset(Control.LayoutPreset.FullRect); + AddChild(_vignetteRect); + + // Dark backdrop under _schematic so inactive holes (e.g. Raptor) show panel BgDark instead of 3D world + _bottomLeftBg = new ColorRect + { + Name = "BottomLeftBackdrop", + Color = BgDark, + MouseFilter = Control.MouseFilterEnum.Ignore + }; + AddChild(_bottomLeftBg); + + _schematic = new InventoryGridControl + { + Name = "SchematicGrid", + ExternalHbGpuOwner = true, + CustomMinimumSize = new Vector2(180f, 188f) + }; + _schematic.HardpointClicked += OnHardpointClicked; + _schematic.HoverChanged += OnSchematicHoverChanged; + AddChild(_schematic); + + // Single-draw-call HarfBuzz hb-gpu overlay sits strictly ABOVE _schematic's bilinear thermal backdrop + _hbCanvas = new HbGpuCanvas + { + Name = "HbGpuCanvas", + MouseFilter = Control.MouseFilterEnum.Ignore + }; + _hbCanvas.SetAnchorsAndOffsetsPreset(Control.LayoutPreset.FullRect); + AddChild(_hbCanvas); + + BuildNetworkPanel(); + + _lastViewportSize = GetViewportSizeSafe(); + RecomputeLayoutRects(_lastViewportSize, _latestSession); } public void ToggleNetworkPanel() => SetNetworkPanelOpen(!_netPanel.Visible); @@ -175,9 +319,15 @@ public partial class Hud : CanvasLayer public void ToggleGarage() { _garageExpanded = !_garageExpanded; - _garageDetails.Visible = _garageExpanded; + _lastGarageHash = int.MinValue; _schematic.CustomMinimumSize = _garageExpanded ? new Vector2(198f, 208f) : new Vector2(180f, 188f); - _schematic.QueueRedraw(); + RecomputeLayoutRects(GetViewportSizeSafe(), _latestSession); + _dirtyEmit = true; + } + + public void SetInputBlocked(bool blocked) + { + _inputBlocked = blocked; } public void SetMatchHudActive(bool active) @@ -185,6 +335,7 @@ public partial class Hud : CanvasLayer Visible = active; if (!active) { + _inputBlocked = false; if (_netPanel.Visible) { _netPanel.Visible = false; @@ -199,14 +350,54 @@ public partial class Hud : CanvasLayer } } + public override void _Input(InputEvent @event) + { + if (!Visible || _inputBlocked || _netPanel.Visible) + { + return; + } + + if (@event is InputEventMouseButton mb && mb.Pressed && mb.ButtonIndex == MouseButton.Left) + { + if (_lastCargoGrid is not null && + _bottomLeftRect.HasPoint(mb.Position) && + !_schematic.GetGlobalRect().HasPoint(mb.Position)) + { + for (int i = 0; i < _cargoHitCount; i++) + { + if (_cargoFitRects[i].HasPoint(mb.Position)) + { + AutoFitCargo(_lastCargoGrid, i); + GetViewport().SetInputAsHandled(); + _dirtyEmit = true; + return; + } + if (_cargoRowRects[i].HasPoint(mb.Position)) + { + _selectedCargoIndex = (_selectedCargoIndex == i) ? -1 : i; + if (_lastHoveredCell is null) + { + UpdateCargoSelectionTooltip(_lastCargoGrid); + } + GetViewport().SetInputAsHandled(); + _dirtyEmit = true; + return; + } + } + } + } + } + public override void _Process(double delta) { if (!Visible) { + _emittedThisFrame = false; return; } + float dt = (float)delta; - _crosshair?.Advance(dt); + bool timerAdvanced = AdvanceTimers(dt); if (_vignetteRect is not null) { @@ -226,6 +417,50 @@ public partial class Hud : CanvasLayer _vignetteMat.SetShaderParameter("time_sec", _vignetteTime); } } + else if (dt > 0f) + { + _vignetteTime += dt; + } + + if ((_dirtyEmit || timerAdvanced) && !_emittedThisFrame && _latestSession is not null) + { + EmitHudFrame(_latestSession); + } + + _emittedThisFrame = false; + _dirtyEmit = false; + } + + private bool AdvanceTimers(float dt) + { + bool dirty = false; + if (_incomingArcCount > 0 && dt > 0f) + { + int write = 0; + for (int i = 0; i < _incomingArcCount; i++) + { + _incomingArcs[i].Age += dt; + if (_incomingArcs[i].Age < HitArcDuration) + { + _incomingArcs[write++] = _incomingArcs[i]; + } + } + _incomingArcCount = write; + dirty = true; + } + + if (_hitMarkerRemaining > 0f && dt > 0f) + { + _hitMarkerRemaining = MathF.Max(0f, _hitMarkerRemaining - dt); + if (_hitMarkerRemaining <= 0.001f) + { + _hitMarkerRemaining = 0f; + _hitMarkerKind = HitMarkerKind.None; + } + dirty = true; + } + + return dirty; } public void ConsumeEvents( @@ -246,7 +481,7 @@ public partial class Hud : CanvasLayer if (hit.TargetKind == (byte)HitTargetKind.Contender && hit.TargetId == localContenderId) { var wc = (WeaponVisualClass)hit.WeaponClass; - _crosshair?.PushTestHitArc(hit.SourceX, hit.SourceZ, wc); + PushTestHitArc(hit.SourceX, hit.SourceZ, wc); float pulse = wc is WeaponVisualClass.Explosive or WeaponVisualClass.RocketSalvo or WeaponVisualClass.GaussRail ? 0.95f : 0.62f; @@ -256,7 +491,7 @@ public partial class Hud : CanvasLayer || hit.TargetKind == (byte)HitTargetKind.Spectator; if (targetIsVehicle && hit.IsContenderShooter && hit.ShooterId == localContenderId) { - _crosshair?.TriggerHitMarker(hit.CoreDamage > 0.001f, hit.Killed); + TriggerHitMarker(hit.CoreDamage > 0.001f, hit.Killed); } break; } @@ -283,44 +518,60 @@ public partial class Hud : CanvasLayer } } - public override void _Ready() + private void TriggerHitMarker(bool coreHit, bool killed) { - BuildCrosshair(); - BuildTopLeft(); - BuildTopRightRadar(); - BuildBottomLeftSchematic(); - BuildBottomCenterChyron(); - BuildOutcomeBanner(); - BuildNetworkPanel(); + HitMarkerKind nextKind = killed + ? HitMarkerKind.Kill + : (coreHit ? HitMarkerKind.Core : HitMarkerKind.Armor); + if (_hitMarkerRemaining > 0f && (int)nextKind < (int)_hitMarkerKind) + { + nextKind = _hitMarkerKind; + } + _hitMarkerKind = nextKind; + _hitMarkerDuration = nextKind switch + { + HitMarkerKind.Kill => 0.38f, + HitMarkerKind.Core => 0.26f, + _ => 0.18f + }; + _hitMarkerRemaining = _hitMarkerDuration; + _dirtyEmit = true; } public bool IsPointerOverInteractiveHud(Vector2 screenPos) { - return (_topLeftPanel.Visible && _topLeftPanel.GetGlobalRect().HasPoint(screenPos)) - || (_topRightPanel.Visible && _topRightPanel.GetGlobalRect().HasPoint(screenPos)) - || (_bottomLeftPanel.Visible && _bottomLeftPanel.GetGlobalRect().HasPoint(screenPos)) - || (_chyronPanel.Visible && _chyronPanel.GetGlobalRect().HasPoint(screenPos)) - || (_chyronBox.Visible && _chyronBox.GetGlobalRect().HasPoint(screenPos)) - || (_outcomeBanner.Visible && _outcomeBanner.GetGlobalRect().HasPoint(screenPos)) + return (Visible && _topLeftRect.HasPoint(screenPos)) + || (Visible && _topRightRect.HasPoint(screenPos)) + || (Visible && _bottomLeftRect.HasPoint(screenPos)) + || (Visible && _chyronRect.HasPoint(screenPos)) + || (Visible && _outcomeVisible && _outcomeRect.HasPoint(screenPos)) || (_netPanel.Visible && _netPanel.GetGlobalRect().HasPoint(screenPos)); } public bool HasPanelOverlapOrClip(Vector2 viewportSize) { - var panels = new[] { _topLeftPanel, _topRightPanel, _bottomLeftPanel, _chyronPanel, _netPanel }; - var bounds = new Rect2(Vector2.Zero, viewportSize + new Vector2(1f, 1f)); - for (int i = 0; i < panels.Length; i++) + RecomputeLayoutRects(viewportSize, _latestSession); + Span rects = stackalloc Rect2[5]; + int count = 0; + rects[count++] = _topLeftRect; + rects[count++] = _topRightRect; + rects[count++] = _bottomLeftRect; + rects[count++] = _chyronRect; + if (_netPanel.Visible) { - if (!panels[i].Visible) continue; - var ri = panels[i].GetGlobalRect(); - if (!bounds.Encloses(ri)) + rects[count++] = _netPanel.GetGlobalRect(); + } + + var bounds = new Rect2(Vector2.Zero, viewportSize + new Vector2(1f, 1f)); + for (int i = 0; i < count; i++) + { + if (!bounds.Encloses(rects[i])) { return true; } - for (int j = i + 1; j < panels.Length; j++) + for (int j = i + 1; j < count; j++) { - if (!panels[j].Visible) continue; - if (ri.Intersects(panels[j].GetGlobalRect())) + if (rects[i].Intersects(rects[j])) { return true; } @@ -331,177 +582,32 @@ public partial class Hud : CanvasLayer public void Sync(IClientArenaSession session) { + _latestSession = session; var state = session.ViewState; + if (!ReferenceEquals(_lastCrosshairState, state)) + { + _lastCrosshairState = state; + _incomingArcCount = 0; + _hitMarkerKind = HitMarkerKind.None; + _hitMarkerRemaining = 0f; + _hitMarkerDuration = 0f; + } + var player = session.LocalContender; var net = session.ConnectionStatus; - // Top-Left Status - OrbitalPod? localPod = null; - if (player.IsInDropPod) - { - var pods = session.ActivePods; - for (int i = 0; i < pods.Count; i++) - { - if (pods[i].PodKind == OrbitalPodKind.Contender && pods[i].ContenderId == player.Id) - { - localPod = pods[i]; - break; - } - } - } - - int aliveCount = 0; - for (int i = 0; i < state.Contenders.Count; i++) - { - if (state.Contenders[i].Alive) aliveCount++; - } - - if (player.IsInDropPod) - { - float agl = localPod is not null - ? MathF.Max(0f, localPod.LastAgl) - : MathF.Max(0f, player.Y - state.Terrain.SampleHeight(player.X, player.Z)); - float velDown = localPod is not null ? MathF.Max(0f, -localPod.VelY) : MathF.Max(0f, -player.VelY); - bool burning = localPod?.Phase == OrbitalPodPhase.RetroBurn; - _chassisHeader.Text = "ORBITAL DROP POD"; - _planeBadge.Text = burning ? "RETRO BURN" : "FREEFALL"; - _planeBadge.Modulate = burning ? OrangeCol : CyanCol; - _statsLabel.Text = $"ALT {agl:F0}m | VEL {velDown:F0} m/s | ALIVE {aliveCount} / {state.Contenders.Count}"; - _controlsHint.Text = "WASD Steer Pod | Mouse Look | Retro-Burn Auto | Wheel Zoom"; - } - else - { - _chassisHeader.Text = player.Grid.Spec.Name.ToUpperInvariant(); - bool isCoronal = player.Grid.Spec.Plane == GridPlane.Coronal; - _planeBadge.Text = isCoronal ? "CORONAL" : "DORSAL"; - _planeBadge.Modulate = isCoronal ? CyanCol : OliveCol; - - if (player.Grid.Spec.IsVtol) - { - float agl = MathF.Max(0f, player.Y - player.Grid.Spec.HalfHeight - state.Terrain.SampleHeight(player.X, player.Z)); - _statsLabel.Text = $"SPD {player.Speed:F1} m/s | ALT {agl:F1}m | ALIVE {aliveCount} / {state.Contenders.Count} | KILLS {player.Kills}"; - _controlsHint.Text = "WASD Fly | Space/C Alt | Mouse Aim | LMB Fire | E Bolt | Tab Garage | M Map | F9 Net"; - } - else - { - _statsLabel.Text = $"SPD {player.Speed:F1} m/s | ALIVE {aliveCount} / {state.Contenders.Count} | KILLS {player.Kills}"; - _controlsHint.Text = "WASD Drive | Mouse Aim | LMB Fire | E Bolt | Tab Garage | M Map | F9 Net | Wheel Zoom"; - } - } - - _coreHpBar.MaxValue = Math.Max(1f, player.Grid.MaxCoreHp); - _coreHpBar.Value = Math.Max(0f, player.Grid.CoreHp); - _coreHpLabel.Text = $"CORE {player.Grid.CoreHp:F0} / {player.Grid.MaxCoreHp:F0}"; - - _radarTitle.Text = state.MapKind == ArenaMapKind.Sion - ? "SION 3KM • RADAR" - : "DESERT RING • RADAR"; - _mapAttribLabel.Text = state.MapKind == ArenaMapKind.Sion - ? "Data: swisstopo | [M] Switch Map" - : "[M] Switch to Sion 3 km"; - - float distCenter = MathF.Sqrt(player.X * player.X + player.Z * player.Z); - float outside = distCenter - state.Spectators.SafeRadius; - int cleared = state.Spectators.CountClearedFor(player.Id); - int provoked = state.Spectators.CountProvokedFor(player.Id); - - if (outside <= 0f) - { - _safeLabel.Text = $"RING SAFE ({-outside:F0}m margin)" + (provoked > 0 ? $" • {provoked} PROVOKED!" : ""); - _safeLabel.Modulate = provoked > 0 ? OrangeCol : OliveCol; - } - else - { - _safeLabel.Text = $"OUTSIDE +{outside:F0}m — {cleared} CLEARED" + (provoked > 0 ? $" / {provoked} PROVOKED!" : "!"); - _safeLabel.Modulate = RedCol; - } - - int detectedBy = session.LocalDetectedByCount; - if (detectedBy > 0) - { - _detectionLabel.Text = $"DETECTED BY {detectedBy}"; - _detectionLabel.Modulate = RedCol; - } - else - { - _detectionLabel.Text = "CONCEALED (TERRAIN)"; - _detectionLabel.Modulate = OliveCol; - } - - var wave = session.DropWaveState; - if (wave.RespawnCutoffReached) - { - _waveLabel.Text = "FINAL RING — RESPAWNS CLOSED"; - _waveLabel.Modulate = RedCol; - } - else if (wave.NextWaveAtSec is float nextWaveAt) - { - float eta = MathF.Max(0f, nextWaveAt - state.Time); - _waveLabel.Text = $"PATRON WAVE {wave.NextWaveIndex} IN {eta:F0}s • RESP {player.RespawnsRemaining}"; - _waveLabel.Modulate = eta <= 10f ? GoldCol : CyanCol; - } - else - { - _waveLabel.Text = $"WAVE {wave.CurrentWaveIndex} ACTIVE • RESP {player.RespawnsRemaining}"; - _waveLabel.Modulate = OliveCol; - } - - if (net.Mode == NetworkMode.Solo) - { - _netStatusLabel.Visible = false; - } - else - { - _netStatusLabel.Visible = true; - if (net.Mode == NetworkMode.ListenHost) - { - _netStatusLabel.Text = $"{net.StateLabel} • HUMANS {net.ConnectedHumans}/{net.MaxHumans} • [F9] NET"; - _netStatusLabel.Modulate = CyanCol; - } - else if (net.Connected) - { - _netStatusLabel.Text = $"PING {net.PingMs} ms • HUMANS {net.ConnectedHumans}/{net.MaxHumans} • [F9] NET"; - _netStatusLabel.Modulate = net.PingMs > 120 ? OrangeCol : CyanCol; - } - else - { - _netStatusLabel.Text = $"{net.StateLabel} • [F9] NET"; - _netStatusLabel.Modulate = net.LastError is not null ? RedCol : OrangeCol; - } - } + OrbitalPod? localPod = FindLocalContenderPod(session, player); if (_netPanel.Visible) { SyncNetworkPanel(net); } - if (player.IsInDropPod) - { - float agl = localPod is not null - ? MathF.Max(0f, localPod.LastAgl) - : MathF.Max(0f, player.Y - state.Terrain.SampleHeight(player.X, player.Z)); - float velDown = localPod is not null ? MathF.Max(0f, -localPod.VelY) : MathF.Max(0f, -player.VelY); - _promptLabel.Text = $"ORBITAL INSERTION — ALT {agl:F0}m | VEL {velDown:F0}m/s | [WASD] STEER" - + (localPod?.Phase == OrbitalPodPhase.RetroBurn ? " [RETRO BURN]" : ""); - _promptLabel.Visible = true; - } - else - { - _promptLabel.Text = BuildInteractionPrompt(state, player); - _promptLabel.Visible = !string.IsNullOrEmpty(_promptLabel.Text); - } + UpdatePromptCache(state, player, localPod); + UpdateHintCache(player); - // Crosshair + Heat Arc / Orbital Altimeter + Directional Incoming Hit Arcs - _crosshair.SetState(state, player, _getCameraYaw(), localPod); - _crosshair.QueueRedraw(); - - // Radar (heading-up with camera yaw) - _radar.SetState(session, _getCameraYaw()); - _radar.QueueRedraw(); - - // Schematic + Cargo _schematic.SetGrid(player.Grid, _selectedCargoIndex); - SyncCargoButtons(player.Grid); + _lastCargoGrid = player.Grid; if (_lastHoveredCell is null) { @@ -510,331 +616,2052 @@ public partial class Hud : CanvasLayer if (_garageExpanded) { - _garageDetails.Text = BuildGarageDetails(player.Grid, _selectedCargoIndex); + UpdateGarageDetailsCache(player.Grid); } - // Broadcast Chyron SyncBroadcastChyron(state.Broadcast); - // Outcome / WaitingForRespawnWave Banner - var outcome = session.LocalOutcome; - if (outcome == ClientMatchOutcome.Victory) + RecomputeLayoutRects(GetViewportSizeSafe(), session); + EmitHudFrame(session); + _emittedThisFrame = true; + _dirtyEmit = false; + } + + private Vector2 GetViewportSizeSafe() + { + Viewport? vp = GetViewport(); + if (vp is not null) { - _outcomeBanner.Visible = true; - _outcomeBanner.ChromeMaterial.SetShaderParameter("accent_color", OliveCol); - _outcomeLabel.Text = net.Mode == NetworkMode.RemoteClient - ? "VICTORY — LAST RIG STANDING\nNext round starting soon..." - : "VICTORY — LAST RIG STANDING\n[R] New Drop"; - _outcomeLabel.Modulate = OliveCol; + Vector2 vis = vp.GetVisibleRect().Size; + if (vis.X >= 64f && vis.Y >= 64f) + { + _lastViewportSize = vis; + return vis; + } } - else if (outcome == ClientMatchOutcome.Defeat) + return _lastViewportSize; + } + + private static OrbitalPod? FindLocalContenderPod(IClientArenaSession session, ContenderState player) + { + if (!player.IsInDropPod) return null; + var pods = session.ActivePods; + for (int i = 0; i < pods.Count; i++) { - _outcomeBanner.Visible = true; - _outcomeBanner.ChromeMaterial.SetShaderParameter("accent_color", RedCol); - string title = !player.Alive ? "CHASSIS DESTROYED" : "MATCH COMPLETED — DEFEAT"; - string sub = net.Mode == NetworkMode.RemoteClient - ? (state.Phase == MatchPhase.Completed ? "Waiting for server next round..." : "Spectating live match...") - : "[R] Redeploy"; - _outcomeLabel.Text = $"{title}\n{sub}"; - _outcomeLabel.Modulate = RedCol; + if (pods[i].PodKind == OrbitalPodKind.Contender && pods[i].ContenderId == player.Id) + { + return pods[i]; + } } - else if (player.WaitingForRespawn) + return null; + } + + private void RecomputeLayoutRects(Vector2 vpSize, IClientArenaSession? session) + { + float vw = MathF.Max(320f, vpSize.X); + float vh = MathF.Max(240f, vpSize.Y); + + // Top-Left panel + float tlW = 396f; + float tlH = 138f + Math.Max(1, _hintLines.Count) * 14f; + if (session is not null && session.ConnectionStatus.Mode != NetworkMode.Solo) { - _outcomeBanner.Visible = true; - _outcomeBanner.ChromeMaterial.SetShaderParameter("accent_color", CyanCol); - float eta = wave.NextWaveAtSec is float nxt ? MathF.Max(0f, nxt - state.Time) : 0f; - _outcomeLabel.Text = $"AWAITING PATRON WAVE {wave.NextWaveIndex}\nRESPAWN IN {eta:F1}s (RESP: {player.RespawnsRemaining} LEFT)"; - _outcomeLabel.Modulate = CyanCol; + tlH += 17f; + } + if (_promptLines.Count > 0) + { + tlH += 4f + _promptLines.Count * 16f; + } + _topLeftRect = new Rect2(14f, 14f, tlW, tlH); + + // Top-Right Radar panel + float trW = 234f; + float trH = 264f; + _topRightRect = new Rect2(vw - 14f - trW, 14f, trW, trH); + + // Bottom-Left Schematic + Cargo + optional Garage panel + float gridW = _garageExpanded ? 198f : 180f; + float gridH = _garageExpanded ? 208f : 188f; + const float cargoW = 156f; + float garageW = _garageExpanded ? 186f : 0f; + float blW = 10f + gridW + 8f + cargoW + (_garageExpanded ? 8f + garageW : 0f) + 10f; + + float hoverH = MathF.Max(28f, _hoverLines.Count * 14f); + float leftColH = 18f + gridH + 4f + hoverH; + + int cargoCount = session?.LocalContender.Grid.Cargo.Count ?? 0; + float cargoColH = 18f + (cargoCount > 0 ? cargoCount * 21f : 34f); + float garageColH = _garageExpanded ? MathF.Max(140f, _garageLines.Count * 13.5f + 8f) : 0f; + float blH = 8f + MathF.Max(leftColH, MathF.Max(cargoColH, garageColH)) + 8f; + + _bottomLeftRect = new Rect2(14f, vh - 14f - blH, blW, blH); + _schematicRect = new Rect2(_bottomLeftRect.Position.X + 10f, _bottomLeftRect.Position.Y + 8f + 18f, gridW, gridH); + + if (_bottomLeftBg is not null) + { + if (_bottomLeftBg.Position != _bottomLeftRect.Position) _bottomLeftBg.Position = _bottomLeftRect.Position; + if (_bottomLeftBg.Size != _bottomLeftRect.Size) _bottomLeftBg.Size = _bottomLeftRect.Size; + } + if (_schematic is not null) + { + if (_schematic.Position != _schematicRect.Position) _schematic.Position = _schematicRect.Position; + if (_schematic.Size != _schematicRect.Size) _schematic.Size = _schematicRect.Size; + } + + // Bottom-Right Chyron panel + const float chW = 570f; + const float chH = 92f; + _chyronRect = new Rect2(vw - 14f - chW, vh - 14f - chH, chW, chH); + + // Outcome banner + _outcomeRect = new Rect2(vw * 0.5f - 210f, vh * 0.28f - 40f, 420f, 80f); + _outcomeVisible = false; + if (session is not null) + { + var outcome = session.LocalOutcome; + _outcomeVisible = outcome == ClientMatchOutcome.Victory + || outcome == ClientMatchOutcome.Defeat + || session.LocalContender.WaitingForRespawn; + } + } + + private void EmitHudFrame(IClientArenaSession session) + { + if (_hbCanvas is null || !Visible) + { + return; + } + + Vector2 vpSize = GetViewportSizeSafe(); + var state = session.ViewState; + var player = session.LocalContender; + var net = session.ConnectionStatus; + OrbitalPod? localPod = FindLocalContenderPod(session, player); + + _hbCanvas.BeginFrame(); + + // 1. 3D Projected World Markers (behind panels, above scene) + EmitWorldMarkers(session, state, player, vpSize); + + // 2. Center Crosshair, Thermal Heat Arc, Incoming Hit Arcs, Hit-Marker X, Pod Altimeter + EmitCrosshairAndCombatFeedback(state, player, localPod, vpSize * 0.5f); + + // 3. Top-Left Telemetry Panel + EmitTopLeftPanel(session, state, player, net, localPod); + + // 4. Top-Right Radar Panel + EmitTopRightRadarPanel(session, state); + + // 5. Bottom-Left Schematic Panel Frame + Hardpoint Overlay + Hover + Cargo Rack + Garage + EmitBottomLeftPanel(player.Grid); + + // 6. Bottom-Right Broadcast Chyron + EmitChyronPanel(); + + // 7. Outcome / Awaiting Wave Banner + if (_outcomeVisible) + { + EmitOutcomeBanner(session, state, player, net); + } + + // 8. Optional [F9] Network panel chrome + cyan brackets (drawn behind transparent _netPanel controls) + if (_netPanel.Visible) + { + _hbCanvas.DrawPanelFrame(_netPanel.GetGlobalRect(), BgDark, CyanCol, CyanCol, cornerLen: 14f, borderPx: 1.5f, drawBg: true); + } + + _hbCanvas.EndFrameAndSubmit(); + } + + // ------------------------------------------------------------------------- + // 1. Top-Left Panel (0 GC allocs) + // ------------------------------------------------------------------------- + private void EmitTopLeftPanel( + IClientArenaSession session, + MatchState state, + ContenderState player, + NetworkStatusSnapshot net, + OrbitalPod? localPod) + { + _hbCanvas.DrawPanelFrame(_topLeftRect, BgDark, BorderCol, OliveCol, cornerLen: 12f, borderPx: 1.5f); + + float x = _topLeftRect.Position.X + 10f; + float rightX = _topLeftRect.End.X - 10f; + float y = _topLeftRect.Position.Y + 8f; + + int aliveCount = 0; + for (int i = 0; i < state.Contenders.Count; i++) + { + if (state.Contenders[i].Alive) aliveCount++; + } + + // Header + Dorsal/Coronal/Pod badge + if (player.IsInDropPod) + { + bool burning = localPod?.Phase == OrbitalPodPhase.RetroBurn; + _hbCanvas.DrawText("ORBITAL DROP POD", x, y + 14f, 16f, TextLight, wght: 700f); + ReadOnlySpan badge = burning ? "RETRO BURN" : "FREEFALL"; + Color bCol = burning ? OrangeCol : CyanCol; + float bw = _hbCanvas.MeasureTextWidth(badge, 12.5f, wght: 600f); + _hbCanvas.DrawText(badge, rightX - bw, y + 13f, 12.5f, bCol, wght: 600f); } else { - _outcomeBanner.Visible = false; - } - } - - private void BuildCrosshair() - { - Shader vigShader = GD.Load("res://hud_vignette.gdshader") - ?? throw new InvalidOperationException("Failed to load res://hud_vignette.gdshader"); - _vignetteMat = new ShaderMaterial { Shader = vigShader }; - _vignetteRect = new ColorRect - { - Name = "HudVignette", - Material = _vignetteMat, - MouseFilter = Control.MouseFilterEnum.Ignore, - Visible = false - }; - _vignetteRect.SetAnchorsPreset(Control.LayoutPreset.FullRect); - AddChild(_vignetteRect); - - _crosshair = new CrosshairOverlay { Name = "Crosshair" }; - _crosshair.SetAnchorsPreset(Control.LayoutPreset.FullRect); - _crosshair.MouseFilter = Control.MouseFilterEnum.Ignore; - AddChild(_crosshair); - } - - private void BuildTopLeft() - { - var panel = CreateStyledPanel(OliveCol); - _topLeftPanel = panel; - panel.AnchorLeft = 0f; - panel.AnchorTop = 0f; - panel.OffsetLeft = 14f; - panel.OffsetTop = 14f; - panel.CustomMinimumSize = new Vector2(360f, 0f); - AddChild(panel); - - var vbox = new VBoxContainer { Theme = null }; - vbox.AddThemeConstantOverride("separation", 5); - panel.AddChild(vbox); - - var headRow = new HBoxContainer(); - headRow.AddThemeConstantOverride("separation", 10); - vbox.AddChild(headRow); - - _chassisHeader = new Label { Text = "DUNE BUGGY", SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }; - _chassisHeader.AddThemeColorOverride("font_color", TextLight); - _chassisHeader.AddThemeFontSizeOverride("font_size", 17); - headRow.AddChild(_chassisHeader); - - _planeBadge = new Label { Text = "DORSAL" }; - _planeBadge.AddThemeFontSizeOverride("font_size", 13); - headRow.AddChild(_planeBadge); - - var hpRow = new HBoxContainer(); - hpRow.AddThemeConstantOverride("separation", 8); - vbox.AddChild(hpRow); - - _coreHpBar = new ProgressBar - { - ShowPercentage = false, - SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, - CustomMinimumSize = new Vector2(180f, 16f) - }; - var barBg = new StyleBoxFlat { BgColor = BgInner, BorderColor = BorderCol }; - barBg.SetBorderWidthAll(1); - var barFill = new StyleBoxFlat { BgColor = OliveCol }; - _coreHpBar.AddThemeStyleboxOverride("background", barBg); - _coreHpBar.AddThemeStyleboxOverride("fill", barFill); - hpRow.AddChild(_coreHpBar); - - _coreHpLabel = new Label { Text = "CORE 100 / 100" }; - _coreHpLabel.AddThemeColorOverride("font_color", TextLight); - _coreHpLabel.AddThemeFontSizeOverride("font_size", 13); - hpRow.AddChild(_coreHpLabel); - - _statsLabel = new Label { Text = "SPD 0.0 m/s" }; - _statsLabel.AddThemeColorOverride("font_color", TextMuted); - _statsLabel.AddThemeFontSizeOverride("font_size", 13); - vbox.AddChild(_statsLabel); - - _safeLabel = new Label { Text = "RING SAFE" }; - _safeLabel.AddThemeFontSizeOverride("font_size", 13); - vbox.AddChild(_safeLabel); - - _detectionLabel = new Label { Text = "CONCEALED (TERRAIN)" }; - _detectionLabel.AddThemeFontSizeOverride("font_size", 13); - vbox.AddChild(_detectionLabel); - - _waveLabel = new Label { Text = "WAVE 0" }; - _waveLabel.AddThemeFontSizeOverride("font_size", 12); - _waveLabel.AddThemeColorOverride("font_color", CyanCol); - vbox.AddChild(_waveLabel); - - _netStatusLabel = new Label { Text = "", Visible = false }; - _netStatusLabel.AddThemeFontSizeOverride("font_size", 12); - vbox.AddChild(_netStatusLabel); - - _promptLabel = new Label - { - Text = "", - Visible = false, - AutowrapMode = TextServer.AutowrapMode.Word, - CustomMinimumSize = new Vector2(336f, 0f) - }; - _promptLabel.AddThemeColorOverride("font_color", CyanCol); - _promptLabel.AddThemeFontSizeOverride("font_size", 13); - vbox.AddChild(_promptLabel); - - _controlsHint = new Label { Text = "WASD Drive | Mouse Aim | LMB Fire | E Loot/Swap | Tab Garage | Wheel Zoom" }; - _controlsHint.AddThemeColorOverride("font_color", TextMuted); - _controlsHint.AddThemeFontSizeOverride("font_size", 11); - vbox.AddChild(_controlsHint); - } - - private void BuildTopRightRadar() - { - var panel = CreateStyledPanel(OrangeCol); - _topRightPanel = panel; - panel.AnchorLeft = 1f; - panel.AnchorRight = 1f; - panel.AnchorTop = 0f; - panel.OffsetLeft = -246f; - panel.OffsetRight = -14f; - panel.OffsetTop = 14f; - AddChild(panel); - - var vbox = new VBoxContainer(); - vbox.AddThemeConstantOverride("separation", 4); - panel.AddChild(vbox); - - _radarTitle = new Label { Text = "SION 3KM • RADAR", HorizontalAlignment = HorizontalAlignment.Center }; - _radarTitle.AddThemeColorOverride("font_color", OrangeCol); - _radarTitle.AddThemeFontSizeOverride("font_size", 12); - vbox.AddChild(_radarTitle); - - _radar = new RadarWidget - { - CustomMinimumSize = new Vector2(214f, 214f) - }; - vbox.AddChild(_radar); - - _mapAttribLabel = new Label { Text = "Data: swisstopo | [M] Switch Map", HorizontalAlignment = HorizontalAlignment.Center }; - _mapAttribLabel.AddThemeColorOverride("font_color", TextMuted); - _mapAttribLabel.AddThemeFontSizeOverride("font_size", 10); - vbox.AddChild(_mapAttribLabel); - } - - private void BuildBottomLeftSchematic() - { - _bottomLeftPanel = CreateStyledPanel(OrangeCol); - _bottomLeftPanel.AnchorLeft = 0f; - _bottomLeftPanel.AnchorTop = 1f; - _bottomLeftPanel.AnchorBottom = 1f; - _bottomLeftPanel.GrowVertical = Control.GrowDirection.Begin; - _bottomLeftPanel.OffsetLeft = 14f; - _bottomLeftPanel.OffsetTop = -248f; - _bottomLeftPanel.OffsetBottom = -14f; - AddChild(_bottomLeftPanel); - - var hbox = new HBoxContainer(); - hbox.AddThemeConstantOverride("separation", 8); - _bottomLeftPanel.AddChild(hbox); - - var leftCol = new VBoxContainer(); - leftCol.AddThemeConstantOverride("separation", 4); - hbox.AddChild(leftCol); - - var headRow = new HBoxContainer(); - headRow.AddThemeConstantOverride("separation", 6); - leftCol.AddChild(headRow); - - var title = new Label - { - Text = "HARDPOINTS & HEAT", - SizeFlagsHorizontal = Control.SizeFlags.ExpandFill - }; - title.AddThemeColorOverride("font_color", OrangeCol); - title.AddThemeFontSizeOverride("font_size", 12); - headRow.AddChild(title); - - _schematic = new InventoryGridControl - { - CustomMinimumSize = new Vector2(180f, 188f) - }; - _schematic.HardpointClicked += OnHardpointClicked; - _schematic.HoverChanged += OnSchematicHoverChanged; - leftCol.AddChild(_schematic); - - _hoverLabel = new Label - { - Text = "HOVER CELL FOR TELEMETRY", - AutowrapMode = TextServer.AutowrapMode.Word, - CustomMinimumSize = new Vector2(180f, 28f) - }; - _hoverLabel.AddThemeColorOverride("font_color", TextMuted); - _hoverLabel.AddThemeFontSizeOverride("font_size", 10); - leftCol.AddChild(_hoverLabel); - - var rightCol = new VBoxContainer { CustomMinimumSize = new Vector2(156f, 0f) }; - rightCol.AddThemeConstantOverride("separation", 3); - hbox.AddChild(rightCol); - - _cargoHeader = new Label { Text = "SALVAGE CARGO (0/4)" }; - _cargoHeader.AddThemeColorOverride("font_color", OliveCol); - _cargoHeader.AddThemeFontSizeOverride("font_size", 11); - rightCol.AddChild(_cargoHeader); - - _cargoList = new VBoxContainer(); - _cargoList.AddThemeConstantOverride("separation", 2); - rightCol.AddChild(_cargoList); - - _garageDetails = new Label { Visible = false, AutowrapMode = TextServer.AutowrapMode.Word }; - _garageDetails.AddThemeColorOverride("font_color", TextMuted); - _garageDetails.AddThemeFontSizeOverride("font_size", 10); - _garageDetails.CustomMinimumSize = new Vector2(178f, 0f); - hbox.AddChild(_garageDetails); - } - - private void BuildBottomCenterChyron() - { - _chyronPanel = CreateStyledPanel(GoldCol); - var panel = _chyronPanel; - panel.AnchorLeft = 1f; - panel.AnchorRight = 1f; - panel.AnchorTop = 1f; - panel.AnchorBottom = 1f; - panel.GrowHorizontal = Control.GrowDirection.Begin; - panel.GrowVertical = Control.GrowDirection.Begin; - panel.OffsetLeft = -584f; - panel.OffsetRight = -14f; - panel.OffsetTop = -104f; - panel.OffsetBottom = -14f; - AddChild(panel); - - var vbox = new VBoxContainer(); - vbox.AddThemeConstantOverride("separation", 3); - panel.AddChild(vbox); - - var header = new Label { Text = "IMPERIAL BROADCAST FEED" }; - header.AddThemeColorOverride("font_color", GoldCol); - header.AddThemeFontSizeOverride("font_size", 11); - vbox.AddChild(header); - - _chyronBox = new VBoxContainer(); - _chyronBox.AddThemeConstantOverride("separation", 2); - vbox.AddChild(_chyronBox); - - for (int i = 0; i < _chyronLabels.Length; i++) - { - var lbl = new Label + string rawName = player.Grid.Spec.Name; + if (!ReferenceEquals(_cachedChassisName, rawName)) { - Visible = false, - AutowrapMode = TextServer.AutowrapMode.Word - }; - lbl.AddThemeFontSizeOverride("font_size", 11); - lbl.AddThemeColorOverride("font_color", TextMuted); - _chyronBox.AddChild(lbl); - _chyronLabels[i] = lbl; + _cachedChassisName = rawName; + _cachedChassisUpper = rawName.ToUpperInvariant(); + } + _hbCanvas.DrawText(_cachedChassisUpper, x, y + 14f, 16f, TextLight, wght: 700f); + bool isCoronal = player.Grid.Spec.Plane == GridPlane.Coronal; + ReadOnlySpan badge = isCoronal ? "CORONAL" : "DORSAL"; + Color bCol = isCoronal ? CyanCol : OliveCol; + float bw = _hbCanvas.MeasureTextWidth(badge, 12.5f, wght: 600f); + _hbCanvas.DrawText(badge, rightX - bw, y + 13f, 12.5f, bCol, wght: 600f); + } + y += 22f; + + // Core HP vector bar + label + float maxCore = MathF.Max(1f, player.Grid.MaxCoreHp); + float coreHp = MathF.Max(0f, player.Grid.CoreHp); + float hpFrac = Math.Clamp(coreHp / maxCore, 0f, 1f); + + SpanWriter sw = new(_scratch); + sw.Append("CORE "); + sw.AppendFloat(coreHp, "F0"); + sw.Append(" / "); + sw.AppendFloat(maxCore, "F0"); + ReadOnlySpan hpSpan = sw.Span; + float hpLabelW = _hbCanvas.MeasureTextWidth(hpSpan, 12.5f, wght: 550f); + float barW = MathF.Max(80f, rightX - x - hpLabelW - 10f); + + _hbCanvas.DrawRectFilled(x, y, barW, 15f, BgInner); + _hbCanvas.DrawRectOutline(x, y, barW, 15f, 1.0f, BorderCol); + if (hpFrac > 0.001f) + { + Color fillCol = hpFrac < 0.35f ? RedCol : OliveCol; + _hbCanvas.DrawRectFilled(x + 1f, y + 1f, MathF.Max(1f, (barW - 2f) * hpFrac), 13f, fillCol); + } + _hbCanvas.DrawText(hpSpan, x + barW + 8f, y + 12f, 12.5f, TextLight, wght: 550f); + y += 21f; + + // Stats line + sw = new SpanWriter(_scratch); + if (player.IsInDropPod) + { + float agl = localPod is not null + ? MathF.Max(0f, localPod.LastAgl) + : MathF.Max(0f, player.Y - state.Terrain.SampleHeight(player.X, player.Z)); + float velDown = localPod is not null ? MathF.Max(0f, -localPod.VelY) : MathF.Max(0f, -player.VelY); + float horizSpeed = localPod is not null + ? MathF.Sqrt(localPod.VelX * localPod.VelX + localPod.VelZ * localPod.VelZ) + : player.Speed; + sw.Append("ALT "); sw.AppendFloat(agl, "F0"); sw.Append("m | HORIZ "); + sw.AppendFloat(horizSpeed, "F0"); sw.Append(" m/s | VERT "); + sw.AppendFloat(velDown, "F0"); sw.Append(" m/s | ALIVE "); + sw.AppendInt(aliveCount); sw.Append(" / "); sw.AppendInt(state.Contenders.Count); + } + else if (player.Grid.Spec.IsVtol) + { + float agl = MathF.Max(0f, player.Y - player.Grid.Spec.HalfHeight - state.Terrain.SampleHeight(player.X, player.Z)); + sw.Append("SPD "); sw.AppendFloat(player.Speed, "F1"); sw.Append(" m/s | ALT "); + sw.AppendFloat(agl, "F1"); sw.Append("m | ALIVE "); + sw.AppendInt(aliveCount); sw.Append(" / "); sw.AppendInt(state.Contenders.Count); + sw.Append(" | KILLS "); sw.AppendInt(player.Kills); + } + else + { + sw.Append("SPD "); sw.AppendFloat(player.Speed, "F1"); sw.Append(" m/s | ALIVE "); + sw.AppendInt(aliveCount); sw.Append(" / "); sw.AppendInt(state.Contenders.Count); + sw.Append(" | KILLS "); sw.AppendInt(player.Kills); + } + _hbCanvas.DrawText(sw.Span, x, y + 11f, 12f, TextMuted, wght: 400f); + y += 18f; + + // Safe ring status + float distCenter = MathF.Sqrt(player.X * player.X + player.Z * player.Z); + float outside = distCenter - state.Spectators.SafeRadius; + int cleared = state.Spectators.CountClearedFor(player.Id); + int provoked = state.Spectators.CountProvokedFor(player.Id); + + sw = new SpanWriter(_scratch); + Color safeCol; + if (outside <= 0f) + { + sw.Append("RING SAFE ("); sw.AppendFloat(-outside, "F0"); sw.Append("m margin)"); + if (provoked > 0) + { + sw.Append(" • "); sw.AppendInt(provoked); sw.Append(" PROVOKED!"); + } + safeCol = provoked > 0 ? OrangeCol : OliveCol; + } + else + { + sw.Append("OUTSIDE +"); sw.AppendFloat(outside, "F0"); sw.Append("m — "); + sw.AppendInt(cleared); sw.Append(" CLEARED"); + if (provoked > 0) + { + sw.Append(" / "); sw.AppendInt(provoked); sw.Append(" PROVOKED!"); + } + else + { + sw.Append("!"); + } + safeCol = RedCol; + } + _hbCanvas.DrawText(sw.Span, x, y + 11f, 12.5f, safeCol, wght: 500f); + y += 18f; + + // Detection status + int detectedBy = session.LocalDetectedByCount; + sw = new SpanWriter(_scratch); + Color detCol; + if (detectedBy > 0) + { + sw.Append("DETECTED BY "); sw.AppendInt(detectedBy); + detCol = RedCol; + } + else + { + sw.Append("CONCEALED (TERRAIN)"); + detCol = OliveCol; + } + _hbCanvas.DrawText(sw.Span, x, y + 11f, 12.5f, detCol, wght: 500f); + y += 18f; + + // Drop wave / respawn status + var wave = session.DropWaveState; + sw = new SpanWriter(_scratch); + Color waveCol; + if (wave.RespawnCutoffReached) + { + sw.Append("FINAL RING — RESPAWNS CLOSED"); + waveCol = RedCol; + } + else if (wave.NextWaveAtSec is float nextWaveAt) + { + float eta = MathF.Max(0f, nextWaveAt - state.Time); + sw.Append("PATRON WAVE "); sw.AppendInt(wave.NextWaveIndex); + sw.Append(" IN "); sw.AppendFloat(eta, "F0"); + sw.Append("s • RESP "); sw.AppendInt(player.RespawnsRemaining); + waveCol = eta <= 10f ? GoldCol : CyanCol; + } + else + { + sw.Append("WAVE "); sw.AppendInt(wave.CurrentWaveIndex); + sw.Append(" ACTIVE • RESP "); sw.AppendInt(player.RespawnsRemaining); + waveCol = OliveCol; + } + _hbCanvas.DrawText(sw.Span, x, y + 11f, 11.8f, waveCol, wght: 450f); + y += 17f; + + // Network status (only non-Solo) + if (net.Mode != NetworkMode.Solo) + { + sw = new SpanWriter(_scratch); + Color netCol; + if (net.Mode == NetworkMode.ListenHost) + { + sw.Append(net.StateLabel); sw.Append(" • HUMANS "); + sw.AppendInt(net.ConnectedHumans); sw.Append("/"); sw.AppendInt(net.MaxHumans); + sw.Append(" • [F9] NET"); + netCol = CyanCol; + } + else if (net.Connected) + { + sw.Append("PING "); sw.AppendInt(net.PingMs); sw.Append(" ms • HUMANS "); + sw.AppendInt(net.ConnectedHumans); sw.Append("/"); sw.AppendInt(net.MaxHumans); + sw.Append(" • [F9] NET"); + netCol = net.PingMs > 120 ? OrangeCol : CyanCol; + } + else + { + sw.Append(net.StateLabel); sw.Append(" • [F9] NET"); + netCol = net.LastError is not null ? RedCol : OrangeCol; + } + _hbCanvas.DrawText(sw.Span, x, y + 11f, 11.8f, netCol, wght: 450f); + y += 17f; + } + + // Interaction or orbital prompt + if (_promptLines.Count > 0) + { + y += 4f; + for (int i = 0; i < _promptLines.Count; i++) + { + _hbCanvas.DrawText(_promptLines[i], x, y + 11f, 12f, CyanCol, wght: 550f); + y += 16f; + } + } + + // Controls hint (wrapped & clipped cleanly inside panel width) + HbGpuCommandWriter.PackClipRect( + _topLeftRect.Position.X + 8f, + _topLeftRect.Position.Y + 6f, + _topLeftRect.Size.X - 16f, + _topLeftRect.Size.Y - 12f, + out uint tlClipMin, + out uint tlClipMax); + + if (_hintLines.Count == 0) + { + UpdateHintCache(player); + } + float hintY = _topLeftRect.End.Y - 8f - Math.Max(0, _hintLines.Count - 1) * 13.5f; + for (int i = 0; i < _hintLines.Count; i++) + { + _hbCanvas.DrawText( + _hintLines[i], + x, + hintY, + 10.0f, + TextMuted, + wght: 350f, + clipMinPacked: tlClipMin, + clipMaxPacked: tlClipMax); + hintY += 13.5f; } } - private void BuildOutcomeBanner() + // ------------------------------------------------------------------------- + // 2. Top-Right Radar Panel (0 GC allocs) + // ------------------------------------------------------------------------- + private void EmitTopRightRadarPanel(IClientArenaSession session, MatchState state) { - _outcomeBanner = CreateStyledPanel(OliveCol, cornerLen: 16f, borderPx: 2f); - _outcomeBanner.AnchorLeft = 0.5f; - _outcomeBanner.AnchorRight = 0.5f; - _outcomeBanner.AnchorTop = 0.28f; - _outcomeBanner.AnchorBottom = 0.28f; - _outcomeBanner.OffsetLeft = -210f; - _outcomeBanner.OffsetRight = 210f; - _outcomeBanner.OffsetTop = -40f; - _outcomeBanner.OffsetBottom = 40f; - _outcomeBanner.Visible = false; - AddChild(_outcomeBanner); + _hbCanvas.DrawPanelFrame(_topRightRect, BgDark, BorderCol, OrangeCol, cornerLen: 12f, borderPx: 1.5f); - _outcomeLabel = new Label + float panelCenterX = _topRightRect.Position.X + _topRightRect.Size.X * 0.5f; + ReadOnlySpan title = state.MapKind == ArenaMapKind.Sion + ? "SION 3KM • RADAR" + : "DESERT RING • RADAR"; + float titleW = _hbCanvas.MeasureTextWidth(title, 12f, wght: 650f); + _hbCanvas.DrawText(title, panelCenterX - titleW * 0.5f, _topRightRect.Position.Y + 20f, 12f, OrangeCol, wght: 650f); + + Vector2 center = new(panelCenterX, _topRightRect.Position.Y + 26f + 107f); + const float radius = 214f * 0.47f; + float maxBlipRadius = MathF.Max(4f, radius - 3f); + float arenaHalf = MathF.Max(1f, state.Terrain.MapHalfExtent); + float scale = radius / arenaHalf; + float cameraYaw = _getCameraYaw(); + int localId = session.LocalContenderId; + + _hbCanvas.DrawCircleFilled(center.X, center.Y, radius, BgInner); + _hbCanvas.DrawCircleRing(center.X, center.Y, radius, 1.5f, BorderCol); + _hbCanvas.DrawLineSegment(center.X, center.Y - radius, center.X, center.Y - radius + 6f, 2.0f, CyanCol); + + // Safe Circle + float safePx = MathF.Min(state.Spectators.SafeRadius * scale, maxBlipRadius); + _hbCanvas.DrawCircleRing(center.X, center.Y, safePx, 1.6f, OrangeCol); + + // Ground drops + for (int i = 0; i < state.GroundDrops.Count; i++) { - HorizontalAlignment = HorizontalAlignment.Center, - VerticalAlignment = VerticalAlignment.Center - }; - _outcomeLabel.AddThemeFontSizeOverride("font_size", 22); - _outcomeBanner.AddChild(_outcomeLabel); + var d = state.GroundDrops[i]; + if (d.PickedUp) continue; + var p = ClampToRadarDisc(center, MathF.Max(4f, radius - 4f), WorldToRadar(center, scale, d.X, d.Z, cameraYaw)); + if (d.Chassis is not null) + { + _hbCanvas.DrawRectFilled(p.X - 2.5f, p.Y - 2.5f, 5f, 5f, CyanCol); + } + else if (d.Module is { IsImperial: true }) + { + _hbCanvas.DrawCircleFilled(p.X, p.Y, 3.0f, GoldCol); + } + } + + // Active descending Orbital Pods + var pods = session.ActivePods; + for (int i = 0; i < pods.Count; i++) + { + var pod = pods[i]; + if (pod.Phase == OrbitalPodPhase.Popped) continue; + var pp = ClampToRadarDisc(center, MathF.Max(4f, radius - 5f), WorldToRadar(center, scale, pod.X, pod.Z, cameraYaw)); + if (pod.PodKind == OrbitalPodKind.Contender) + { + bool isLocalPod = pod.ContenderId == localId; + bool isAllyPod = !isLocalPod && state.AreAllies(localId, pod.ContenderId); + if (isAllyPod) + { + _hbCanvas.DrawDiamond(pp.X, pp.Y, 4.6f, AlliedCol); + } + else + { + Color pCol = isLocalPod ? OliveCol : OrangeCol; + float sz = isLocalPod ? 10.5f : 7.0f; + _hbCanvas.DrawChevron(pp.X, pp.Y, sz, -MathF.PI * 0.5f, pCol); + } + } + else + { + bool isImp = pod.WaveIndex > 0 || pod.Module?.IsImperial == true; + _hbCanvas.DrawDiamond(pp.X, pp.Y, 3.2f, isImp ? GoldCol : CyanCol); + } + } + + // Spectator Wall (LOS / Tourist horizon rule / 5s ghost memory) + var contenderContacts = session.LocalContenderContacts; + var spectatorContacts = session.LocalSpectatorContacts; + var specs = state.Spectators.Spectators; + for (int i = 0; i < specs.Count; i++) + { + var s = specs[i]; + if (!s.Alive) continue; + + spectatorContacts.TryGetValue(s.Id, out var mem); + if (!MatchState.IsContactOnRadar(mem)) continue; + + bool live = mem!.VisibleToPlayer; + bool hasLivePos = session.IsSpectatorVisible(s.Id) && (live || mem.FaintHorizonPing); + if (!hasLivePos && !mem.HasEverBeenSeen) continue; + + float drawX = hasLivePos ? s.X : mem.LastSeenX; + float drawZ = hasLivePos ? s.Z : mem.LastSeenZ; + float blipR = 1.6f + s.RadarSignature * 3.1f; + float specClampR = MathF.Max(4f, radius - blipR - 1f); + var p = ClampToRadarDisc(center, specClampR, WorldToRadar(center, scale, drawX, drawZ, cameraYaw)); + + Color col = s.Tier switch + { + SpectatorTier.Tourist => GoldCol, + SpectatorTier.Patron => PatronColor, + _ => RedCol + }; + + if (live && s.Stance != SpectatorStance.Neutral && s.HasTargetLos && s.TargetContenderId.HasValue) + { + int tid = s.TargetContenderId.Value; + if (tid >= 0 && tid < state.Contenders.Count && state.Contenders[tid].Alive) + { + var tgt = state.Contenders[tid]; + bool targetVisible = tgt.Id == localId || + (session.IsContenderVisible(tgt.Id) && contenderContacts.TryGetValue(tgt.Id, out var tgtMem) && tgtMem.VisibleToPlayer); + if (targetVisible) + { + float tgtClampR = MathF.Max(4f, radius - (tgt.Id == localId ? 7.5f : 4.3f)); + var tp = ClampToRadarDisc(center, tgtClampR, WorldToRadar(center, scale, tgt.X, tgt.Z, cameraYaw)); + _hbCanvas.DrawLineSegment(p.X, p.Y, tp.X, tp.Y, 1.3f, new Color(RedCol.R, RedCol.G, RedCol.B, 0.65f)); + } + } + col = RedCol; + } + + if (!live) + { + float alpha = mem.FaintHorizonPing + ? 0.42f + : Math.Clamp((1f - mem.LastSeenAge / MatchState.ContactGhostDuration) * 0.48f, 0.08f, 0.48f); + Color ghostCol = mem.FaintHorizonPing ? GoldCol : col; + _hbCanvas.DrawCircleFilled(p.X, p.Y, blipR, new Color(ghostCol.R, ghostCol.G, ghostCol.B, alpha)); + } + else + { + _hbCanvas.DrawCircleFilled(p.X, p.Y, blipR, col); + } + } + + // Contenders (player live chevron; allies diamond; rivals LOS + 5s ghost memory) + float sinY = MathF.Sin(cameraYaw); + float cosY = MathF.Cos(cameraYaw); + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (!c.IsGroundedActive) continue; + + if (c.Id == localId) + { + float playerClampR = MathF.Max(4f, radius - 6.5f - 1f); + var (lPos, _, _) = session.GetInterpolatedContenderPose(localId, 1f); + var p = ClampToRadarDisc(center, playerClampR, WorldToRadar(center, scale, lPos.X, lPos.Z, cameraYaw)); + var dir = new Vector2( + -MathF.Sin(c.Yaw) * cosY + MathF.Cos(c.Yaw) * sinY, + -(MathF.Sin(c.Yaw) * sinY + MathF.Cos(c.Yaw) * cosY)); + float ang = MathF.Atan2(dir.Y, dir.X); + _hbCanvas.DrawChevron(p.X, p.Y, 12.5f, ang, OliveCol); + continue; + } + + if (state.AreAllies(localId, c.Id)) + { + float allyClampR = MathF.Max(4f, radius - 4.6f - 1f); + var (aPos, _, _) = session.GetInterpolatedContenderPose(c.Id, 1f); + var p = ClampToRadarDisc(center, allyClampR, WorldToRadar(center, scale, aPos.X, aPos.Z, cameraYaw)); + _hbCanvas.DrawDiamond(p.X, p.Y, 4.6f, AlliedCol); + continue; + } + + contenderContacts.TryGetValue(c.Id, out var mem); + if (!MatchState.IsContactOnRadar(mem)) continue; + + if (mem!.VisibleToPlayer) + { + float rivalClampR = MathF.Max(4f, radius - 3.3f - 1f); + float rx = session.IsContenderVisible(c.Id) ? c.X : mem.LastSeenX; + float rz = session.IsContenderVisible(c.Id) ? c.Z : mem.LastSeenZ; + var p = ClampToRadarDisc(center, rivalClampR, WorldToRadar(center, scale, rx, rz, cameraYaw)); + _hbCanvas.DrawCircleFilled(p.X, p.Y, 3.3f, OrangeCol); + } + else + { + float ghostClampR = MathF.Max(4f, radius - 2.8f - 1f); + var p = ClampToRadarDisc(center, ghostClampR, WorldToRadar(center, scale, mem.LastSeenX, mem.LastSeenZ, cameraYaw)); + float alpha = Math.Clamp((1f - mem.LastSeenAge / MatchState.ContactGhostDuration) * 0.48f, 0.08f, 0.48f); + _hbCanvas.DrawCircleFilled(p.X, p.Y, 2.8f, new Color(OrangeCol.R, OrangeCol.G, OrangeCol.B, alpha)); + } + } + + ReadOnlySpan attrib = state.MapKind == ArenaMapKind.Sion + ? "Data: swisstopo | [M] Switch Map" + : "[M] Switch to Sion 3 km"; + float attribW = _hbCanvas.MeasureTextWidth(attrib, 10f, wght: 350f); + _hbCanvas.DrawText(attrib, panelCenterX - attribW * 0.5f, _topRightRect.End.Y - 9f, 10f, TextMuted, wght: 350f); } + private static Vector2 WorldToRadar(Vector2 center, float scale, float wx, float wz, float camYaw) + { + float sinY = MathF.Sin(camYaw); + float cosY = MathF.Cos(camYaw); + float rx = -wx * cosY + wz * sinY; + float fy = wx * sinY + wz * cosY; + return center + new Vector2(rx, -fy) * scale; + } + + private static Vector2 ClampToRadarDisc(Vector2 center, float maxRadius, Vector2 pt) + { + Vector2 delta = pt - center; + float dist = delta.Length(); + if (dist > maxRadius && dist > 1e-4f) + { + return center + delta * (maxRadius / dist); + } + return pt; + } + + // ------------------------------------------------------------------------- + // 3. Crosshair, Heat Arc, Incoming Hit Arcs, Hit-Marker X, Pod Altimeter + // ------------------------------------------------------------------------- + private void EmitCrosshairAndCombatFeedback( + MatchState state, + ContenderState player, + OrbitalPod? localPod, + Vector2 center) + { + const float gap = 6f; + const float tick = 10f; + bool allDisabled = player.Alive && + player.InArcWeaponCount == 0 && player.OutOfArcWeaponCount == 0 && player.DisabledWeaponCount > 0; + bool outOfArc = player.Alive && player.AllWeaponsOutOfArc; + Color retCol = (outOfArc || allDisabled) + ? new Color(RedCol.R, RedCol.G, RedCol.B, 0.95f) + : new Color(TextLight.R, TextLight.G, TextLight.B, 0.88f); + + _hbCanvas.DrawCircleFilled(center.X, center.Y, 1.8f, retCol); + _hbCanvas.DrawLineSegment(center.X - gap - tick, center.Y, center.X - gap, center.Y, 1.6f, retCol); + _hbCanvas.DrawLineSegment(center.X + gap, center.Y, center.X + gap + tick, center.Y, 1.6f, retCol); + _hbCanvas.DrawLineSegment(center.X, center.Y - gap - tick, center.X, center.Y - gap, 1.6f, retCol); + _hbCanvas.DrawLineSegment(center.X, center.Y + gap, center.X, center.Y + gap + tick, 1.6f, retCol); + + // Outgoing hit-marker X-flash + if (_hitMarkerRemaining > 0f && _hitMarkerDuration > 0.001f && _hitMarkerKind != HitMarkerKind.None) + { + float frac = Math.Clamp(_hitMarkerRemaining / _hitMarkerDuration, 0f, 1f); + float pop = 1.0f + (1.0f - frac) * 0.25f; + Color xCol = _hitMarkerKind switch + { + HitMarkerKind.Kill => new Color(RedCol.R, RedCol.G, RedCol.B, frac * 0.98f), + HitMarkerKind.Core => new Color(1.0f, 0.28f, 0.16f, frac * 0.95f), + _ => new Color(1.0f, 0.95f, 0.78f, frac * 0.92f) + }; + float xWidth = _hitMarkerKind == HitMarkerKind.Armor ? 2.0f : 2.8f; + float rIn = 6.5f * pop; + float rOut = (_hitMarkerKind == HitMarkerKind.Armor ? 13.5f : 15.5f) * pop; + const float diag = 0.70710678f; + for (int q = 0; q < 4; q++) + { + float sx = (q & 1) == 0 ? 1f : -1f; + float sy = (q & 2) == 0 ? 1f : -1f; + Vector2 dir = new(sx * diag, sy * diag); + _hbCanvas.DrawLineSegment( + center.X + dir.X * rIn, center.Y + dir.Y * rIn, + center.X + dir.X * rOut, center.Y + dir.Y * rOut, + xWidth, xCol); + if (_hitMarkerKind == HitMarkerKind.Kill) + { + _hbCanvas.DrawLineSegment( + center.X + dir.X * (rOut + 4f), center.Y + dir.Y * (rOut + 4f), + center.X + dir.X * (rOut + 10.5f), center.Y + dir.Y * (rOut + 10.5f), + 2.2f, new Color(GoldCol.R, GoldCol.G, GoldCol.B, frac * 0.95f)); + } + } + } + + if (allDisabled) + { + ReadOnlySpan msg = "WEAPONS STRIPPED"; + float mw = _hbCanvas.MeasureTextWidth(msg, 11.5f, wght: 600f); + _hbCanvas.DrawText(msg, center.X - mw * 0.5f, center.Y + 38f, 11.5f, RedCol, wght: 600f); + } + else if (outOfArc) + { + ReadOnlySpan msg = "OUT OF ARC"; + float mw = _hbCanvas.MeasureTextWidth(msg, 11.5f, wght: 600f); + _hbCanvas.DrawText(msg, center.X - mw * 0.5f, center.Y + 38f, 11.5f, RedCol, wght: 600f); + } + + if (!player.Alive) + { + return; + } + + if (player.IsInDropPod) + { + float agl = localPod is not null ? MathF.Max(0f, localPod.LastAgl) : 0f; + float vel = localPod is not null ? MathF.Max(0f, -localPod.VelY) : 0f; + float horizSpeed = localPod is not null + ? MathF.Sqrt(localPod.VelX * localPod.VelX + localPod.VelZ * localPod.VelZ) + : player.Speed; + bool burning = localPod?.Phase == OrbitalPodPhase.RetroBurn; + Color bracketCol = burning ? OrangeCol : CyanCol; + + float startAlt = OrbitalPodPreset.GetStartAltAgl(OrbitalPodKind.Contender, state.MapKind); + float altFrac = Math.Clamp(agl / MathF.Max(1f, startAlt), 0f, 1f); + const float barX = 72f; + const float barH = 76f; + float topY = center.Y - barH * 0.5f; + Color trackCol = new(BorderCol.R, BorderCol.G, BorderCol.B, 0.55f); + _hbCanvas.DrawLineSegment(center.X - barX, topY, center.X - barX, topY + barH, 2.0f, trackCol); + _hbCanvas.DrawLineSegment(center.X + barX, topY, center.X + barX, topY + barH, 2.0f, trackCol); + + float fillH = barH * altFrac; + if (fillH > 0.5f) + { + _hbCanvas.DrawLineSegment(center.X - barX, topY + barH - fillH, center.X - barX, topY + barH, 3.0f, bracketCol); + _hbCanvas.DrawLineSegment(center.X + barX, topY + barH - fillH, center.X + barX, topY + barH, 3.0f, bracketCol); + } + + SpanWriter sw = new(_scratch); + sw.Append("ALT "); sw.AppendFloat(agl, "F0"); sw.Append("m | HORIZ "); + sw.AppendFloat(horizSpeed, "F0"); sw.Append(" m/s | VERT "); + sw.AppendFloat(vel, "F0"); sw.Append(" m/s"); + float tw = _hbCanvas.MeasureTextWidth(sw.Span, 11.5f, wght: 500f); + _hbCanvas.DrawText(sw.Span, center.X - tw * 0.5f, center.Y + 56f, 11.5f, bracketCol, wght: 500f); + + if (burning) + { + ReadOnlySpan burnTxt = "RETRO BURN ACTIVE"; + float bw = _hbCanvas.MeasureTextWidth(burnTxt, 11.5f, wght: 650f); + _hbCanvas.DrawText(burnTxt, center.X - bw * 0.5f, center.Y - 50f, 11.5f, OrangeCol, wght: 650f); + } + return; + } + + // Thermal heat-arc indicator around crosshair + float heatRatio = 0f; + bool overPlateau = false; + var mounted = player.Grid.Mounted; + for (int i = 0; i < mounted.Count; i++) + { + var m = mounted[i]; + if (m.Spec.Kind == HardpointKind.Weapon) + { + float r = Math.Clamp( + (m.CurrentTemp - ChassisGrid.AmbientTemp) / MathF.Max(1f, m.Spec.MaxTemp - ChassisGrid.AmbientTemp), + 0f, 1f); + if (r > heatRatio) heatRatio = r; + if (m.CurrentTemp > m.Spec.OptimalTemp + m.Spec.PlateauWidth * 0.5f) + { + overPlateau = true; + } + } + } + + const float arcRadius = 21f; + const float startAngle = -MathF.PI * 0.75f; + const float maxSweep = MathF.PI * 1.5f; + _hbCanvas.DrawArcStrokeStatic( + center.X, center.Y, arcRadius, 2.0f, + startAngle, startAngle + maxSweep, + rotationRadScreen: 0f, + new VectorBlobKey(VectorShapeKind.ThermalHeatArc, 0, 0), + new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.40f)); + + if (heatRatio > 0.01f) + { + const int heatSteps = 135; // 2-degree increments across 270 deg + int step = Math.Clamp((int)MathF.Round(heatRatio * heatSteps), 1, heatSteps); + float sweep = maxSweep * (step / (float)heatSteps); + Color heatCol = overPlateau ? RedCol : (heatRatio > 0.65f ? OrangeCol : OliveCol); + _hbCanvas.DrawArcStrokeStatic( + center.X, center.Y, arcRadius, 2.5f, + startAngle, startAngle + sweep, + rotationRadScreen: 0f, + new VectorBlobKey(VectorShapeKind.ThermalHeatArc, (ushort)step, 1), + heatCol); + } + + // Directional incoming-hit indicator arcs (single cached static arc rotated per angle -> 0 dynamic atlas uploads) + if (_incomingArcCount > 0) + { + float cameraYaw = _getCameraYaw(); + float sinY = MathF.Sin(cameraYaw); + float cosY = MathF.Cos(cameraYaw); + for (int i = 0; i < _incomingArcCount; i++) + { + var arc = _incomingArcs[i]; + float alpha = Math.Clamp(1f - arc.Age / HitArcDuration, 0f, 1f); + if (alpha <= 0.01f) continue; + + float dx = arc.SourceX - player.X; + float dz = arc.SourceZ - player.Z; + float rx = -dx * cosY + dz * sinY; + float fy = dx * sinY + dz * cosY; + float angle = (rx * rx + fy * fy) > 1e-4f ? MathF.Atan2(-fy, rx) : 0f; + + Color arcCol = arc.WeaponClass switch + { + WeaponVisualClass.Explosive => new Color(1.0f, 0.36f, 0.12f, alpha * 0.96f), + WeaponVisualClass.RocketSalvo => new Color(1.0f, 0.56f, 0.14f, alpha * 0.96f), + WeaponVisualClass.ThermalBeam => new Color(0.30f, 0.90f, 1.0f, alpha * 0.96f), + WeaponVisualClass.GaussRail => new Color(0.24f, 0.78f, 1.0f, alpha * 0.98f), + WeaponVisualClass.PlasmaPpc => new Color(0.18f, 0.92f, 0.96f, alpha * 0.96f), + WeaponVisualClass.SwarmSmart => new Color(0.56f, 0.96f, 0.28f, alpha * 0.96f), + _ => new Color(0.96f, 0.72f, 0.22f, alpha * 0.94f) + }; + + const float hitR = 39f; + const float halfSpan = 0.34f; + _hbCanvas.DrawArcStrokeStatic( + center.X, center.Y, hitR, 4.2f, + -halfSpan, halfSpan, + rotationRadScreen: angle, + new VectorBlobKey(VectorShapeKind.IncomingHitArc, 0, 0), + arcCol); + if (arc.WeaponClass is WeaponVisualClass.ThermalBeam or WeaponVisualClass.GaussRail or WeaponVisualClass.PlasmaPpc) + { + _hbCanvas.DrawArcStrokeStatic( + center.X, center.Y, hitR - 3.5f, 2.0f, + -halfSpan * 0.75f, halfSpan * 0.75f, + rotationRadScreen: angle, + new VectorBlobKey(VectorShapeKind.IncomingHitArc, 1, 0), + new Color(GoldCol.R, GoldCol.G, GoldCol.B, alpha * 0.90f)); + } + + float cosA = MathF.Cos(angle); + float sinA = MathF.Sin(angle); + _hbCanvas.DrawDirectionalArrow(center.X + cosA * (hitR + 4.5f), center.Y + sinA * (hitR + 4.5f), 11f, angle, arcCol); + } + + var latest = _incomingArcs[_incomingArcCount - 1]; + float tagAlpha = Math.Clamp(1f - latest.Age / HitArcDuration, 0f, 1f); + (string tagText, Color tagCol) = latest.WeaponClass switch + { + WeaponVisualClass.Autocannon => ("20MM IMPACT", new Color(0.98f, 0.70f, 0.20f, tagAlpha)), + WeaponVisualClass.Explosive => ("BLAST IMPACT", new Color(1.0f, 0.38f, 0.14f, tagAlpha)), + WeaponVisualClass.RocketSalvo => ("ROCKET HIT", new Color(1.0f, 0.58f, 0.18f, tagAlpha)), + WeaponVisualClass.ThermalBeam => ("THERMAL HIT", new Color(0.36f, 0.92f, 1.0f, tagAlpha)), + WeaponVisualClass.GaussRail => ("GAUSS RAIL", new Color(0.28f, 0.84f, 1.0f, tagAlpha)), + WeaponVisualClass.PlasmaPpc => ("PLASMA BURN", new Color(0.24f, 0.94f, 0.98f, tagAlpha)), + WeaponVisualClass.SwarmSmart => ("SWARM HIT", new Color(0.58f, 0.96f, 0.30f, tagAlpha)), + _ => ("KINETIC HIT", new Color(0.96f, 0.78f, 0.28f, tagAlpha)) + }; + float tagW = _hbCanvas.MeasureTextWidth(tagText, 10.5f, wght: 600f); + _hbCanvas.DrawText(tagText, center.X - tagW * 0.5f, center.Y + 56f, 10.5f, tagCol, wght: 600f); + } + } + + // ------------------------------------------------------------------------- + // 4. Bottom-Left Panel: Schematic + Hover + Cargo + Garage + // ------------------------------------------------------------------------- + private void EmitBottomLeftPanel(ChassisGrid grid) + { + // Draw frame & borders ONLY (backdrop is _bottomLeftBg behind _schematic so inactive holes stay BgDark) + _hbCanvas.DrawPanelFrame(_bottomLeftRect, BgDark, BorderCol, OrangeCol, cornerLen: 12f, borderPx: 1.5f, drawBg: false); + + float leftX = _bottomLeftRect.Position.X + 10f; + float topY = _bottomLeftRect.Position.Y + 8f; + float gridW = _schematicRect.Size.X; + + _hbCanvas.DrawText("HARDPOINTS & HEAT", leftX, topY + 12f, 12f, OrangeCol, wght: 650f); + + // Hardpoint L-brackets, hull outlines, stripped X-marks, compatibility pulses, Krypton labels + _schematic.EmitHbGpuOverlay(_hbCanvas, _schematicRect.Position, _vignetteTime); + + // Hover telemetry beneath schematic + float hoverY = _schematicRect.End.Y + 4f; + for (int i = 0; i < _hoverLines.Count; i++) + { + _hbCanvas.DrawText(_hoverLines[i], leftX, hoverY + 11f, 10f, _cachedHoverColor, wght: 400f); + hoverY += 13.5f; + } + + // Middle column: Salvage Cargo Rack (0 dynamic Button nodes) + float cargoX = _schematicRect.End.X + 8f; + const float cargoW = 156f; + SpanWriter sw = new(_scratch); + sw.Append("SALVAGE CARGO ("); + sw.AppendInt(grid.Cargo.Count); + sw.Append("/"); + sw.AppendInt(grid.Spec.CargoCapacity); + sw.Append(")"); + _hbCanvas.DrawText(sw.Span, cargoX, topY + 11f, 11f, OliveCol, wght: 600f); + + float rowY = topY + 18f; + _cargoHitCount = 0; + if (grid.Cargo.Count == 0) + { + _hbCanvas.DrawText("No modules in rack.", cargoX, rowY + 11f, 10.5f, TextMuted, wght: 350f); + _hbCanvas.DrawText("Press [E] near crates.", cargoX, rowY + 24f, 10.5f, TextMuted, wght: 350f); + } + else + { + Viewport? vp = GetViewport(); + Vector2 mousePos = (vp is not null && Input.MouseMode == Input.MouseModeEnum.Visible) + ? vp.GetMousePosition() + : new Vector2(-9999f, -9999f); + + int count = Math.Min(grid.Cargo.Count, MaxCargoHitRects); + for (int i = 0; i < count; i++) + { + var mod = grid.Cargo[i]; + const float rowH = 19f; + const float fitW = 32f; + Rect2 rowRect = new(cargoX, rowY, cargoW - fitW - 3f, rowH); + Rect2 fitRect = new(cargoX + cargoW - fitW, rowY, fitW, rowH); + _cargoRowRects[i] = rowRect; + _cargoFitRects[i] = fitRect; + _cargoHitCount = i + 1; + + bool rowHovered = rowRect.HasPoint(mousePos); + bool fitHovered = fitRect.HasPoint(mousePos); + bool selected = _selectedCargoIndex == i; + + Color rowBg = selected ? new Color(0.24f, 0.18f, 0.10f, 0.92f) : (rowHovered ? BgRowHover : BgInner); + Color rowBorder = selected ? OrangeCol : (mod.IsImperial ? GoldCol : BorderCol); + _hbCanvas.DrawRectFilled(rowRect.Position.X, rowRect.Position.Y, rowRect.Size.X, rowRect.Size.Y, rowBg); + _hbCanvas.DrawRectOutline(rowRect.Position.X, rowRect.Position.Y, rowRect.Size.X, rowRect.Size.Y, 1.0f, rowBorder); + + Color txtCol = selected ? OrangeCol : (mod.IsImperial ? GoldCol : TextLight); + float nameX = rowRect.Position.X + 5f; + float maxTextW = rowRect.Size.X - 10f; + if (mod.IsImperial) + { + float starW = _hbCanvas.DrawText("* ", nameX, rowRect.Position.Y + 13f, 10f, GoldCol, wght: 700f); + nameX += starW; + maxTextW = MathF.Max(8f, maxTextW - starW); + } + ReadOnlySpan displayName = TruncateWithEllipsis(mod.Name, maxTextW, 10f, 450f, _scratch); + _hbCanvas.DrawText(displayName, nameX, rowRect.Position.Y + 13f, 10f, txtCol, wght: 450f); + + Color fitBg = fitHovered ? new Color(0.22f, 0.28f, 0.20f, 0.96f) : BgInner; + _hbCanvas.DrawRectFilled(fitRect.Position.X, fitRect.Position.Y, fitRect.Size.X, fitRect.Size.Y, fitBg); + _hbCanvas.DrawRectOutline(fitRect.Position.X, fitRect.Position.Y, fitRect.Size.X, fitRect.Size.Y, 1.0f, fitHovered ? OliveCol : BorderCol); + float fw = _hbCanvas.MeasureTextWidth("FIT", 9.5f, wght: 650f); + _hbCanvas.DrawText("FIT", fitRect.Position.X + (fitW - fw) * 0.5f, fitRect.Position.Y + 13f, 9.5f, fitHovered ? Colors.White : TextLight, wght: 650f); + + rowY += 21f; + } + } + + // Optional Garage Details column when Tab is expanded + if (_garageExpanded) + { + float garageX = cargoX + cargoW + 8f; + float gy = topY + 11f; + for (int i = 0; i < _garageLines.Count; i++) + { + _hbCanvas.DrawText(_garageLines[i], garageX, gy, 10f, i <= 1 ? OliveCol : TextMuted, wght: i <= 1 ? 550f : 380f); + gy += 13.5f; + } + } + } + + // ------------------------------------------------------------------------- + // 5. Broadcast Chyron & Outcome Banner + // ------------------------------------------------------------------------- + private void EmitChyronPanel() + { + _hbCanvas.DrawPanelFrame(_chyronRect, BgDark, BorderCol, GoldCol, cornerLen: 12f, borderPx: 1.5f); + + float x = _chyronRect.Position.X + 10f; + float y = _chyronRect.Position.Y + 8f; + _hbCanvas.DrawText("IMPERIAL BROADCAST FEED", x, y + 11f, 11f, GoldCol, wght: 650f); + y += 17f; + + HbGpuCommandWriter.PackClipRect( + _chyronRect.Position.X + 8f, _chyronRect.Position.Y + 6f, + _chyronRect.Size.X - 16f, _chyronRect.Size.Y - 12f, + out uint cMin, out uint cMax); + + for (int i = 0; i < _chyronLineCount; i++) + { + bool latest = _chyronIsLatest[i]; + _hbCanvas.DrawText( + _chyronDisplayLines[i], + x, y + 12f, + latest ? 11.5f : 10.8f, + latest ? TextLight : TextMuted, + wght: latest ? 500f : 380f, + clipMinPacked: cMin, + clipMaxPacked: cMax); + y += 19f; + } + } + + private void EmitOutcomeBanner( + IClientArenaSession session, + MatchState state, + ContenderState player, + NetworkStatusSnapshot net) + { + var outcome = session.LocalOutcome; + Color accent; + ReadOnlySpan title; + ReadOnlySpan sub; + + if (outcome == ClientMatchOutcome.Victory) + { + accent = OliveCol; + title = "VICTORY — LAST RIG STANDING"; + sub = net.Mode == NetworkMode.RemoteClient ? "Next round starting soon..." : "[R] New Drop"; + } + else if (outcome == ClientMatchOutcome.Defeat) + { + accent = RedCol; + title = !player.Alive ? "CHASSIS DESTROYED" : "MATCH COMPLETED — DEFEAT"; + sub = net.Mode == NetworkMode.RemoteClient + ? (state.Phase == MatchPhase.Completed ? "Waiting for server next round..." : "Spectating live match...") + : "[R] Redeploy"; + } + else + { + accent = CyanCol; + var wave = session.DropWaveState; + float eta = wave.NextWaveAtSec is float nxt ? MathF.Max(0f, nxt - state.Time) : 0f; + SpanWriter sw = new(_scratch); + sw.Append("AWAITING PATRON WAVE "); + sw.AppendInt(wave.NextWaveIndex); + _hbCanvas.DrawPanelFrame(_outcomeRect, BgDark, BorderCol, accent, cornerLen: 16f, borderPx: 2.0f); + float cx = _outcomeRect.Position.X + _outcomeRect.Size.X * 0.5f; + float w1 = _hbCanvas.MeasureTextWidth(sw.Span, 20f, wght: 700f); + _hbCanvas.DrawText(sw.Span, cx - w1 * 0.5f, _outcomeRect.Position.Y + 36f, 20f, accent, wght: 700f); + + sw = new SpanWriter(_scratch); + sw.Append("RESPAWN IN "); + sw.AppendFloat(eta, "F1"); + sw.Append("s (RESP: "); + sw.AppendInt(player.RespawnsRemaining); + sw.Append(" LEFT)"); + float w2 = _hbCanvas.MeasureTextWidth(sw.Span, 14f, wght: 500f); + _hbCanvas.DrawText(sw.Span, cx - w2 * 0.5f, _outcomeRect.Position.Y + 60f, 14f, accent, wght: 500f); + return; + } + + _hbCanvas.DrawPanelFrame(_outcomeRect, BgDark, BorderCol, accent, cornerLen: 16f, borderPx: 2.0f); + float centerX = _outcomeRect.Position.X + _outcomeRect.Size.X * 0.5f; + float tw1 = _hbCanvas.MeasureTextWidth(title, 20f, wght: 700f); + float tw2 = _hbCanvas.MeasureTextWidth(sub, 14f, wght: 500f); + _hbCanvas.DrawText(title, centerX - tw1 * 0.5f, _outcomeRect.Position.Y + 36f, 20f, accent, wght: 700f); + _hbCanvas.DrawText(sub, centerX - tw2 * 0.5f, _outcomeRect.Position.Y + 60f, 14f, accent, wght: 500f); + } + + // ------------------------------------------------------------------------- + // 6. 3D World Markers: Squad Chevrons + Target Boxes + Offscreen Arrows + // Preserves ALL Soul-verified invariants from 8310246 (0 GC allocs on hot path) + // ------------------------------------------------------------------------- + private void EmitWorldMarkers( + IClientArenaSession session, + MatchState state, + ContenderState localPlayer, + Vector2 viewSize) + { + if (_projectWorld is null || viewSize.X < 64f || viewSize.Y < 64f) + { + return; + } + + int localId = session.LocalContenderId; + if (localId < 0 || localId >= state.Contenders.Count || !localPlayer.Alive) + { + return; + } + + var (localPos, _, _) = session.GetInterpolatedContenderPose(localId, 1f); + Vector2 center = viewSize * 0.5f; + float halfW = MathF.Max(16f, center.X - BorderPad); + float halfH = MathF.Max(16f, center.Y - BorderPad); + + // 1. Allied squad chevrons (only when SquadSize > 1: Solo vs Trio mutual exclusion) + if (state.SquadSize > 1) + { + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (c.Id == localId || !c.Alive || !state.AreAllies(localId, c.Id)) continue; + + var (allyPos, _, _) = session.GetInterpolatedContenderPose(c.Id, 1f); + float dist = (allyPos - localPos).Length(); + float headOffset = c.IsInDropPod ? 3.4f : (c.Grid.Spec.HalfHeight + 1.9f); + var worldHead = new System.Numerics.Vector3(allyPos.X, allyPos.Y + headOffset, allyPos.Z); + var (valid, inFront, sp, camLocal) = _projectWorld(worldHead); + if (!valid) continue; + + bool inFrame = inFront && + sp.X >= BorderPad && sp.X <= viewSize.X - BorderPad && + sp.Y >= BorderPad && sp.Y <= viewSize.Y - BorderPad; + + SpanWriter sw = new(_scratch); + sw.Append(c.Name); + sw.Append(" "); + sw.AppendFloat(dist, "F0"); + sw.Append("m"); + ReadOnlySpan label = sw.Span; + + if (inFrame) + { + // Pointing down chevron above ally head (+PI/2 in screen coords) + _hbCanvas.DrawChevron(sp.X, sp.Y, 12f, MathF.PI * 0.5f, AlliedCol); + float lw = _hbCanvas.MeasureTextWidth(label, 10.5f, wght: 550f); + float lx = Math.Clamp(sp.X - lw * 0.5f, 6f, MathF.Max(6f, viewSize.X - lw - 6f)); + float ly = sp.Y - 10f; + var aboveBox = new Rect2(lx - 1f, ly - 11f, lw + 2f, 13f); + if (IntersectsStaticHudPanel(aboveBox) || aboveBox.Position.Y < 2f) + { + ly = sp.Y + 19f; + } + var finalBox = new Rect2(lx - 1f, ly - 11f, lw + 2f, 13f); + if (!IntersectsStaticHudPanel(finalBox)) + { + _hbCanvas.DrawText(label, lx, ly, 10.5f, AlliedCol, wght: 550f); + } + } + else + { + Vector2 dir = ComputeOffscreenDirection(camLocal); + Vector2 edge = ComputeSafeEdgePos(center, halfW, halfH, dir); + float angle = MathF.Atan2(dir.Y, dir.X); + _hbCanvas.DrawDirectionalArrow(edge.X, edge.Y, 13f, angle, new Color(AlliedCol.R, AlliedCol.G, AlliedCol.B, 0.88f)); + Vector2 textPos = ComputeInwardLabelPos(edge, dir, viewSize, label); + _hbCanvas.DrawText(label, textPos.X, textPos.Y, 10.5f, new Color(AlliedCol.R, AlliedCol.G, AlliedCol.B, 0.90f), wght: 550f); + } + } + } + + // 2. Visible enemy contenders (strictly obeying fog-of-war / LOS) + var contenderContacts = session.LocalContenderContacts; + var spectatorContacts = session.LocalSpectatorContacts; + _offscreenHostiles.Clear(); + + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (c.Id == localId || !c.Alive || state.AreAllies(localId, c.Id)) continue; + if (!session.IsContenderVisible(c.Id)) continue; + if (!contenderContacts.TryGetValue(c.Id, out var mem) || !mem.VisibleToPlayer) continue; + + var (pos, rot, _) = session.GetInterpolatedContenderPose(c.Id, 1f); + float dist = (pos - localPos).Length(); + bool targetingLocal = c.AiTargetContenderId == localId; + Color col = targetingLocal ? RedCol : OrangeCol; + float hpRatio = c.Grid.MaxCoreHp > 0f ? c.Grid.CoreHp / c.Grid.MaxCoreHp : 1f; + + float halfBoundW = c.IsInDropPod ? 1.4f : c.Grid.Spec.HalfWidth; + float halfBoundH = c.IsInDropPod ? 1.8f : c.Grid.Spec.HalfHeight; + float halfBoundL = c.IsInDropPod ? 1.4f : c.Grid.Spec.HalfLength; + + ProcessHostileTarget( + pos, rot, halfBoundW, halfBoundH, halfBoundL, + dist, hpRatio, col, targetingLocal, viewSize); + } + + // 3. Visible hostile/provoked spectators (neutral tourists do NOT get hostile target boxes) + var specs = state.Spectators.Spectators; + for (int i = 0; i < specs.Count; i++) + { + var s = specs[i]; + if (!s.Alive || s.Stance == SpectatorStance.Neutral) continue; + if (!session.IsSpectatorVisible(s.Id)) continue; + if (!spectatorContacts.TryGetValue(s.Id, out var mem) || !mem.VisibleToPlayer) continue; + + var (pos, rot, _) = session.GetInterpolatedSpectatorPose(s.Id, 1f); + float dist = (pos - localPos).Length(); + bool lockedOnLocal = s.TargetContenderId == localId; + float hpRatio = s.Grid.MaxCoreHp > 0f ? s.Grid.CoreHp / s.Grid.MaxCoreHp : 1f; + + ProcessHostileTarget( + pos, rot, s.Grid.Spec.HalfWidth, s.Grid.Spec.HalfHeight, s.Grid.Spec.HalfLength, + dist, hpRatio, RedCol, lockedOnLocal, viewSize); + } + + // 4. Off-screen hostile arrows (locked-on threats first, then nearest visible hostiles) + if (_offscreenHostiles.Count > 0) + { + _offscreenHostiles.Sort(OffscreenSortComparison); + int count = Math.Min(_offscreenHostiles.Count, MaxOffscreenHostileArrows); + for (int i = 0; i < count; i++) + { + EmitOffscreenArrow(_offscreenHostiles[i], viewSize, center, halfW, halfH); + } + } + } + + private void ProcessHostileTarget( + System.Numerics.Vector3 worldCenter, + System.Numerics.Quaternion rot, + float halfBoundW, + float halfBoundH, + float halfBoundL, + float dist, + float hpRatio, + Color col, + bool isLockedOnLocal, + Vector2 viewSize) + { + var (cValid, cInFront, cSp, cCamLocal) = _projectWorld!(worldCenter); + if (!cValid) return; + + bool inFrame = cInFront && + cSp.X >= BorderPad && cSp.X <= viewSize.X - BorderPad && + cSp.Y >= BorderPad && cSp.Y <= viewSize.Y - BorderPad; + + if (!inFrame) + { + if (isLockedOnLocal || dist <= OffscreenHostileMaxDistance) + { + _offscreenHostiles.Add(new OffscreenMarker(cCamLocal, dist, col, isLockedOnLocal)); + } + return; + } + + float minX = float.PositiveInfinity, minY = float.PositiveInfinity; + float maxX = float.NegativeInfinity, maxY = float.NegativeInfinity; + bool allCornersInFront = true; + + for (int sx = -1; sx <= 1; sx += 2) + { + for (int sy = -1; sy <= 1; sy += 2) + { + for (int sz = -1; sz <= 1; sz += 2) + { + var localCorner = new System.Numerics.Vector3(sx * halfBoundW, sy * halfBoundH, sz * halfBoundL); + var worldCorner = worldCenter + System.Numerics.Vector3.Transform(localCorner, rot); + var (valid, inFront, sp, _) = _projectWorld(worldCorner); + if (!valid || !inFront) + { + allCornersInFront = false; + break; + } + if (sp.X < minX) minX = sp.X; + if (sp.X > maxX) maxX = sp.X; + if (sp.Y < minY) minY = sp.Y; + if (sp.Y > maxY) maxY = sp.Y; + } + if (!allCornersInFront) break; + } + if (!allCornersInFront) break; + } + + if (!allCornersInFront) + { + var (topValid, topFront, topSp, _) = _projectWorld(worldCenter + new System.Numerics.Vector3(0f, halfBoundH, 0f)); + var (botValid, botFront, botSp, _) = _projectWorld(worldCenter - new System.Numerics.Vector3(0f, halfBoundH, 0f)); + float rawH = (topValid && topFront && botValid && botFront) + ? MathF.Abs(botSp.Y - topSp.Y) + 8f + : 44f; + float horizRadius = MathF.Max(halfBoundW, halfBoundL); + float rawW = rawH * (horizRadius / MathF.Max(0.4f, halfBoundH)); + minX = cSp.X - rawW * 0.5f; + maxX = cSp.X + rawW * 0.5f; + minY = cSp.Y - rawH * 0.5f; + maxY = cSp.Y + rawH * 0.5f; + } + else + { + minX -= 3f; + maxX += 3f; + minY -= 3f; + maxY += 3f; + } + + float boxW = Math.Clamp(maxX - minX, 22f, 220f); + float boxH = Math.Clamp(maxY - minY, 22f, 220f); + Vector2 boxCenter = new((minX + maxX) * 0.5f, (minY + maxY) * 0.5f); + var rect = new Rect2(boxCenter.X - boxW * 0.5f, boxCenter.Y - boxH * 0.5f, boxW, boxH); + + EmitTargetBox(rect, col, dist, hpRatio, isLockedOnLocal, viewSize); + } + + private void EmitTargetBox(Rect2 rect, Color col, float dist, float hpRatio, bool isLockedOnLocal, Vector2 viewSize) + { + float x0 = rect.Position.X; + float y0 = rect.Position.Y; + float x1 = x0 + rect.Size.X; + float y1 = y0 + rect.Size.Y; + float arm = Math.Clamp(MathF.Min(rect.Size.X, rect.Size.Y) * 0.22f, 5f, 26f); + + Color shadowCol = new(0.04f, 0.05f, 0.04f, 0.78f); + Color strokeCol = new(col.R, col.G, col.B, 0.95f); + + // Dark shadow pass then crisp target brackets across all 4 quadrants + _hbCanvas.DrawTargetBracketCorner(x0 - 0.8f, y0 - 0.8f, arm + 1.5f, 3.6f, 0, shadowCol); + _hbCanvas.DrawTargetBracketCorner(x1 + 0.8f, y0 - 0.8f, arm + 1.5f, 3.6f, 1, shadowCol); + _hbCanvas.DrawTargetBracketCorner(x1 + 0.8f, y1 + 0.8f, arm + 1.5f, 3.6f, 2, shadowCol); + _hbCanvas.DrawTargetBracketCorner(x0 - 0.8f, y1 + 0.8f, arm + 1.5f, 3.6f, 3, shadowCol); + + _hbCanvas.DrawTargetBracketCorner(x0, y0, arm, 2.0f, 0, strokeCol); + _hbCanvas.DrawTargetBracketCorner(x1, y0, arm, 2.0f, 1, strokeCol); + _hbCanvas.DrawTargetBracketCorner(x1, y1, arm, 2.0f, 2, strokeCol); + _hbCanvas.DrawTargetBracketCorner(x0, y1, arm, 2.0f, 3, strokeCol); + + // Format distance + LOCK tag + SpanWriter sw = new(_scratch); + sw.AppendFloat(dist, "F0"); + sw.Append("m"); + if (isLockedOnLocal) + { + sw.Append(" LOCK"); + } + ReadOnlySpan label = sw.Span; + float textW = _hbCanvas.MeasureTextWidth(label, 10.5f, wght: 600f); + + float barW = Math.Clamp(rect.Size.X, 22f, 64f); + float centerX = (x0 + x1) * 0.5f; + float barX = Math.Clamp(centerX - barW * 0.5f, 6f, MathF.Max(6f, viewSize.X - barW - 6f)); + float tx = Math.Clamp(centerX - textW * 0.5f, 6f, MathF.Max(6f, viewSize.X - textW - 6f)); + + // Prefer above-box; flip below-box if obstructed by static HUD panels (e.g. TopLeft/TopRight) or top edge + float aboveBarY = y0 - 7f; + float aboveTextY = aboveBarY - 3f; + Rect2 aboveBounds = MakeTagBounds(barX, aboveBarY, barW, tx, aboveTextY, textW, above: true); + + float belowBarY = y1 + 5f; + float belowTextY = belowBarY + 14f; + Rect2 belowBounds = MakeTagBounds(barX, belowBarY, barW, tx, belowTextY, textW, above: false); + + float chosenBarY; + float chosenTextY; + if (!IntersectsStaticHudPanel(aboveBounds) && aboveBounds.Position.Y >= 2f) + { + chosenBarY = aboveBarY; + chosenTextY = aboveTextY; + } + else if (!IntersectsStaticHudPanel(belowBounds) && belowBounds.End.Y <= viewSize.Y - 2f) + { + chosenBarY = belowBarY; + chosenTextY = belowTextY; + } + else + { + // Both top and bottom overlap static HUD panels: nudge horizontally out of top corner panels if possible, else omit unobstructed tag + float nudgedTx = tx; + float nudgedBarX = barX; + if (aboveBounds.Intersects(_topLeftRect)) + { + float shift = _topLeftRect.End.X + 8f - MathF.Min(tx, barX); + if (shift > 0f && MathF.Max(tx + textW, barX + barW) + shift < _topRightRect.Position.X - 8f) + { + nudgedTx += shift; + nudgedBarX += shift; + } + } + else if (aboveBounds.Intersects(_topRightRect)) + { + float shift = MathF.Max(tx + textW, barX + barW) - (_topRightRect.Position.X - 8f); + if (shift > 0f && MathF.Min(tx, barX) - shift > _topLeftRect.End.X + 8f) + { + nudgedTx -= shift; + nudgedBarX -= shift; + } + } + + Rect2 nudgedBounds = MakeTagBounds(nudgedBarX, aboveBarY, barW, nudgedTx, aboveTextY, textW, above: true); + if (!IntersectsStaticHudPanel(nudgedBounds) && nudgedBounds.Position.Y >= 2f) + { + barX = nudgedBarX; + tx = nudgedTx; + chosenBarY = aboveBarY; + chosenTextY = aboveTextY; + } + else + { + return; + } + } + + _hbCanvas.DrawRectFilled(barX - 1f, chosenBarY - 1f, barW + 2f, 4f, shadowCol); + _hbCanvas.DrawRectFilled(barX, chosenBarY, barW * Math.Clamp(hpRatio, 0f, 1f), 2f, strokeCol); + + _hbCanvas.DrawText(label, tx + 1f, chosenTextY + 1f, 10.5f, ShadowCol, wght: 600f); + _hbCanvas.DrawText(label, tx, chosenTextY, 10.5f, strokeCol, wght: 600f); + } + + private static Rect2 MakeTagBounds(float barX, float barY, float barW, float tx, float ty, float textW, bool above) + { + float left = MathF.Min(barX - 1f, tx - 1f); + float right = MathF.Max(barX + barW + 1f, tx + textW + 1f); + if (above) + { + float top = ty - 11f; + float bottom = barY + 3f; + return new Rect2(left, top, right - left, bottom - top); + } + else + { + float top = barY - 1f; + float bottom = ty + 3f; + return new Rect2(left, top, right - left, bottom - top); + } + } + + private bool IntersectsStaticHudPanel(Rect2 rect) + { + return rect.Intersects(_topLeftRect) + || rect.Intersects(_topRightRect) + || rect.Intersects(_bottomLeftRect) + || rect.Intersects(_chyronRect); + } + + private void EmitOffscreenArrow(OffscreenMarker m, Vector2 viewSize, Vector2 center, float halfW, float halfH) + { + Vector2 dir = ComputeOffscreenDirection(m.CamLocal); + Vector2 edge = ComputeSafeEdgePos(center, halfW, halfH, dir); + float angle = MathF.Atan2(dir.Y, dir.X); + + _hbCanvas.DrawDirectionalArrow(edge.X, edge.Y, 18f, angle, new Color(0.04f, 0.05f, 0.04f, 0.74f)); + Color arrowCol = new(m.Color.R, m.Color.G, m.Color.B, 0.94f); + _hbCanvas.DrawDirectionalArrow(edge.X, edge.Y, 14.5f, angle, arrowCol); + + SpanWriter sw = new(_scratch); + sw.AppendFloat(m.Distance, "F0"); + sw.Append("m"); + if (m.IsLockedOnLocal) + { + sw.Append(" !"); + } + ReadOnlySpan label = sw.Span; + Vector2 textPos = ComputeInwardLabelPos(edge, dir, viewSize, label); + _hbCanvas.DrawText(label, textPos.X + 1f, textPos.Y + 1f, 10.5f, ShadowCol, wght: 600f); + _hbCanvas.DrawText(label, textPos.X, textPos.Y, 10.5f, arrowCol, wght: 600f); + } + + private static Vector2 ComputeOffscreenDirection(System.Numerics.Vector3 camLocal) + { + if (!float.IsFinite(camLocal.X) || !float.IsFinite(camLocal.Y) || !float.IsFinite(camLocal.Z)) + { + return Vector2.Down; + } + + Vector2 dir; + if (camLocal.Z >= 0f) + { + dir = new Vector2(camLocal.X, -camLocal.Y); + } + else + { + float horiz = MathF.Sqrt(camLocal.X * camLocal.X + camLocal.Z * camLocal.Z); + float t = Math.Clamp(-camLocal.Z / MathF.Max(1e-4f, horiz * 0.35f), 0f, 1f); + Vector2 sideDir = new(camLocal.X, -camLocal.Y); + Vector2 behindArcDir = new(camLocal.X, MathF.Max(-camLocal.Z, 0.35f * horiz)); + dir = sideDir.Lerp(behindArcDir, t); + if (MathF.Abs(camLocal.X) < 0.35f * horiz) + { + float minDown = 0.25f * dir.Length(); + if (dir.Y < minDown) + { + dir.Y = MathF.Max(minDown, 0.25f); + } + } + } + + float lenSq = dir.LengthSquared(); + if (!float.IsFinite(lenSq) || lenSq < 1e-6f) + { + return camLocal.Z < 0f ? Vector2.Down : Vector2.Up; + } + return dir / MathF.Sqrt(lenSq); + } + + private Vector2 ComputeSafeEdgePos(Vector2 center, float halfW, float halfH, Vector2 dir) + { + float tx = MathF.Abs(dir.X) > 1e-4f ? halfW / MathF.Abs(dir.X) : float.PositiveInfinity; + float ty = MathF.Abs(dir.Y) > 1e-4f ? halfH / MathF.Abs(dir.Y) : float.PositiveInfinity; + float tBest = MathF.Min(tx, ty); + + Span avoid = stackalloc Rect2[4] + { + _topLeftRect, + _topRightRect, + _bottomLeftRect, + _chyronRect + }; + for (int i = 0; i < avoid.Length; i++) + { + Rect2 r = avoid[i].Grow(PanelAvoidPad); + if (r.HasPoint(center)) continue; + if (TryRayEnterRect(center, dir, r, out float tEnter) && tEnter > 24f && tEnter < tBest) + { + tBest = tEnter; + } + } + + tBest = MathF.Max(24f, tBest); + return center + dir * tBest; + } + + private static bool TryRayEnterRect(Vector2 origin, Vector2 dir, Rect2 r, out float tEnter) + { + float tMin = 0f; + float tMax = float.PositiveInfinity; + + if (MathF.Abs(dir.X) < 1e-5f) + { + if (origin.X < r.Position.X || origin.X > r.End.X) + { + tEnter = 0f; + return false; + } + } + else + { + float invX = 1f / dir.X; + float t1 = (r.Position.X - origin.X) * invX; + float t2 = (r.End.X - origin.X) * invX; + if (t1 > t2) (t1, t2) = (t2, t1); + tMin = MathF.Max(tMin, t1); + tMax = MathF.Min(tMax, t2); + if (tMin > tMax) + { + tEnter = 0f; + return false; + } + } + + if (MathF.Abs(dir.Y) < 1e-5f) + { + if (origin.Y < r.Position.Y || origin.Y > r.End.Y) + { + tEnter = 0f; + return false; + } + } + else + { + float invY = 1f / dir.Y; + float t1 = (r.Position.Y - origin.Y) * invY; + float t2 = (r.End.Y - origin.Y) * invY; + if (t1 > t2) (t1, t2) = (t2, t1); + tMin = MathF.Max(tMin, t1); + tMax = MathF.Min(tMax, t2); + if (tMin > tMax) + { + tEnter = 0f; + return false; + } + } + + tEnter = tMin; + return true; + } + + private Vector2 ComputeInwardLabelPos(Vector2 edge, Vector2 dir, Vector2 viewSize, ReadOnlySpan label) + { + float w = _hbCanvas.MeasureTextWidth(label, 10.5f, wght: 600f); + const float h = 11f; + Vector2 inward = edge - dir * 14f; + float textX; + float textY; + + if (MathF.Abs(dir.X) >= MathF.Abs(dir.Y)) + { + textX = dir.X > 0f ? (inward.X - w - 4f) : (inward.X + 6f); + textY = inward.Y + h * 0.3f; + } + else + { + textX = inward.X - w * 0.5f; + textY = dir.Y > 0f ? (inward.Y - 4f) : (inward.Y + h + 4f); + } + + return new Vector2( + Math.Clamp(textX, 10f, MathF.Max(10f, viewSize.X - w - 10f)), + Math.Clamp(textY, 16f, MathF.Max(16f, viewSize.Y - 10f))); + } + + // ------------------------------------------------------------------------- + // Cached Text Helpers (Rebuild ONLY on state delta -> 0 B/frame steady state) + // ------------------------------------------------------------------------- + private void UpdatePromptCache(MatchState state, ContenderState player, OrbitalPod? localPod) + { + if (player.IsInDropPod) + { + int aglR = localPod is not null + ? Mathf.RoundToInt(MathF.Max(0f, localPod.LastAgl)) + : Mathf.RoundToInt(MathF.Max(0f, player.Y - state.Terrain.SampleHeight(player.X, player.Z))); + int velR = localPod is not null + ? Mathf.RoundToInt(MathF.Max(0f, -localPod.VelY)) + : Mathf.RoundToInt(MathF.Max(0f, -player.VelY)); + int horR = localPod is not null + ? Mathf.RoundToInt(MathF.Sqrt(localPod.VelX * localPod.VelX + localPod.VelZ * localPod.VelZ)) + : Mathf.RoundToInt(player.Speed); + bool burn = localPod?.Phase == OrbitalPodPhase.RetroBurn; + + if (_lastPromptPod && aglR == _lastPodAglRounded && horR == _lastPodHorizRounded && velR == _lastPodVertRounded && burn == _lastPodBurn) + { + return; + } + _lastPromptPod = true; + _lastPodAglRounded = aglR; + _lastPodHorizRounded = horR; + _lastPodVertRounded = velR; + _lastPodBurn = burn; + + _cachedPromptText = $"ORBITAL INSERTION — ALT {aglR}m | HORIZ {horR} m/s | VERT {velR} m/s | [WASD] STEER" + + (burn ? " [RETRO BURN]" : ""); + WrapTextInto(_cachedPromptText, 344f, 12f, 550f, _promptLines); + return; + } + + _lastPromptPod = false; + GroundDrop? nearest = state.FindNearestInteractableDrop(player.Id); + int promptKey = nearest is null + ? -1 + : HashCode.Combine( + nearest.Id, + nearest.Module?.Id ?? string.Empty, + nearest.Chassis?.Id ?? string.Empty, + nearest.Module is { } m ? (player.Grid.FindFirstEmptyCompatibleHardpoint(m)?.Id ?? string.Empty) : string.Empty); + + if (promptKey == _lastPromptKey) + { + return; + } + _lastPromptKey = promptKey; + + _cachedPromptText = BuildInteractionPrompt(player, nearest); + if (string.IsNullOrEmpty(_cachedPromptText)) + { + _promptLines.Clear(); + } + else + { + WrapTextInto(_cachedPromptText, 344f, 12f, 550f, _promptLines); + } + } + + private static string BuildInteractionPrompt(ContenderState player, GroundDrop? nearest) + { + if (nearest is null) return string.Empty; + if (nearest.Module is { } mod) + { + var freeHp = player.Grid.FindFirstEmptyCompatibleHardpoint(mod); + if (mod.Procedural is { } proc) + { + string action = freeHp is not null + ? $"[E] Bolt [{proc.ManufacturerLabel}] {mod.Name} -> {freeHp.Id}" + : $"[E] Loot [{proc.ManufacturerLabel}] {mod.Name}"; + return $"{action}\n{proc.SummaryLine1} | {proc.SummaryLine2}"; + } + return freeHp is not null + ? $"[E] Bolt {(mod.IsImperial ? "IMPERIAL " : "")}{mod.Name} -> {freeHp.Id}" + : $"[E] Loot {(mod.IsImperial ? "IMPERIAL " : "")}{mod.Name}"; + } + if (nearest.Chassis is { } ch) + { + return $"[E] Swap to {ch.Name} ({ch.Plane})"; + } + return string.Empty; + } + + private void UpdateHintCache(ContenderState player) + { + int mode = player.IsInDropPod ? 0 : (player.Grid.Spec.IsVtol ? 1 : 2); + if (mode == _lastHintMode && _hintLines.Count > 0) + { + return; + } + _lastHintMode = mode; + + string hint = mode switch + { + 0 => "WASD Steer Pod | Mouse Look | Retro-Burn Auto | Wheel Zoom", + 1 => "WASD Fly | Space/C Alt | Mouse Aim | LMB Fire | E Bolt | Tab Garage | M Map | F9 Net", + _ => "WASD Drive | Mouse Aim | LMB Fire | E Bolt | Tab Garage | M Map | F9 Net | Wheel Zoom" + }; + WrapTextInto(hint, 376f, 10.0f, 350f, _hintLines); + } + + private ReadOnlySpan TruncateWithEllipsis(string text, float maxWidthPx, float fontSizePx, float wght, char[] scratch) + { + if (string.IsNullOrEmpty(text) || _hbCanvas is null || _hbCanvas.MeasureTextWidth(text, fontSizePx, wght: wght) <= maxWidthPx) + { + return text; + } + + const string ellipsis = "..."; + int maxCopy = Math.Min(text.Length, scratch.Length - ellipsis.Length); + int bestLen = 0; + for (int len = 1; len <= maxCopy; len++) + { + scratch[len - 1] = text[len - 1]; + scratch[len] = '.'; + scratch[len + 1] = '.'; + scratch[len + 2] = '.'; + if (_hbCanvas.MeasureTextWidth(scratch.AsSpan(0, len + 3), fontSizePx, wght: wght) > maxWidthPx) + { + break; + } + bestLen = len; + } + for (int i = 0; i < bestLen; i++) + { + scratch[i] = text[i]; + } + scratch[bestLen] = '.'; + scratch[bestLen + 1] = '.'; + scratch[bestLen + 2] = '.'; + return scratch.AsSpan(0, bestLen + 3); + } + + private void SyncBroadcastChyron(BroadcastFeed broadcast) + { + var lines = broadcast.Lines; + if (ReferenceEquals(_lastBroadcastFeed, broadcast) && broadcast.Version == _lastChyronVersion) + { + return; + } + + _lastBroadcastFeed = broadcast; + _lastChyronVersion = broadcast.Version; + + // Evict by whole message from newest backwards so partial tail fragments of evicted messages never appear + int capacity = _chyronDisplayLines.Length; + int remaining = capacity; + int writeBack = capacity; + for (int m = lines.Count - 1; m >= 0 && remaining > 0; m--) + { + var line = lines[m]; + bool isLatestMsg = m == lines.Count - 1; + string formatted = $"[{line.Timestamp:00.0}s] {line.Text}"; + WrapTextInto(formatted, 548f, isLatestMsg ? 11.5f : 10.8f, isLatestMsg ? 500f : 380f, _chyronWrapScratch); + + int msgLineCount = _chyronWrapScratch.Count; + if (msgLineCount == 0) + { + continue; + } + + if (isLatestMsg && msgLineCount > remaining) + { + int skip = msgLineCount - remaining; + for (int w = msgLineCount - 1; w >= skip; w--) + { + writeBack--; + _chyronDisplayLines[writeBack] = _chyronWrapScratch[w]; + _chyronIsLatest[writeBack] = true; + } + remaining = 0; + break; + } + + if (msgLineCount > remaining) + { + // Whole-message eviction: stop before emitting a partial tail of an older message + break; + } + + for (int w = msgLineCount - 1; w >= 0; w--) + { + writeBack--; + _chyronDisplayLines[writeBack] = _chyronWrapScratch[w]; + _chyronIsLatest[writeBack] = isLatestMsg; + } + remaining -= msgLineCount; + } + + int total = capacity - writeBack; + if (writeBack > 0 && total > 0) + { + for (int i = 0; i < total; i++) + { + _chyronDisplayLines[i] = _chyronDisplayLines[writeBack + i]; + _chyronIsLatest[i] = _chyronIsLatest[writeBack + i]; + } + } + _chyronLineCount = total; + } + + private void OnHardpointClicked(string hardpointId) + { + var session = _getSession(); + if (session is null) return; + var cargo = session.LocalContender.Grid.Cargo; + if (_selectedCargoIndex >= 0 && _selectedCargoIndex < cargo.Count) + { + _onEquipCargo(_selectedCargoIndex, hardpointId); + _selectedCargoIndex = -1; + _lastGarageHash = int.MinValue; + _dirtyEmit = true; + } + } + + private void AutoFitCargo(ChassisGrid grid, int cargoIndex) + { + if (cargoIndex < 0 || cargoIndex >= grid.Cargo.Count) return; + var mod = grid.Cargo[cargoIndex]; + for (int i = 0; i < grid.Spec.Hardpoints.Length; i++) + { + var hp = grid.Spec.Hardpoints[i]; + if (ChassisGrid.CanFit(hp, mod)) + { + _onEquipCargo(cargoIndex, hp.Id); + _selectedCargoIndex = -1; + _lastGarageHash = int.MinValue; + _dirtyEmit = true; + return; + } + } + } + + private void OnSchematicHoverChanged(Vector2I? cell, HardpointSpec? hp) + { + _lastHoveredCell = cell; + var grid = _schematic.Grid; + if (cell is null || grid is null) + { + if (!UpdateCargoSelectionTooltip(grid)) + { + SetHoverText("HOVER CELL FOR TELEMETRY", TextMuted); + } + return; + } + + var c = cell.Value; + float arm = grid.Armor[c.X, c.Y]; + float maxArm = grid.MaxArmor[c.X, c.Y]; + float temp = grid.Temperature[c.X, c.Y]; + if (hp is not null) + { + var mounted = grid.GetMountedOn(hp.Id); + bool strippedHp = !grid.IsHardpointOperational(hp); + string hpStatus = strippedHp ? " [STRIPPED]" : ""; + if (mounted is not null && mounted.Spec.Procedural is { } proc) + { + SetHoverText( + $"[{proc.ManufacturerLabel}] {proc.SummaryLine1}{hpStatus}\n{proc.SummaryLine2}", + (arm <= 0.01f || strippedHp) ? RedCol : ResolveManufacturerHudColor(proc.Manufacturer)); + } + else + { + string txt = mounted is not null + ? $"{hp.Kind.ToString().ToUpperInvariant()}: {mounted.Spec.Name} {mounted.CurrentTemp:F0}°C ({mounted.CurrentPerformance * 100f:F0}%){hpStatus}" + : $"{hp.Kind.ToString().ToUpperInvariant()} SLOT [{hp.Width}x{hp.Height}] EMPTY{hpStatus}"; + SetHoverText(txt, (arm <= 0.01f || strippedHp) ? RedCol : TextLight); + } + } + else + { + string txt = arm <= 0.01f + ? $"CELL ({c.X},{c.Y}) STRIPPED! {temp:F0}°C" + : $"HULL ({c.X},{c.Y}) ARM {arm:F0}/{maxArm:F0} {temp:F0}°C"; + SetHoverText(txt, arm <= 0.01f ? RedCol : TextMuted); + } + } + + private bool UpdateCargoSelectionTooltip(ChassisGrid? grid) + { + if (grid is null || _selectedCargoIndex < 0 || _selectedCargoIndex >= grid.Cargo.Count) + { + return false; + } + var mod = grid.Cargo[_selectedCargoIndex]; + if (mod.Procedural is { } proc) + { + SetHoverText($"[{proc.ManufacturerLabel}] {proc.SummaryLine1}\n{proc.SummaryLine2}", ResolveManufacturerHudColor(proc.Manufacturer)); + } + else + { + SetHoverText($"CARGO: {mod.Name} [{mod.Width}x{mod.Height}]", mod.IsImperial ? GoldCol : TextLight); + } + return true; + } + + private void SetHoverText(string text, Color color) + { + if (string.Equals(_cachedHoverText, text, StringComparison.Ordinal) && _cachedHoverColor == color) + { + return; + } + _cachedHoverText = text; + _cachedHoverColor = color; + float maxW = _garageExpanded ? 198f : 180f; + WrapTextInto(text, maxW, 10f, 400f, _hoverLines); + _dirtyEmit = true; + } + + private void UpdateGarageDetailsCache(ChassisGrid grid) + { + var hc = new HashCode(); + hc.Add(grid.Spec.Id); + hc.Add(grid.Mounted.Count); + hc.Add(_selectedCargoIndex); + if (_selectedCargoIndex >= 0 && _selectedCargoIndex < grid.Cargo.Count) + { + hc.Add(grid.Cargo[_selectedCargoIndex].Id); + } + for (int i = 0; i < grid.Mounted.Count; i++) + { + var m = grid.Mounted[i]; + hc.Add(m.HardpointId); + hc.Add(m.Spec.Id); + hc.Add(Mathf.RoundToInt(m.CurrentTemp)); + hc.Add(grid.IsHardpointOperational(m.HardpointId)); + } + int sig = hc.ToHashCode(); + if (sig == _lastGarageHash) + { + return; + } + _lastGarageHash = sig; + + _garageLines.Clear(); + var rawLines = new List(16) + { + $"COND {grid.Spec.HullConductivity:F1} | THRUST {grid.ComputeDriveThrust():F0} N", + "MOUNTED:" + }; + _garageLines.Add(rawLines[0]); + _garageLines.Add(rawLines[1]); + for (int i = 0; i < grid.Mounted.Count; i++) + { + var m = grid.Mounted[i]; + string stateTag = grid.IsHardpointOperational(m.HardpointId) ? "" : " [STRIPPED]"; + if (m.Spec.Procedural is { } proc) + { + string l0 = $"• [{proc.ManufacturerLabel}] {m.Spec.Name} {m.CurrentTemp:F0}°C{stateTag}"; + rawLines.Add(l0); + rawLines.Add($" {proc.SummaryLine1}"); + rawLines.Add($" {proc.SummaryLine2}"); + WrapTextInto(l0, 184f, 10f, 400f, _garageLines, clearDest: false); + WrapTextInto($" {proc.SummaryLine1}", 184f, 10f, 400f, _garageLines, clearDest: false); + WrapTextInto($" {proc.SummaryLine2}", 184f, 10f, 400f, _garageLines, clearDest: false); + } + else + { + string l0 = $"• {m.HardpointId}: {m.Spec.Name} {m.CurrentTemp:F0}°C ({m.CurrentPerformance * 100f:F0}%){stateTag}"; + rawLines.Add(l0); + WrapTextInto(l0, 184f, 10f, 400f, _garageLines, clearDest: false); + } + } + if (_selectedCargoIndex >= 0 && _selectedCargoIndex < grid.Cargo.Count && + grid.Cargo[_selectedCargoIndex].Procedural is { } cargoProc) + { + string l0 = $"SEL [{cargoProc.ManufacturerLabel}]:"; + rawLines.Add(l0); + rawLines.Add($" {cargoProc.SummaryLine1}"); + rawLines.Add($" {cargoProc.SummaryLine2}"); + _garageLines.Add(l0); + WrapTextInto($" {cargoProc.SummaryLine1}", 184f, 10f, 400f, _garageLines, clearDest: false); + WrapTextInto($" {cargoProc.SummaryLine2}", 184f, 10f, 400f, _garageLines, clearDest: false); + } + _cachedGarageDetails = string.Join("\n", rawLines); + } + + private void WrapTextInto(string text, float maxWidthPx, float fontSizePx, float wght, List dest, bool clearDest = true) + { + if (clearDest) + { + dest.Clear(); + } + if (string.IsNullOrEmpty(text)) + { + return; + } + + int lineStart = 0; + for (int idx = 0; idx <= text.Length; idx++) + { + if (idx == text.Length || text[idx] == '\n') + { + WrapParagraph(text.AsSpan(lineStart, idx - lineStart), maxWidthPx, fontSizePx, wght, dest); + lineStart = idx + 1; + } + } + } + + private void WrapParagraph(ReadOnlySpan para, float maxWidthPx, float fontSizePx, float wght, List dest) + { + if (para.IsEmpty) + { + dest.Add(string.Empty); + return; + } + + if (_hbCanvas is null || _hbCanvas.MeasureTextWidth(para, fontSizePx, wght: wght) <= maxWidthPx) + { + dest.Add(new string(para)); + return; + } + + int pos = 0; + while (pos < para.Length) + { + int bestEnd = pos + 1; + int lastSpace = -1; + for (int end = pos + 1; end <= para.Length; end++) + { + if (end < para.Length && para[end] == ' ') + { + lastSpace = end; + } + float w = _hbCanvas.MeasureTextWidth(para.Slice(pos, end - pos), fontSizePx, wght: wght); + if (w > maxWidthPx) + { + break; + } + bestEnd = end; + } + + int cut = (bestEnd < para.Length && lastSpace > pos) ? lastSpace : bestEnd; + dest.Add(new string(para.Slice(pos, cut - pos))); + pos = cut; + while (pos < para.Length && para[pos] == ' ') + { + pos++; + } + } + } + + private static Color ResolveManufacturerHudColor(ManufacturerId mfg) => mfg switch + { + ManufacturerId.ScrapFrontier => Color.FromHtml("#ffaa33"), + ManufacturerId.KorrathiIronworks => Color.FromHtml("#f2c422"), + ManufacturerId.AuralianOptics => Color.FromHtml("#38e8ff"), + ManufacturerId.VexNineCollective => Color.FromHtml("#7cf230"), + ManufacturerId.ThalassanForge => Color.FromHtml("#2cb8ff"), + _ => GoldCol + }; + + // ------------------------------------------------------------------------- + // [F9] Interactive Multiplayer Link Panel (Godot Controls kept until Cut 14c) + // ------------------------------------------------------------------------- private void BuildNetworkPanel() { - _netPanel = CreateStyledPanel(CyanCol, cornerLen: 14f, borderPx: 1.5f); + var panelStyle = new StyleBoxFlat + { + BgColor = new Color(0f, 0f, 0f, 0f), + BorderColor = new Color(0f, 0f, 0f, 0f), + ContentMarginLeft = 10, + ContentMarginRight = 10, + ContentMarginTop = 8, + ContentMarginBottom = 8 + }; + panelStyle.SetBorderWidthAll(0); + + _netPanel = new PanelContainer + { + Name = "NetworkLinkPanel", + Visible = false + }; + _netPanel.AddThemeStyleboxOverride("panel", panelStyle); _netPanel.AnchorLeft = 0.5f; _netPanel.AnchorRight = 0.5f; _netPanel.AnchorTop = 0.32f; @@ -843,7 +2670,6 @@ public partial class Hud : CanvasLayer _netPanel.OffsetRight = 188f; _netPanel.OffsetTop = 0f; _netPanel.OffsetBottom = 0f; - _netPanel.Visible = false; AddChild(_netPanel); var vbox = new VBoxContainer(); @@ -1011,888 +2837,43 @@ public partial class Hud : CanvasLayer return fallback; } - private void OnHardpointClicked(string hardpointId) + private ref struct SpanWriter { - var session = _getSession(); - if (session is null) return; - var cargo = session.LocalContender.Grid.Cargo; - if (_selectedCargoIndex >= 0 && _selectedCargoIndex < cargo.Count) - { - _onEquipCargo(_selectedCargoIndex, hardpointId); - _selectedCargoIndex = -1; - _lastCargoHash = -1; - } - } + private readonly char[] _buf; + private int _pos; - private void OnSchematicHoverChanged(Vector2I? cell, HardpointSpec? hp) - { - _lastHoveredCell = cell; - var grid = _schematic.Grid; - if (cell is null || grid is null) + public SpanWriter(char[] buf) { - if (!UpdateCargoSelectionTooltip(grid)) + _buf = buf; + _pos = 0; + } + + public readonly ReadOnlySpan Span => _buf.AsSpan(0, _pos); + + public void Append(ReadOnlySpan s) + { + int copy = Math.Min(s.Length, _buf.Length - _pos); + if (copy > 0) { - _hoverLabel.Text = "HOVER CELL FOR TELEMETRY"; - _hoverLabel.AddThemeColorOverride("font_color", TextMuted); - } - return; - } - - var c = cell.Value; - float arm = grid.Armor[c.X, c.Y]; - float maxArm = grid.MaxArmor[c.X, c.Y]; - float temp = grid.Temperature[c.X, c.Y]; - if (hp is not null) - { - var mounted = grid.GetMountedOn(hp.Id); - bool strippedHp = !grid.IsHardpointOperational(hp); - string hpStatus = strippedHp ? " [STRIPPED]" : ""; - if (mounted is not null && mounted.Spec.Procedural is { } proc) - { - _hoverLabel.Text = $"[{proc.ManufacturerLabel}] {proc.SummaryLine1}{hpStatus}\n{proc.SummaryLine2}"; - _hoverLabel.AddThemeColorOverride("font_color", - (arm <= 0.01f || strippedHp) ? RedCol : ResolveManufacturerHudColor(proc.Manufacturer)); - } - else - { - _hoverLabel.Text = mounted is not null - ? $"{hp.Kind.ToString().ToUpperInvariant()}: {mounted.Spec.Name} {mounted.CurrentTemp:F0}°C ({mounted.CurrentPerformance * 100f:F0}%){hpStatus}" - : $"{hp.Kind.ToString().ToUpperInvariant()} SLOT [{hp.Width}x{hp.Height}] EMPTY{hpStatus}"; - _hoverLabel.AddThemeColorOverride("font_color", (arm <= 0.01f || strippedHp) ? RedCol : TextLight); - } - } - else - { - _hoverLabel.Text = arm <= 0.01f - ? $"CELL ({c.X},{c.Y}) STRIPPED! {temp:F0}°C" - : $"HULL ({c.X},{c.Y}) ARM {arm:F0}/{maxArm:F0} {temp:F0}°C"; - _hoverLabel.AddThemeColorOverride("font_color", arm <= 0.01f ? RedCol : TextMuted); - } - } - - private bool UpdateCargoSelectionTooltip(ChassisGrid? grid) - { - if (grid is null || _selectedCargoIndex < 0 || _selectedCargoIndex >= grid.Cargo.Count) - { - return false; - } - var mod = grid.Cargo[_selectedCargoIndex]; - if (mod.Procedural is { } proc) - { - _hoverLabel.Text = $"[{proc.ManufacturerLabel}] {proc.SummaryLine1}\n{proc.SummaryLine2}"; - _hoverLabel.AddThemeColorOverride("font_color", ResolveManufacturerHudColor(proc.Manufacturer)); - } - else - { - _hoverLabel.Text = $"CARGO: {mod.Name} [{mod.Width}x{mod.Height}]"; - _hoverLabel.AddThemeColorOverride("font_color", mod.IsImperial ? GoldCol : TextLight); - } - return true; - } - - private static Color ResolveManufacturerHudColor(ManufacturerId mfg) => mfg switch - { - ManufacturerId.ScrapFrontier => Color.FromHtml("#ffaa33"), - ManufacturerId.KorrathiIronworks => Color.FromHtml("#f2c422"), - ManufacturerId.AuralianOptics => Color.FromHtml("#38e8ff"), - ManufacturerId.VexNineCollective => Color.FromHtml("#7cf230"), - ManufacturerId.ThalassanForge => Color.FromHtml("#2cb8ff"), - _ => GoldCol - }; - - private void SyncCargoButtons(ChassisGrid grid) - { - int hash = HashCode.Combine(grid.Cargo.Count, grid.Spec.CargoCapacity, _selectedCargoIndex); - for (int i = 0; i < grid.Cargo.Count; i++) - { - hash = HashCode.Combine(hash, grid.Cargo[i].Id); - } - if (hash == _lastCargoHash) return; - _lastCargoHash = hash; - - _cargoHeader.Text = $"SALVAGE CARGO ({grid.Cargo.Count}/{grid.Spec.CargoCapacity})"; - for (int i = _cargoList.GetChildCount() - 1; i >= 0; i--) - { - var c = _cargoList.GetChild(i); - _cargoList.RemoveChild(c); - c.QueueFree(); - } - - if (grid.Cargo.Count == 0) - { - var empty = new Label { Text = "No modules in rack.\nPress [E] near crates." }; - empty.AddThemeColorOverride("font_color", TextMuted); - empty.AddThemeFontSizeOverride("font_size", 11); - _cargoList.AddChild(empty); - return; - } - - for (int i = 0; i < grid.Cargo.Count; i++) - { - int idx = i; - var mod = grid.Cargo[i]; - var row = new HBoxContainer(); - row.AddThemeConstantOverride("separation", 4); - - var selectBtn = new Button - { - Text = $"{(mod.IsImperial ? "★ " : "")}{mod.Name}", - SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, - Alignment = HorizontalAlignment.Left, - FocusMode = Control.FocusModeEnum.None, - ClipText = true, - CustomMinimumSize = new Vector2(114f, 0f) - }; - selectBtn.AddThemeFontSizeOverride("font_size", 10); - if (_selectedCargoIndex == idx) - { - selectBtn.Modulate = OrangeCol; - } - else if (mod.IsImperial) - { - selectBtn.Modulate = GoldCol; - } - selectBtn.Pressed += () => - { - _selectedCargoIndex = (_selectedCargoIndex == idx) ? -1 : idx; - _lastCargoHash = -1; - }; - row.AddChild(selectBtn); - - var fitBtn = new Button { Text = "FIT", FocusMode = Control.FocusModeEnum.None }; - fitBtn.AddThemeFontSizeOverride("font_size", 10); - fitBtn.Pressed += () => AutoFitCargo(grid, idx); - row.AddChild(fitBtn); - - _cargoList.AddChild(row); - } - } - - private void AutoFitCargo(ChassisGrid grid, int cargoIndex) - { - if (cargoIndex < 0 || cargoIndex >= grid.Cargo.Count) return; - var mod = grid.Cargo[cargoIndex]; - for (int i = 0; i < grid.Spec.Hardpoints.Length; i++) - { - var hp = grid.Spec.Hardpoints[i]; - if (ChassisGrid.CanFit(hp, mod)) - { - _onEquipCargo(cargoIndex, hp.Id); - _selectedCargoIndex = -1; - _lastCargoHash = -1; - return; - } - } - } - - private void SyncBroadcastChyron(BroadcastFeed broadcast) - { - var lines = broadcast.Lines; - if (ReferenceEquals(_lastBroadcastFeed, broadcast) && broadcast.Version == _lastChyronVersion) - { - return; - } - - _lastBroadcastFeed = broadcast; - _lastChyronVersion = broadcast.Version; - - int start = Math.Max(0, lines.Count - _chyronLabels.Length); - int visibleCount = lines.Count - start; - for (int slot = 0; slot < _chyronLabels.Length; slot++) - { - var lbl = _chyronLabels[slot]; - if (slot < visibleCount) - { - int lineIdx = start + slot; - var line = lines[lineIdx]; - bool isLatest = lineIdx == lines.Count - 1; - lbl.Visible = true; - lbl.Text = $"[{line.Timestamp:00.0}s] {line.Text}"; - lbl.AddThemeFontSizeOverride("font_size", isLatest ? 12 : 11); - lbl.AddThemeColorOverride("font_color", isLatest ? TextLight : TextMuted); - } - else - { - lbl.Visible = false; - lbl.Text = ""; - } - } - } - - private static string BuildInteractionPrompt(MatchState state, ContenderState player) - { - GroundDrop? nearest = state.FindNearestInteractableDrop(player.Id); - if (nearest is null) return ""; - if (nearest.Module is { } mod) - { - var freeHp = player.Grid.FindFirstEmptyCompatibleHardpoint(mod); - if (mod.Procedural is { } proc) - { - string action = freeHp is not null - ? $"[E] Bolt [{proc.ManufacturerLabel}] {mod.Name} -> {freeHp.Id}" - : $"[E] Loot [{proc.ManufacturerLabel}] {mod.Name}"; - return $"{action}\n{proc.SummaryLine1} | {proc.SummaryLine2}"; - } - return freeHp is not null - ? $"[E] Bolt {(mod.IsImperial ? "IMPERIAL " : "")}{mod.Name} -> {freeHp.Id}" - : $"[E] Loot {(mod.IsImperial ? "IMPERIAL " : "")}{mod.Name}"; - } - if (nearest.Chassis is { } ch) - { - return $"[E] Swap to {ch.Name} ({ch.Plane})"; - } - return ""; - } - - private static string BuildGarageDetails(ChassisGrid grid, int selectedCargoIndex = -1) - { - var lines = new List - { - $"COND {grid.Spec.HullConductivity:F1} | THRUST {grid.ComputeDriveThrust():F0} N", - "MOUNTED:" - }; - for (int i = 0; i < grid.Mounted.Count; i++) - { - var m = grid.Mounted[i]; - string stateTag = grid.IsHardpointOperational(m.HardpointId) ? "" : " [STRIPPED]"; - if (m.Spec.Procedural is { } proc) - { - lines.Add($"• [{proc.ManufacturerLabel}] {m.Spec.Name} {m.CurrentTemp:F0}°C{stateTag}"); - lines.Add($" {proc.SummaryLine1}"); - lines.Add($" {proc.SummaryLine2}"); - } - else - { - lines.Add($"• {m.HardpointId}: {m.Spec.Name} {m.CurrentTemp:F0}°C ({(m.CurrentPerformance * 100f):F0}%){stateTag}"); - } - } - if (selectedCargoIndex >= 0 && selectedCargoIndex < grid.Cargo.Count && - grid.Cargo[selectedCargoIndex].Procedural is { } cargoProc) - { - lines.Add($"SEL [{cargoProc.ManufacturerLabel}]:"); - lines.Add($" {cargoProc.SummaryLine1}"); - lines.Add($" {cargoProc.SummaryLine2}"); - } - return string.Join("\n", lines); - } - - private static ChromePanel CreateStyledPanel(Color accentColor, float cornerLen = 12f, float borderPx = 1.5f) - { - return new ChromePanel(accentColor, cornerLen, borderPx); - } - - private sealed partial class ChromePanel : PanelContainer - { - private static Shader? _sharedChromeShader; - private static ImageTexture? _sharedWhiteTex; - private readonly ShaderMaterial _material; - - public ChromePanel(Color accentColor, float cornerLen, float borderPx) - { - _sharedChromeShader ??= GD.Load("res://panel_chrome.gdshader"); - if (_sharedWhiteTex is null) - { - var img = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8); - img.SetPixel(0, 0, Colors.White); - _sharedWhiteTex = ImageTexture.CreateFromImage(img); - } - - _material = new ShaderMaterial { Shader = _sharedChromeShader }; - _material.SetShaderParameter("bg_color", new Color(BgDark.R, BgDark.G, BgDark.B, 0.88f)); - _material.SetShaderParameter("border_color", BorderCol); - _material.SetShaderParameter("accent_color", accentColor); - _material.SetShaderParameter("corner_len", cornerLen); - _material.SetShaderParameter("border_px", borderPx); - Material = _material; - - var empty = new StyleBoxEmpty - { - ContentMarginLeft = 10, - ContentMarginRight = 10, - ContentMarginTop = 8, - ContentMarginBottom = 8 - }; - AddThemeStyleboxOverride("panel", empty); - } - - public ShaderMaterial ChromeMaterial => _material; - - public override void _Notification(int what) - { - if (what == NotificationResized) - { - _material.SetShaderParameter("rect_size", Size); - QueueRedraw(); + s[..copy].CopyTo(_buf.AsSpan(_pos)); + _pos += copy; } } - public override void _Draw() + public void AppendInt(int val) { - if (Size.X < 2f || Size.Y < 2f || _sharedWhiteTex is null) return; - _material.SetShaderParameter("rect_size", Size); - DrawTextureRect(_sharedWhiteTex, new Rect2(Vector2.Zero, Size), false, Colors.White); - } - } - - private sealed partial class CrosshairOverlay : Control - { - private const float HitArcDuration = 0.65f; - - private sealed class IncomingHitArc - { - public float SourceX; - public float SourceZ; - public WeaponVisualClass WeaponClass; - public float Age; - } - - private ContenderState? _player; - private OrbitalPod? _localPod; - private float _cameraYaw; - private MatchState? _lastState; - private readonly List _incomingArcs = new(); - private HitMarkerKind _hitMarkerKind; - private float _hitMarkerRemaining; - private float _hitMarkerDuration; - - public void SetState(MatchState state, ContenderState player, float cameraYaw, OrbitalPod? localPod = null) - { - if (!ReferenceEquals(_lastState, state)) + if (val.TryFormat(_buf.AsSpan(_pos), out int written, default, CultureInfo.InvariantCulture)) { - _lastState = state; - ResetFeedback(); - } - - _player = player; - _localPod = localPod; - _cameraYaw = cameraYaw; - } - - public void ResetFeedback() - { - _incomingArcs.Clear(); - _hitMarkerKind = HitMarkerKind.None; - _hitMarkerRemaining = 0f; - _hitMarkerDuration = 0f; - QueueRedraw(); - } - - public void TriggerHitMarker(bool coreHit, bool killed) - { - HitMarkerKind nextKind = killed - ? HitMarkerKind.Kill - : (coreHit ? HitMarkerKind.Core : HitMarkerKind.Armor); - // Preserve stronger hit-marker kind while active (Kill > Core > Armor) - if (_hitMarkerRemaining > 0f && (int)nextKind < (int)_hitMarkerKind) - { - nextKind = _hitMarkerKind; - } - _hitMarkerKind = nextKind; - _hitMarkerDuration = nextKind switch - { - HitMarkerKind.Kill => 0.38f, - HitMarkerKind.Core => 0.26f, - _ => 0.18f - }; - _hitMarkerRemaining = _hitMarkerDuration; - QueueRedraw(); - } - - public void Advance(float dt) - { - bool dirty = false; - if (_incomingArcs.Count > 0 && dt > 0f) - { - for (int i = _incomingArcs.Count - 1; i >= 0; i--) - { - _incomingArcs[i].Age += dt; - if (_incomingArcs[i].Age >= HitArcDuration) - { - _incomingArcs.RemoveAt(i); - } - } - dirty = true; - } - - if (_hitMarkerRemaining > 0f && dt > 0f) - { - _hitMarkerRemaining = MathF.Max(0f, _hitMarkerRemaining - dt); - if (_hitMarkerRemaining <= 0.001f) - { - _hitMarkerRemaining = 0f; - _hitMarkerKind = HitMarkerKind.None; - } - dirty = true; - } - - if (dirty) - { - QueueRedraw(); + _pos += written; } } - public void PushTestHitArc(float sourceX, float sourceZ, WeaponVisualClass weaponClass) + public void AppendFloat(float val, ReadOnlySpan fmt) { - if (_incomingArcs.Count >= 8) _incomingArcs.RemoveAt(0); - _incomingArcs.Add(new IncomingHitArc + if (val.TryFormat(_buf.AsSpan(_pos), out int written, fmt, CultureInfo.InvariantCulture)) { - SourceX = sourceX, - SourceZ = sourceZ, - WeaponClass = weaponClass, - Age = 0f - }); - QueueRedraw(); - } - - public int ActiveHitArcCount => _incomingArcs.Count; - public bool HasActiveHitMarker => _hitMarkerRemaining > 0f && _hitMarkerKind != HitMarkerKind.None; - public HitMarkerKind ActiveHitMarkerKind => HasActiveHitMarker ? _hitMarkerKind : HitMarkerKind.None; - - public override void _Draw() - { - Vector2 center = Size * 0.5f; - float gap = 6f; - float tick = 10f; - bool allDisabled = _player is not null && _player.Alive && - _player.InArcWeaponCount == 0 && _player.OutOfArcWeaponCount == 0 && _player.DisabledWeaponCount > 0; - bool outOfArc = _player is not null && _player.Alive && _player.AllWeaponsOutOfArc; - Color retCol = (outOfArc || allDisabled) - ? new Color(RedCol.R, RedCol.G, RedCol.B, 0.95f) - : new Color(TextLight.R, TextLight.G, TextLight.B, 0.88f); - - // Clean 4-tick center crosshair + center pip - DrawCircle(center, 1.8f, retCol); - DrawLine(center + new Vector2(-gap - tick, 0f), center + new Vector2(-gap, 0f), retCol, 1.6f); - DrawLine(center + new Vector2(gap, 0f), center + new Vector2(gap + tick, 0f), retCol, 1.6f); - DrawLine(center + new Vector2(0f, -gap - tick), center + new Vector2(0f, -gap), retCol, 1.6f); - DrawLine(center + new Vector2(0f, gap), center + new Vector2(0f, gap + tick), retCol, 1.6f); - - // Outgoing reticle hit-marker X-flash (white/gold armor, crimson core, crimson double-X kill) - if (_hitMarkerRemaining > 0f && _hitMarkerDuration > 0.001f && _hitMarkerKind != HitMarkerKind.None) - { - float frac = Math.Clamp(_hitMarkerRemaining / _hitMarkerDuration, 0f, 1f); - float pop = 1.0f + (1.0f - frac) * 0.25f; - Color xCol = _hitMarkerKind switch - { - HitMarkerKind.Kill => new Color(RedCol.R, RedCol.G, RedCol.B, frac * 0.98f), - HitMarkerKind.Core => new Color(1.0f, 0.28f, 0.16f, frac * 0.95f), - _ => new Color(1.0f, 0.95f, 0.78f, frac * 0.92f) - }; - float xWidth = _hitMarkerKind == HitMarkerKind.Armor ? 2.0f : 2.8f; - float rIn = 6.5f * pop; - float rOut = (_hitMarkerKind == HitMarkerKind.Armor ? 13.5f : 15.5f) * pop; - const float diag = 0.70710678f; - for (int q = 0; q < 4; q++) - { - float sx = (q & 1) == 0 ? 1f : -1f; - float sy = (q & 2) == 0 ? 1f : -1f; - Vector2 dir = new(sx * diag, sy * diag); - DrawLine(center + dir * rIn, center + dir * rOut, xCol, xWidth); - if (_hitMarkerKind == HitMarkerKind.Kill) - { - DrawLine(center + dir * (rOut + 4f), center + dir * (rOut + 10.5f), new Color(GoldCol.R, GoldCol.G, GoldCol.B, frac * 0.95f), 2.2f); - } - } - } - - if (allDisabled) - { - DrawString( - ThemeDB.FallbackFont, - center + new Vector2(-52f, 36f), - "WEAPONS STRIPPED", - HorizontalAlignment.Left, - -1, - 11, - RedCol); - } - else if (outOfArc) - { - DrawString( - ThemeDB.FallbackFont, - center + new Vector2(-34f, 36f), - "OUT OF ARC", - HorizontalAlignment.Left, - -1, - 11, - RedCol); - } - - if (_player is null || !_player.Alive) - { - return; - } - - if (_player.IsInDropPod) - { - float agl = _localPod is not null ? MathF.Max(0f, _localPod.LastAgl) : 0f; - float vel = _localPod is not null ? MathF.Max(0f, -_localPod.VelY) : 0f; - bool burning = _localPod?.Phase == OrbitalPodPhase.RetroBurn; - Color bracketCol = burning ? OrangeCol : CyanCol; - - float altFrac = Math.Clamp(agl / 410f, 0f, 1f); - const float barX = 72f; - const float barH = 76f; - Vector2 topL = center + new Vector2(-barX, -barH * 0.5f); - Vector2 topR = center + new Vector2(barX, -barH * 0.5f); - DrawLine(topL, topL + new Vector2(0f, barH), new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.55f), 2.0f); - DrawLine(topR, topR + new Vector2(0f, barH), new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.55f), 2.0f); - - float fillH = barH * altFrac; - DrawLine(topL + new Vector2(0f, barH - fillH), topL + new Vector2(0f, barH), bracketCol, 3.0f); - DrawLine(topR + new Vector2(0f, barH - fillH), topR + new Vector2(0f, barH), bracketCol, 3.0f); - - DrawString( - ThemeDB.FallbackFont, - center + new Vector2(-46f, 54f), - $"ALT {agl:F0}m | {vel:F0}m/s", - HorizontalAlignment.Left, - -1, - 11, - bracketCol); - if (burning) - { - DrawString( - ThemeDB.FallbackFont, - center + new Vector2(-46f, -52f), - "RETRO BURN ACTIVE", - HorizontalAlignment.Left, - -1, - 11, - OrangeCol); - } - return; - } - - // Thermal heat-arc indicator around crosshair - float heatRatio = 0f; - bool overPlateau = false; - var mounted = _player.Grid.Mounted; - for (int i = 0; i < mounted.Count; i++) - { - var m = mounted[i]; - if (m.Spec.Kind == HardpointKind.Weapon) - { - float r = Math.Clamp( - (m.CurrentTemp - ChassisGrid.AmbientTemp) / MathF.Max(1f, m.Spec.MaxTemp - ChassisGrid.AmbientTemp), - 0f, 1f); - if (r > heatRatio) heatRatio = r; - if (m.CurrentTemp > m.Spec.OptimalTemp + m.Spec.PlateauWidth * 0.5f) - { - overPlateau = true; - } - } - } - - float arcRadius = 21f; - float startAngle = -MathF.PI * 0.75f; - float maxSweep = MathF.PI * 1.5f; - DrawArc(center, arcRadius, startAngle, startAngle + maxSweep, 24, new Color(BorderCol.R, BorderCol.G, BorderCol.B, 0.4f), 2.0f); - - if (heatRatio > 0.01f) - { - Color heatCol = overPlateau - ? RedCol - : (heatRatio > 0.65f ? OrangeCol : OliveCol); - DrawArc(center, arcRadius, startAngle, startAngle + maxSweep * heatRatio, 24, heatCol, 2.4f); - } - - // Directional incoming-hit indicator arcs (fade over 0.65s) - if (_incomingArcs.Count > 0) - { - float sinY = MathF.Sin(_cameraYaw); - float cosY = MathF.Cos(_cameraYaw); - for (int i = 0; i < _incomingArcs.Count; i++) - { - var arc = _incomingArcs[i]; - float alpha = Math.Clamp(1f - arc.Age / HitArcDuration, 0f, 1f); - if (alpha <= 0.01f) - { - continue; - } - - float dx = arc.SourceX - _player.X; - float dz = arc.SourceZ - _player.Z; - float rx = -dx * cosY + dz * sinY; - float fy = dx * sinY + dz * cosY; - float angle = (rx * rx + fy * fy) > 1e-4f ? MathF.Atan2(-fy, rx) : 0f; - - Color arcCol = arc.WeaponClass switch - { - WeaponVisualClass.Explosive => new Color(1.0f, 0.36f, 0.12f, alpha * 0.96f), - WeaponVisualClass.RocketSalvo => new Color(1.0f, 0.56f, 0.14f, alpha * 0.96f), - WeaponVisualClass.ThermalBeam => new Color(0.30f, 0.90f, 1.0f, alpha * 0.96f), - WeaponVisualClass.GaussRail => new Color(0.24f, 0.78f, 1.0f, alpha * 0.98f), - WeaponVisualClass.PlasmaPpc => new Color(0.18f, 0.92f, 0.96f, alpha * 0.96f), - WeaponVisualClass.SwarmSmart => new Color(0.56f, 0.96f, 0.28f, alpha * 0.96f), - _ => new Color(0.96f, 0.72f, 0.22f, alpha * 0.94f) - }; - - const float hitR = 39f; - const float halfSpan = 0.34f; - DrawArc(center, hitR, angle - halfSpan, angle + halfSpan, 14, arcCol, 4.2f); - if (arc.WeaponClass is WeaponVisualClass.ThermalBeam or WeaponVisualClass.GaussRail or WeaponVisualClass.PlasmaPpc) - { - DrawArc(center, hitR - 3.5f, angle - halfSpan * 0.75f, angle + halfSpan * 0.75f, 10, - new Color(GoldCol.R, GoldCol.G, GoldCol.B, alpha * 0.90f), 2.0f); - } - - Vector2 dirVec = new(MathF.Cos(angle), MathF.Sin(angle)); - Vector2 perp = new(-dirVec.Y, dirVec.X); - Vector2 tip = center + dirVec * (hitR + 9f); - Vector2 baseL = center + dirVec * (hitR + 1.5f) - perp * 4.5f; - Vector2 baseR = center + dirVec * (hitR + 1.5f) + perp * 4.5f; - DrawColoredPolygon(new[] { tip, baseL, baseR }, arcCol); - } - - var latest = _incomingArcs[^1]; - float tagAlpha = Math.Clamp(1f - latest.Age / HitArcDuration, 0f, 1f); - (string tagText, Color tagCol) = latest.WeaponClass switch - { - WeaponVisualClass.Autocannon => ("20MM IMPACT", new Color(0.98f, 0.70f, 0.20f, tagAlpha)), - WeaponVisualClass.Explosive => ("BLAST IMPACT", new Color(1.0f, 0.38f, 0.14f, tagAlpha)), - WeaponVisualClass.RocketSalvo => ("ROCKET HIT", new Color(1.0f, 0.58f, 0.18f, tagAlpha)), - WeaponVisualClass.ThermalBeam => ("THERMAL HIT", new Color(0.36f, 0.92f, 1.0f, tagAlpha)), - WeaponVisualClass.GaussRail => ("GAUSS RAIL", new Color(0.28f, 0.84f, 1.0f, tagAlpha)), - WeaponVisualClass.PlasmaPpc => ("PLASMA BURN", new Color(0.24f, 0.94f, 0.98f, tagAlpha)), - WeaponVisualClass.SwarmSmart => ("SWARM HIT", new Color(0.58f, 0.96f, 0.30f, tagAlpha)), - _ => ("KINETIC HIT", new Color(0.96f, 0.78f, 0.28f, tagAlpha)) - }; - DrawString( - ThemeDB.FallbackFont, - center + new Vector2(-36f, 54f), - tagText, - HorizontalAlignment.Left, - -1, - 10, - tagCol); + _pos += written; } } } - - private sealed partial class RadarWidget : Control - { - private IClientArenaSession? _session; - private float _cameraYaw; - - public void SetState(IClientArenaSession session, float cameraYaw) - { - _session = session; - _cameraYaw = cameraYaw; - } - - private static Vector2 WorldToRadar(Vector2 center, float scale, float wx, float wz, float camYaw) - { - // Heading-up 3P radar: camera forward (sinY, cosY) is always UP (-screenY), camera right (-cosY, sinY) is RIGHT (+screenX). - float sinY = MathF.Sin(camYaw); - float cosY = MathF.Cos(camYaw); - float rx = -wx * cosY + wz * sinY; - float fy = wx * sinY + wz * cosY; - return center + new Vector2(rx, -fy) * scale; - } - - private static Vector2 ClampToRadarDisc(Vector2 center, float maxRadius, Vector2 pt) - { - Vector2 delta = pt - center; - float dist = delta.Length(); - if (dist > maxRadius && dist > 1e-4f) - { - return center + delta * (maxRadius / dist); - } - return pt; - } - - public override void _Draw() - { - Vector2 center = Size * 0.5f; - float radius = MathF.Min(Size.X, Size.Y) * 0.47f; - float maxBlipRadius = MathF.Max(4f, radius - 3f); - var state = _session?.ViewState; - float arenaHalf = MathF.Max(1f, state?.Terrain.MapHalfExtent ?? MatchState.ArenaHalfExtent); - float scale = radius / arenaHalf; - - DrawCircle(center, radius, BgInner); - DrawArc(center, radius, 0f, MathF.Tau, 48, BorderCol, 1.5f); - // Forward-up indicator tick at top of radar - DrawLine(center + new Vector2(0f, -radius), center + new Vector2(0f, -radius + 6f), CyanCol, 2.0f); - - if (_session is null || state is null) return; - - int localId = _session.LocalContenderId; - - // Safe Circle - float safePx = MathF.Min(state.Spectators.SafeRadius * scale, maxBlipRadius); - DrawArc(center, safePx, 0f, MathF.Tau, 64, OrangeCol, 1.6f); - - // Ground drops - for (int i = 0; i < state.GroundDrops.Count; i++) - { - var d = state.GroundDrops[i]; - if (d.PickedUp) continue; - var p = ClampToRadarDisc(center, MathF.Max(4f, radius - 4f), WorldToRadar(center, scale, d.X, d.Z, _cameraYaw)); - if (d.Chassis is not null) - { - DrawRect(new Rect2(p - new Vector2(2.5f, 2.5f), new Vector2(5f, 5f)), CyanCol); - } - else if (d.Module is { IsImperial: true }) - { - DrawCircle(p, 3.0f, GoldCol); - } - } - - // Active descending Orbital Pods (cyan/gold diamonds for gear, chevrons for contenders) - var pods = _session.ActivePods; - for (int i = 0; i < pods.Count; i++) - { - var pod = pods[i]; - if (pod.Phase == OrbitalPodPhase.Popped) continue; - var pp = ClampToRadarDisc(center, MathF.Max(4f, radius - 5f), WorldToRadar(center, scale, pod.X, pod.Z, _cameraYaw)); - if (pod.PodKind == OrbitalPodKind.Contender) - { - bool isLocalPod = pod.ContenderId == localId; - Color pCol = isLocalPod ? OliveCol : OrangeCol; - float sz = isLocalPod ? 5.5f : 3.6f; - var pts = new[] - { - pp + new Vector2(0f, -sz), - pp + new Vector2(-sz * 0.8f, sz * 0.7f), - pp + new Vector2(sz * 0.8f, sz * 0.7f) - }; - DrawColoredPolygon(pts, pCol); - } - else - { - bool isImp = pod.WaveIndex > 0 || pod.Module?.IsImperial == true; - Color gCol = isImp ? GoldCol : CyanCol; - const float d = 3.2f; - var pts = new[] - { - pp + new Vector2(0f, -d), - pp + new Vector2(d, 0f), - pp + new Vector2(0f, d), - pp + new Vector2(-d, 0f) - }; - DrawColoredPolygon(pts, gCol); - } - } - - // Spectator Wall (LOS / Tourist horizon rule / 5s ghost memory; hidden Exemplars vanish!) - var contenderContacts = _session.LocalContenderContacts; - var spectatorContacts = _session.LocalSpectatorContacts; - var specs = state.Spectators.Spectators; - for (int i = 0; i < specs.Count; i++) - { - var s = specs[i]; - if (!s.Alive) continue; - - spectatorContacts.TryGetValue(s.Id, out var mem); - if (!MatchState.IsContactOnRadar(mem)) - { - continue; - } - - bool live = mem!.VisibleToPlayer; - bool hasLivePos = _session.IsSpectatorVisible(s.Id) && (live || mem.FaintHorizonPing); - if (!hasLivePos && !mem.HasEverBeenSeen) - { - continue; - } - float drawX = hasLivePos ? s.X : mem.LastSeenX; - float drawZ = hasLivePos ? s.Z : mem.LastSeenZ; - float blipR = 1.6f + s.RadarSignature * 3.1f; - float specClampR = MathF.Max(4f, radius - blipR - 1f); - var p = ClampToRadarDisc(center, specClampR, WorldToRadar(center, scale, drawX, drawZ, _cameraYaw)); - - Color col = s.Tier switch - { - SpectatorTier.Tourist => GoldCol, - SpectatorTier.Patron => PatronColor, - _ => RedCol - }; - - if (live && s.Stance != SpectatorStance.Neutral && s.HasTargetLos && s.TargetContenderId.HasValue) - { - int tid = s.TargetContenderId.Value; - if (tid >= 0 && tid < state.Contenders.Count && state.Contenders[tid].Alive) - { - var tgt = state.Contenders[tid]; - bool targetVisible = tgt.Id == localId || - (_session.IsContenderVisible(tgt.Id) && contenderContacts.TryGetValue(tgt.Id, out var tgtMem) && tgtMem.VisibleToPlayer); - if (targetVisible) - { - float tgtClampR = MathF.Max(4f, radius - (tgt.Id == localId ? 7.5f : 4.3f)); - var tp = ClampToRadarDisc(center, tgtClampR, WorldToRadar(center, scale, tgt.X, tgt.Z, _cameraYaw)); - DrawLine(p, tp, new Color(RedCol.R, RedCol.G, RedCol.B, 0.65f), 1.3f); - } - } - col = RedCol; - } - - if (!live) - { - float alpha = mem.FaintHorizonPing - ? 0.42f - : Math.Clamp((1f - mem.LastSeenAge / MatchState.ContactGhostDuration) * 0.48f, 0.08f, 0.48f); - Color ghostCol = mem.FaintHorizonPing ? GoldCol : col; - DrawCircle(p, blipR, new Color(ghostCol.R, ghostCol.G, ghostCol.B, alpha)); - } - else - { - DrawCircle(p, blipR, col); - } - } - - // Contenders (player always live; rivals obey LOS + 5s ghost memory) - float sinY = MathF.Sin(_cameraYaw); - float cosY = MathF.Cos(_cameraYaw); - for (int i = 0; i < state.Contenders.Count; i++) - { - var c = state.Contenders[i]; - if (!c.IsGroundedActive) continue; - - if (c.Id == localId) - { - float playerClampR = MathF.Max(4f, radius - 6.5f - 1f); - var (lPos, _, _) = _session.GetInterpolatedContenderPose(localId, 1f); - var p = ClampToRadarDisc(center, playerClampR, WorldToRadar(center, scale, lPos.X, lPos.Z, _cameraYaw)); - var dir = new Vector2( - -MathF.Sin(c.Yaw) * cosY + MathF.Cos(c.Yaw) * sinY, - -(MathF.Sin(c.Yaw) * sinY + MathF.Cos(c.Yaw) * cosY)); - var perp = new Vector2(-dir.Y, dir.X); - var pts = new[] - { - p + dir * 6.5f, - p - dir * 4.5f + perp * 4.2f, - p - dir * 4.5f - perp * 4.2f - }; - DrawColoredPolygon(pts, OliveCol); - continue; - } - - contenderContacts.TryGetValue(c.Id, out var mem); - if (!MatchState.IsContactOnRadar(mem)) - { - continue; - } - - if (mem!.VisibleToPlayer) - { - float rivalClampR = MathF.Max(4f, radius - 3.3f - 1f); - float rx = _session.IsContenderVisible(c.Id) ? c.X : mem.LastSeenX; - float rz = _session.IsContenderVisible(c.Id) ? c.Z : mem.LastSeenZ; - var p = ClampToRadarDisc(center, rivalClampR, WorldToRadar(center, scale, rx, rz, _cameraYaw)); - DrawCircle(p, 3.3f, OrangeCol); - } - else - { - float ghostClampR = MathF.Max(4f, radius - 2.8f - 1f); - var p = ClampToRadarDisc(center, ghostClampR, WorldToRadar(center, scale, mem.LastSeenX, mem.LastSeenZ, _cameraYaw)); - float alpha = Math.Clamp((1f - mem.LastSeenAge / MatchState.ContactGhostDuration) * 0.48f, 0.08f, 0.48f); - DrawCircle(p, 2.8f, new Color(OrangeCol.R, OrangeCol.G, OrangeCol.B, alpha)); - } - } - } - - private static readonly Color PatronColor = Color.FromHtml("#4ba8a5"); - } } diff --git a/client/InventoryGridControl.cs b/client/InventoryGridControl.cs index d80d283..1c5fafd 100644 --- a/client/InventoryGridControl.cs +++ b/client/InventoryGridControl.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using Godot; using RustToDust.Core; +using RustToDust.HbGpu; namespace RustToDust.Client; @@ -38,8 +39,14 @@ public partial class InventoryGridControl : Control private static Shader? _sharedShader; private readonly TextureRect _gridSurface; - private readonly LabelsOverlay _labelsOverlay; private readonly ShaderMaterial _material; + private HbGpuCanvas? _standaloneCanvas; + + private readonly Dictionary _lastEmittedTags = new(StringComparer.Ordinal); + private readonly char[] _tagScratch = new char[32]; + private int _overlayEmitCount; + private float _standaloneTime; + private bool _standaloneDirty = true; private Image? _dataImage; private ImageTexture? _dataTex; @@ -83,17 +90,10 @@ public partial class InventoryGridControl : Control _gridSurface.SetAnchorsPreset(LayoutPreset.FullRect); AddChild(_gridSurface); - _labelsOverlay = new LabelsOverlay(this) - { - Name = "GridLabelsOverlay", - MouseFilter = MouseFilterEnum.Ignore - }; - _labelsOverlay.SetAnchorsPreset(LayoutPreset.FullRect); - AddChild(_labelsOverlay); - MouseExited += OnMouseExited; } + public bool ExternalHbGpuOwner { get; set; } public ShaderMaterial ShaderMaterial => _material; public Control ShaderSurface => _gridSurface; public ChassisGrid? Grid => _grid; @@ -103,9 +103,24 @@ public partial class InventoryGridControl : Control ? _hardpointLookup[c.X, c.Y] : null; - internal int LabelsDrawCount => _labelsOverlay.DrawCount; - internal string? GetLastDrawnLabel(string hardpointId) => - _labelsOverlay.LastDrawnTags.TryGetValue(hardpointId, out string? tag) ? tag : null; + internal int OverlayEmitCount => _overlayEmitCount; + internal HbGpuCanvas? StandaloneCanvas => _standaloneCanvas; + internal string? GetLastEmittedLabel(string hardpointId) => + _lastEmittedTags.TryGetValue(hardpointId, out string? tag) ? tag : null; + + public override void _Ready() + { + if (!ExternalHbGpuOwner && _standaloneCanvas is null) + { + _standaloneCanvas = new HbGpuCanvas + { + Name = "StandaloneHbGpuCanvas", + MouseFilter = MouseFilterEnum.Ignore + }; + _standaloneCanvas.SetAnchorsPreset(LayoutPreset.FullRect); + AddChild(_standaloneCanvas); + } + } public event Action? CellClicked; public event Action? HardpointClicked; @@ -116,13 +131,14 @@ public partial class InventoryGridControl : Control if (what == NotificationResized) { SyncRectUniform(); - _labelsOverlay.QueueRedraw(); + _standaloneDirty = true; } } public override void _Process(double delta) { float dt = (float)delta; + _standaloneTime += MathF.Max(0f, dt); bool anyPulse = false; for (int y = 0; y < _gridHeight; y++) @@ -141,6 +157,19 @@ public partial class InventoryGridControl : Control { PackDataTexture(_grid); FlushTextures(); + _standaloneDirty = true; + } + + if (!ExternalHbGpuOwner && _standaloneCanvas is not null && _grid is not null) + { + bool hasCompatiblePulse = _selectedCargoIndex >= 0 && _selectedCargoIndex < _grid.Cargo.Count; + if (_standaloneDirty || hasCompatiblePulse) + { + _standaloneDirty = false; + _standaloneCanvas.BeginFrame(); + EmitHbGpuOverlay(_standaloneCanvas, Vector2.Zero, _standaloneTime); + _standaloneCanvas.EndFrameAndSubmit(); + } } } @@ -195,7 +224,7 @@ public partial class InventoryGridControl : Control PackTempTexture(grid); FlushTextures(); SyncRectUniform(); - _labelsOverlay.QueueRedraw(); + _standaloneDirty = true; return; } @@ -224,7 +253,7 @@ public partial class InventoryGridControl : Control } if (dataChanged || tempChanged) { - _labelsOverlay.QueueRedraw(); + _standaloneDirty = true; FlushTextures(); } } @@ -236,6 +265,7 @@ public partial class InventoryGridControl : Control _hitPulse[x, y] = Math.Clamp(intensity, 0f, 1f); PackDataTexture(_grid); FlushTextures(); + _standaloneDirty = true; } public bool TryGetCellAt(Vector2 localPos, out Vector2I cell) @@ -282,6 +312,7 @@ public partial class InventoryGridControl : Control { PackDataTexture(_grid); FlushTextures(); + _standaloneDirty = true; } } } @@ -301,6 +332,7 @@ public partial class InventoryGridControl : Control { PackDataTexture(_grid); FlushTextures(); + _standaloneDirty = true; } } @@ -685,62 +717,218 @@ public partial class InventoryGridControl : Control _ => ColTextLight }; - private sealed partial class LabelsOverlay : Control + /// + /// Emits crisp analytic vector cell borders, hardpoint L-brackets, compatibility pulses, + /// stripped X-marks, and Monaspace Krypton hardpoint labels into . + /// Zero GC allocations on steady-state calls. + /// + public void EmitHbGpuOverlay(HbGpuCanvas canvas, Vector2 originOffset, float timeSec) { - private readonly InventoryGridControl _owner; - public int DrawCount { get; private set; } - public readonly Dictionary LastDrawnTags = new(StringComparer.Ordinal); - - public LabelsOverlay(InventoryGridControl owner) => _owner = owner; - - public override void _Draw() + _overlayEmitCount++; + var grid = _grid; + if (grid is null) { - DrawCount++; - LastDrawnTags.Clear(); - var grid = _owner._grid; - if (grid is null) return; + return; + } - _owner.ComputeCellLayout(out float cellSize, out Vector2 origin); - if (cellSize < 14f) return; + ComputeCellLayout(out float cellSize, out Vector2 origin); + if (cellSize < 8f) + { + return; + } - var spec = grid.Spec; - int fontSize = cellSize >= 38f ? 10 : 9; - float alpha = 0.95f; + Vector2 basePos = originOffset + origin; + var spec = grid.Spec; + ModuleSpec? selectedCargo = _selectedCargoIndex >= 0 && _selectedCargoIndex < grid.Cargo.Count + ? grid.Cargo[_selectedCargoIndex] + : null; + HardpointSpec? hoveredHp = HoveredHardpoint; + Color flashCol = new(1.0f, 0.76f, 0.38f, 1.0f); + Color redAccent = new(0.92f, 0.26f, 0.18f, 1.0f); - for (int i = 0; i < spec.Hardpoints.Length; i++) + // 1. Hull cell outlines, internal subdivisions, and stripped-cell X marks + for (int y = 0; y < _gridHeight; y++) + { + for (int x = 0; x < _gridWidth; x++) { - var hp = spec.Hardpoints[i]; - var mounted = grid.GetMountedOn(hp.Id); - var pos = origin + new Vector2(hp.X * cellSize, hp.Y * cellSize); - float maxW = MathF.Max(12f, hp.Width * cellSize - 6f); + if (!spec.IsActive(x, y)) + { + continue; + } - string tag = mounted is not null - ? $"{mounted.Spec.Kind.ToString()[..1]}:{mounted.CurrentTemp:F0}°" - : hp.Kind.ToString()[..3].ToUpperInvariant(); - LastDrawnTags[hp.Id] = tag; + float cx = basePos.X + x * cellSize; + float cy = basePos.Y + y * cellSize; + bool stripped = grid.Armor[x, y] <= 0.01f; + var hp = _hardpointLookup[x, y]; + + if (hp is null) + { + Color edgeCol = grid.BorderCells[x, y] + ? ColBorderHull.Lerp(ColBorderRadiatorCell, 0.30f) + : ColBorderHull; + float pulse = Math.Clamp(_hitPulse[x, y], 0f, 1f); + bool isCellHovered = _hoveredCell is { } hc && hc.X == x && hc.Y == y; + if (stripped) edgeCol = edgeCol.Lerp(redAccent, 0.65f); + if (isCellHovered) edgeCol = edgeCol.Lerp(Colors.White, 0.35f); + if (pulse > 0.01f) edgeCol = edgeCol.Lerp(flashCol, pulse * 0.90f); + + float inset = 1.5f; + float x0 = cx + inset; + float y0 = cy + inset; + float x1 = cx + cellSize - inset; + float y1 = cy + cellSize - inset; + + // Outer hull perimeter edges get crisp medium lines; internal matched hull edges get faint hairlines + bool nMatch = spec.IsActive(x, y - 1) && _hardpointLookup[x, y - 1] is null; + bool sMatch = spec.IsActive(x, y + 1) && _hardpointLookup[x, y + 1] is null; + bool wMatch = spec.IsActive(x - 1, y) && _hardpointLookup[x - 1, y] is null; + bool eMatch = spec.IsActive(x + 1, y) && _hardpointLookup[x + 1, y] is null; + + Color outerCol = new(edgeCol.R, edgeCol.G, edgeCol.B, isCellHovered ? 0.85f : 0.42f); + Color innerCol = new(edgeCol.R, edgeCol.G, edgeCol.B, 0.14f); + + if (!nMatch) canvas.DrawLineSegment(x0, y0, x1, y0, 1.2f, outerCol); + if (!sMatch) canvas.DrawLineSegment(x0, y1, x1, y1, 1.2f, outerCol); + else canvas.DrawLineSegment(cx + 2f, cy + cellSize, cx + cellSize - 2f, cy + cellSize, 0.9f, innerCol); + if (!wMatch) canvas.DrawLineSegment(x0, y0, x0, y1, 1.2f, outerCol); + if (!eMatch) canvas.DrawLineSegment(x1, y0, x1, y1, 1.2f, outerCol); + else canvas.DrawLineSegment(cx + cellSize, cy + 2f, cx + cellSize, cy + cellSize - 2f, 0.9f, innerCol); + } + + if (stripped) + { + float pad = MathF.Max(4.5f, cellSize * 0.18f); + Color xCol = new(0.95f, 0.28f, 0.20f, 0.78f); + canvas.DrawLineSegment(cx + pad, cy + pad, cx + cellSize - pad, cy + cellSize - pad, 1.5f, xCol); + canvas.DrawLineSegment(cx + cellSize - pad, cy + pad, cx + pad, cy + cellSize - pad, 1.5f, xCol); + } + } + } + + // 2. Contiguous hardpoint borders, L-brackets, and Krypton tags + float fontSize = cellSize >= 38f ? 10.5f : 9.2f; + float compatPulse = 0.72f + 0.28f * MathF.Sin(timeSec * 6.5f); + + for (int i = 0; i < spec.Hardpoints.Length; i++) + { + var hp = spec.Hardpoints[i]; + var mounted = grid.GetMountedOn(hp.Id); + float hx = basePos.X + hp.X * cellSize; + float hy = basePos.Y + hp.Y * cellSize; + float hw = hp.Width * cellSize; + float hh = hp.Height * cellSize; + + bool strippedHp = !grid.IsHardpointOperational(hp); + bool isCompatible = selectedCargo is not null && ChassisGrid.CanFit(hp, selectedCargo); + bool isHovered = hoveredHp is not null && ReferenceEquals(hp, hoveredHp); + + float maxPulse = 0f; + for (int dy = 0; dy < hp.Height; dy++) + { + for (int dx = 0; dx < hp.Width; dx++) + { + int cx = hp.X + dx; + int cy = hp.Y + dy; + if (cx >= 0 && cy >= 0 && cx < _gridWidth && cy < _gridHeight) + { + maxPulse = MathF.Max(maxPulse, _hitPulse[cx, cy]); + } + } + } + + Color accent; + if (isCompatible) + { + accent = ColGold; + } + else if (mounted is { Spec.IsImperial: true }) + { + accent = ColGold; + } + else + { + accent = KindColor(hp.Kind); + if (mounted is null) + { + accent = accent.Lerp(ColBorderHull, 0.45f); + } + } + + if (strippedHp) accent = accent.Lerp(redAccent, 0.70f); + if (isCompatible) accent = accent.Lerp(new Color(0.96f, 0.82f, 0.30f, 1f), compatPulse); + if (isHovered) accent = accent.Lerp(Colors.White, 0.35f); + if (maxPulse > 0.01f) accent = accent.Lerp(flashCol, maxPulse * 0.90f); + + const float inset = 1.8f; + float rx = hx + inset; + float ry = hy + inset; + float rw = MathF.Max(2f, hw - inset * 2f); + float rh = MathF.Max(2f, hh - inset * 2f); + + float ruleAlpha = isCompatible ? 0.68f : (isHovered ? 0.60f : 0.34f); + canvas.DrawRectOutline(rx, ry, rw, rh, isCompatible ? 1.5f : 1.0f, new Color(accent.R, accent.G, accent.B, ruleAlpha)); + + float arm = Math.Clamp(MathF.Min(rw, rh) * 0.28f, 4.5f, 12f); + float bracketThick = (isCompatible || isHovered) ? 2.4f : 1.8f; + Color bracketCol = new(accent.R, accent.G, accent.B, 0.96f); + canvas.DrawTargetBracketCorner(rx, ry, arm, bracketThick, 0, bracketCol); + canvas.DrawTargetBracketCorner(rx + rw, ry, arm, bracketThick, 1, bracketCol); + canvas.DrawTargetBracketCorner(rx + rw, ry + rh, arm, bracketThick, 2, bracketCol); + canvas.DrawTargetBracketCorner(rx, ry + rh, arm, bracketThick, 3, bracketCol); + + if (cellSize >= 14f) + { + ReadOnlySpan tagSpan = FormatHardpointTag(hp, mounted, _tagScratch); + if (!_lastEmittedTags.TryGetValue(hp.Id, out string? existingTag) || !tagSpan.SequenceEqual(existingTag)) + { + _lastEmittedTags[hp.Id] = new string(tagSpan); + } Color col = mounted is { Spec.IsImperial: true } ? ColGold : ColTextLight; - col.A = alpha; + col.A = 0.95f; + HbGpuCommandWriter.PackClipRect(hx + 2f, hy + 2f, hw - 4f, hh - 4f, out uint clipMin, out uint clipMax); - // Dark shadow for crisp legibility over bright thermal glow - DrawString( - ThemeDB.FallbackFont, - pos + new Vector2(7f, fontSize + 6f), - tag, - HorizontalAlignment.Left, - maxW - 2f, - fontSize, - new Color(0.04f, 0.05f, 0.04f, alpha * 0.9f)); - - DrawString( - ThemeDB.FallbackFont, - pos + new Vector2(6f, fontSize + 5f), - tag, - HorizontalAlignment.Left, - maxW - 2f, - fontSize, - col); + float tx = hx + 5f; + float ty = hy + fontSize + 4.5f; + canvas.DrawText(tagSpan, tx + 1f, ty + 1f, fontSize, new Color(0.04f, 0.05f, 0.04f, 0.90f), + wght: 550f, stemDarken: true, clipMinPacked: clipMin, clipMaxPacked: clipMax); + canvas.DrawText(tagSpan, tx, ty, fontSize, col, + wght: 550f, stemDarken: true, clipMinPacked: clipMin, clipMaxPacked: clipMax); } } } + + private static ReadOnlySpan FormatHardpointTag(HardpointSpec hp, MountedModule? mounted, char[] buf) + { + if (mounted is null) + { + return hp.Kind switch + { + HardpointKind.Weapon => "WPN", + HardpointKind.Engine => "ENG", + HardpointKind.Radiator => "RAD", + HardpointKind.Armor => "ARM", + HardpointKind.Utility => "UTL", + _ => "MOD" + }; + } + + buf[0] = mounted.Spec.Kind switch + { + HardpointKind.Weapon => 'W', + HardpointKind.Engine => 'E', + HardpointKind.Radiator => 'R', + HardpointKind.Armor => 'A', + HardpointKind.Utility => 'U', + _ => 'M' + }; + buf[1] = ':'; + int pos = 2; + if (mounted.CurrentTemp.TryFormat(buf.AsSpan(pos), out int written, "F0", System.Globalization.CultureInfo.InvariantCulture)) + { + pos += written; + } + buf[pos++] = '°'; + return buf.AsSpan(0, pos); + } } diff --git a/client/LobbyScreen.cs b/client/LobbyScreen.cs index 7a64842..e74bfc1 100644 --- a/client/LobbyScreen.cs +++ b/client/LobbyScreen.cs @@ -16,11 +16,22 @@ public sealed partial class LobbyScreen : CanvasLayer { public required PanelContainer Frame; public required Label IndexLabel; + public required Label SquadBadge; public required Label NameLabel; public required Label RoleBadge; public required Label ReadyBadge; } + private static readonly Color[] SquadColors = + { + Color.FromHtml("#52e3a8"), + ImperialChrome.CyanCol, + ImperialChrome.GoldCol, + ImperialChrome.OrangeCol, + ImperialChrome.OliveCol, + Color.FromHtml("#d67cff") + }; + private readonly SlotRowView[] _slotViews = new SlotRowView[MatchState.ContenderCount]; private Control _root = null!; @@ -32,11 +43,13 @@ public sealed partial class LobbyScreen : CanvasLayer private OptionButton _mapOption = null!; private LineEdit _seedEdit = null!; + private OptionButton _squadOption = null!; private Button _applyConfigBtn = null!; private Button _randomSeedBtn = null!; private Label _authorityNoteLabel = null!; private Label _netStatusLabel = null!; + private Button _switchSquadBtn = null!; private Button _readyBtn = null!; private Button _launchBtn = null!; private Button _leaveBtn = null!; @@ -44,6 +57,7 @@ public sealed partial class LobbyScreen : CanvasLayer private IClientArenaSession? _activeSession; private int? _lastSyncedSeed; private byte? _lastSyncedMap; + private byte? _lastSyncedSquadSize; public LobbyScreen() { @@ -72,6 +86,7 @@ public sealed partial class LobbyScreen : CanvasLayer _activeSession = null; _lastSyncedSeed = null; _lastSyncedMap = null; + _lastSyncedSquadSize = null; _seedEdit?.ReleaseFocus(); } } @@ -101,9 +116,11 @@ public sealed partial class LobbyScreen : CanvasLayer _countdownLabel.AddThemeColorOverride("font_color", net.LastError is not null ? ImperialChrome.RedCol : ImperialChrome.OrangeCol); _rosterSummaryLabel.Text = "Awaiting authoritative lobby roster..."; _readyBtn.Disabled = true; + _switchSquadBtn.Disabled = true; _launchBtn.Visible = false; _mapOption.Disabled = true; _seedEdit.Editable = false; + _squadOption.Disabled = true; _applyConfigBtn.Disabled = true; _randomSeedBtn.Disabled = true; _authorityNoteLabel.Text = "Waiting for server snapshot..."; @@ -114,9 +131,11 @@ public sealed partial class LobbyScreen : CanvasLayer int localId = session.LocalContenderId; bool isHost = lobby.HostSlotId.HasValue && lobby.HostSlotId.Value == localId; bool localReady = false; + byte localSquadId = 0; int humanCount = 0; int readyCount = 0; int aiCount = 0; + byte squadSize = (byte)Math.Clamp((int)lobby.SquadSize, 1, 4); for (int i = 0; i < _slotViews.Length; i++) { @@ -126,8 +145,19 @@ public sealed partial class LobbyScreen : CanvasLayer var slot = lobby.Slots[i]; bool isLocalSlot = slot.SlotId == localId; bool isHostSlot = lobby.HostSlotId.HasValue && slot.SlotId == lobby.HostSlotId.Value; + if (isLocalSlot) localSquadId = slot.SquadId; view.IndexLabel.Text = $"SLOT {slot.SlotId + 1:00}"; + if (squadSize > 1) + { + view.SquadBadge.Text = $"[SQ {slot.SquadId + 1}]"; + view.SquadBadge.AddThemeColorOverride("font_color", SquadColors[slot.SquadId % SquadColors.Length]); + } + else + { + view.SquadBadge.Text = "[FFA]"; + view.SquadBadge.AddThemeColorOverride("font_color", ImperialChrome.TextMuted); + } if (slot.IsHuman) { humanCount++; @@ -183,7 +213,7 @@ public sealed partial class LobbyScreen : CanvasLayer _panel.SetAccentColor(ImperialChrome.CyanCol); } - // Sync Map & Seed without clobbering active typing by host + // Sync Map, Seed & SquadSize without clobbering active typing by host if (_lastSyncedMap != lobby.SelectedMap) { _lastSyncedMap = lobby.SelectedMap; @@ -194,17 +224,28 @@ public sealed partial class LobbyScreen : CanvasLayer _lastSyncedSeed = lobby.SelectedSeed; _seedEdit.Text = lobby.SelectedSeed.ToString(CultureInfo.InvariantCulture); } + if (_lastSyncedSquadSize != squadSize) + { + _lastSyncedSquadSize = squadSize; + _squadOption.Select(squadSize - 1); + } // Strict host authority gating _mapOption.Disabled = !isHost; _seedEdit.Editable = isHost; + _squadOption.Disabled = !isHost; _applyConfigBtn.Disabled = !isHost; _randomSeedBtn.Disabled = !isHost; _authorityNoteLabel.Text = isHost - ? "HOST AUTHORITY: You control drop zone, seed, and forced launch." - : "READ-ONLY: Only the match host can edit map, seed, or force launch."; + ? "HOST AUTHORITY: You control drop zone, seed, squad mode, and forced launch." + : "READ-ONLY: Only the match host can edit map, seed, squad mode, or force launch."; _authorityNoteLabel.AddThemeColorOverride("font_color", isHost ? ImperialChrome.GoldCol : ImperialChrome.TextMuted); + _switchSquadBtn.Disabled = squadSize <= 1; + _switchSquadBtn.Text = squadSize > 1 + ? $"SWITCH SQUAD [SQ {localSquadId + 1}]" + : "SWITCH SQUAD (FFA)"; + _readyBtn.Disabled = false; _readyBtn.Text = localReady ? "READY [ON] — CLICK TO UNREADY" : "READY UP"; ImperialChrome.StyleButton(_readyBtn, localReady ? ImperialChrome.OliveCol : ImperialChrome.CyanCol, 14); @@ -240,10 +281,10 @@ public sealed partial class LobbyScreen : CanvasLayer _panel.AnchorRight = 0.5f; _panel.AnchorTop = 0.5f; _panel.AnchorBottom = 0.5f; - _panel.OffsetLeft = -500f; - _panel.OffsetRight = 500f; - _panel.OffsetTop = -305f; - _panel.OffsetBottom = 305f; + _panel.OffsetLeft = -515f; + _panel.OffsetRight = 515f; + _panel.OffsetTop = -330f; + _panel.OffsetBottom = 330f; _root.AddChild(_panel); var vbox = new VBoxContainer(); @@ -309,9 +350,13 @@ public sealed partial class LobbyScreen : CanvasLayer frame.AddChild(row); var idxLbl = ImperialChrome.CreateLabel($"SLOT {i + 1:00}", 11, ImperialChrome.TextMuted); - idxLbl.CustomMinimumSize = new Vector2(64f, 0f); + idxLbl.CustomMinimumSize = new Vector2(60f, 0f); row.AddChild(idxLbl); + var sqLbl = ImperialChrome.CreateLabel("[SQ 1]", 11, SquadColors[0]); + sqLbl.CustomMinimumSize = new Vector2(54f, 0f); + row.AddChild(sqLbl); + var nameLbl = ImperialChrome.CreateLabel("AI BACKFILL", 12, ImperialChrome.TextMuted); nameLbl.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill; nameLbl.ClipText = true; @@ -332,6 +377,7 @@ public sealed partial class LobbyScreen : CanvasLayer { Frame = frame, IndexLabel = idxLbl, + SquadBadge = sqLbl, NameLabel = nameLbl, RoleBadge = roleLbl, ReadyBadge = readyLbl @@ -392,7 +438,23 @@ public sealed partial class LobbyScreen : CanvasLayer }; seedRow.AddChild(_randomSeedBtn); - _applyConfigBtn = ImperialChrome.CreateButton("APPLY MAP & SEED", ImperialChrome.GoldCol, 12, 32f); + var squadRow = new HBoxContainer(); + squadRow.AddThemeConstantOverride("separation", 8); + rightCol.AddChild(squadRow); + var squadLbl = ImperialChrome.CreateLabel("SQUAD", 12, ImperialChrome.TextMuted); + squadLbl.CustomMinimumSize = new Vector2(68f, 0f); + squadRow.AddChild(squadLbl); + _squadOption = new OptionButton { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }; + _squadOption.AddItem("FFA (1)", 0); + _squadOption.AddItem("DUO (2)", 1); + _squadOption.AddItem("TRIO (3)", 2); + _squadOption.AddItem("QUAD (4)", 3); + _squadOption.Select(2); + ImperialChrome.StyleOptionButton(_squadOption, ImperialChrome.CyanCol, 13); + _squadOption.ItemSelected += _ => ApplyConfigFromUi(); + squadRow.AddChild(_squadOption); + + _applyConfigBtn = ImperialChrome.CreateButton("APPLY MAP, SEED & SQUAD", ImperialChrome.GoldCol, 12, 32f); _applyConfigBtn.Pressed += ApplyConfigFromUi; rightCol.AddChild(_applyConfigBtn); @@ -405,6 +467,10 @@ public sealed partial class LobbyScreen : CanvasLayer var spacer = new Control { SizeFlagsVertical = Control.SizeFlags.ExpandFill }; rightCol.AddChild(spacer); + _switchSquadBtn = ImperialChrome.CreateButton("SWITCH SQUAD [SQ 1]", SquadColors[0], 13, 36f); + _switchSquadBtn.Pressed += OnSwitchSquadPressed; + rightCol.AddChild(_switchSquadBtn); + _readyBtn = ImperialChrome.CreateButton("READY UP", ImperialChrome.CyanCol, 14, 42f); _readyBtn.Pressed += OnReadyPressed; rightCol.AddChild(_readyBtn); @@ -438,6 +504,27 @@ public sealed partial class LobbyScreen : CanvasLayer _activeSession.SetLobbyReady(!currentReady); } + private void OnSwitchSquadPressed() + { + if (_activeSession is null || _activeSession.LobbyState is not { } lobby) return; + byte squadSize = (byte)Math.Clamp((int)lobby.SquadSize, 1, 4); + if (squadSize <= 1) return; + + int maxSquads = Math.Max(1, (MatchState.ContenderCount + squadSize - 1) / squadSize); + int localId = _activeSession.LocalContenderId; + byte curSq = 0; + for (int i = 0; i < lobby.Slots.Count; i++) + { + if (lobby.Slots[i].SlotId == localId) + { + curSq = lobby.Slots[i].SquadId; + break; + } + } + byte nextSq = (byte)((curSq + 1) % maxSquads); + _activeSession.RequestLobbySquad(nextSq); + } + private void OnLaunchPressed() { _activeSession?.RequestLobbyStart(); @@ -452,9 +539,10 @@ public sealed partial class LobbyScreen : CanvasLayer int seed = int.TryParse(_seedEdit.Text.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsed) ? parsed : lobby.SelectedSeed; + byte squadSize = (byte)Math.Clamp(_squadOption.Selected + 1, 1, 4); _seedEdit.ReleaseFocus(); - _activeSession.RequestLobbyConfig(seed, mapKind); + _activeSession.RequestLobbyConfig(seed, mapKind, squadSize); } private static void ApplyRowFrame(PanelContainer frame, Color borderColor, bool highlighted) diff --git a/client/Main.cs b/client/Main.cs index 9d76e57..ef7f1dd 100644 --- a/client/Main.cs +++ b/client/Main.cs @@ -17,7 +17,8 @@ public enum ClientScreenMode ServerBrowser, Lobby, InMatch, - PauseOverlay + PauseOverlay, + Settings } /// @@ -32,18 +33,23 @@ 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!; private Hud _hud = null!; private AtmosphereSystem _atmosphere = null!; private MainMenu _mainMenu = null!; + private SettingsOverlay _settingsOverlay = null!; private ServerBrowser _serverBrowser = null!; private LobbyScreen _lobbyScreen = null!; + private GraphicsSettings _graphicsSettings = new(); private IClientArenaSession? _session; private MatchState? _boundViewState; private bool _wasNetConnected; private ClientScreenMode _screenMode = ClientScreenMode.MainMenu; + private ClientScreenMode _settingsReturnMode = ClientScreenMode.MainMenu; + private bool _hasWindowOverride; private DirectoryReporter? _directoryReporter; private string _directoryUrl = ServerBrowser.DefaultDirectoryUrl; private string _publicHostOverride = "auto"; @@ -64,6 +70,7 @@ public partial class Main : Node3D private readonly List _frameEvents = new(128); private readonly List _frameFootsteps = new(32); private ArenaMapKind _mapKind = ArenaMapKind.Sion; + private byte _squadSize = 3; private string _callsign = "Pilot"; private string _lastEndpoint = $"127.0.0.1:{DefaultNetPort}"; @@ -102,6 +109,7 @@ public partial class Main : Node3D private readonly List _perfNodeCount = new(); private readonly List _perfTimeProcess = new(); private readonly List _perfTimePhysicsProcess = new(); + private readonly List _perfViewportGpuMs = new(); private double _perfPendingStepMs; private double _perfPendingTerrainMs; private double _perfPendingArenaMs; @@ -112,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; @@ -120,6 +129,8 @@ public partial class Main : Node3D public Hud Hud => _hud; public AtmosphereSystem Atmosphere => _atmosphere; public MainMenu MainMenuOverlay => _mainMenu; + public SettingsOverlay SettingsOverlay => _settingsOverlay; + public GraphicsSettings GraphicsSettings => _graphicsSettings; public ServerBrowser ServerBrowserOverlay => _serverBrowser; public LobbyScreen LobbyOverlay => _lobbyScreen; public ArenaMapKind MapKind => _mapKind; @@ -135,10 +146,16 @@ public partial class Main : Node3D public override void _Ready() { + ClientAssets.EnsureAssetsRootRegistered(); GetViewport().UseTaa = true; + _graphicsSettings = GraphicsSettings.Load(ResolveGraphicsSettingsPath()); + ApplyGraphicsEnvOverrides(_graphicsSettings); + _graphicsSettings.Changed += OnGraphicsSettingsChanged; + _atmosphere = new AtmosphereSystem { Name = "AtmosphereSystem" }; AddChild(_atmosphere); _atmosphere.EnsureInitialized(); + _atmosphere.ApplyGraphicsSettings(_graphicsSettings); _terrain = new TerrainRenderer { Name = "Terrain" }; AddChild(_terrain); @@ -146,9 +163,13 @@ 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(); + _atmosphere.BindEmitterPool(_arena.Volumetrics); _audio = new ArenaAudioSystem { Name = "ArenaAudio" }; AddChild(_audio); @@ -158,11 +179,11 @@ public partial class Main : Node3D Name = "ShoulderCamera", Current = true, Fov = 58f, - Far = 4200f + Far = 4800f }; AddChild(_camera); - _hud = new Hud(() => _session, OnEquipCargo, () => _cameraYaw) { Name = "Hud" }; + _hud = new Hud(() => _session, OnEquipCargo, () => _cameraYaw, ProjectWorldToHud) { Name = "Hud" }; _hud.JoinRequested += OnJoinRequested; _hud.HostRequested += OnHostRequested; _hud.SoloRequested += OnSoloRequested; @@ -187,8 +208,22 @@ public partial class Main : Node3D } }; _mainMenu.ReturnToMainMenuRequested += ReturnToMainMenu; + _mainMenu.SettingsRequested += OpenSettingsFromCurrentScreen; AddChild(_mainMenu); + _settingsOverlay = new SettingsOverlay { Name = "SettingsOverlay" }; + _settingsOverlay.SetGraphicsValues( + _graphicsSettings.VfxResolution, + _graphicsSettings.VolumetricSamples, + _graphicsSettings.SdfgiQuality, + _graphicsSettings.BorderlessFullscreen); + _settingsOverlay.GraphicsChanged += (res, samples, sdfgi, fullscreen) => + _graphicsSettings.Apply(res, samples, sdfgi, fullscreen, persist: !IsAutomatedRun); + _settingsOverlay.ResetDefaultsRequested += () => + _graphicsSettings.ResetToDefaults(persist: !IsAutomatedRun); + _settingsOverlay.BackRequested += CloseSettings; + AddChild(_settingsOverlay); + _serverBrowser = new ServerBrowser { Name = "ServerBrowser" }; _serverBrowser.JoinRequested += OnBrowserJoinRequested; _serverBrowser.HostRequested += () => @@ -226,6 +261,11 @@ public partial class Main : Node3D string? cliName = GetCliArg("--name"); string? cliMap = GetCliArg("--map"); string? cliSeed = GetCliArg("--seed"); + string? cliSquadSize = GetCliArg("--squad-size"); + if (int.TryParse(cliSquadSize ?? System.Environment.GetEnvironmentVariable("RTD_SQUAD_SIZE"), NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsedSquad)) + { + _squadSize = (byte)Math.Clamp(parsedSquad, 1, 4); + } bool cliSolo = GetCliArg("--solo", allowBareFlag: true) is not null || System.Environment.GetEnvironmentVariable("RTD_SOLO") == "1"; bool cliLobby = GetCliArg("--lobby", allowBareFlag: true) is not null @@ -291,13 +331,22 @@ public partial class Main : Node3D : $"127.0.0.1:{hostTarget.Trim()}"; } _hud.SetNetworkDefaults(_lastEndpoint, _callsign); - _mainMenu.SetDefaults(_callsign, _directoryUrl, _mapKind, DefaultNetPort); + _mainMenu.SetDefaults(_callsign, _directoryUrl, _mapKind, DefaultNetPort, _squadSize); _serverBrowser.Configure(_directoryUrl, _callsign, _lastEndpoint); if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_PERF_FRAMES"), out int perfFrames) && perfFrames > 0) { _perfTargetFrames = perfFrames; ArenaSession.PerfEnabled = true; + RenderingServer.ViewportSetMeasureRenderTime(GetViewport().GetViewportRid(), true); + if (_atmosphere.VolumetricEffect is not null) + { + _atmosphere.VolumetricEffect.ProfilingEnabled = true; + } + if (_hud?.HbCanvas is not null) + { + _hud.HbCanvas.ProfilingEnabled = true; + } } else if (int.TryParse(System.Environment.GetEnvironmentVariable("RTD_AUTO_EXIT_FRAMES"), out int autoExitFrames) && autoExitFrames > 0) { @@ -310,6 +359,28 @@ public partial class Main : Node3D } _menuPreviewOut = System.Environment.GetEnvironmentVariable("RTD_MENU_PREVIEW_OUT"); + _hasWindowOverride = GetCliArg("--windowed", allowBareFlag: true) is not null + || GetCliArg("--resolution", allowBareFlag: true) is not null + || GetCliArg("-w", allowBareFlag: true) is not null; + if (!IsAutomatedRun && !_hasWindowOverride) + { + ApplyWindowMode(_graphicsSettings.BorderlessFullscreen); + } + else + { + if (IsAutomatedRun && DisplayServer.GetName() != "headless") + { + DisplayServer.WindowSetFlag(DisplayServer.WindowFlags.NoFocus, true); + } + if (_hasWindowOverride && DisplayServer.GetName() != "headless") + { + var winMode = DisplayServer.WindowGetMode(); + bool actualFullscreen = winMode == DisplayServer.WindowMode.Fullscreen + || winMode == DisplayServer.WindowMode.ExclusiveFullscreen; + _graphicsSettings.SetBorderlessFullscreen(actualFullscreen, persist: false); + } + } + bool perfCombat = _perfTargetFrames > 0 && System.Environment.GetEnvironmentVariable("RTD_PERF_COMBAT") == "1"; bool skipInitialDrop = InitialSkipDropOverride || perfCombat; bool autoBypassMenu = InitialMapKindOverride.HasValue @@ -419,13 +490,17 @@ public partial class Main : Node3D DisposeSessionAndDirectory(); } - public void Reset(int seed, ArenaMapKind? mapKind = null, bool skipInitialDrop = false) + public void Reset(int seed, ArenaMapKind? mapKind = null, bool skipInitialDrop = false, byte? squadSize = null) { _seed = seed; if (mapKind.HasValue) { _mapKind = mapKind.Value; } + if (squadSize.HasValue) + { + _squadSize = (byte)Math.Clamp((int)squadSize.Value, 1, 4); + } DisposeSessionAndDirectory(); Failure = null; @@ -433,7 +508,7 @@ public partial class Main : Node3D try { - _session = new LocalArenaSession(seed, _mapKind, _callsign, skipInitialDrop); + _session = new LocalArenaSession(seed, _mapKind, _callsign, skipInitialDrop, squadSize: _squadSize); SetScreenMode(ClientScreenMode.InMatch); BindSessionPresentation(resetCamera: true); } @@ -450,7 +525,7 @@ public partial class Main : Node3D Failure = null; _hud.SetNetworkError(null); EnsureMenuSionBackdrop(); - _mainMenu.SetDefaults(_callsign, _directoryUrl, _mapKind, DefaultNetPort); + _mainMenu.SetDefaults(_callsign, _directoryUrl, _mapKind, DefaultNetPort, _squadSize); _mainMenu.SetHostPanelOpen(false); SetScreenMode(ClientScreenMode.MainMenu); } @@ -483,23 +558,29 @@ public partial class Main : Node3D private void EnsureMenuSionBackdrop() { _menuSionData ??= SionMapLoader.Load(); - _menuSionTerrain ??= TerrainField.LoadHeightmap( + _menuSionTerrain ??= TerrainField.LoadSharedHeightmap( _menuSionData.Metadata.SizeMeters, _menuSionData.Metadata.GridRes, - _menuSionData.Heights, + _menuSionData.Metadata.TileGrid, + _menuSionData.BaseDem, + _menuSionData.BaseDemMinY, + _menuSionData.BaseDemScale, _menuSionData.Metadata.MinY, _menuSionData.Metadata.MaxY, 42UL); - _terrain.Visible = false; + _terrain.Visible = true; _sionMap.Visible = true; _arena.Visible = false; _dropReticleMesh.Visible = false; _camera.Far = 4200f; _atmosphere.ApplyMap(ArenaMapKind.Sion); - _sionMap.EnsureBuilt(_menuSionData, _menuSionTerrain); + _sionMap.EnsureBuilt(_menuSionData); UpdateLobbyOrMenuOrbitCamera(ArenaMapKind.Sion, _menuSionTerrain); + _terrain.UpdateTileLod(_camera.GlobalPosition); + _terrain.Sync(_menuSionTerrain, _menuSionData); _sionMap.UpdateLod(_camera.GlobalPosition); + _foliage.SyncBackdrop(_menuSionData, _camera.GlobalPosition); } private void UpdateLobbyOrMenuOrbitCamera(ArenaMapKind mapKind, TerrainField terrain) @@ -526,7 +607,9 @@ public partial class Main : Node3D switch (mode) { case ClientScreenMode.MainMenu: + _hud.SetInputBlocked(true); _hud.SetMatchHudActive(false); + _settingsOverlay.SetSettingsVisible(false); _serverBrowser.SetBrowserVisible(false); _lobbyScreen.SetLobbyVisible(false); _mainMenu.SetOverlayKind(MainMenu.OverlayKind.MainMenu); @@ -535,7 +618,9 @@ public partial class Main : Node3D break; case ClientScreenMode.ServerBrowser: + _hud.SetInputBlocked(true); _hud.SetMatchHudActive(false); + _settingsOverlay.SetSettingsVisible(false); _mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden); _lobbyScreen.SetLobbyVisible(false); _serverBrowser.Configure(_directoryUrl, _callsign, _lastEndpoint); @@ -545,7 +630,9 @@ public partial class Main : Node3D break; case ClientScreenMode.Lobby: + _hud.SetInputBlocked(true); _hud.SetMatchHudActive(false); + _settingsOverlay.SetSettingsVisible(false); _mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden); _serverBrowser.SetBrowserVisible(false); _lobbyScreen.SetLobbyVisible(true); @@ -554,21 +641,44 @@ public partial class Main : Node3D break; case ClientScreenMode.InMatch: + _settingsOverlay.SetSettingsVisible(false); _mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden); _serverBrowser.SetBrowserVisible(false); _lobbyScreen.SetLobbyVisible(false); _arena.Visible = true; _hud.SetMatchHudActive(true); + _hud.SetInputBlocked(false); break; case ClientScreenMode.PauseOverlay: + _settingsOverlay.SetSettingsVisible(false); _serverBrowser.SetBrowserVisible(false); _lobbyScreen.SetLobbyVisible(false); _arena.Visible = true; _hud.SetMatchHudActive(true); + _hud.SetInputBlocked(true); _mainMenu.SetPauseContext(BuildPauseContextLine()); _mainMenu.SetOverlayKind(MainMenu.OverlayKind.PauseOverlay); break; + + case ClientScreenMode.Settings: + _mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden); + _serverBrowser.SetBrowserVisible(false); + _lobbyScreen.SetLobbyVisible(false); + bool showMatchBehind = _settingsReturnMode == ClientScreenMode.PauseOverlay; + _arena.Visible = showMatchBehind; + _hud.SetMatchHudActive(showMatchBehind); + if (!showMatchBehind) + { + _dropReticleMesh.Visible = false; + } + _settingsOverlay.SetGraphicsValues( + _graphicsSettings.VfxResolution, + _graphicsSettings.VolumetricSamples, + _graphicsSettings.SdfgiQuality, + _graphicsSettings.BorderlessFullscreen); + _settingsOverlay.SetSettingsVisible(true); + break; } SyncMouseMode(); } @@ -593,10 +703,13 @@ public partial class Main : Node3D string serverName, bool startInLobby, bool listOnPublicDirectory, - bool fallbackToLocalOnFailure) + bool fallbackToLocalOnFailure, + byte? squadSize = null) { string nextCallsign = string.IsNullOrWhiteSpace(callsign) ? "Host" : callsign.Trim(); string cleanServerName = string.IsNullOrWhiteSpace(serverName) ? "Rust to Dust" : serverName.Trim(); + byte activeSquadSize = (byte)Math.Clamp((int)(squadSize ?? _squadSize), 1, 4); + _squadSize = activeSquadSize; Failure = null; _hud.SetNetworkError(null); _mainMenu.SetHostError(null); @@ -612,7 +725,8 @@ public partial class Main : Node3D mapKind, startInLobby: startInLobby, serverName: cleanServerName, - minHumansToStart: 1); + minHumansToStart: 1, + squadSize: activeSquadSize); hostSession.Host.Session.SetHumanSlot(0, true, nextCallsign); DisposeSessionAndDirectory(); @@ -641,7 +755,7 @@ public partial class Main : Node3D Failure = ex.Message; if (fallbackToLocalOnFailure && _session is null) { - _session = new LocalArenaSession(_seed, _mapKind, _callsign); + _session = new LocalArenaSession(_seed, _mapKind, _callsign, squadSize: _squadSize); SetScreenMode(ClientScreenMode.InMatch); BindSessionPresentation(resetCamera: false); } @@ -677,7 +791,7 @@ public partial class Main : Node3D Failure = ex.Message; if (!fromBrowser && _session is null && _screenMode == ClientScreenMode.InMatch) { - _session = new LocalArenaSession(_seed, _mapKind, _callsign); + _session = new LocalArenaSession(_seed, _mapKind, _callsign, squadSize: _squadSize); SetScreenMode(ClientScreenMode.InMatch); BindSessionPresentation(resetCamera: false); } @@ -737,11 +851,12 @@ public partial class Main : Node3D } } - private void OnMainMenuPlaySolo(ArenaMapKind mapKind, string callsign) + private void OnMainMenuPlaySolo(ArenaMapKind mapKind, string callsign, byte squadSize) { _callsign = string.IsNullOrWhiteSpace(callsign) ? "Pilot" : callsign.Trim(); + _squadSize = (byte)Math.Clamp((int)squadSize, 1, 4); _hud.SetNetworkDefaults(_lastEndpoint, _callsign); - Reset(_seed, mapKind, skipInitialDrop: false); + Reset(_seed, mapKind, skipInitialDrop: false, squadSize: _squadSize); } private void OnMainMenuServerBrowser(string callsign) @@ -751,10 +866,11 @@ public partial class Main : Node3D SetScreenMode(ClientScreenMode.ServerBrowser); } - private void OnMainMenuHostLobby(int port, string serverName, ArenaMapKind mapKind, bool listOnPublicDirectory, string callsign) + private void OnMainMenuHostLobby(int port, string serverName, ArenaMapKind mapKind, bool listOnPublicDirectory, string callsign, byte squadSize) { string? envBind = System.Environment.GetEnvironmentVariable("RTD_BIND"); string hostArg = !string.IsNullOrWhiteSpace(envBind) ? $"{envBind.Trim()}:{port}" : port.ToString(CultureInfo.InvariantCulture); + _squadSize = (byte)Math.Clamp((int)squadSize, 1, 4); StartListenHostSession( hostArg, callsign, @@ -762,7 +878,8 @@ public partial class Main : Node3D serverName, startInLobby: true, listOnPublicDirectory: listOnPublicDirectory, - fallbackToLocalOnFailure: false); + fallbackToLocalOnFailure: false, + squadSize: _squadSize); } private void OnBrowserJoinRequested(string endpointText, string callsign) @@ -810,7 +927,7 @@ public partial class Main : Node3D _prevLocalLifecycle = p.Lifecycle; if (p.IsInDropPod) { - _cameraPitch = Mathf.DegToRad(36f); + _cameraPitch = Mathf.DegToRad(34f); _orbitalPodCamBlend = 1.0f; } else @@ -833,16 +950,20 @@ public partial class Main : Node3D _audio.ResetForSession(_session); } - _camera.Far = _mapKind == ArenaMapKind.Sion ? 4200f : 1800f; + _camera.Far = _mapKind == ArenaMapKind.Sion ? 4800f : 2600f; _atmosphere.ApplyMap(_mapKind); bool inLobby = _screenMode == ClientScreenMode.Lobby || state.Phase == MatchPhase.Lobby; + _terrain.Visible = true; + _terrain.InvalidateAll(); + _terrain.UpdateTileLod(_camera.GlobalPosition); + _terrain.Sync(state.Terrain, state.SionMap); + if (_mapKind == ArenaMapKind.Sion && state.SionMap is not null) { - _terrain.Visible = false; _sionMap.Visible = true; - _sionMap.EnsureBuilt(state.SionMap, state.Terrain); + _sionMap.EnsureBuilt(state.SionMap); if (!inLobby) { _arena.Sync(_session, _elapsedSeconds, 0f, 1f); @@ -852,14 +973,14 @@ public partial class Main : Node3D { UpdateLobbyOrMenuOrbitCamera(_mapKind, state.Terrain); } + _terrain.UpdateTileLod(_camera.GlobalPosition); _sionMap.UpdateLod(_camera.GlobalPosition); + _foliage.Sync(state, _camera.GlobalPosition); } else { _sionMap.Visible = false; - _terrain.Visible = true; - _terrain.InvalidateAll(); - _terrain.Sync(state.Terrain); + _foliage.Visible = false; if (!inLobby) { _arena.Sync(_session, _elapsedSeconds, 0f, 1f); @@ -878,6 +999,7 @@ public partial class Main : Node3D Vector3 startVec = new(localStart.X, localStart.Y, localStart.Z); Vector3 startFwd = new(MathF.Sin(localStart.Yaw), 0f, MathF.Cos(localStart.Yaw)); _arena.Particles.PrewarmFlashLights(startVec, startFwd); + _arena.GpuSparks.Prewarm(startVec); _arena.PomDecals.PrewarmShader(startVec); _hud.Sync(_session); } @@ -888,10 +1010,166 @@ public partial class Main : Node3D SyncMouseMode(); } + private bool IsAutomatedRun => + DisplayServer.GetName() == "headless" + || InitialMapKindOverride.HasValue + || InitialSkipDropOverride + || InitialSkipMenuOverride + || _perfTargetFrames > 0 + || _menuPreviewTargetFrames > 0 + || string.Equals(GetCliArg("--audio-driver"), "Dummy", StringComparison.OrdinalIgnoreCase) + || GetCliArg("--script", allowBareFlag: true) is not null + || !string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("RTD_NO_CAPTURE")) + || !string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("RTD_PERF_FRAMES")) + || !string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("RTD_AUTO_EXIT_FRAMES")) + || !string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("RTD_MENU_EXIT_FRAMES")); + + public override void _Notification(int what) + { + if (what == NotificationApplicationFocusOut || what == NotificationWMWindowFocusOut) + { + Input.MouseMode = Input.MouseModeEnum.Visible; + } + else if (what == NotificationApplicationFocusIn || what == NotificationWMWindowFocusIn) + { + if (IsInsideTree()) + { + SyncMouseMode(); + } + } + } + + private void OpenSettingsFromCurrentScreen() + { + if (_screenMode == ClientScreenMode.PauseOverlay || _screenMode == ClientScreenMode.MainMenu) + { + _settingsReturnMode = _screenMode; + } + SetScreenMode(ClientScreenMode.Settings); + } + + private void CloseSettings() + { + if (_screenMode == ClientScreenMode.Settings) + { + SetScreenMode(_settingsReturnMode); + } + } + + private void OnGraphicsSettingsChanged(GraphicsSettings settings) + { + _atmosphere.ApplyGraphicsSettings(settings); + _settingsOverlay?.SetGraphicsValues( + settings.VfxResolution, + settings.VolumetricSamples, + settings.SdfgiQuality, + settings.BorderlessFullscreen); + if (!IsAutomatedRun && DisplayServer.GetName() != "headless") + { + ApplyWindowMode(settings.BorderlessFullscreen); + } + } + + private static string? ResolveGraphicsSettingsPath() + { + try + { + return ProjectSettings.GlobalizePath("user://" + GraphicsSettings.DefaultFileName); + } + catch + { + return null; + } + } + + private static void ApplyGraphicsEnvOverrides(GraphicsSettings settings) + { + string? resEnv = System.Environment.GetEnvironmentVariable("RTD_VFX_RES"); + if (!string.IsNullOrWhiteSpace(resEnv)) + { + VfxResolutionScale? parsed = resEnv.Trim().ToLowerInvariant() switch + { + "half" or "0.5" or "0.5x" => VfxResolutionScale.Half, + "threequarter" or "three_quarter" or "high" or "0.75" or "0.75x" => VfxResolutionScale.ThreeQuarter, + "full" or "1.0" or "1.0x" or "native" => VfxResolutionScale.Full, + _ => null + }; + if (parsed.HasValue) + { + settings.SetVfxResolution(parsed.Value, persist: false); + } + } + + string? samplesEnv = System.Environment.GetEnvironmentVariable("RTD_VFX_SAMPLES"); + if (!string.IsNullOrWhiteSpace(samplesEnv)) + { + VolumetricSamples? parsed = samplesEnv.Trim().ToLowerInvariant() switch + { + "low" or "8" => VolumetricSamples.Low, + "medium" or "10" => VolumetricSamples.Medium, + "high" or "16" => VolumetricSamples.High, + "ultra" or "24" => VolumetricSamples.Ultra, + _ => null + }; + if (parsed.HasValue) + { + settings.SetVolumetricSamples(parsed.Value, persist: false); + } + } + + string? sdfgiEnv = System.Environment.GetEnvironmentVariable("RTD_SDFGI_QUALITY"); + if (!string.IsNullOrWhiteSpace(sdfgiEnv)) + { + SdfgiQuality? parsed = sdfgiEnv.Trim().ToLowerInvariant() switch + { + "off" => SdfgiQuality.Off, + "balanced" => SdfgiQuality.Balanced, + "high" => SdfgiQuality.High, + _ => null + }; + if (parsed.HasValue) + { + settings.SetSdfgiQuality(parsed.Value, persist: false); + } + } + } + + private static void ApplyWindowMode(bool borderlessFullscreen) + { + if (DisplayServer.GetName() == "headless") + { + return; + } + var current = DisplayServer.WindowGetMode(); + bool isFullscreen = current == DisplayServer.WindowMode.Fullscreen || current == DisplayServer.WindowMode.ExclusiveFullscreen; + if (isFullscreen != borderlessFullscreen) + { + DisplayServer.WindowSetMode(borderlessFullscreen ? DisplayServer.WindowMode.Fullscreen : DisplayServer.WindowMode.Windowed); + } + } + + private void ToggleBorderlessFullscreen() + { + if (IsAutomatedRun || DisplayServer.GetName() == "headless") + { + return; + } + var mode = DisplayServer.WindowGetMode(); + bool nextFullscreen = !(mode == DisplayServer.WindowMode.Fullscreen || mode == DisplayServer.WindowMode.ExclusiveFullscreen); + DisplayServer.WindowSetMode(nextFullscreen ? DisplayServer.WindowMode.Fullscreen : DisplayServer.WindowMode.Windowed); + _graphicsSettings.SetBorderlessFullscreen(nextFullscreen, persist: !IsAutomatedRun); + } + private void SyncMouseMode() { - if (DisplayServer.GetName() == "headless" || _perfTargetFrames > 0) + if (IsAutomatedRun) { + Input.MouseMode = Input.MouseModeEnum.Visible; + return; + } + if (!IsInsideTree() || GetWindow() is not { } win || !win.HasFocus()) + { + Input.MouseMode = Input.MouseModeEnum.Visible; return; } if (_screenMode != ClientScreenMode.InMatch) @@ -905,10 +1183,10 @@ public partial class Main : Node3D private static string? GetCliArg(string flag, bool allowBareFlag = false) { - static string? SearchArgs(string[] args, string flagName, bool bare) + static string? SearchArgs(string[] args, string flagName, bool bare, int startIndex = 0) { string prefix = flagName + "="; - for (int i = 0; i < args.Length; i++) + for (int i = startIndex; i < args.Length; i++) { string a = args[i]; if (a.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) @@ -931,7 +1209,8 @@ public partial class Main : Node3D } return SearchArgs(OS.GetCmdlineUserArgs(), flag, allowBareFlag) - ?? SearchArgs(OS.GetCmdlineArgs(), flag, allowBareFlag); + ?? SearchArgs(OS.GetCmdlineArgs(), flag, allowBareFlag) + ?? SearchArgs(System.Environment.GetCommandLineArgs(), flag, allowBareFlag, startIndex: 1); } private static void ParseBindAndPort(string? raw, IPAddress defaultIp, int defaultPort, out IPAddress bindIp, out int port) @@ -1013,6 +1292,21 @@ public partial class Main : Node3D public void SetScriptedInput(PlayerInput? input) => _scriptedInput = input; + public override void _Input(InputEvent @event) + { + if (@event is InputEventKey key && key.Pressed && !key.Echo) + { + bool isAltEnter = (key.Keycode == Key.Enter || key.Keycode == Key.KpEnter) + && key.AltPressed && !key.CtrlPressed && !key.ShiftPressed; + bool isF11 = key.Keycode == Key.F11 && !key.AltPressed && !key.CtrlPressed && !key.ShiftPressed; + if (isAltEnter || isF11) + { + ToggleBorderlessFullscreen(); + GetViewport().SetInputAsHandled(); + } + } + } + public override void _UnhandledInput(InputEvent @event) { if (@event is InputEventKey key && key.Pressed && !key.Echo) @@ -1045,6 +1339,14 @@ public partial class Main : Node3D } return; } + if (_screenMode == ClientScreenMode.Settings) + { + if (key.Keycode == Key.Escape) + { + CloseSettings(); + } + return; + } if (key.Keycode == Key.F9) { @@ -1125,10 +1427,9 @@ public partial class Main : Node3D Input.MouseMode == Input.MouseModeEnum.Visible && !_hud.GarageExpanded && !_hud.NetworkPanelOpen && - !_hud.IsPointerOverInteractiveHud(mb.Position) && - DisplayServer.GetName() != "headless") + !_hud.IsPointerOverInteractiveHud(mb.Position)) { - Input.MouseMode = Input.MouseModeEnum.Captured; + SyncMouseMode(); } } } @@ -1237,18 +1538,13 @@ public partial class Main : Node3D { _frameEvents.Clear(); _session.DrainSimEvents(_frameEvents); - if (_mapKind == ArenaMapKind.Desert) - { - _terrain.Sync(_session.ViewState.Terrain); - } UpdateLobbyOrMenuOrbitCamera(_mapKind, _session.ViewState.Terrain); + _terrain.UpdateTileLod(_camera.GlobalPosition); + _terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap); if (_mapKind == ArenaMapKind.Sion) { _sionMap.UpdateLod(_camera.GlobalPosition); - } - else - { - _terrain.UpdateTileLod(_camera.GlobalPosition); + _foliage.Sync(_session.ViewState, _camera.GlobalPosition); } _lobbyScreen.Sync(_session); return; @@ -1264,10 +1560,8 @@ public partial class Main : Node3D } double toMs = 1000.0 / Stopwatch.Frequency; long tt0 = Stopwatch.GetTimestamp(); - if (_mapKind == ArenaMapKind.Desert) - { - _terrain.Sync(_session.ViewState.Terrain); - } + _terrain.UpdateTileLod(_camera.GlobalPosition); + _terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap); long tt1 = Stopwatch.GetTimestamp(); _arena.Sync(_session, _elapsedSeconds, (float)delta, alpha); DrainAndFanSimEvents((float)delta, alpha); @@ -1278,13 +1572,11 @@ public partial class Main : Node3D long tc0 = Stopwatch.GetTimestamp(); UpdateCamera((float)delta, alpha); _audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, (float)delta, alpha); + _terrain.UpdateTileLod(_camera.GlobalPosition); if (_mapKind == ArenaMapKind.Sion) { _sionMap.UpdateLod(_camera.GlobalPosition); - } - else - { - _terrain.UpdateTileLod(_camera.GlobalPosition); + _foliage.Sync(_session.ViewState, _camera.GlobalPosition); } long th0 = Stopwatch.GetTimestamp(); var localP = _session.LocalContender; @@ -1318,6 +1610,10 @@ public partial class Main : Node3D _perfNodeCount.Add(Performance.GetMonitor(Performance.Monitor.ObjectNodeCount)); _perfTimeProcess.Add(Performance.GetMonitor(Performance.Monitor.TimeProcess) * 1000.0); _perfTimePhysicsProcess.Add(Performance.GetMonitor(Performance.Monitor.TimePhysicsProcess) * 1000.0); + if (ArenaSession.PerfEnabled) + { + _perfViewportGpuMs.Add(RenderingServer.ViewportGetMeasuredRenderTimeGpu(GetViewport().GetViewportRid())); + } _perfFrameCount++; if (_perfFrameCount >= _perfTargetFrames) @@ -1327,21 +1623,17 @@ public partial class Main : Node3D } else { - if (_mapKind == ArenaMapKind.Desert) - { - _terrain.Sync(_session.ViewState.Terrain); - } + _terrain.UpdateTileLod(_camera.GlobalPosition); + _terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap); _arena.Sync(_session, _elapsedSeconds, (float)delta, alpha); DrainAndFanSimEvents((float)delta, alpha); UpdateCamera((float)delta, alpha); _audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, (float)delta, alpha); + _terrain.UpdateTileLod(_camera.GlobalPosition); if (_mapKind == ArenaMapKind.Sion) { _sionMap.UpdateLod(_camera.GlobalPosition); - } - else - { - _terrain.UpdateTileLod(_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; @@ -1381,7 +1673,7 @@ public partial class Main : Node3D var local = _session.LocalContender; if (local.Lifecycle == ContenderLifecycle.Deploying && _prevLocalLifecycle != ContenderLifecycle.Deploying) { - _cameraPitch = Mathf.DegToRad(36f); + _cameraPitch = Mathf.DegToRad(34f); _orbitalPodCamBlend = 1.0f; } _prevLocalLifecycle = local.Lifecycle; @@ -1389,28 +1681,34 @@ public partial class Main : Node3D var localPos = new System.Numerics.Vector3(local.X, local.Y, local.Z); _camJuice.ConsumeEvents(_frameEvents, _session.LocalContenderId, localPos, _session); _camJuice.ConsumeFootsteps(_frameFootsteps, _session.LocalContenderId); + OrbitalPodPhase localPodPhase = OrbitalPodPhase.Freefall; + float camHorizSpeed = local.Speed; if (local.IsInDropPod) { var pods = _session.ActivePods; for (int i = 0; i < pods.Count; i++) { if (pods[i].PodKind == OrbitalPodKind.Contender && - pods[i].ContenderId == _session.LocalContenderId && - pods[i].Phase == OrbitalPodPhase.RetroBurn) + pods[i].ContenderId == _session.LocalContenderId) { - _camJuice.ApplyOrbitalBurnRumble(1.0f); + localPodPhase = pods[i].Phase; + camHorizSpeed = MathF.Sqrt(pods[i].VelX * pods[i].VelX + pods[i].VelZ * pods[i].VelZ); + if (pods[i].Phase == OrbitalPodPhase.RetroBurn) + { + _camJuice.ApplyOrbitalBurnRumble(1.0f); + } break; } } } - _camJuice.Update(dt, local.Speed, local.Grid.Spec.IsVtol); + _camJuice.Update(dt, camHorizSpeed, local.Grid.Spec.IsVtol, local.IsInDropPod, localPodPhase); } private static readonly Color DesertDustTint = new(0.76f, 0.59f, 0.40f, 1.0f); internal Color SampleCurrentMapGroundTint(float worldX, float worldZ) => _mapKind == ArenaMapKind.Sion - ? _sionMap.SampleGroundTint(worldX, worldZ) + ? _terrain.SampleGroundTint(worldX, worldZ) : DesertDustTint; private System.Numerics.Vector3? ResolveLiveWalkerFootWorld(bool isContender, int id, int legIndex) @@ -1467,7 +1765,7 @@ public partial class Main : Node3D double steadyFps = steadyAvgMs > 0 ? 1000.0 / steadyAvgMs : 0; GD.Print("=== PERF BENCHMARK SUMMARY ==="); - GD.Print($"Frames={_perfFrameMs.Count} PhysicsTicks={_perfPhysicsTicks} AvgFPS={fps:F2} SteadyFPS(10..59)={steadyFps:F2} EngineFPS={Engine.GetFramesPerSecond():F1}"); + GD.Print($"Frames={_perfFrameMs.Count} PhysicsTicks={_perfPhysicsTicks} AvgFPS={fps:F2} SteadyFPS(10..{_perfFrameMs.Count - 1})={steadyFps:F2} EngineFPS={Engine.GetFramesPerSecond():F1}"); GD.Print($"frameMs: avg={Avg(_perfFrameMs):F2} steadyAvg={steadyAvgMs:F2} p95={P95(_perfFrameMs):F2}"); GD.Print($"physicsStepMs/frame: avg={Avg(_perfPhysicsStepMs):F2} p95={P95(_perfPhysicsStepMs):F2}"); GD.Print($"terrainSyncMs/frame: avg={Avg(_perfTerrainSyncMs):F2} p95={P95(_perfTerrainSyncMs):F2} dirtyRebakesTotal={rebakeTotal} dirtyRebakesAvg={rebakeAvg:F2}"); @@ -1482,7 +1780,28 @@ public partial class Main : Node3D GD.Print($"UpdateCameraMs/frame: avg={_perfCamMsSum / _perfFrameMs.Count:F2}"); int ticks = Math.Max(1, _perfPhysicsTicks); GD.Print($"StepBreakdownMs/tick: ring={ArenaSession.PerfRingMs / ticks:F2} ai={ArenaSession.PerfAiMs / ticks:F2} drive={ArenaSession.PerfDriveMs / ticks:F2} world={ArenaSession.PerfWorldMs / ticks:F2} sync={ArenaSession.PerfBodySyncMs / ticks:F2} detect={ArenaSession.PerfDetectMs / ticks:F2} weapons={ArenaSession.PerfWeaponsMs / ticks:F2}"); - GD.Print($"CombatProbes: syncDamageHeatMsTotal={VehicleVisualInstance.PerfDamageHeatMs:F2} matDups={VehicleVisualInstance.PerfMaterialDupCount} bakeTileMsTotal={TerrainRenderer.PerfBakeTileMs:F2} bakeTileCalls={TerrainRenderer.PerfBakeTileCalls} debrisActive={_arena.Debris.ActiveCount} particlesActive={_arena.Particles.ActiveParticleCount} flashLightsPeak={_arena.Particles.PeakFlashLightCount} tracers={_session?.ViewState.Tracers.Count ?? 0}"); + GD.Print($"CombatProbes: syncDamageHeatMsTotal={VehicleVisualInstance.PerfDamageHeatMs:F2} matDups={VehicleVisualInstance.PerfMaterialDupCount} bakeTileMsTotal={TerrainRenderer.PerfBakeTileMs:F2} bakeTileCalls={TerrainRenderer.PerfBakeTileCalls} debrisActive={_arena.Debris.ActiveCount} gpuSparksEmitted={_arena.GpuSparks.TotalEmittedCount} volEmitters={_arena.Volumetrics.ActiveEmitterCount} volImpulses={_arena.Volumetrics.ActiveImpulseCount} flashLightsPeak={_arena.Particles.PeakFlashLightCount} tracers={_session?.ViewState.Tracers.Count ?? 0}"); + if (_atmosphere.VolumetricEffect is { } volFx) + { + Rid vpRid = GetViewport().GetViewportRid(); + double vpGpuMs = RenderingServer.ViewportGetMeasuredRenderTimeGpu(vpRid); + double vpCpuMs = RenderingServer.ViewportGetMeasuredRenderTimeCpu(vpRid); + GD.Print($"Cut10bGpuMs: total={volFx.LastTotalGpuMs:F3} flow={volFx.LastFlowGpuMs:F3} cull={volFx.LastCullGpuMs:F3} march={volFx.LastMarchGpuMs:F3} comp={volFx.LastCompGpuMs:F3} marchSize={volFx.LastMarchSize.X}x{volFx.LastMarchSize.Y} maxSteps={volFx.CurrentMaxSteps} maxIter={volFx.CurrentMaxIter} vfxRes={_graphicsSettings.VfxResolution} volSamples={_graphicsSettings.VolumetricSamples} sdfgi={_graphicsSettings.SdfgiQuality} viewportGpuMs={vpGpuMs:F2} viewportCpuMs={vpCpuMs:F2}"); + if (_perfViewportGpuMs.Count > 10) + { + var steadyGpu = new List(_perfViewportGpuMs.Count - 10); + for (int i = 10; i < _perfViewportGpuMs.Count; i++) steadyGpu.Add(_perfViewportGpuMs[i]); + steadyGpu.Sort(); + double gpuP50 = steadyGpu[(int)Math.Clamp(Math.Floor(steadyGpu.Count * 0.50), 0, steadyGpu.Count - 1)]; + double gpuP95 = steadyGpu[(int)Math.Clamp(Math.Ceiling(steadyGpu.Count * 0.95) - 1, 0, steadyGpu.Count - 1)]; + double gpuMax = steadyGpu[^1]; + GD.Print($"viewportGpuMsTimeline(10..{_perfViewportGpuMs.Count - 1}): avg={Avg(steadyGpu):F2} p50={gpuP50:F2} p95={gpuP95:F2} max={gpuMax:F2}"); + } + } + if (_hud?.HbCanvas is { } hb) + { + GD.Print($"HbGpuHud: drawCalls={hb.LastDrawCallCount} quads={hb.LastQuadCount} gpuMs={hb.LastHbGpuMs:F4}"); + } if (_session is not null) { var net = _session.ConnectionStatus; @@ -1491,7 +1810,7 @@ public partial class Main : Node3D } if (_mapKind == ArenaMapKind.Sion) { - GD.Print($"SionMap: chunks={_sionMap.TerrainChunkCount} tiles={_sionMap.BuildingTileCount} lod1={_sionMap.ActiveLod1TileCount} lod2={_sionMap.ActiveLod2TileCount} culled={_sionMap.CulledTileCount}"); + GD.Print($"SionMap: terrainTiles={_terrain.BakedTileCount} gpuScarSlots={_terrain.ActiveGpuScarSlots} bldgTiles={_sionMap.BuildingTileCount} lod1={_sionMap.ActiveLod1TileCount} lod2={_sionMap.ActiveLod2TileCount} culled={_sionMap.CulledTileCount}"); } foreach (var kv in _arena.AssetCache.Vehicles) { @@ -1768,11 +2087,11 @@ public partial class Main : Node3D new Vector3(posInterp.X, surfY + 0.35f, posInterp.Z)); _orbitalPodCamBlend = 1.0f; - float backDist = 23.0f * _cameraZoom; - Vector3 pivot = new(posInterp.X, posInterp.Y + 3.2f, posInterp.Z); + float backDist = 28.0f * _cameraZoom; + Vector3 pivot = new(posInterp.X, posInterp.Y + 4.0f, posInterp.Z); lookDir = (camFwdHoriz * MathF.Cos(_cameraPitch) - Vector3.Up * MathF.Sin(_cameraPitch)).Normalized(); - float effectiveRight = 2.6f; + float effectiveRight = 1.6f; if (CastStaticCameraRay(pivot, camRight, effectiveRight, out float rightHitDist)) { effectiveRight = MathF.Min(effectiveRight, SafeCameraPullbackDist(rightHitDist)); @@ -1966,7 +2285,7 @@ public partial class Main : Node3D var pt = new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z); float distFromOrigin = origin.DistanceTo(pt); - if (hit.StableId < ContenderStableIdBase) + if (ArenaSession.IsStaticWorldStableId(hit.StableId)) { if (distFromOrigin < hitDist) { @@ -1993,4 +2312,33 @@ public partial class Main : Node3D { _session?.RequestEquipCargo(cargoIndex, hardpointId); } + + private (bool Valid, bool InFront, Vector2 ScreenPos, System.Numerics.Vector3 CamLocal) ProjectWorldToHud(System.Numerics.Vector3 worldPos) + { + if (_camera is null || !GodotObject.IsInstanceValid(_camera) || !_camera.IsInsideTree()) + { + return (false, false, Vector2.Zero, System.Numerics.Vector3.Zero); + } + var wp = new Vector3(worldPos.X, worldPos.Y, worldPos.Z); + Transform3D camXform = _camera.GlobalTransform; + Vector3 rel = wp - camXform.Origin; + Basis b = camXform.Basis; + // Godot Camera3D local axes: +X = right, +Y = up, -Z = forward + float localRight = rel.Dot(b.X); + float localUp = rel.Dot(b.Y); + float localForward = -rel.Dot(b.Z); + var camLocal = new System.Numerics.Vector3(localRight, localUp, localForward); + + if (localForward <= 0.1f) + { + return (true, false, Vector2.Zero, camLocal); + } + + Vector2 sp = _camera.UnprojectPosition(wp); + if (!float.IsFinite(sp.X) || !float.IsFinite(sp.Y)) + { + return (true, false, Vector2.Zero, camLocal); + } + return (true, true, sp, camLocal); + } } diff --git a/client/MainMenu.cs b/client/MainMenu.cs index 15c8da9..2e1ec20 100644 --- a/client/MainMenu.cs +++ b/client/MainMenu.cs @@ -22,11 +22,13 @@ public sealed partial class MainMenu : CanvasLayer private ImperialChromePanel _menuPanel = null!; private ImperialChromePanel _hostPanel = null!; private LineEdit _callsignEdit = null!; + private OptionButton _soloSquadOption = null!; private Label _statusLabel = null!; private LineEdit _serverNameEdit = null!; private LineEdit _portEdit = null!; private OptionButton _hostMapOption = null!; + private OptionButton _hostSquadOption = null!; private CheckBox _listPublicCheck = null!; private Label _directoryHintLabel = null!; private Label _hostErrorLabel = null!; @@ -42,13 +44,14 @@ public sealed partial class MainMenu : CanvasLayer Layer = 20; } - public event Action? PlaySoloRequested; + public event Action? PlaySoloRequested; public event Action? ServerBrowserRequested; - public event Action? HostLobbyRequested; + public event Action? HostLobbyRequested; public event Action? CallsignChanged; public event Action? QuitRequested; public event Action? ResumeRequested; public event Action? ReturnToMainMenuRequested; + public event Action? SettingsRequested; public bool IsHostPanelOpen => _hostPanel is not null && _hostPanel.Visible; public bool IsTextInputFocused => @@ -97,13 +100,16 @@ public sealed partial class MainMenu : CanvasLayer } } - public void SetDefaults(string callsign, string directoryUrl, ArenaMapKind defaultMap = ArenaMapKind.Sion, int defaultPort = 3076) + public void SetDefaults(string callsign, string directoryUrl, ArenaMapKind defaultMap = ArenaMapKind.Sion, int defaultPort = 3076, byte defaultSquadSize = 3) { _directoryUrl = directoryUrl ?? string.Empty; if (_callsignEdit is not null) { _callsignEdit.Text = SanitizeCallsign(callsign); } + int sqIdx = Math.Clamp((int)defaultSquadSize, 1, 4) - 1; + _soloSquadOption?.Select(sqIdx); + _hostSquadOption?.Select(sqIdx); if (_portEdit is not null) { _portEdit.Text = defaultPort.ToString(CultureInfo.InvariantCulture); @@ -120,6 +126,14 @@ public sealed partial class MainMenu : CanvasLayer } } + public byte SelectedSoloSquadSize => _soloSquadOption is not null + ? (byte)Math.Clamp(_soloSquadOption.Selected + 1, 1, 4) + : (byte)3; + + public byte SelectedHostSquadSize => _hostSquadOption is not null + ? (byte)Math.Clamp(_hostSquadOption.Selected + 1, 1, 4) + : (byte)3; + public void SetStatus(string? message, bool isError = false) { if (_statusLabel is null) return; @@ -213,14 +227,26 @@ public sealed partial class MainMenu : CanvasLayer _callsignEdit.TextChanged += txt => CallsignChanged?.Invoke(SanitizeCallsign(txt)); callRow.AddChild(_callsignEdit); + var squadRow = new HBoxContainer(); + squadRow.AddThemeConstantOverride("separation", 10); + vbox.AddChild(squadRow); + + var squadLbl = ImperialChrome.CreateLabel("SQUAD MODE", 12, ImperialChrome.TextMuted); + squadLbl.CustomMinimumSize = new Vector2(82f, 0f); + squadRow.AddChild(squadLbl); + + _soloSquadOption = CreateSquadOptionButton(); + _soloSquadOption.ItemSelected += idx => _hostSquadOption?.Select((int)idx); + squadRow.AddChild(_soloSquadOption); + vbox.AddChild(ImperialChrome.MakeRule()); var playSionBtn = ImperialChrome.CreateButton("PLAY SOLO — SION", ImperialChrome.OliveCol, 14, 38f); - playSionBtn.Pressed += () => PlaySoloRequested?.Invoke(ArenaMapKind.Sion, Callsign); + playSionBtn.Pressed += () => PlaySoloRequested?.Invoke(ArenaMapKind.Sion, Callsign, SelectedSoloSquadSize); vbox.AddChild(playSionBtn); var playDesertBtn = ImperialChrome.CreateButton("PLAY SOLO — DESERT", ImperialChrome.OrangeCol, 14, 38f); - playDesertBtn.Pressed += () => PlaySoloRequested?.Invoke(ArenaMapKind.Desert, Callsign); + playDesertBtn.Pressed += () => PlaySoloRequested?.Invoke(ArenaMapKind.Desert, Callsign, SelectedSoloSquadSize); vbox.AddChild(playDesertBtn); var browserBtn = ImperialChrome.CreateButton("SERVER BROWSER", ImperialChrome.CyanCol, 14, 38f); @@ -231,6 +257,14 @@ public sealed partial class MainMenu : CanvasLayer hostBtn.Pressed += () => SetHostPanelOpen(!IsHostPanelOpen); vbox.AddChild(hostBtn); + var settingsBtn = ImperialChrome.CreateButton("SETTINGS", ImperialChrome.CyanCol, 14, 38f); + settingsBtn.Pressed += () => + { + SetHostPanelOpen(false); + SettingsRequested?.Invoke(); + }; + vbox.AddChild(settingsBtn); + vbox.AddChild(ImperialChrome.MakeRule()); var quitBtn = ImperialChrome.CreateButton("QUIT", ImperialChrome.RedCol, 13, 34f); @@ -314,6 +348,15 @@ public sealed partial class MainMenu : CanvasLayer ImperialChrome.StyleOptionButton(_hostMapOption, ImperialChrome.OliveCol, 13); mapRow.AddChild(_hostMapOption); + var hostSqRow = new HBoxContainer(); + hostSqRow.AddThemeConstantOverride("separation", 8); + vbox.AddChild(hostSqRow); + var hostSqLbl = ImperialChrome.CreateLabel("SQUAD MODE", 11, ImperialChrome.TextMuted); + hostSqLbl.CustomMinimumSize = new Vector2(106f, 0f); + hostSqRow.AddChild(hostSqLbl); + _hostSquadOption = CreateSquadOptionButton(); + hostSqRow.AddChild(_hostSquadOption); + _listPublicCheck = new CheckBox { Text = "List on Public Directory", @@ -361,7 +404,22 @@ public sealed partial class MainMenu : CanvasLayer bool listPublic = _listPublicCheck.ButtonPressed; SetHostError(null); - HostLobbyRequested?.Invoke(port, serverName, mapKind, listPublic, Callsign); + HostLobbyRequested?.Invoke(port, serverName, mapKind, listPublic, Callsign, SelectedHostSquadSize); + } + + private static OptionButton CreateSquadOptionButton() + { + var opt = new OptionButton + { + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill + }; + opt.AddItem("FFA (1)", 0); + opt.AddItem("DUO (2)", 1); + opt.AddItem("TRIO (3)", 2); + opt.AddItem("QUAD (4)", 3); + opt.Select(2); + ImperialChrome.StyleOptionButton(opt, ImperialChrome.CyanCol, 13); + return opt; } private void BuildPauseRoot() @@ -390,8 +448,8 @@ public sealed partial class MainMenu : CanvasLayer panel.AnchorBottom = 0.5f; panel.OffsetLeft = -190f; panel.OffsetRight = 190f; - panel.OffsetTop = -132f; - panel.OffsetBottom = 132f; + panel.OffsetTop = -156f; + panel.OffsetBottom = 156f; _pauseRoot.AddChild(panel); var vbox = new VBoxContainer(); @@ -408,6 +466,10 @@ public sealed partial class MainMenu : CanvasLayer resumeBtn.Pressed += () => ResumeRequested?.Invoke(); vbox.AddChild(resumeBtn); + var settingsBtn = ImperialChrome.CreateButton("SETTINGS", ImperialChrome.CyanCol, 14, 36f); + settingsBtn.Pressed += () => SettingsRequested?.Invoke(); + vbox.AddChild(settingsBtn); + var menuBtn = ImperialChrome.CreateButton("RETURN TO MAIN MENU", ImperialChrome.OrangeCol, 14, 36f); menuBtn.Pressed += () => ReturnToMainMenuRequested?.Invoke(); vbox.AddChild(menuBtn); diff --git a/client/NativeLibraries.cs b/client/NativeLibraries.cs index e5bafde..a2973a2 100644 --- a/client/NativeLibraries.cs +++ b/client/NativeLibraries.cs @@ -4,38 +4,66 @@ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Godot; +using RustToDust.HbGpu; using Ymir.Box3D; namespace RustToDust.Client; /// -/// Finds ymir_box3d for Ymir.Box3D's DllImports. Godot loads game assemblies into its own load context, so the -/// default probing does not look beside them. A run from the editor or --path loads the library from the -/// project's build directory; an exported run from the data folder Godot puts beside the executable. +/// Resolves native libraries (ymir_box3d, rtd_hbgpu) for Godot's AssemblyLoadContext. /// internal static class NativeLibraries { - private const string Library = "ymir_box3d"; + private const string YmirLibrary = "ymir_box3d"; + private const string HbGpuLibrary = "rtd_hbgpu"; #pragma warning disable CA2255 // application code: the resolver must exist before the first DllImport [ModuleInitializer] - internal static void Register() => + internal static void Register() + { NativeLibrary.SetDllImportResolver(typeof(Box3DSoaWorld).Assembly, Resolve); + NativeLibrary.SetDllImportResolver(typeof(HbGpuNative).Assembly, Resolve); + } private static IntPtr Resolve(string name, Assembly assembly, DllImportSearchPath? searchPath) { - if (name != Library) return IntPtr.Zero; - string fileName = FileName(); + string? stem = name switch + { + YmirLibrary => YmirLibrary, + HbGpuLibrary => HbGpuLibrary, + _ => null + }; + if (stem is null) + { + return IntPtr.Zero; + } + + string fileName = FileName(stem); if (OS.HasFeature("template")) { - string exportPath = Path.Combine( - Path.GetDirectoryName(OS.GetExecutablePath())!, - $"data_RustToDust.Client_{Platform()}_{Arch()}", - fileName); - return File.Exists(exportPath) && NativeLibrary.TryLoad(exportPath, out var exportHandle) - ? exportHandle - : IntPtr.Zero; + string exePath = OS.GetExecutablePath(); + string exeDir = exePath.GetBaseDir(); + string exeStem = Path.GetFileNameWithoutExtension(exePath); + string platArch = $"{Platform()}_{Arch()}"; + + string[] candidates = + { + Path.Combine(exeDir, fileName), + Path.Combine(exeDir, $"data_{exeStem}_{platArch}", fileName), + Path.Combine(exeDir, $"data_RustToDust_{platArch}", fileName), + Path.Combine(exeDir, $"data_RustToDust.Client_{platArch}", fileName), + Path.Combine(AppContext.BaseDirectory, fileName), + }; + + foreach (string candidate in candidates) + { + if (File.Exists(candidate) && NativeLibrary.TryLoad(candidate, out var exportHandle)) + { + return exportHandle; + } + } + return IntPtr.Zero; } string debugPath = Path.Combine(ProjectSettings.GlobalizePath("res://.godot/mono/temp/bin/Debug"), fileName); @@ -50,8 +78,8 @@ internal static class NativeLibraries : IntPtr.Zero; } - private static string FileName() => - OperatingSystem.IsWindows() ? "ymir_box3d.dll" : OperatingSystem.IsMacOS() ? "libymir_box3d.dylib" : "libymir_box3d.so"; + private static string FileName(string stem) => + OperatingSystem.IsWindows() ? $"{stem}.dll" : OperatingSystem.IsMacOS() ? $"lib{stem}.dylib" : $"lib{stem}.so"; private static string Platform() => OperatingSystem.IsWindows() ? "windows" : OperatingSystem.IsMacOS() ? "macos" : "linuxbsd"; diff --git a/client/ParticlePool.cs b/client/ParticlePool.cs index 3e61689..6c0c823 100644 --- a/client/ParticlePool.cs +++ b/client/ParticlePool.cs @@ -6,40 +6,16 @@ using RustToDust.Core; namespace RustToDust.Client; /// -/// Single-draw-call GPU billboard particle pool ( backed by -/// particle_billboard.gdshader) plus the strictly capped [2] -/// dynamic combat flash pool for Forward+ Vulkan. +/// Owns ONLY the strictly capped [2] dynamic combat flash pool +/// plus idempotent deduplication and dispatch into +/// (smoke/fire/shockwaves) and +/// ( sparks/embers/dust/muzzle bursts). +/// Zero CPU particle buffers or billboard MultiMeshes. /// public partial class ParticlePool : Node3D { - public const int MaxParticles = 512; public const int MaxFlashLights = 2; - public const float ModeDustSmoke = 0f; - public const float ModeMuzzleStarburst = 1f; - public const float ModeSparkStreak = 2f; - public const float ModeSteamFire = 3f; - - private struct ParticleSlot - { - public bool Active; - public float Mode; - public Vector3 Position; - public Vector3 Velocity; - public float Gravity; - public float Drag; - public float StartSize; - public float EndSize; - public float AspectY; - public float Rotation; - public float AngularVel; - public float Emissive; - public Color ColorStart; - public Color ColorEnd; - public float Age; - public float Lifetime; - } - private struct FlashLightSlot { public OmniLight3D Light; @@ -52,7 +28,6 @@ public partial class ParticlePool : Node3D public Color Color; } - private readonly ParticleSlot[] _particles = new ParticleSlot[MaxParticles]; private readonly FlashLightSlot[] _flashLights = new FlashLightSlot[MaxFlashLights]; // Bounded rolling dedupe buffers (zero polling cursor on MatchState) @@ -61,15 +36,11 @@ public partial class ParticlePool : Node3D private readonly long[] _recentHitIds = new long[64]; private int _recentHitCursor; - private MultiMesh _multiMesh = null!; - private MultiMeshInstance3D _instanceNode = null!; - private ShaderMaterial _material = null!; - private int _writeCursor; + private VolumetricEmitterPool? _volumetrics; + private GpuSparksSystem? _gpuSparks; private int _warmupFramesRemaining; private bool _initialized; - private uint _rng = 0x7A3B91E5u; - public int ActiveParticleCount { get; private set; } public int FlashLightPoolSize => MaxFlashLights; public int ActiveFlashLightCount @@ -87,6 +58,12 @@ public partial class ParticlePool : Node3D public int PeakFlashLightCount { get; private set; } + public void BindTargets(VolumetricEmitterPool volumetrics, GpuSparksSystem gpuSparks) + { + _volumetrics = volumetrics; + _gpuSparks = gpuSparks; + } + public override void _Ready() { EnsureInitialized(); @@ -100,32 +77,6 @@ public partial class ParticlePool : Node3D } _initialized = true; - Shader shader = GD.Load("res://particle_billboard.gdshader") - ?? throw new InvalidOperationException("Failed to load res://particle_billboard.gdshader"); - _material = new ShaderMaterial { Shader = shader }; - - _multiMesh = new MultiMesh - { - TransformFormat = MultiMesh.TransformFormatEnum.Transform3D, - UseColors = true, - UseCustomData = true, - Mesh = new QuadMesh { Size = Vector2.One }, - InstanceCount = MaxParticles, - VisibleInstanceCount = 0 - }; - - _instanceNode = new MultiMeshInstance3D - { - Name = "ParticleBillboardBatch", - Multimesh = _multiMesh, - MaterialOverride = _material, - CastShadow = GeometryInstance3D.ShadowCastingSetting.Off, - CustomAabb = new Aabb(new Vector3(-1600f, -60f, -1600f), new Vector3(3200f, 500f, 3200f)), - PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, - Visible = false - }; - AddChild(_instanceNode); - for (int i = 0; i < MaxFlashLights; i++) { var light = new OmniLight3D @@ -144,7 +95,7 @@ public partial class ParticlePool : Node3D } /// - /// Pre-warms the pooled nodes on startup for 1 rendered frame + /// Pre-warms the pooled nodes on startup for 2 rendered frames /// with near-zero energy so Forward+ compiles lit shader variants before combat begins. /// public void PrewarmFlashLights(Vector3 nearPos, Vector3 forwardHoriz) @@ -168,31 +119,18 @@ public partial class ParticlePool : Node3D slot.Light.LightEnergy = 0.001f; slot.Light.Visible = true; } - - // Also pre-warm the particle billboard shader on frame 0 with 1 micro-quad - _multiMesh.SetInstanceTransform(0, new Transform3D(Basis.FromScale(new Vector3(0.01f, 0.01f, 1f)), nearPos)); - _multiMesh.SetInstanceColor(0, new Color(1f, 1f, 1f, 0.01f)); - _multiMesh.SetInstanceCustomData(0, new Color(ModeDustSmoke, 0f, 0f, 0f)); - _multiMesh.VisibleInstanceCount = 1; - _instanceNode.Visible = true; } public void ClearAll() { EnsureInitialized(); - Array.Clear(_particles, 0, _particles.Length); Array.Clear(_recentShotIds, 0, _recentShotIds.Length); Array.Clear(_recentHitIds, 0, _recentHitIds.Length); _recentShotCursor = 0; _recentHitCursor = 0; - _writeCursor = 0; _warmupFramesRemaining = 0; - ActiveParticleCount = 0; PeakFlashLightCount = 0; - _multiMesh.VisibleInstanceCount = 0; - _instanceNode.Visible = false; - for (int i = 0; i < _flashLights.Length; i++) { _flashLights[i].Active = false; @@ -293,35 +231,9 @@ public partial class ParticlePool : Node3D float massScale = Math.Clamp(pulse.MassKg / 2600f, 0.72f, 1.55f); float loadScale = Math.Clamp(pulse.LoadG, 0.5f, 1.8f); - int count = pulse.MassKg >= 3600f ? 3 : 2; - - Color dustStart = new(groundTint.R, groundTint.G, groundTint.B, 0.50f); - Color dustEnd = new(groundTint.R * 0.92f, groundTint.G * 0.92f, groundTint.B * 0.92f, 0.0f); - - for (int i = 0; i < count; i++) - { - float ang = (i / (float)count) * MathF.Tau + NextFloat() * 0.8f; - float speed = (2.2f + NextFloat() * 2.6f) * massScale * MathF.Sqrt(loadScale); - Vector3 vel = new(MathF.Cos(ang) * speed, 0.85f + NextFloat() * 1.1f, MathF.Sin(ang) * speed); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeDustSmoke, - Position = footPos + new Vector3(MathF.Cos(ang) * 0.25f, 0f, MathF.Sin(ang) * 0.25f), - Velocity = vel, - Gravity = 0.25f, - Drag = 2.8f, - StartSize = 0.55f * massScale, - EndSize = MathF.Min(2.2f, 1.55f * massScale), - AspectY = 1.0f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.4f, - Emissive = 0f, - ColorStart = dustStart, - ColorEnd = dustEnd, - Lifetime = 0.35f + NextFloat() * 0.18f - }); - } + int count = pulse.MassKg >= 3600f ? 42 : 26; + _gpuSparks?.EmitDustMotes(footPos, Vector3.Up, count, groundTint with { A = 0.76f }, 3.4f * massScale * MathF.Sqrt(loadScale), 0.048f * massScale); + _volumetrics?.EmitFootstepOrTirePuff(footPos, groundTint, massScale); } public void EmitTireDust(Vector3 worldPos, Vector3 vehicleVel, Color groundTint, float intensity, Vector3 camPos, bool hasCam) @@ -333,27 +245,8 @@ public partial class ParticlePool : Node3D } float scale = Math.Clamp(intensity, 0.5f, 1.5f); - Color dustStart = new(groundTint.R, groundTint.G, groundTint.B, 0.42f); - Color dustEnd = new(groundTint.R * 0.95f, groundTint.G * 0.95f, groundTint.B * 0.95f, 0.0f); - - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeDustSmoke, - Position = worldPos + new Vector3(NextSigned() * 0.3f, 0.18f, NextSigned() * 0.3f), - Velocity = -vehicleVel * 0.15f + new Vector3(NextSigned() * 1.1f, 0.9f + NextFloat() * 0.8f, NextSigned() * 1.1f), - Gravity = 0.15f, - Drag = 2.4f, - StartSize = 0.50f * scale, - EndSize = MathF.Min(2.1f, 1.65f * scale), - AspectY = 1.0f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.2f, - Emissive = 0f, - ColorStart = dustStart, - ColorEnd = dustEnd, - Lifetime = 0.36f + NextFloat() * 0.16f - }); + _gpuSparks?.EmitDustMotes(worldPos, Vector3.Up, 18, groundTint with { A = 0.70f }, 2.6f * scale, 0.045f * scale); + _volumetrics?.EmitFootstepOrTirePuff(worldPos, groundTint, scale * 0.9f); } public void EmitThermalVent(Vector3 worldPos, float thermalRatio, Vector3 camPos, bool hasCam) @@ -364,46 +257,10 @@ public partial class ParticlePool : Node3D return; } - float heatT = Math.Clamp((thermalRatio - 0.85f) / 0.25f, 0f, 1f); - SpawnParticle(new ParticleSlot + _volumetrics?.EmitThermalVentPlume(worldPos, thermalRatio); + if (thermalRatio >= 0.94f) { - Active = true, - Mode = ModeSteamFire, - Position = worldPos + new Vector3(NextSigned() * 0.25f, 0.15f, NextSigned() * 0.25f), - Velocity = new Vector3(NextSigned() * 0.9f, 2.2f + NextFloat() * 1.5f, NextSigned() * 0.9f), - Gravity = -0.35f, - Drag = 1.6f, - StartSize = 0.40f, - EndSize = 1.25f + heatT * 0.35f, - AspectY = 1.0f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.8f, - Emissive = 0.35f + heatT * 0.85f, - ColorStart = new Color(0.95f, 0.88f - heatT * 0.32f, 0.78f - heatT * 0.50f, 0.62f), - ColorEnd = new Color(0.65f, 0.58f, 0.54f, 0.0f), - Lifetime = 0.36f + NextFloat() * 0.16f - }); - - if (heatT > 0.35f) - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSparkStreak, - Position = worldPos, - Velocity = new Vector3(NextSigned() * 3.5f, 2.5f + NextFloat() * 3.5f, NextSigned() * 3.5f), - Gravity = 9.0f, - Drag = 0.6f, - StartSize = 0.24f, - EndSize = 0.10f, - AspectY = 1.3f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = 0f, - Emissive = 2.6f, - ColorStart = new Color(1.0f, 0.62f, 0.16f, 0.95f), - ColorEnd = new Color(0.9f, 0.24f, 0.06f, 0.0f), - Lifetime = 0.22f + NextFloat() * 0.12f - }); + _gpuSparks?.EmitSparkBurst(worldPos, Vector3.Up, 20, new Color(4.6f, 2.4f, 0.55f, 0.96f), 6.5f, 0.026f); } } @@ -415,46 +272,128 @@ public partial class ParticlePool : Node3D return; } - float dmgT = Math.Clamp((0.35f - coreHpRatio) / 0.35f, 0f, 1f); - SpawnParticle(new ParticleSlot + _volumetrics?.EmitDamageSmokePlume(worldPos, coreHpRatio); + if (coreHpRatio < 0.24f) { - Active = true, - Mode = ModeDustSmoke, - Position = worldPos + new Vector3(NextSigned() * 0.35f, 0.35f, NextSigned() * 0.35f), - Velocity = new Vector3(NextSigned() * 0.8f, 2.4f + NextFloat() * 1.4f, NextSigned() * 0.8f), - Gravity = -0.35f, - Drag = 1.2f, - StartSize = 0.58f, - EndSize = MathF.Min(2.2f, 1.65f + dmgT * 0.55f), - AspectY = 1.0f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.1f, - Emissive = 0f, - ColorStart = new Color(0.18f, 0.16f, 0.15f, 0.70f), - ColorEnd = new Color(0.10f, 0.10f, 0.10f, 0.0f), - Lifetime = 0.55f + NextFloat() * 0.25f - }); + _gpuSparks?.EmitEmberBurst(worldPos, 16, new Color(4.2f, 1.8f, 0.35f, 0.94f), 2.4f, 0.030f); + } + } - if (dmgT > 0.3f && NextFloat() < 0.65f) + public void EmitOrdnanceBurst(Vector3 pos, Color accentCol, int sparkCount, float radiusScale, Vector3 camPos, bool hasCam) + { + EnsureInitialized(); + if (hasCam && pos.DistanceSquaredTo(camPos) > 220f * 220f) { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = worldPos + new Vector3(NextSigned() * 0.22f, 0.25f, NextSigned() * 0.22f), - Velocity = new Vector3(NextSigned() * 0.6f, 2.1f + NextFloat() * 1.1f, NextSigned() * 0.6f), - Gravity = -0.4f, - Drag = 1.8f, - StartSize = 0.45f, - EndSize = 0.95f, - AspectY = 1.0f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 2.0f, - Emissive = 2.2f, - ColorStart = new Color(1.0f, 0.56f, 0.14f, 0.92f), - ColorEnd = new Color(0.65f, 0.16f, 0.04f, 0.0f), - Lifetime = 0.26f + NextFloat() * 0.12f - }); + return; + } + + Color moltenHdr = new(4.8f, 2.6f, 0.65f, 0.98f); + Color subtleTint = new( + Mathf.Lerp(moltenHdr.R, accentCol.R * 3.8f, 0.25f), + Mathf.Lerp(moltenHdr.G, accentCol.G * 3.8f, 0.25f), + Mathf.Lerp(moltenHdr.B, accentCol.B * 3.8f, 0.25f), + 0.98f); + _gpuSparks?.EmitSparkBurst(pos, Vector3.Up, Math.Clamp(sparkCount * 16, 48, 160), subtleTint, 15f * radiusScale, 0.028f); + _gpuSparks?.EmitEmberBurst(pos, Math.Clamp(sparkCount * 7, 22, 80), moltenHdr * 0.85f, 5.0f * radiusScale, 0.032f); + } + + public void EmitThermalPoolEmber(Vector3 pos, float radius, Color accentCol, Vector3 camPos, bool hasCam) + { + EnsureInitialized(); + if (hasCam && pos.DistanceSquaredTo(camPos) > 150f * 150f) + { + return; + } + + _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(); + if (hasCam && podPos.DistanceSquaredTo(camPos) > 650f * 650f) + { + return; + } + + _volumetrics?.EmitPodReentryPlume(podPos, podVel, heatGlow, isContender); + _gpuSparks?.EmitEmberBurst(podPos, isContender ? 20 : 12, new Color(4.4f, 2.2f, 0.55f, 0.95f), 2.8f, 0.030f); + } + + public void EmitPodRetroBurn( + Vector3 podBasePos, + float agl, + Color groundTint, + bool isContender, + bool isLocal, + Vector3 camPos, + bool hasCam) + { + EnsureInitialized(); + float distSq = hasCam ? podBasePos.DistanceSquaredTo(camPos) : 0f; + if (hasCam && distSq > 480f * 480f) + { + return; + } + + _volumetrics?.EmitPodRetroPlume(podBasePos, agl, groundTint, isContender); + _gpuSparks?.EmitPodRetroSparksAndDust(podBasePos, agl, groundTint, isContender); + + if (isLocal || !hasCam || distSq <= 95f * 95f) + { + SpawnFlashLight(podBasePos - new Vector3(0f, 0.6f, 0f), new Color(1.0f, 0.60f, 0.18f), 3.8f, 14f, 0.09f, priority: isLocal ? 8 : 3); + } + } + + public void EmitPodTouchdownBurst( + Vector3 pos, + Vector3 normal, + Color groundTint, + bool isContender, + bool isLocal, + Vector3 camPos, + bool hasCam) + { + EnsureInitialized(); + float distSq = hasCam ? pos.DistanceSquaredTo(camPos) : 0f; + if (!isLocal && hasCam && distSq > 360f * 360f) + { + return; + } + + _volumetrics?.EmitPodTouchdownPlume(pos, normal, groundTint, isContender); + _gpuSparks?.EmitPodTouchdownSparksAndDust(pos, normal, groundTint, isContender); + + if (isLocal || !hasCam || distSq <= 140f * 140f) + { + SpawnFlashLight(pos + normal * 1.2f, new Color(1.0f, 0.58f, 0.16f), 5.8f, 18f, 0.18f, priority: isLocal ? 10 : 6); } } @@ -469,49 +408,6 @@ public partial class ParticlePool : Node3D EnsureInitialized(); float stepDt = float.IsFinite(dt) && dt > 0f ? Math.Clamp(dt, 0f, 0.05f) : 0f; - // 1. Advance particles and pack active billboards into MultiMesh - int visibleCount = 0; - for (int i = 0; i < MaxParticles; i++) - { - ref ParticleSlot p = ref _particles[i]; - if (!p.Active) - { - continue; - } - - if (stepDt > 0f) - { - p.Age += stepDt; - if (p.Age >= p.Lifetime) - { - p.Active = false; - continue; - } - if (p.Drag > 0f) - { - p.Velocity *= MathF.Exp(-p.Drag * stepDt); - } - p.Velocity.Y -= p.Gravity * stepDt; - p.Position += p.Velocity * stepDt; - p.Rotation += p.AngularVel * stepDt; - } - - float ageNorm = Math.Clamp(p.Age / MathF.Max(0.01f, p.Lifetime), 0f, 1f); - float size = Mathf.Lerp(p.StartSize, p.EndSize, ageNorm); - Color col = p.ColorStart.Lerp(p.ColorEnd, ageNorm); - - var scale = new Vector3(size, size * p.AspectY, 1f); - _multiMesh.SetInstanceTransform(visibleCount, new Transform3D(Basis.FromScale(scale), p.Position)); - _multiMesh.SetInstanceColor(visibleCount, col); - _multiMesh.SetInstanceCustomData(visibleCount, new Color(p.Mode, ageNorm, p.Emissive, p.Rotation)); - visibleCount++; - } - - ActiveParticleCount = visibleCount; - _multiMesh.VisibleInstanceCount = visibleCount; - _instanceNode.Visible = visibleCount > 0; - - // 2. Advance pooled OmniLight3D[2] dynamic flashes int activeLights = 0; for (int i = 0; i < _flashLights.Length; i++) { @@ -586,7 +482,7 @@ public partial class ParticlePool : Node3D Vector3 start = new(shot.StartX, shot.StartY, shot.StartZ); Vector3 end = new(shot.EndX, shot.EndY, shot.EndZ); - if (hasCam && start.DistanceSquaredTo(camPos) > 120f * 120f) + if (hasCam && start.DistanceSquaredTo(camPos) > 140f * 140f) { return; } @@ -595,268 +491,80 @@ public partial class ParticlePool : Node3D bool isRecoilless = string.Equals(shot.WeaponId, "recoilless", StringComparison.Ordinal); bool isLance = string.Equals(shot.WeaponId, "gilded_lance", StringComparison.Ordinal); bool isPd = string.Equals(shot.WeaponId, "pd_flak", StringComparison.Ordinal); + Vector3 aimDir = (end - start).LengthSquared() > 1e-4f ? (end - start).Normalized() : Vector3.Forward; switch (wClass) { case WeaponVisualClass.KineticLight: - { - float flashSize = isPd ? 0.62f : 0.44f; - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeMuzzleStarburst, - Position = start, - Velocity = Vector3.Zero, - StartSize = flashSize, - EndSize = flashSize * 0.45f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 2.2f, - ColorStart = new Color(1.0f, 0.85f, 0.42f, 0.95f), - ColorEnd = new Color(0.95f, 0.55f, 0.16f, 0.0f), - Lifetime = 0.065f - }); + _gpuSparks?.EmitMuzzleStarburst(start, new Color(4.2f, 2.8f, 1.0f, 0.96f), isPd ? 0.42f : 0.30f, 0.07f); + _gpuSparks?.EmitSparkBurst(start, aimDir, 18, new Color(4.5f, 2.8f, 0.8f, 0.96f), 11f, 0.024f); break; - } case WeaponVisualClass.Autocannon: - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeMuzzleStarburst, - Position = start, - Velocity = Vector3.Zero, - StartSize = 1.05f, - EndSize = 0.45f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 2.8f, - ColorStart = new Color(1.0f, 0.72f, 0.25f, 0.98f), - ColorEnd = new Color(0.95f, 0.40f, 0.10f, 0.0f), - Lifetime = 0.08f - }); - for (int p = 0; p < 2; p++) - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeDustSmoke, - Position = start + new Vector3(NextSigned() * 0.2f, NextFloat() * 0.15f, NextSigned() * 0.2f), - Velocity = new Vector3(NextSigned() * 0.9f, 1.1f + NextFloat() * 0.8f, NextSigned() * 0.9f), - Gravity = -0.15f, - Drag = 2.2f, - StartSize = 0.35f, - EndSize = 1.15f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.4f, - Emissive = 0f, - ColorStart = new Color(0.55f, 0.50f, 0.44f, 0.46f), - ColorEnd = new Color(0.42f, 0.40f, 0.38f, 0.0f), - Lifetime = 0.32f - }); - } + _gpuSparks?.EmitMuzzleStarburst(start, new Color(4.6f, 2.6f, 0.75f, 0.98f), 0.56f, 0.08f); + _gpuSparks?.EmitSparkBurst(start, aimDir, 32, new Color(4.8f, 2.6f, 0.65f, 0.96f), 13f, 0.026f); + _volumetrics?.EmitMuzzleBreechPuff(start, end, sampleGroundTint(start.X, start.Z), wClass, isRecoilless: false); if (!hasCam || start.DistanceSquaredTo(camPos) <= 45f * 45f) { SpawnFlashLight(start, new Color(1.0f, 0.68f, 0.24f), 2.8f, 10.5f, 0.10f, priority: 3); } break; - } case WeaponVisualClass.Explosive: - { - float flashSize = isRecoilless ? 1.55f : 0.85f; - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeMuzzleStarburst, - Position = start, - Velocity = Vector3.Zero, - StartSize = flashSize, - EndSize = flashSize * 0.48f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 3.2f, - ColorStart = new Color(1.0f, 0.68f, 0.22f, 0.98f), - ColorEnd = new Color(0.95f, 0.32f, 0.08f, 0.0f), - Lifetime = 0.095f - }); - - int puffs = isRecoilless ? 4 : 2; - Color gTint = sampleGroundTint(start.X, start.Z); - Color smokeCol = new( - Mathf.Lerp(0.56f, gTint.R, 0.35f), - Mathf.Lerp(0.52f, gTint.G, 0.35f), - Mathf.Lerp(0.46f, gTint.B, 0.35f), - 0.58f); - for (int p = 1; p <= puffs; p++) - { - float frac = p / (float)(puffs + 1); - Vector3 smokePos = start.Lerp(end, frac); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeDustSmoke, - Position = smokePos, - Velocity = new Vector3(NextSigned() * 0.6f, 1.3f + NextFloat() * 0.6f, NextSigned() * 0.6f), - Gravity = -0.2f, - Drag = 1.8f, - StartSize = isRecoilless ? 0.48f : 0.30f, - EndSize = isRecoilless ? 1.65f : 0.95f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.2f, - Emissive = 0f, - ColorStart = smokeCol, - ColorEnd = smokeCol with { A = 0f }, - Lifetime = isRecoilless ? 0.48f : 0.32f - }); - } - + _gpuSparks?.EmitMuzzleStarburst(start, new Color(5.0f, 2.6f, 0.70f, 0.98f), isRecoilless ? 0.78f : 0.48f, 0.09f); + _gpuSparks?.EmitSparkBurst(start, aimDir, isRecoilless ? 64 : 32, new Color(5.0f, 2.5f, 0.60f, 0.98f), 15f, 0.028f); + _volumetrics?.EmitMuzzleBreechPuff(start, end, sampleGroundTint(start.X, start.Z), wClass, isRecoilless); if (!hasCam || start.DistanceSquaredTo(camPos) <= 65f * 65f) { SpawnFlashLight(start, new Color(1.0f, 0.58f, 0.18f), isRecoilless ? 4.2f : 2.6f, isRecoilless ? 14f : 10f, 0.13f, priority: 5); } break; - } case WeaponVisualClass.ThermalBeam: { - Color beamCol = isLance - ? new Color(1.0f, 0.78f, 0.28f, 0.96f) - : new Color(0.32f, 0.90f, 1.0f, 0.96f); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeMuzzleStarburst, - Position = start, - Velocity = Vector3.Zero, - StartSize = isLance ? 1.25f : 0.85f, - EndSize = 0.42f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 3.4f, - ColorStart = beamCol, - ColorEnd = beamCol with { A = 0f }, - Lifetime = 0.09f - }); + Color beamCol = isLance ? new Color(4.8f, 3.2f, 0.95f, 0.96f) : new Color(2.8f, 3.4f, 3.8f, 0.96f); + _gpuSparks?.EmitMuzzleStarburst(start, beamCol, isLance ? 0.68f : 0.48f, 0.09f); if (!hasCam || start.DistanceSquaredTo(camPos) <= 45f * 45f) { - SpawnFlashLight(start, beamCol with { A = 1f }, isLance ? 3.5f : 2.6f, 11f, 0.12f, priority: 4); + Color lCol = isLance ? new Color(1.0f, 0.78f, 0.28f) : new Color(0.32f, 0.90f, 1.0f); + SpawnFlashLight(start, lCol, isLance ? 3.5f : 2.6f, 11f, 0.12f, priority: 4); } break; } case WeaponVisualClass.GaussRail: { - Color gaussCol = new(0.22f, 0.78f, 1.0f, 0.98f); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeMuzzleStarburst, - Position = start, - Velocity = Vector3.Zero, - StartSize = 1.45f, - EndSize = 0.50f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 3.8f, - ColorStart = new Color(0.75f, 0.96f, 1.0f, 1.0f), - ColorEnd = gaussCol with { A = 0f }, - Lifetime = 0.095f - }); - SpawnSparkBurst(start, (end - start).Normalized(), 4, gaussCol, 14f); + Color gaussHdr = new(3.6f, 2.8f, 1.8f, 0.98f); + _gpuSparks?.EmitMuzzleStarburst(start, new Color(1.4f, 3.5f, 4.8f, 0.98f), 0.72f, 0.09f); + _gpuSparks?.EmitSparkBurst(start, aimDir, 56, gaussHdr, 19f, 0.026f); if (!hasCam || start.DistanceSquaredTo(camPos) <= 65f * 65f) { - SpawnFlashLight(start, gaussCol with { A = 1f }, 4.2f, 14f, 0.11f, priority: 5); + SpawnFlashLight(start, new Color(0.22f, 0.78f, 1.0f), 4.2f, 14f, 0.11f, priority: 5); } break; } case WeaponVisualClass.PlasmaPpc: { - Color plasmaCol = new(0.16f, 0.88f, 0.95f, 0.96f); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = start, - Velocity = (end - start).Normalized() * 3.5f, - StartSize = 0.85f, - EndSize = 2.0f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 3.2f, - ColorStart = plasmaCol, - ColorEnd = new Color(0.08f, 0.45f, 0.65f, 0f), - Lifetime = 0.24f - }); + Color plasmaHdr = new(3.4f, 2.8f, 1.6f, 0.96f); + _gpuSparks?.EmitMuzzleStarburst(start, new Color(1.0f, 3.4f, 4.2f, 0.96f), 0.65f, 0.09f); + _gpuSparks?.EmitSparkBurst(start, aimDir, 38, plasmaHdr, 12f, 0.028f); if (!hasCam || start.DistanceSquaredTo(camPos) <= 55f * 55f) { - SpawnFlashLight(start, plasmaCol with { A = 1f }, 3.4f, 12f, 0.12f, priority: 4); + SpawnFlashLight(start, new Color(0.16f, 0.88f, 0.95f), 3.4f, 12f, 0.12f, priority: 4); } break; } case WeaponVisualClass.RocketSalvo: - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeMuzzleStarburst, - Position = start, - Velocity = Vector3.Zero, - StartSize = 1.15f, - EndSize = 0.55f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 3.0f, - ColorStart = new Color(1.0f, 0.72f, 0.24f, 0.96f), - ColorEnd = new Color(0.95f, 0.35f, 0.08f, 0f), - Lifetime = 0.10f - }); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeDustSmoke, - Position = start, - Velocity = new Vector3(NextSigned() * 1.2f, 1.4f, NextSigned() * 1.2f), - Gravity = -0.15f, - Drag = 1.8f, - StartSize = 0.55f, - EndSize = 1.85f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.3f, - Emissive = 0f, - ColorStart = new Color(0.62f, 0.58f, 0.52f, 0.55f), - ColorEnd = new Color(0.45f, 0.42f, 0.38f, 0f), - Lifetime = 0.42f - }); + _gpuSparks?.EmitMuzzleStarburst(start, new Color(4.8f, 2.6f, 0.75f, 0.96f), 0.62f, 0.095f); + _gpuSparks?.EmitSparkBurst(start, aimDir, 42, new Color(4.8f, 2.4f, 0.60f, 0.96f), 13f, 0.028f); + _volumetrics?.EmitMuzzleBreechPuff(start, end, sampleGroundTint(start.X, start.Z), wClass, isRecoilless: false); break; - } case WeaponVisualClass.SwarmSmart: - { - Color swarmCol = new(0.56f, 0.96f, 0.28f, 0.96f); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeMuzzleStarburst, - Position = start, - Velocity = Vector3.Zero, - StartSize = 0.78f, - EndSize = 0.36f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 2.6f, - ColorStart = swarmCol, - ColorEnd = new Color(0.55f, 0.28f, 0.88f, 0f), - Lifetime = 0.085f - }); + _gpuSparks?.EmitMuzzleStarburst(start, new Color(2.8f, 3.8f, 1.2f, 0.96f), 0.48f, 0.085f); break; - } } } @@ -880,7 +588,7 @@ public partial class ParticlePool : Node3D } Vector3 pos = new(hit.HitX, hit.HitY, hit.HitZ); - if (hasCam && pos.DistanceSquaredTo(camPos) > 125f * 125f) + if (hasCam && pos.DistanceSquaredTo(camPos) > 180f * 180f) { return; } @@ -895,23 +603,9 @@ public partial class ParticlePool : Node3D if (hit.IsAirburst || (wClass == WeaponVisualClass.KineticLight && string.Equals(hit.WeaponId, "pd_flak", StringComparison.Ordinal))) { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = pos, - Velocity = Vector3.Zero, - StartSize = 0.50f, - EndSize = 2.15f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.5f, - Emissive = 1.6f, - ColorStart = new Color(1.0f, 0.55f, 0.16f, 0.90f), - ColorEnd = new Color(0.24f, 0.16f, 0.12f, 0.0f), - Lifetime = 0.35f - }); - SpawnSparkBurst(pos, normal, 3, new Color(1.0f, 0.68f, 0.24f, 0.98f), 10f); + _volumetrics?.EmitExplosiveHit(pos, normal, groundTint, wClass, isRecoilless: false, isAirburst: true); + _gpuSparks?.EmitSparkBurst(pos, normal, 76, new Color(5.0f, 2.7f, 0.70f, 0.98f), 14f, 0.026f); + _gpuSparks?.EmitEmberBurst(pos, 28, new Color(4.0f, 1.8f, 0.35f, 0.95f), 4.5f, 0.030f); return; } @@ -920,45 +614,27 @@ public partial class ParticlePool : Node3D case WeaponVisualClass.KineticLight: if (isTerrain) { - EmitImpactDustPlume(pos, normal, groundTint, count: 2, size: 1.0f); + _gpuSparks?.EmitDustMotes(pos, normal, 36, groundTint with { A = 0.76f }, 4.5f, 0.045f); } else { - SpawnSparkBurst(pos, normal, 3, new Color(1.0f, 0.88f, 0.45f, 0.96f), 8.5f); + _gpuSparks?.EmitSparkBurst(pos, normal, 62, new Color(4.8f, 3.0f, 0.95f, 0.96f), 11f, 0.024f); } break; case WeaponVisualClass.Autocannon: - EmitImpactDustPlume(pos, normal, groundTint, count: 2, size: 1.45f); - SpawnSparkBurst(pos, normal, 3, new Color(1.0f, 0.72f, 0.26f, 0.98f), 11.5f); + _gpuSparks?.EmitSparkBurst(pos, normal, 76, new Color(4.8f, 2.6f, 0.70f, 0.98f), 13.5f, 0.026f); + _gpuSparks?.EmitDustMotes(pos, normal, 42, groundTint with { A = 0.78f }, 5.5f, 0.048f); + _volumetrics?.EmitFootstepOrTirePuff(pos, groundTint, 1.0f); break; case WeaponVisualClass.Explosive: { bool isRecoilless = string.Equals(hit.WeaponId, "recoilless", StringComparison.Ordinal); - EmitImpactDustPlume(pos, normal, groundTint, count: isRecoilless ? 4 : 2, size: isRecoilless ? 1.85f : 1.35f); - for (int f = 0; f < (isRecoilless ? 3 : 2); f++) - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = pos + normal * 0.25f + new Vector3(NextSigned() * 0.5f, NextFloat() * 0.4f, NextSigned() * 0.5f), - Velocity = normal * (1.8f + NextFloat() * 1.8f) + new Vector3(NextSigned(), 1.2f, NextSigned()), - Gravity = -0.3f, - Drag = 1.6f, - StartSize = isRecoilless ? 0.95f : 0.65f, - EndSize = isRecoilless ? 3.1f : 2.0f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.4f, - Emissive = 2.6f, - ColorStart = new Color(1.0f, 0.64f, 0.18f, 0.95f), - ColorEnd = new Color(0.28f, 0.16f, 0.12f, 0.0f), - Lifetime = isRecoilless ? 0.38f : 0.35f - }); - } - SpawnSparkBurst(pos, normal, isRecoilless ? 5 : 3, new Color(1.0f, 0.64f, 0.20f, 0.98f), 14f); + _volumetrics?.EmitExplosiveHit(pos, normal, groundTint, wClass, isRecoilless, isAirburst: false); + _gpuSparks?.EmitSparkBurst(pos, normal, isRecoilless ? 140 : 88, new Color(5.2f, 2.6f, 0.65f, 0.98f), 17f, 0.028f); + _gpuSparks?.EmitEmberBurst(pos, isRecoilless ? 54 : 32, new Color(4.2f, 1.7f, 0.35f, 0.95f), 5.5f, 0.032f); + _gpuSparks?.EmitDustMotes(pos, normal, isRecoilless ? 68 : 44, groundTint with { A = 0.80f }, 7.5f, 0.052f); if (!hasCam || pos.DistanceSquaredTo(camPos) <= 75f * 75f) { SpawnFlashLight(pos + normal * 0.45f, new Color(1.0f, 0.55f, 0.16f), isRecoilless ? 4.8f : 3.2f, isRecoilless ? 14.5f : 11f, 0.14f, priority: 7); @@ -967,27 +643,14 @@ public partial class ParticlePool : Node3D } case WeaponVisualClass.ThermalBeam: - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = pos, - Velocity = normal * 1.4f, - StartSize = 0.60f, - EndSize = 1.75f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 2.8f, - ColorStart = new Color(0.45f, 0.94f, 1.0f, 0.94f), - ColorEnd = new Color(0.95f, 0.52f, 0.16f, 0.0f), - Lifetime = 0.35f - }); - SpawnSparkBurst(pos, normal, 4, new Color(0.55f, 0.92f, 1.0f, 0.98f), 12f); + _volumetrics?.EmitExplosiveHit(pos, normal, groundTint, wClass, isRecoilless: false, isAirburst: false); + _gpuSparks?.EmitSparkBurst(pos, normal, 68, new Color(4.6f, 2.8f, 1.4f, 0.98f), 13f, 0.026f); break; case WeaponVisualClass.GaussRail: - EmitImpactDustPlume(pos, normal, groundTint, count: 3, size: 1.65f); - SpawnSparkBurst(pos, normal, 6, new Color(0.30f, 0.84f, 1.0f, 0.98f), 17f); + _gpuSparks?.EmitSparkBurst(pos, normal, 96, new Color(4.2f, 3.0f, 1.8f, 0.98f), 20f, 0.026f); + _gpuSparks?.EmitDustMotes(pos, normal, 48, groundTint with { A = 0.78f }, 6.5f, 0.048f); + _volumetrics?.EmitFootstepOrTirePuff(pos, groundTint, 1.2f); if (!hasCam || pos.DistanceSquaredTo(camPos) <= 65f * 65f) { SpawnFlashLight(pos + normal * 0.35f, new Color(0.28f, 0.82f, 1.0f), 4.0f, 13f, 0.12f, priority: 6); @@ -995,44 +658,16 @@ public partial class ParticlePool : Node3D break; case WeaponVisualClass.PlasmaPpc: - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = pos + normal * 0.2f, - Velocity = normal * 1.6f, - StartSize = 0.90f, - EndSize = 2.6f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 3.2f, - ColorStart = new Color(0.20f, 0.88f, 1.0f, 0.95f), - ColorEnd = new Color(0.12f, 0.38f, 0.52f, 0f), - Lifetime = 0.42f - }); - SpawnSparkBurst(pos, normal, 5, new Color(0.32f, 0.94f, 1.0f, 0.98f), 12.5f); + _volumetrics?.EmitExplosiveHit(pos, normal, groundTint, wClass, isRecoilless: false, isAirburst: false); + _gpuSparks?.EmitSparkBurst(pos, normal, 84, new Color(4.0f, 2.8f, 1.6f, 0.98f), 15f, 0.028f); + _gpuSparks?.EmitEmberBurst(pos, 40, new Color(3.6f, 2.0f, 0.85f, 0.92f), 4.5f, 0.032f); break; case WeaponVisualClass.RocketSalvo: - EmitImpactDustPlume(pos, normal, groundTint, count: 4, size: 1.75f); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = pos + normal * 0.25f, - Velocity = normal * 2.2f, - Gravity = -0.25f, - Drag = 1.6f, - StartSize = 0.95f, - EndSize = 2.95f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 2.8f, - ColorStart = new Color(1.0f, 0.62f, 0.18f, 0.96f), - ColorEnd = new Color(0.28f, 0.16f, 0.12f, 0f), - Lifetime = 0.38f - }); - SpawnSparkBurst(pos, normal, 5, new Color(1.0f, 0.68f, 0.22f, 0.98f), 14.5f); + _volumetrics?.EmitExplosiveHit(pos, normal, groundTint, wClass, isRecoilless: false, isAirburst: false); + _gpuSparks?.EmitSparkBurst(pos, normal, 112, new Color(5.0f, 2.7f, 0.65f, 0.98f), 16f, 0.028f); + _gpuSparks?.EmitEmberBurst(pos, 38, new Color(4.0f, 1.7f, 0.35f, 0.95f), 5.0f, 0.032f); + _gpuSparks?.EmitDustMotes(pos, normal, 56, groundTint with { A = 0.80f }, 7.0f, 0.052f); if (!hasCam || pos.DistanceSquaredTo(camPos) <= 75f * 75f) { SpawnFlashLight(pos + normal * 0.45f, new Color(1.0f, 0.56f, 0.16f), 4.5f, 14f, 0.14f, priority: 7); @@ -1040,131 +675,12 @@ public partial class ParticlePool : Node3D break; case WeaponVisualClass.SwarmSmart: - EmitImpactDustPlume(pos, normal, groundTint, count: 2, size: 1.25f); - SpawnSparkBurst(pos, normal, 4, new Color(0.56f, 0.96f, 0.32f, 0.98f), 12f); + _volumetrics?.EmitExplosiveHit(pos, normal, groundTint, wClass, isRecoilless: false, isAirburst: false); + _gpuSparks?.EmitSparkBurst(pos, normal, 68, new Color(4.2f, 2.8f, 0.85f, 0.98f), 13f, 0.026f); break; } } - public void EmitOrdnanceTrail(Vector3 pos, Vector3 vel, Color accentCol, bool isRocket, Vector3 camPos, bool hasCam) - { - EnsureInitialized(); - if (hasCam && pos.DistanceSquaredTo(camPos) > 220f * 220f) - { - return; - } - - Vector3 backVel = vel.LengthSquared() > 1f ? -vel.Normalized() * 4.5f : Vector3.Up * 1.2f; - if (isRocket) - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeMuzzleStarburst, - Position = pos, - Velocity = backVel * 0.4f, - StartSize = 0.58f, - EndSize = 0.20f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 2.8f, - ColorStart = new Color(1.0f, 0.72f, 0.24f, 0.92f), - ColorEnd = accentCol with { A = 0f }, - Lifetime = 0.12f - }); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeDustSmoke, - Position = pos, - Velocity = backVel * 0.25f + new Vector3(NextSigned() * 0.6f, 0.7f, NextSigned() * 0.6f), - Gravity = -0.15f, - Drag = 1.8f, - StartSize = 0.32f, - EndSize = 1.25f, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.4f, - Emissive = 0f, - ColorStart = new Color(0.58f, 0.54f, 0.48f, 0.46f), - ColorEnd = new Color(0.40f, 0.38f, 0.36f, 0f), - Lifetime = 0.42f - }); - } - else - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSparkStreak, - Position = pos, - Velocity = backVel * 0.25f, - StartSize = 0.24f, - EndSize = 0.08f, - AspectY = 1.4f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 2.4f, - ColorStart = accentCol with { A = 0.90f }, - ColorEnd = accentCol with { A = 0f }, - Lifetime = 0.16f - }); - } - } - - public void EmitOrdnanceBurst(Vector3 pos, Color accentCol, int sparkCount, float radiusScale, Vector3 camPos, bool hasCam) - { - EnsureInitialized(); - if (hasCam && pos.DistanceSquaredTo(camPos) > 220f * 220f) - { - return; - } - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = pos, - Velocity = Vector3.Up * 1.5f, - StartSize = 0.65f * radiusScale, - EndSize = 2.2f * radiusScale, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 2.8f, - ColorStart = accentCol with { A = 0.94f }, - ColorEnd = new Color(0.24f, 0.16f, 0.14f, 0f), - Lifetime = 0.34f - }); - SpawnSparkBurst(pos, Vector3.Up, Math.Clamp(sparkCount, 1, 8), accentCol with { A = 0.98f }, 12f * radiusScale); - } - - public void EmitThermalPoolEmber(Vector3 pos, float radius, Color accentCol, Vector3 camPos, bool hasCam) - { - EnsureInitialized(); - if (hasCam && pos.DistanceSquaredTo(camPos) > 150f * 150f) - { - return; - } - float ang = NextFloat() * MathF.Tau; - float r = MathF.Sqrt(NextFloat()) * MathF.Max(0.5f, radius * 0.85f); - Vector3 p = pos + new Vector3(MathF.Cos(ang) * r, 0.18f, MathF.Sin(ang) * r); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = p, - Velocity = new Vector3(NextSigned() * 0.5f, 1.8f + NextFloat() * 1.4f, NextSigned() * 0.5f), - Gravity = -0.3f, - Drag = 1.2f, - StartSize = 0.36f, - EndSize = 0.92f, - AspectY = 1.25f, - Rotation = NextFloat() * MathF.Tau, - Emissive = 2.9f, - ColorStart = accentCol with { A = 0.88f }, - ColorEnd = accentCol with { A = 0f }, - Lifetime = 0.45f - }); - } - private void EmitChassisExplosion( Vector3 pos, float massKg, @@ -1172,311 +688,23 @@ public partial class ParticlePool : Node3D bool hasCam, Func sampleGroundTint) { - if (hasCam && pos.DistanceSquaredTo(camPos) > 160f * 160f) + if (hasCam && pos.DistanceSquaredTo(camPos) > 280f * 280f) { return; } - float sizeScale = Math.Clamp(massKg / 2800f, 0.85f, 1.55f); Color gTint = sampleGroundTint(pos.X, pos.Z); + _volumetrics?.EmitChassisExplosion(pos, massKg, gTint); + _gpuSparks?.EmitSparkBurst(pos, Vector3.Up, 260, new Color(5.6f, 2.9f, 0.70f, 0.98f), 22f, 0.028f); + _gpuSparks?.EmitEmberBurst(pos, 140, new Color(4.4f, 1.8f, 0.35f, 0.95f), 7.5f, 0.034f); + _gpuSparks?.EmitDustMotes(pos, Vector3.Up, 64, gTint with { A = 0.82f }, 9.0f, 0.056f); - for (int i = 0; i < 4; i++) - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = pos + new Vector3(NextSigned() * 0.8f, NextFloat() * 0.9f, NextSigned() * 0.8f), - Velocity = new Vector3(NextSigned() * 2.4f, 2.2f + NextFloat() * 2.8f, NextSigned() * 2.4f), - Gravity = -0.35f, - Drag = 1.4f, - StartSize = 1.1f * sizeScale, - EndSize = MathF.Min(3.8f, 2.7f * sizeScale), - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.5f, - Emissive = 3.0f, - ColorStart = new Color(1.0f, 0.62f, 0.16f, 0.98f), - ColorEnd = new Color(0.22f, 0.12f, 0.08f, 0.0f), - Lifetime = 0.42f + NextFloat() * 0.18f - }); - } - - for (int i = 0; i < 5; i++) - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeDustSmoke, - Position = pos + new Vector3(NextSigned() * 1.1f, NextFloat() * 0.8f, NextSigned() * 1.1f), - Velocity = new Vector3(NextSigned() * 2.8f, 3.0f + NextFloat() * 2.8f, NextSigned() * 2.8f), - Gravity = -0.35f, - Drag = 1.1f, - StartSize = 1.0f * sizeScale, - EndSize = MathF.Min(2.2f, 1.55f * sizeScale), - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.1f, - Emissive = 0f, - ColorStart = new Color(0.20f * 0.6f + gTint.R * 0.2f, 0.18f * 0.6f + gTint.G * 0.2f, 0.16f * 0.6f + gTint.B * 0.2f, 0.80f), - ColorEnd = new Color(0.10f, 0.10f, 0.10f, 0.0f), - Lifetime = 0.72f + NextFloat() * 0.30f - }); - } - - SpawnSparkBurst(pos, Vector3.Up, 6, new Color(1.0f, 0.68f, 0.22f, 0.98f), 17f); if (!hasCam || pos.DistanceSquaredTo(camPos) <= 95f * 95f) { SpawnFlashLight(pos + new Vector3(0f, 1.2f, 0f), new Color(1.0f, 0.56f, 0.14f), 6.2f, 16f, 0.18f, priority: 10); } } - public void EmitPodReentryStreak(Vector3 podPos, Vector3 podVel, float heatGlow, bool isContender, Vector3 camPos, bool hasCam) - { - EnsureInitialized(); - if (hasCam && podPos.DistanceSquaredTo(camPos) > 650f * 650f) - { - return; - } - - float scale = isContender ? 1.25f : 0.85f; - Vector3 upTrail = (-podVel.Normalized()) * (3.5f + NextFloat() * 3.0f); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = podPos + new Vector3(NextSigned() * 0.55f, 0.6f, NextSigned() * 0.55f), - Velocity = upTrail + new Vector3(NextSigned() * 1.1f, 1.8f, NextSigned() * 1.1f), - Gravity = -1.5f, - Drag = 2.2f, - StartSize = 0.85f * scale, - EndSize = 0.28f * scale, - AspectY = 2.0f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 2.5f, - Emissive = 2.4f + heatGlow * 1.4f, - ColorStart = new Color(1.0f, 0.64f, 0.20f, 0.88f), - ColorEnd = new Color(0.75f, 0.22f, 0.06f, 0.0f), - Lifetime = 0.20f + NextFloat() * 0.10f - }); - } - - public void EmitPodRetroBurn( - Vector3 podBasePos, - float agl, - Color groundTint, - bool isContender, - bool isLocal, - Vector3 camPos, - bool hasCam) - { - EnsureInitialized(); - float distSq = hasCam ? podBasePos.DistanceSquaredTo(camPos) : 0f; - if (hasCam && distSq > 480f * 480f) - { - return; - } - - float scale = isContender ? 1.20f : 0.85f; - // Downward fiery retro plume - for (int i = 0; i < 2; i++) - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSteamFire, - Position = podBasePos + new Vector3(NextSigned() * 0.65f, 0.05f, NextSigned() * 0.65f), - Velocity = new Vector3(NextSigned() * 2.2f, -(14f + NextFloat() * 9f), NextSigned() * 2.2f), - Gravity = -2.0f, - Drag = 2.4f, - StartSize = 0.72f * scale, - EndSize = 1.65f * scale, - AspectY = 1.45f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 3.0f, - Emissive = 3.1f, - ColorStart = new Color(1.0f, 0.72f, 0.26f, 0.94f), - ColorEnd = new Color(0.85f, 0.24f, 0.05f, 0.0f), - Lifetime = 0.16f + NextFloat() * 0.08f - }); - } - - // Hot retro ember spark - if (NextFloat() < 0.7f) - { - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSparkStreak, - Position = podBasePos + new Vector3(NextSigned() * 0.7f, 0.1f, NextSigned() * 0.7f), - Velocity = new Vector3(NextSigned() * 6.5f, -(9f + NextFloat() * 6f), NextSigned() * 6.5f), - Gravity = 6.0f, - Drag = 1.2f, - StartSize = 0.26f, - EndSize = 0.10f, - AspectY = 1.6f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = 0f, - Emissive = 3.2f, - ColorStart = new Color(1.0f, 0.78f, 0.30f, 0.96f), - ColorEnd = new Color(0.95f, 0.28f, 0.06f, 0.0f), - Lifetime = 0.18f + NextFloat() * 0.08f - }); - } - - // Ground dust wash when < 55m AGL - if (agl < 55f && (!hasCam || distSq <= 240f * 240f)) - { - float washT = Math.Clamp(1f - agl / 55f, 0.15f, 1f); - Vector3 groundPos = podBasePos - new Vector3(0f, MathF.Max(0f, agl), 0f) + new Vector3(0f, 0.25f, 0f); - Color dustStart = new(groundTint.R, groundTint.G, groundTint.B, 0.56f * washT); - Color dustEnd = new(groundTint.R * 0.9f, groundTint.G * 0.9f, groundTint.B * 0.9f, 0.0f); - int dustCount = isContender ? 2 : 1; - for (int d = 0; d < dustCount; d++) - { - float ang = NextFloat() * MathF.Tau; - float spd = (6.5f + NextFloat() * 7.0f) * washT * scale; - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeDustSmoke, - Position = groundPos + new Vector3(MathF.Cos(ang) * 0.9f, 0f, MathF.Sin(ang) * 0.9f), - Velocity = new Vector3(MathF.Cos(ang) * spd, 1.2f + NextFloat() * 1.4f, MathF.Sin(ang) * spd), - Gravity = 0.35f, - Drag = 2.6f, - StartSize = 0.85f * scale, - EndSize = 2.35f * scale, - AspectY = 1.0f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.8f, - Emissive = 0f, - ColorStart = dustStart, - ColorEnd = dustEnd, - Lifetime = 0.42f + NextFloat() * 0.18f - }); - } - } - - if (isLocal || !hasCam || distSq <= 95f * 95f) - { - SpawnFlashLight(podBasePos - new Vector3(0f, 0.6f, 0f), new Color(1.0f, 0.60f, 0.18f), 3.8f, 14f, 0.09f, priority: isLocal ? 8 : 3); - } - } - - public void EmitPodTouchdownBurst( - Vector3 pos, - Vector3 normal, - Color groundTint, - bool isContender, - bool isLocal, - Vector3 camPos, - bool hasCam) - { - EnsureInitialized(); - float distSq = hasCam ? pos.DistanceSquaredTo(camPos) : 0f; - if (!isLocal && hasCam && distSq > 360f * 360f) - { - return; - } - - float scale = isContender ? 1.35f : 0.95f; - int dustCount = isContender ? 7 : 4; - Color dustStart = new(groundTint.R, groundTint.G, groundTint.B, 0.68f); - Color dustEnd = new(groundTint.R * 0.88f, groundTint.G * 0.88f, groundTint.B * 0.88f, 0.0f); - for (int i = 0; i < dustCount; i++) - { - float ang = (i / (float)dustCount) * MathF.Tau + NextFloat() * 0.4f; - float spd = (7.5f + NextFloat() * 6.5f) * scale; - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeDustSmoke, - Position = pos + normal * 0.35f + new Vector3(MathF.Cos(ang) * 1.1f, 0f, MathF.Sin(ang) * 1.1f), - Velocity = new Vector3(MathF.Cos(ang) * spd, 1.8f + NextFloat() * 2.2f, MathF.Sin(ang) * spd), - Gravity = 0.45f, - Drag = 2.2f, - StartSize = 0.95f * scale, - EndSize = 2.55f * scale, - AspectY = 1.0f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.6f, - Emissive = 0f, - ColorStart = dustStart, - ColorEnd = dustEnd, - Lifetime = 0.55f + NextFloat() * 0.25f - }); - } - - SpawnSparkBurst(pos + normal * 0.5f, normal, isContender ? 8 : 4, new Color(1.0f, 0.68f, 0.20f, 0.98f), 16f * scale); - - if (isLocal || !hasCam || distSq <= 140f * 140f) - { - SpawnFlashLight(pos + normal * 1.2f, new Color(1.0f, 0.58f, 0.16f), 5.8f, 18f, 0.18f, priority: isLocal ? 10 : 6); - } - } - - private void EmitImpactDustPlume(Vector3 pos, Vector3 normal, Color groundTint, int count, float size) - { - Color c0 = new(groundTint.R, groundTint.G, groundTint.B, 0.60f); - Color c1 = new(groundTint.R * 0.88f, groundTint.G * 0.88f, groundTint.B * 0.88f, 0.0f); - float endSize = MathF.Min(2.2f, size * 1.15f); - for (int i = 0; i < count; i++) - { - Vector3 vel = normal * (1.8f + NextFloat() * 2.4f) + new Vector3(NextSigned() * 1.6f, 0.8f + NextFloat() * 1.2f, NextSigned() * 1.6f); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeDustSmoke, - Position = pos + normal * 0.12f, - Velocity = vel, - Gravity = 0.45f, - Drag = 2.0f, - StartSize = size * 0.40f, - EndSize = endSize, - AspectY = 1f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 1.4f, - Emissive = 0f, - ColorStart = c0, - ColorEnd = c1, - Lifetime = 0.35f + NextFloat() * 0.16f - }); - } - } - - private void SpawnSparkBurst(Vector3 pos, Vector3 normal, int count, Color color, float speed) - { - for (int i = 0; i < count; i++) - { - Vector3 rand = new(NextSigned(), MathF.Abs(NextSigned()) + 0.35f, NextSigned()); - Vector3 dir = (normal * 0.75f + rand).Normalized(); - SpawnParticle(new ParticleSlot - { - Active = true, - Mode = ModeSparkStreak, - Position = pos, - Velocity = dir * (speed * (0.6f + 0.75f * NextFloat())), - Gravity = 11.0f, - Drag = 0.8f, - StartSize = 0.26f, - EndSize = 0.10f, - AspectY = 1.45f, - Rotation = NextFloat() * MathF.Tau, - AngularVel = NextSigned() * 6f, - Emissive = 2.8f, - ColorStart = color, - ColorEnd = color with { A = 0f }, - Lifetime = 0.16f + 0.10f * NextFloat() - }); - } - } - - private void SpawnParticle(in ParticleSlot slot) - { - _particles[_writeCursor] = slot; - _writeCursor = (_writeCursor + 1) % MaxParticles; - } - private void SpawnFlashLight(Vector3 pos, Color color, float energy, float range, float duration, int priority) { int targetIdx = -1; @@ -1530,16 +758,4 @@ public partial class ParticlePool : Node3D PeakFlashLightCount = active; } } - - private float NextFloat() - { - uint x = _rng; - x ^= x << 13; - x ^= x >> 17; - x ^= x << 5; - _rng = x; - return (x & 0x00FFFFFFu) / 16777216f; - } - - private float NextSigned() => NextFloat() * 2f - 1f; } diff --git a/client/PomDecalPool.cs b/client/PomDecalPool.cs index c7472d5..edeeeb7 100644 --- a/client/PomDecalPool.cs +++ b/client/PomDecalPool.cs @@ -58,9 +58,7 @@ public partial class PomDecalPool : Node3D Shader shader = GD.Load("res://decal_pom.gdshader") ?? throw new InvalidOperationException("Failed to load res://decal_pom.gdshader"); - string vehiclesDir = VehicleCatalogLoader.LocateVehiclesDirectory(); - string assetsDir = Directory.GetParent(vehiclesDir)?.FullName - ?? throw new DirectoryNotFoundException("Could not locate assets directory."); + string assetsDir = ClientAssets.LocateAssetsDirectory(); string decalsDir = Path.Combine(assetsDir, "decals"); _albedoTex = LoadTextureWithMips(Path.Combine(decalsDir, "decal_atlas_albedo.png")); diff --git a/client/ProceduralAudioBank.cs b/client/ProceduralAudioBank.cs index ee5db96..22aaa0c 100644 --- a/client/ProceduralAudioBank.cs +++ b/client/ProceduralAudioBank.cs @@ -56,9 +56,7 @@ public sealed class ProceduralAudioBank public static string LocateHavenAudioDirectory() { - string vehiclesDir = VehicleCatalogLoader.LocateVehiclesDirectory(); - string assetsDir = Directory.GetParent(vehiclesDir)?.FullName - ?? throw new DirectoryNotFoundException("Could not locate assets directory."); + string assetsDir = ClientAssets.LocateAssetsDirectory(); string havenDir = Path.Combine(assetsDir, "audio", "haven"); if (!Directory.Exists(havenDir)) { diff --git a/client/RustToDust.Client.csproj b/client/RustToDust.Client.csproj index 29e8ed6..6ed04f3 100644 --- a/client/RustToDust.Client.csproj +++ b/client/RustToDust.Client.csproj @@ -10,6 +10,7 @@ + diff --git a/client/SettingsOverlay.cs b/client/SettingsOverlay.cs new file mode 100644 index 0000000..e6ce30f --- /dev/null +++ b/client/SettingsOverlay.cs @@ -0,0 +1,407 @@ +using System; +using Godot; + +namespace RustToDust.Client; + +/// +/// Industrial Imperial Settings overlay with left-rail submenu navigation +/// (GRAPHICS active; Audio/Controls placeholders for future passes). +/// Decoupled from persistence: receives values via +/// and emits change/reset/back events. +/// +public sealed partial class SettingsOverlay : CanvasLayer +{ + public enum SettingsCategory + { + Graphics = 0 + } + + private Control _root = null!; + private ImperialChromePanel _panel = null!; + private Button _graphicsTabBtn = null!; + private Control _graphicsPane = null!; + + private readonly Button[] _vfxResButtons = new Button[3]; + private readonly Button[] _volSampleButtons = new Button[4]; + private readonly Button[] _sdfgiButtons = new Button[3]; + private readonly Button[] _displayModeButtons = new Button[2]; + + private VfxResolutionScale _vfxRes = VfxResolutionScale.Half; + private VolumetricSamples _volSamples = VolumetricSamples.Medium; + private SdfgiQuality _sdfgi = SdfgiQuality.Balanced; + private bool _borderlessFullscreen = true; + private bool _built; + + public SettingsOverlay() + { + Layer = 22; + } + + public event Action? GraphicsChanged; + public event Action? ResetDefaultsRequested; + public event Action? BackRequested; + + public bool IsOpen => Visible; + + public override void _Ready() + { + BuildUi(); + SetSettingsVisible(false); + } + + public void SetSettingsVisible(bool visible) + { + Visible = visible; + if (_root is not null) + { + _root.Visible = visible; + } + } + + public void SetGraphicsValues( + VfxResolutionScale vfxRes, + VolumetricSamples volSamples, + SdfgiQuality sdfgi, + bool borderlessFullscreen) + { + _vfxRes = vfxRes; + _volSamples = volSamples; + _sdfgi = sdfgi; + _borderlessFullscreen = borderlessFullscreen; + if (_built) + { + RefreshSelectionVisuals(); + } + } + + private void BuildUi() + { + _root = new Control + { + Name = "SettingsOverlayRoot", + MouseFilter = Control.MouseFilterEnum.Stop + }; + _root.SetAnchorsPreset(Control.LayoutPreset.FullRect); + AddChild(_root); + + var scrim = new ColorRect + { + Color = ImperialChrome.ScrimCol, + MouseFilter = Control.MouseFilterEnum.Stop + }; + scrim.SetAnchorsPreset(Control.LayoutPreset.FullRect); + _root.AddChild(scrim); + + _panel = ImperialChrome.CreatePanel( + ImperialChrome.OrangeCol, + cornerLen: 18f, + borderPx: 2f, + bgAlpha: 0.94f, + padH: 22, + padV: 20); + _panel.Name = "SettingsPanel"; + _panel.AnchorLeft = 0.5f; + _panel.AnchorRight = 0.5f; + _panel.AnchorTop = 0.5f; + _panel.AnchorBottom = 0.5f; + _panel.OffsetLeft = -440f; + _panel.OffsetRight = 440f; + _panel.OffsetTop = -255f; + _panel.OffsetBottom = 255f; + _root.AddChild(_panel); + + var outerVbox = new VBoxContainer(); + outerVbox.AddThemeConstantOverride("separation", 12); + _panel.AddChild(outerVbox); + + // Header + var headerRow = new HBoxContainer(); + headerRow.AddThemeConstantOverride("separation", 12); + outerVbox.AddChild(headerRow); + + var titleCol = new VBoxContainer { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }; + titleCol.AddThemeConstantOverride("separation", 2); + headerRow.AddChild(titleCol); + titleCol.AddChild(ImperialChrome.CreateLabel("SYSTEM CONFIGURATION • SUBMENU", 11, ImperialChrome.GoldCol)); + titleCol.AddChild(ImperialChrome.CreateLabel("SETTINGS", 24, ImperialChrome.TextLight)); + + var liveBadge = ImperialChrome.CreateLabel("LIVE APPLY • NO RESTART", 11, ImperialChrome.CyanCol, HorizontalAlignment.Right); + liveBadge.VerticalAlignment = VerticalAlignment.Bottom; + headerRow.AddChild(liveBadge); + + outerVbox.AddChild(ImperialChrome.MakeRule()); + + // Main Split: Submenu Rail + Content Pane + var split = new HBoxContainer + { + SizeFlagsVertical = Control.SizeFlags.ExpandFill + }; + split.AddThemeConstantOverride("separation", 18); + outerVbox.AddChild(split); + + var navCol = new VBoxContainer + { + CustomMinimumSize = new Vector2(168f, 0f) + }; + navCol.AddThemeConstantOverride("separation", 8); + split.AddChild(navCol); + + navCol.AddChild(ImperialChrome.CreateLabel("CATEGORIES", 10, ImperialChrome.TextMuted)); + + _graphicsTabBtn = ImperialChrome.CreateButton("GRAPHICS", ImperialChrome.CyanCol, 13, 38f); + StyleSegmentedButton(_graphicsTabBtn, selected: true, ImperialChrome.CyanCol); + _graphicsTabBtn.Pressed += () => SelectCategory(SettingsCategory.Graphics); + navCol.AddChild(_graphicsTabBtn); + + var audioTabBtn = ImperialChrome.CreateButton("AUDIO [SOON]", ImperialChrome.BorderCol, 12, 34f); + audioTabBtn.Disabled = true; + audioTabBtn.TooltipText = "Audio controls arrive in a future pass"; + navCol.AddChild(audioTabBtn); + + var controlsTabBtn = ImperialChrome.CreateButton("CONTROLS [SOON]", ImperialChrome.BorderCol, 12, 34f); + controlsTabBtn.Disabled = true; + controlsTabBtn.TooltipText = "Input bindings arrive in a future pass"; + navCol.AddChild(controlsTabBtn); + + var vSep = new VSeparator(); + vSep.AddThemeStyleboxOverride("separator", new StyleBoxLine + { + Color = new Color(ImperialChrome.BorderCol.R, ImperialChrome.BorderCol.G, ImperialChrome.BorderCol.B, 0.75f), + Thickness = 1, + Vertical = true + }); + split.AddChild(vSep); + + _graphicsPane = new VBoxContainer + { + Name = "GraphicsSettingsPane", + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, + SizeFlagsVertical = Control.SizeFlags.ExpandFill + }; + ((VBoxContainer)_graphicsPane).AddThemeConstantOverride("separation", 12); + split.AddChild(_graphicsPane); + + _graphicsPane.AddChild(ImperialChrome.CreateLabel("GRAPHICS • VOLUMETRICS, GI & DISPLAY", 14, ImperialChrome.CyanCol)); + + // 1. VFX / Fog Resolution + AddSettingRow( + _graphicsPane, + "VFX / FOG RESOLUTION", + "Compute resolution for raymarched smoke, fireballs & plumes (Full = 1:1 native)", + new[] + { + ("Half (0.5x)", (Action)(() => OnGraphicsOptionSelected(vfxRes: VfxResolutionScale.Half))), + ("High (0.75x)", (Action)(() => OnGraphicsOptionSelected(vfxRes: VfxResolutionScale.ThreeQuarter))), + ("Full (1.0x)", (Action)(() => OnGraphicsOptionSelected(vfxRes: VfxResolutionScale.Full))) + }, + _vfxResButtons); + + // 2. Volumetric Sample Count + AddSettingRow( + _graphicsPane, + "VOLUMETRIC SAMPLE COUNT", + "Raymarch step budget per pixel (higher = smoother volume density & gradients)", + new[] + { + ("Low (8)", (Action)(() => OnGraphicsOptionSelected(volSamples: VolumetricSamples.Low))), + ("Medium (10)", (Action)(() => OnGraphicsOptionSelected(volSamples: VolumetricSamples.Medium))), + ("High (16)", (Action)(() => OnGraphicsOptionSelected(volSamples: VolumetricSamples.High))), + ("Ultra (24)", (Action)(() => OnGraphicsOptionSelected(volSamples: VolumetricSamples.Ultra))) + }, + _volSampleButtons); + + // 3. Global Illumination (SDFGI) + AddSettingRow( + _graphicsPane, + "GLOBAL ILLUMINATION (SDFGI)", + "Signed-distance multi-bounce sky & terrain indirect lighting", + new[] + { + ("Off", (Action)(() => OnGraphicsOptionSelected(sdfgi: SdfgiQuality.Off))), + ("Balanced", (Action)(() => OnGraphicsOptionSelected(sdfgi: SdfgiQuality.Balanced))), + ("High", (Action)(() => OnGraphicsOptionSelected(sdfgi: SdfgiQuality.High))) + }, + _sdfgiButtons); + + // 4. Display Mode + AddSettingRow( + _graphicsPane, + "DISPLAY MODE", + "Window presentation mode (also toggleable anytime via Alt+Enter or F11)", + new[] + { + ("Borderless Fullscreen", (Action)(() => OnGraphicsOptionSelected(borderlessFullscreen: true))), + ("Windowed", (Action)(() => OnGraphicsOptionSelected(borderlessFullscreen: false))) + }, + _displayModeButtons); + + outerVbox.AddChild(ImperialChrome.MakeRule()); + + // Footer + var footerRow = new HBoxContainer(); + footerRow.AddThemeConstantOverride("separation", 10); + outerVbox.AddChild(footerRow); + + var resetBtn = ImperialChrome.CreateButton("RESET DEFAULTS", ImperialChrome.GoldCol, 13, 36f); + resetBtn.CustomMinimumSize = new Vector2(180f, 36f); + resetBtn.Pressed += () => ResetDefaultsRequested?.Invoke(); + footerRow.AddChild(resetBtn); + + footerRow.AddChild(new Control { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }); + + var backBtn = ImperialChrome.CreateButton("BACK [ESC]", ImperialChrome.OrangeCol, 13, 36f); + backBtn.CustomMinimumSize = new Vector2(160f, 36f); + backBtn.Pressed += () => BackRequested?.Invoke(); + footerRow.AddChild(backBtn); + + _built = true; + RefreshSelectionVisuals(); + } + + private static void AddSettingRow( + Control parent, + string labelText, + string hintText, + (string Text, Action OnSelect)[] options, + Button[] targetButtons) + { + var block = new VBoxContainer(); + block.AddThemeConstantOverride("separation", 4); + parent.AddChild(block); + + var row = new HBoxContainer(); + row.AddThemeConstantOverride("separation", 12); + block.AddChild(row); + + var lbl = ImperialChrome.CreateLabel(labelText, 12, ImperialChrome.TextLight); + lbl.CustomMinimumSize = new Vector2(228f, 0f); + lbl.VerticalAlignment = VerticalAlignment.Center; + row.AddChild(lbl); + + var btnGroup = new HBoxContainer + { + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill + }; + btnGroup.AddThemeConstantOverride("separation", 6); + row.AddChild(btnGroup); + + for (int i = 0; i < options.Length; i++) + { + var (text, onSelect) = options[i]; + var btn = ImperialChrome.CreateButton(text, ImperialChrome.CyanCol, 12, 32f); + btn.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill; + btn.Pressed += onSelect; + btnGroup.AddChild(btn); + targetButtons[i] = btn; + } + + var hint = ImperialChrome.CreateLabel(hintText, 10, ImperialChrome.TextMuted); + block.AddChild(hint); + } + + private void SelectCategory(SettingsCategory category) + { + if (category == SettingsCategory.Graphics && _graphicsPane is not null) + { + _graphicsPane.Visible = true; + } + } + + private void OnGraphicsOptionSelected( + VfxResolutionScale? vfxRes = null, + VolumetricSamples? volSamples = null, + SdfgiQuality? sdfgi = null, + bool? borderlessFullscreen = null) + { + VfxResolutionScale nextRes = vfxRes ?? _vfxRes; + VolumetricSamples nextSamples = volSamples ?? _volSamples; + SdfgiQuality nextSdfgi = sdfgi ?? _sdfgi; + bool nextFullscreen = borderlessFullscreen ?? _borderlessFullscreen; + + if (nextRes == _vfxRes + && nextSamples == _volSamples + && nextSdfgi == _sdfgi + && nextFullscreen == _borderlessFullscreen) + { + return; + } + + _vfxRes = nextRes; + _volSamples = nextSamples; + _sdfgi = nextSdfgi; + _borderlessFullscreen = nextFullscreen; + RefreshSelectionVisuals(); + GraphicsChanged?.Invoke(_vfxRes, _volSamples, _sdfgi, _borderlessFullscreen); + } + + private void RefreshSelectionVisuals() + { + for (int i = 0; i < _vfxResButtons.Length; i++) + { + StyleSegmentedButton(_vfxResButtons[i], i == (int)_vfxRes, ImperialChrome.CyanCol); + } + for (int i = 0; i < _volSampleButtons.Length; i++) + { + StyleSegmentedButton(_volSampleButtons[i], i == (int)_volSamples, ImperialChrome.CyanCol); + } + for (int i = 0; i < _sdfgiButtons.Length; i++) + { + StyleSegmentedButton(_sdfgiButtons[i], i == (int)_sdfgi, ImperialChrome.OliveCol); + } + StyleSegmentedButton(_displayModeButtons[0], _borderlessFullscreen, ImperialChrome.OrangeCol); + StyleSegmentedButton(_displayModeButtons[1], !_borderlessFullscreen, ImperialChrome.OrangeCol); + } + + private static void StyleSegmentedButton(Button btn, bool selected, Color accentColor) + { + if (selected) + { + btn.AddThemeFontSizeOverride("font_size", 12); + btn.AddThemeColorOverride("font_color", Colors.White); + btn.AddThemeColorOverride("font_hover_color", Colors.White); + btn.AddThemeColorOverride("font_pressed_color", accentColor); + + var activeBox = MakeSegmentBox( + new Color(accentColor.R * 0.24f + ImperialChrome.BgPressed.R * 0.76f, + accentColor.G * 0.24f + ImperialChrome.BgPressed.G * 0.76f, + accentColor.B * 0.24f + ImperialChrome.BgPressed.B * 0.76f, + 1f), + accentColor, + borderW: 2); + btn.AddThemeStyleboxOverride("normal", activeBox); + btn.AddThemeStyleboxOverride("hover", activeBox); + btn.AddThemeStyleboxOverride("pressed", activeBox); + btn.AddThemeStyleboxOverride("focus", activeBox); + } + else + { + btn.AddThemeFontSizeOverride("font_size", 12); + btn.AddThemeColorOverride("font_color", ImperialChrome.TextMuted); + btn.AddThemeColorOverride("font_hover_color", ImperialChrome.TextLight); + btn.AddThemeColorOverride("font_pressed_color", accentColor); + + var normal = MakeSegmentBox(ImperialChrome.BgInner, ImperialChrome.BorderCol, borderW: 1); + var hover = MakeSegmentBox(ImperialChrome.BgHover, new Color(accentColor.R, accentColor.G, accentColor.B, 0.75f), borderW: 1); + var pressed = MakeSegmentBox(ImperialChrome.BgPressed, accentColor, borderW: 2); + btn.AddThemeStyleboxOverride("normal", normal); + btn.AddThemeStyleboxOverride("hover", hover); + btn.AddThemeStyleboxOverride("pressed", pressed); + btn.AddThemeStyleboxOverride("focus", hover); + } + } + + private static StyleBoxFlat MakeSegmentBox(Color bg, Color border, int borderW) + { + var box = new StyleBoxFlat + { + BgColor = bg, + BorderColor = border, + ContentMarginLeft = 8, + ContentMarginRight = 8, + ContentMarginTop = 5, + ContentMarginBottom = 5 + }; + box.SetBorderWidthAll(borderW); + return box; + } +} diff --git a/client/SionMapRenderer.cs b/client/SionMapRenderer.cs index 135ae4e..834ffc2 100644 --- a/client/SionMapRenderer.cs +++ b/client/SionMapRenderer.cs @@ -7,17 +7,15 @@ using RustToDust.Core; namespace RustToDust.Client; /// -/// Renders the 3072m x 3072m Sion, Switzerland arena: -/// - 6x6 (512m) seam-free chunked terrain ArrayMeshes from heightmap.f32 textured with terrain_surface.png + micro-grain shader. -/// - 36 spatial building tiles swapping cleanly between LOD1 (<= 650m), LOD2 (650m..2200m), and culled (> 2200m), -/// with shadow casting restricted to <= 450m and shared PBR materials across all tiles. +/// Renders Sion, Switzerland legacy building tiles (swapping cleanly between LOD1 <= 520m, LOD2 520..2200m, +/// and culled > 2200m). Terrain rendering is unified in . +/// (This class is scheduled for deletion in Cut 13c when WorldCityRenderer lands.) /// public partial class SionMapRenderer : Node3D { - public const float Lod1DistanceM = 520f; - public const float CullDistanceM = 2200f; - public const float ShadowDistanceM = 360f; - private const int ChunkGridVerts = 129; // 128 quads per 512m chunk (4m spacing) + public const float Lod1DistanceM = 400f; + public const float CullDistanceM = 1750f; + public const float ShadowDistanceM = 280f; private sealed class BuildingTileEntry { @@ -30,26 +28,17 @@ public partial class SionMapRenderer : Node3D public required MeshInstance3D Instance; } - private const int GroundTintGridSize = 128; - private static readonly Color NeutralAlpineDustTint = new(0.56f, 0.53f, 0.46f, 1.0f); - - private readonly List _terrainChunks = new(36); private readonly List _buildingTiles = new(36); private readonly Dictionary _sharedBuildingMaterials = new(StringComparer.Ordinal); private string? _builtForDir; - private ShaderMaterial? _terrainMat; - private ImageTexture? _surfaceTex; - private Color[]? _groundTintGrid; - private float _groundTintSizeM; public bool IsBuilt { get; private set; } - public int TerrainChunkCount => _terrainChunks.Count; public int BuildingTileCount => _buildingTiles.Count; public int ActiveLod1TileCount { get; private set; } public int ActiveLod2TileCount { get; private set; } public int CulledTileCount { get; private set; } - public void EnsureBuilt(SionMapData sion, TerrainField terrain) + public void EnsureBuilt(SionMapData sion) { if (IsBuilt && string.Equals(_builtForDir, sion.DirectoryPath, StringComparison.OrdinalIgnoreCase)) { @@ -58,9 +47,6 @@ public partial class SionMapRenderer : Node3D ClearBuilt(); _builtForDir = sion.DirectoryPath; - - BuildTerrainMaterial(sion); - BuildTerrainChunks(sion, terrain); BuildBuildingTiles(sion); IsBuilt = true; } @@ -124,186 +110,6 @@ public partial class SionMapRenderer : Node3D CulledTileCount = culledCount; } - private void BuildTerrainMaterial(SionMapData sion) - { - string surfPath = Path.Combine(sion.DirectoryPath, sion.Metadata.SurfaceTexture); - if (!File.Exists(surfPath)) - { - throw new FileNotFoundException($"Missing Sion terrain surface texture: {surfPath}", surfPath); - } - - var img = Image.LoadFromFile(surfPath); - if (img is null || img.IsEmpty()) - { - throw new InvalidOperationException($"Failed to decode Sion terrain surface texture: {surfPath}"); - } - - // Downsample CPU copy once for zero-readback terrain-tinted dust & impact plumes - var tintImg = (Image)img.Duplicate(); - tintImg.Resize(GroundTintGridSize, GroundTintGridSize, Image.Interpolation.Bilinear); - var grid = new Color[GroundTintGridSize * GroundTintGridSize]; - for (int y = 0; y < GroundTintGridSize; y++) - { - for (int x = 0; x < GroundTintGridSize; x++) - { - Color c = tintImg.GetPixel(x, y); - grid[y * GroundTintGridSize + x] = new Color( - Math.Clamp(c.R + 0.11f, 0.20f, 0.90f), - Math.Clamp(c.G + 0.11f, 0.20f, 0.88f), - Math.Clamp(c.B + 0.10f, 0.18f, 0.84f), - 1.0f); - } - } - _groundTintGrid = grid; - _groundTintSizeM = sion.Metadata.SizeMeters; - - img.GenerateMipmaps(); - _surfaceTex = ImageTexture.CreateFromImage(img); - - var shader = new Shader - { - Code = """ - shader_type spatial; - render_mode cull_back, depth_draw_opaque; - - uniform sampler2D surface_tex : source_color, filter_linear_mipmap, repeat_disable; - - varying vec3 v_world_pos; - varying vec3 v_world_normal; - - float hash21(vec2 p) { - p = fract(p * vec2(123.34, 456.21)); - p += dot(p, p + 45.32); - return fract(p.x * p.y); - } - - float value_noise(vec2 p) { - vec2 i = floor(p); - vec2 f = fract(p); - vec2 u = f * f * (3.0 - 2.0 * f); - float a = hash21(i); - float b = hash21(i + vec2(1.0, 0.0)); - float c = hash21(i + vec2(0.0, 1.0)); - float d = hash21(i + vec2(1.0, 1.0)); - return mix(mix(a, b, u.x), mix(c, d, u.x), u.y); - } - - void vertex() { - v_world_pos = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz; - v_world_normal = normalize((MODEL_MATRIX * vec4(NORMAL, 0.0)).xyz); - } - - void fragment() { - vec3 base_col = texture(surface_tex, UV).rgb; - - // Crisp world-space micro-grain for up-close ground readability - float dist = length((INV_VIEW_MATRIX * vec4(0.0, 0.0, 0.0, 1.0)).xyz - v_world_pos); - float near_fade = clamp(1.0 - smoothstep(140.0, 480.0, dist), 0.12, 1.0); - float macro = (value_noise(v_world_pos.xz * 0.28) - 0.5) * 0.07; - float grit = (hash21(floor(v_world_pos.xz * 8.0)) - 0.5) * 0.045; - - float slope = 1.0 - clamp(v_world_normal.y, 0.0, 1.0); - vec3 col = clamp(base_col * (1.0 + macro * 1.4 + grit * 1.6 * near_fade), vec3(0.0), vec3(1.0)); - ALBEDO = col; - ROUGHNESS = mix(0.88, 0.96, slope); - METALLIC = 0.02; - } - """ - }; - - _terrainMat = new ShaderMaterial { Shader = shader }; - _terrainMat.SetShaderParameter("surface_tex", _surfaceTex); - } - - private void BuildTerrainChunks(SionMapData sion, TerrainField terrain) - { - int grid = sion.Metadata.TileGrid; - float sizeM = sion.Metadata.SizeMeters; - float tileSize = sion.Metadata.TileSizeMeters; - float half = sizeM * 0.5f; - int n = ChunkGridVerts; - float step = tileSize / (n - 1); - - // Precompute shared index buffer for every terrain chunk (Godot ArrayMesh cull_back uses CW front-facing winding) - int quadCount = (n - 1) * (n - 1); - var indices = new int[quadCount * 6]; - int ii = 0; - for (int gz = 0; gz < n - 1; gz++) - { - for (int gx = 0; gx < n - 1; gx++) - { - int i00 = gz * n + gx; - int i10 = i00 + 1; - int i01 = i00 + n; - int i11 = i01 + 1; - - indices[ii++] = i00; - indices[ii++] = i10; - indices[ii++] = i01; - indices[ii++] = i10; - indices[ii++] = i11; - indices[ii++] = i01; - } - } - - int vertCount = n * n; - for (int tz = 0; tz < grid; tz++) - { - for (int tx = 0; tx < grid; tx++) - { - float x0 = -half + tx * tileSize; - float z0 = -half + tz * tileSize; - float cx = x0 + tileSize * 0.5f; - float cz = z0 + tileSize * 0.5f; - - var verts = new Vector3[vertCount]; - var normals = new Vector3[vertCount]; - var uvs = new Vector2[vertCount]; - - for (int gz = 0; gz < n; gz++) - { - float wz = z0 + gz * step; - float lx = 0f; - float lz = wz - cz; - float v = (wz + half) / sizeM; - for (int gx = 0; gx < n; gx++) - { - float wx = x0 + gx * step; - lx = wx - cx; - float h = terrain.SampleHeight(wx, wz); - var (nx, ny, nz) = terrain.SampleNormal(wx, wz); - - int idx = gz * n + gx; - verts[idx] = new Vector3(lx, h, lz); - normals[idx] = new Vector3(nx, ny, nz); - uvs[idx] = new Vector2((wx + half) / sizeM, v); - } - } - - var arrays = new Godot.Collections.Array(); - arrays.Resize((int)Mesh.ArrayType.Max); - arrays[(int)Mesh.ArrayType.Vertex] = verts; - arrays[(int)Mesh.ArrayType.Normal] = normals; - arrays[(int)Mesh.ArrayType.TexUV] = uvs; - arrays[(int)Mesh.ArrayType.Index] = indices; - - var mesh = new ArrayMesh(); - mesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays); - - var chunkNode = new MeshInstance3D - { - Name = $"SionTerrain_{tx}_{tz}", - Mesh = mesh, - MaterialOverride = _terrainMat, - Position = new Vector3(cx, 0f, cz), - CastShadow = GeometryInstance3D.ShadowCastingSetting.On - }; - AddChild(chunkNode); - _terrainChunks.Add(chunkNode); - } - } - } - private void BuildBuildingTiles(SionMapData sion) { var tiles = sion.Metadata.Tiles; @@ -498,47 +304,8 @@ public partial class SionMapRenderer : Node3D return (defaultKey, defMat); } - public Color SampleGroundTint(float worldX, float worldZ) - { - Color[]? grid = _groundTintGrid; - float sizeM = _groundTintSizeM; - if (grid is null || sizeM <= 1f || !float.IsFinite(worldX) || !float.IsFinite(worldZ)) - { - return NeutralAlpineDustTint; - } - - float half = sizeM * 0.5f; - float u = (worldX + half) / sizeM; - float v = (worldZ + half) / sizeM; - if (u < 0f || u > 1f || v < 0f || v > 1f) - { - return NeutralAlpineDustTint; - } - - float fx = u * (GroundTintGridSize - 1); - float fy = v * (GroundTintGridSize - 1); - int x0 = Math.Clamp((int)MathF.Floor(fx), 0, GroundTintGridSize - 1); - int y0 = Math.Clamp((int)MathF.Floor(fy), 0, GroundTintGridSize - 1); - int x1 = Math.Min(x0 + 1, GroundTintGridSize - 1); - int y1 = Math.Min(y0 + 1, GroundTintGridSize - 1); - float tx = fx - x0; - float ty = fy - y0; - - Color c00 = grid[y0 * GroundTintGridSize + x0]; - Color c10 = grid[y0 * GroundTintGridSize + x1]; - Color c01 = grid[y1 * GroundTintGridSize + x0]; - Color c11 = grid[y1 * GroundTintGridSize + x1]; - return c00.Lerp(c10, tx).Lerp(c01.Lerp(c11, tx), ty); - } - private void ClearBuilt() { - for (int i = 0; i < _terrainChunks.Count; i++) - { - _terrainChunks[i].QueueFree(); - } - _terrainChunks.Clear(); - for (int i = 0; i < _buildingTiles.Count; i++) { _buildingTiles[i].Instance.QueueFree(); @@ -546,10 +313,6 @@ public partial class SionMapRenderer : Node3D _buildingTiles.Clear(); _sharedBuildingMaterials.Clear(); - _terrainMat = null; - _surfaceTex = null; - _groundTintGrid = null; - _groundTintSizeM = 0f; _builtForDir = null; IsBuilt = false; ActiveLod1TileCount = 0; diff --git a/client/TerrainRenderer.cs b/client/TerrainRenderer.cs index 92e4a7a..6b01092 100644 --- a/client/TerrainRenderer.cs +++ b/client/TerrainRenderer.cs @@ -1,164 +1,351 @@ using System; using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; using Godot; using RustToDust.Core; namespace RustToDust.Client; /// -/// Top-down orthographic SubViewport brush-to-tile PBR + displacement terrain baker. -/// Maintains an 8x8 grid of 192m x 192m terrain tiles covering [-768, +768] in X and Z. -/// Only tiles whose changed are re-baked. +/// Unified Layer-0 + live GPU brush compute terrain renderer for both Desert (8x8) and Sion (16x16). +/// Replaces permanent SubViewports and CanvasItem brush shaders with one compute shader +/// (terrain_tile_bake.glsl) writing sparse 388x388 delta slots +/// in an LRU pool (max 96 active scarred tiles; untouched tiles bind a 1x1 neutral fallback), +/// rendered via 3 exact-ratio shared PlaneMeshes (192/48/12) with zero T-junction edge morphing. /// public partial class TerrainRenderer : Node3D { - private const int ViewportSize = 256; - private const float InnerTexelSpan = 253.0f; // texel 1 center (1.5) .. texel 254 center (254.5) - private const float GutterCenterOffset = 1.5f; - private const float PixelsPerMeter = InnerTexelSpan / TerrainField.TileSize; - private const float HeightSpan = TerrainField.MaxWorldHeight - TerrainField.MinWorldHeight; - private const float BaseHeightNorm = (0f - TerrainField.MinWorldHeight) / HeightSpan; + public const int DeltaTexSize = 388; + public const float InnerTexelSpan = 384.0f; + public const float GutterStartIndex = 2.0f; + public const float GutterCenterOffset = 2.5f; + public const int MaxGpuScarTiles = 96; + public const int MaxDirtyRebakesPerSync = 4; + private const int BrushStrideBytes = 48; + private const int PushConstantBytes = 48; + private const int MaxSsboBrushes = 8192; + private const int GroundTintGridSize = 128; - private static readonly Color HeightClearColor = new(BaseHeightNorm, 0.88f, 0.0f, 1.0f); - private static readonly Color AlbedoClearColor = new(0.69f, 0.50f, 0.31f, 1.0f); - private static readonly Vector2[] BrushUv = + private static readonly Color DesertAlbedoClear = new(0.69f, 0.50f, 0.31f, 1.0f); + private static readonly Color NeutralAlpineDustTint = new(0.56f, 0.53f, 0.46f, 1.0f); + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + private struct GpuBrush { - new(0f, 0f), - new(1f, 0f), - new(1f, 1f), - new(0f, 1f) - }; - private static readonly Vector2[] UnitQuadPoly = + public Vector4 PosRot; + public Vector4 RadDelta; + public Vector4 MatColor; + } + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + private struct TileBakePush { - new(-1f, -1f), - new(1f, -1f), - new(1f, 1f), - new(-1f, 1f) - }; - private static readonly Vector2[] ClearQuadPoly = - { - new(0f, 0f), - new(ViewportSize, 0f), - new(ViewportSize, ViewportSize), - new(0f, ViewportSize) - }; + public Vector4 TileOriginAndSpan; + public Vector4 BaseColorAndGutter; + public uint BrushStart; + public uint BrushCount; + public uint TexSize; + public uint IsSion; + } private sealed class TileNode { - public SubViewport HeightViewport = null!; - public Node2D HeightCanvas = null!; - public readonly List HeightQuads = new(64); - public SubViewport AlbedoViewport = null!; - public Node2D AlbedoCanvas = null!; - public readonly List AlbedoQuads = new(48); + public int Tx; + public int Tz; + public float OriginX; + public float OriginZ; public MeshInstance3D SurfaceMesh = null!; - public int BakedVersion = -1; + public ShaderMaterial SurfaceMat = null!; + public int BakedStructuralVersion = -1; + public int BakedVisualVersion = -1; + public int LruSlotIndex = -1; + public float TileQuads = 192f; + public float SentTileQuads = -1f; + public Vector4 SentNeighborQuads = new(-1f, -1f, -1f, -1f); } - private readonly TileNode[,] _tiles = new TileNode[TerrainField.TileGridCount, TerrainField.TileGridCount]; + private sealed class LruSlot + { + public int SlotIndex; + public Rid DeltaHeightRid; + public Rid DeltaAlbedoRid; + public Rid UniformSetRid; + public Texture2Drd DeltaHeightTex = null!; + public Texture2Drd DeltaAlbedoTex = null!; + public int AssignedTileIndex = -1; + public ulong LastUsedSeq; + public bool IsRdAllocated; + } + + private sealed class PendingBakeJob + { + public int SlotIndex; + public float TileOriginX; + public float TileOriginZ; + public float TileSize; + public bool IsSion; + public GpuBrush[] Brushes = Array.Empty(); + } + + private TileNode[,]? _tiles; + private int _gridCount; + private float _tileSize = TerrainField.TileSize; + private float _mapSize = TerrainField.ArenaSize; + + private readonly LruSlot[] _lruPool = new LruSlot[MaxGpuScarTiles]; + private ulong _lruClock; + private PlaneMesh _nearPlaneMesh = null!; + private PlaneMesh _midPlaneMesh = null!; private PlaneMesh _farPlaneMesh = null!; - private ImageTexture _white1x1 = null!; - private Shader _clearShader = null!; - private Shader _brushAddShader = null!; - private Shader _brushSubShader = null!; - private Shader _brushAlbedoShader = null!; private Shader _surfaceShader = null!; - private ShaderMaterial _heightClearMat = null!; - private ShaderMaterial _albedoClearMat = null!; - private readonly Dictionary<(Shader Shader, int Kind, float HeightDelta), ShaderMaterial> _heightBrushMatCache = new(); - private readonly Dictionary<(int Kind, float R, float G, float B, float HeightDelta), ShaderMaterial> _albedoBrushMatCache = new(); - private const int MaxDirtyRebakesPerSync = 2; + + private ImageTexture _neutralDeltaHeightTex = null!; + private ImageTexture _neutralDeltaAlbedoTex = null!; + private ImageTexture _zeroDem1x1Tex = null!; + private ImageTexture _whiteSurface1x1Tex = null!; + private ImageTexture _zeroMask1x1Tex = null!; + + private Texture2Drd? _sionDemTexRd; + private Rid _sionDemRid; + private byte[]? _pendingSionDemUpload; + private int _pendingSionDemRes; + private ImageTexture? _sionSurfaceTex; + private ImageTexture? _sionMaskTex; + private Color[]? _groundTintGrid; + private float _groundTintSizeM; + private string? _loadedSionDir; + private float _sionDemMinY; + private float _sionDemScaleSpan; + private TerrainField? _lastTerrain; + private SionMapData? _lastSionMap; + private Vector3 _lastCamPos; private int _rebakeCursor; + private readonly List<(int Idx, float DistSq)> _scarCandidateScratch = new(256); + private readonly List<(int Slot, float DistSq)> _lodResidentScratch = new(MaxGpuScarTiles); + + // Render-thread compute state + private readonly object _jobLock = new(); + private readonly List _pendingJobs = new(); + private readonly byte[] _ssboStagingBytes = new byte[MaxSsboBrushes * BrushStrideBytes]; + private readonly byte[] _pushBytes = new byte[PushConstantBytes]; + private volatile bool _hasQueuedRdFlush; + private bool _rdInitialized; + private bool _rdFailed; + private Rid _bakeShaderRid; + private Rid _bakePipeRid; + private Rid _brushSsboRid; + + // Synchronous test readback state (main thread calls ForceSync + readback via CallOnRenderThread) + private Rid _readbackTargetRid; + private byte[]? _readbackResult; public int BakedTileCount { get; private set; } public int DirtyRebakes { get; private set; } + public int ActiveGpuScarSlots + { + get + { + int count = 0; + for (int i = 0; i < _lruPool.Length; i++) + { + if (_lruPool[i] is not null && _lruPool[i].AssignedTileIndex >= 0) + { + count++; + } + } + return count; + } + } public static double PerfBakeTileMs; public static int PerfBakeTileCalls; public override void _Ready() { - var whiteImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8); - whiteImg.SetPixel(0, 0, Colors.White); - _white1x1 = ImageTexture.CreateFromImage(whiteImg); + var neutralHImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgbah); + neutralHImg.SetPixel(0, 0, new Color(0f, 0.88f, 0f, 0f)); + _neutralDeltaHeightTex = ImageTexture.CreateFromImage(neutralHImg); - _nearPlaneMesh = new PlaneMesh + var neutralAImg = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8); + neutralAImg.SetPixel(0, 0, new Color(DesertAlbedoClear.R, DesertAlbedoClear.G, DesertAlbedoClear.B, 1.0f)); + _neutralDeltaAlbedoTex = ImageTexture.CreateFromImage(neutralAImg); + + var zeroDemImg = Image.CreateEmpty(1, 1, false, Image.Format.Rh); + zeroDemImg.SetPixel(0, 0, new Color(0f, 0f, 0f, 1f)); + _zeroDem1x1Tex = ImageTexture.CreateFromImage(zeroDemImg); + + var surf1x1Img = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8); + surf1x1Img.SetPixel(0, 0, Colors.White); + _whiteSurface1x1Tex = ImageTexture.CreateFromImage(surf1x1Img); + + var mask1x1Img = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8); + mask1x1Img.SetPixel(0, 0, new Color(0f, 0f, 0f, 0f)); + _zeroMask1x1Tex = ImageTexture.CreateFromImage(mask1x1Img); + + _surfaceShader = GD.Load("res://terrain_surface.gdshader") + ?? throw new InvalidOperationException("Failed to load res://terrain_surface.gdshader"); + + for (int i = 0; i < MaxGpuScarTiles; i++) { - Size = new Vector2(TerrainField.TileSize, TerrainField.TileSize), - SubdivideWidth = 64, - SubdivideDepth = 64 - }; - _farPlaneMesh = new PlaneMesh + _lruPool[i] = new LruSlot + { + SlotIndex = i, + DeltaHeightTex = new Texture2Drd(), + DeltaAlbedoTex = new Texture2Drd() + }; + } + } + + public override void _ExitTree() + { + base._ExitTree(); + if (RenderingServer.GetRenderingDevice() is not null) { - Size = new Vector2(TerrainField.TileSize, TerrainField.TileSize), - SubdivideWidth = 16, - SubdivideDepth = 16 - }; - - _clearShader = new Shader - { - Code = """ - shader_type canvas_item; - render_mode blend_disabled; - uniform vec4 clear_vec = vec4(0.0, 0.0, 0.0, 1.0); - void fragment() { - COLOR = clear_vec; - } - """ - }; - _brushAddShader = GD.Load("res://terrain_brush.gdshader"); - _brushSubShader = GD.Load("res://terrain_brush_sub.gdshader"); - _brushAlbedoShader = GD.Load("res://terrain_brush_albedo.gdshader"); - _surfaceShader = GD.Load("res://terrain_surface.gdshader"); - - _heightClearMat = new ShaderMaterial { Shader = _clearShader }; - _heightClearMat.SetShaderParameter("clear_vec", new Vector4(HeightClearColor.R, HeightClearColor.G, HeightClearColor.B, HeightClearColor.A)); - _albedoClearMat = new ShaderMaterial { Shader = _clearShader }; - _albedoClearMat.SetShaderParameter("clear_vec", new Vector4(AlbedoClearColor.R, AlbedoClearColor.G, AlbedoClearColor.B, AlbedoClearColor.A)); - - BuildTileGrid(); + RenderingServer.CallOnRenderThread(Callable.From(DisposeRdResourcesOnRenderThread)); + RenderingServer.ForceSync(); + } } public void InvalidateAll() { - for (int tz = 0; tz < TerrainField.TileGridCount; tz++) + if (_tiles is not null) { - for (int tx = 0; tx < TerrainField.TileGridCount; tx++) + for (int tz = 0; tz < _gridCount; tz++) { - _tiles[tx, tz].BakedVersion = -1; + for (int tx = 0; tx < _gridCount; tx++) + { + var t = _tiles[tx, tz]; + if (t is null) continue; + t.BakedStructuralVersion = -1; + t.BakedVisualVersion = -1; + ReleaseTileSlot(t); + } + } + } + for (int i = 0; i < _lruPool.Length; i++) + { + if (_lruPool[i] is not null) + { + _lruPool[i].AssignedTileIndex = -1; + _lruPool[i].LastUsedSeq = 0; } } BakedTileCount = 0; DirtyRebakes = 0; + _rebakeCursor = 0; _lastTerrain = null; } - public void Sync(TerrainField terrain) + public void Sync(TerrainField terrain, SionMapData? sionMap = null) { - if (!ReferenceEquals(_lastTerrain, terrain)) + bool mapChanged = !ReferenceEquals(_lastTerrain, terrain) || !ReferenceEquals(_lastSionMap, sionMap); + if (mapChanged) { InvalidateAll(); + EnsureGridAllocated(terrain, sionMap); _lastTerrain = terrain; + _lastSionMap = sionMap; } - const int totalTiles = TerrainField.TileGridCount * TerrainField.TileGridCount; - - // 1. Always bake uninitialized tiles and structural/crater dirty tiles immediately - ulong structuralMask = terrain.StructuralDirtyTileMask; - for (int tz = 0; tz < TerrainField.TileGridCount; tz++) + if (_tiles is null) { - for (int tx = 0; tx < TerrainField.TileGridCount; tx++) + return; + } + + int grid = terrain.TileGridCount; + int totalTiles = grid * grid; + bool isSion = sionMap is not null; + float halfTile = _tileSize * 0.5f; + + Span wantSlot = stackalloc bool[totalTiles]; + if (!isSion) + { + wantSlot.Fill(true); + } + else + { + _scarCandidateScratch.Clear(); + for (int tz = 0; tz < grid; tz++) { - var tile = _tiles[tx, tz]; - int version = terrain.TileVersions[tx, tz]; - bool isUninitialized = tile.BakedVersion < 0 && tile.BakedVersion != version; - ulong bit = 1UL << (tz * TerrainField.TileGridCount + tx); - bool isStructuralDirty = (structuralMask & bit) != 0UL && tile.BakedVersion != version; - if (isUninitialized || isStructuralDirty) + for (int tx = 0; tx < grid; tx++) { - BakeTile(tx, tz, tile, terrain); - if (isUninitialized) + if (terrain.GetTileBrushIndices(tx, tz).Count > 0) + { + var tile = _tiles[tx, tz]; + float dx = (tile.OriginX + halfTile) - _lastCamPos.X; + float dz = (tile.OriginZ + halfTile) - _lastCamPos.Z; + _scarCandidateScratch.Add((tz * grid + tx, dx * dx + dz * dz)); + } + } + } + + if (_scarCandidateScratch.Count <= MaxGpuScarTiles) + { + for (int i = 0; i < _scarCandidateScratch.Count; i++) + { + wantSlot[_scarCandidateScratch[i].Idx] = true; + } + } + else + { + _scarCandidateScratch.Sort((a, b) => a.DistSq.CompareTo(b.DistSq)); + for (int i = 0; i < MaxGpuScarTiles; i++) + { + wantSlot[_scarCandidateScratch[i].Idx] = true; + } + } + } + + // 0. Release LRU slots on tiles outside the active top-96 scarred set (graceful Layer-0 DEM fallback) + for (int tz = 0; tz < grid; tz++) + { + for (int tx = 0; tx < grid; tx++) + { + int idx = tz * grid + tx; + if (!wantSlot[idx]) + { + var tile = _tiles[tx, tz]; + if (tile.LruSlotIndex >= 0) + { + ReleaseTileSlot(tile); + tile.SurfaceMat.SetShaderParameter("delta_height_tex", _neutralDeltaHeightTex); + tile.SurfaceMat.SetShaderParameter("delta_albedo_tex", _neutralDeltaAlbedoTex); + } + } + } + } + + // 1. Structural dirty tiles, uninitialized tiles, and newly promoted top-96 tiles bake immediately (never throttled) + for (int tz = 0; tz < grid; tz++) + { + for (int tx = 0; tx < grid; tx++) + { + int idx = tz * grid + tx; + var tile = _tiles[tx, tz]; + int structVer = terrain.StructuralTileVersions[tx, tz]; + int visVer = terrain.VisualTileVersions[tx, tz]; + bool isUninit = tile.BakedVisualVersion < 0; + + if (!wantSlot[idx]) + { + if (isUninit) + { + BakedTileCount++; + } + tile.BakedStructuralVersion = structVer; + tile.BakedVisualVersion = visVer; + continue; + } + + bool isStructDirty = tile.BakedStructuralVersion != structVer; + bool needsSlotReacquire = tile.LruSlotIndex < 0; + + if (isUninit || isStructDirty || needsSlotReacquire) + { + EnqueueTileBake(tx, tz, tile, terrain, isSion); + if (isUninit) { BakedTileCount++; } @@ -166,67 +353,120 @@ public partial class TerrainRenderer : Node3D { DirtyRebakes++; } - tile.BakedVersion = version; - terrain.ClearStructuralDirtyTile(tx, tz); + tile.BakedStructuralVersion = structVer; + tile.BakedVisualVersion = visVer; } } } - // 2. Budget remaining passive dynamic tile rebakes (tracks/scorch) to <= 2 per Sync in round-robin order + // 2. Remaining passive visual dirty tiles (Tracks / Scorch) inside top-96 throttled to <= MaxDirtyRebakesPerSync (4) int rebakedThisSync = 0; - bool anyRemainingDirty = false; int startCursor = _rebakeCursor; for (int step = 0; step < totalTiles; step++) { int idx = (startCursor + step) % totalTiles; - int tx = idx % TerrainField.TileGridCount; - int tz = idx / TerrainField.TileGridCount; + if (!wantSlot[idx]) + { + continue; + } + int tx = idx % grid; + int tz = idx / grid; var tile = _tiles[tx, tz]; - int version = terrain.TileVersions[tx, tz]; - if (tile.BakedVersion != version) + int visVer = terrain.VisualTileVersions[tx, tz]; + if (tile.BakedVisualVersion != visVer) { if (rebakedThisSync < MaxDirtyRebakesPerSync) { - BakeTile(tx, tz, tile, terrain); + EnqueueTileBake(tx, tz, tile, terrain, isSion); DirtyRebakes++; - tile.BakedVersion = version; + tile.BakedStructuralVersion = terrain.StructuralTileVersions[tx, tz]; + tile.BakedVisualVersion = visVer; rebakedThisSync++; _rebakeCursor = (idx + 1) % totalTiles; } else { - anyRemainingDirty = true; + break; } } } - if (!anyRemainingDirty) + DispatchPendingJobsIfNeeded(); + } + + public int CountPendingDirtyVisualTiles(TerrainField terrain) + { + if (_tiles is null || !ReferenceEquals(_lastTerrain, terrain)) { - terrain.ClearDirtyMask(); + return 0; } + int count = 0; + int grid = terrain.TileGridCount; + for (int tz = 0; tz < grid; tz++) + { + for (int tx = 0; tx < grid; tx++) + { + if (_tiles[tx, tz].BakedVisualVersion != terrain.VisualTileVersions[tx, tz]) + { + count++; + } + } + } + return count; } public void UpdateTileLod(Vector3 camPos) { - const float nearRadiusSq = 240f * 240f; - const float shadowRadiusSq = 340f * 340f; - for (int tz = 0; tz < TerrainField.TileGridCount; tz++) + _lastCamPos = camPos; + if (_tiles is null) { - for (int tx = 0; tx < TerrainField.TileGridCount; tx++) + return; + } + + const float nearRadiusSq = 220f * 220f; + const float midRadiusSq = 780f * 780f; + const float shadowRadiusSq = 360f * 360f; + float halfTile = _tileSize * 0.5f; + _lodResidentScratch.Clear(); + + for (int tz = 0; tz < _gridCount; tz++) + { + for (int tx = 0; tx < _gridCount; tx++) { var tile = _tiles[tx, tz]; - if (tile?.SurfaceMesh is null) - { - continue; - } - Vector3 pos = tile.SurfaceMesh.Position; - float dx = pos.X - camPos.X; - float dz = pos.Z - camPos.Z; + float cx = tile.OriginX + halfTile; + float cz = tile.OriginZ + halfTile; + float dx = cx - camPos.X; + float dz = cz - camPos.Z; float d2 = dx * dx + dz * dz; - PlaneMesh desired = d2 <= nearRadiusSq ? _nearPlaneMesh : _farPlaneMesh; - if (!ReferenceEquals(tile.SurfaceMesh.Mesh, desired)) + + if (tile.LruSlotIndex >= 0) { - tile.SurfaceMesh.Mesh = desired; + _lodResidentScratch.Add((tile.LruSlotIndex, d2)); + } + + PlaneMesh desiredMesh; + float quads; + if (d2 <= nearRadiusSq) + { + desiredMesh = _nearPlaneMesh; + quads = 192f; + } + else if (d2 <= midRadiusSq) + { + desiredMesh = _midPlaneMesh; + quads = 48f; + } + else + { + desiredMesh = _farPlaneMesh; + quads = 12f; + } + + tile.TileQuads = quads; + if (!ReferenceEquals(tile.SurfaceMesh.Mesh, desiredMesh)) + { + tile.SurfaceMesh.Mesh = desiredMesh; } var desiredShadow = d2 <= shadowRadiusSq ? GeometryInstance3D.ShadowCastingSetting.On @@ -237,199 +477,402 @@ public partial class TerrainRenderer : Node3D } } } + + for (int tz = 0; tz < _gridCount; tz++) + { + for (int tx = 0; tx < _gridCount; tx++) + { + var tile = _tiles[tx, tz]; + float qSelf = tile.TileQuads; + float qLeft = tx > 0 ? _tiles[tx - 1, tz].TileQuads : qSelf; + float qRight = tx < _gridCount - 1 ? _tiles[tx + 1, tz].TileQuads : qSelf; + float qTop = tz > 0 ? _tiles[tx, tz - 1].TileQuads : qSelf; + float qBottom = tz < _gridCount - 1 ? _tiles[tx, tz + 1].TileQuads : qSelf; + var nq = new Vector4(qLeft, qRight, qTop, qBottom); + + if (tile.SentTileQuads != qSelf) + { + tile.SurfaceMat.SetShaderParameter("tile_quads", qSelf); + tile.SentTileQuads = qSelf; + } + if (tile.SentNeighborQuads != nq) + { + tile.SurfaceMat.SetShaderParameter("neighbor_quads", nq); + tile.SentNeighborQuads = nq; + } + } + } + + if (_lodResidentScratch.Count > 0) + { + _lodResidentScratch.Sort((a, b) => b.DistSq.CompareTo(a.DistSq)); + for (int i = 0; i < _lodResidentScratch.Count; i++) + { + _lruPool[_lodResidentScratch[i].Slot].LastUsedSeq = ++_lruClock; + } + } + } + + public Color SampleGroundTint(float worldX, float worldZ) + { + Color[]? grid = _groundTintGrid; + float sizeM = _groundTintSizeM; + if (grid is null || sizeM <= 1f || !float.IsFinite(worldX) || !float.IsFinite(worldZ)) + { + return NeutralAlpineDustTint; + } + + float half = sizeM * 0.5f; + float u = (worldX + half) / sizeM; + float v = (worldZ + half) / sizeM; + if (u < 0f || u > 1f || v < 0f || v > 1f) + { + return NeutralAlpineDustTint; + } + + float fx = u * (GroundTintGridSize - 1); + float fy = v * (GroundTintGridSize - 1); + int x0 = Math.Clamp((int)MathF.Floor(fx), 0, GroundTintGridSize - 1); + int y0 = Math.Clamp((int)MathF.Floor(fy), 0, GroundTintGridSize - 1); + int x1 = Math.Min(x0 + 1, GroundTintGridSize - 1); + int y1 = Math.Min(y0 + 1, GroundTintGridSize - 1); + float tx = fx - x0; + float ty = fy - y0; + + Color c00 = grid[y0 * GroundTintGridSize + x0]; + Color c10 = grid[y0 * GroundTintGridSize + x1]; + Color c01 = grid[y1 * GroundTintGridSize + x0]; + Color c11 = grid[y1 * GroundTintGridSize + x1]; + return c00.Lerp(c10, tx).Lerp(c01.Lerp(c11, tx), ty); } public bool TryGetHeightImageFormat(out Image.Format format) { format = Image.Format.Max; - var img = _tiles[0, 0]?.HeightViewport?.GetTexture()?.GetImage(); - if (img is null || img.IsEmpty()) + if (RenderingServer.GetRenderingDevice() is null || _rdFailed) { return false; } - format = img.GetFormat(); + format = Image.Format.Rgbah; return true; } public bool TrySampleBakedHeight(float wx, float wz, out float bakedHeight) { bakedHeight = 0f; - float cx = Math.Clamp(wx, -TerrainField.HalfExtent, TerrainField.HalfExtent); - float cz = Math.Clamp(wz, -TerrainField.HalfExtent, TerrainField.HalfExtent); - TerrainField.WorldToTile(cx, cz, out int tx, out int tz); - - var tile = _tiles[tx, tz]; - var tex = tile?.HeightViewport?.GetTexture(); - var img = tex?.GetImage(); - if (img is null || img.IsEmpty() || img.GetWidth() < ViewportSize || img.GetHeight() < ViewportSize) + if (_lastTerrain is not { } terrain || _tiles is null) + { + return false; + } + if (RenderingServer.GetRenderingDevice() is null || _rdFailed) { return false; } - float tileMinX = -TerrainField.HalfExtent + tx * TerrainField.TileSize; - float tileMinZ = -TerrainField.HalfExtent + tz * TerrainField.TileSize; - float px = GutterCenterOffset + (cx - tileMinX) * PixelsPerMeter; - float py = GutterCenterOffset + (cz - tileMinZ) * PixelsPerMeter; + if (_hasQueuedRdFlush) + { + RenderingServer.ForceSync(); + } + + float half = terrain.MapHalfExtent; + float cx = Math.Clamp(wx, -half, half); + float cz = Math.Clamp(wz, -half, half); + terrain.MapWorldToTile(cx, cz, out int tx, out int tz); + + var tile = _tiles[tx, tz]; + float baseH = terrain.SampleBaseHeight(cx, cz); + + if (tile.LruSlotIndex < 0) + { + bakedHeight = Math.Clamp(baseH, terrain.MapMinHeight, terrain.MapMaxHeight); + return true; + } + + var slot = _lruPool[tile.LruSlotIndex]; + if (!slot.IsRdAllocated || !slot.DeltaHeightRid.IsValid) + { + return false; + } + + _readbackTargetRid = slot.DeltaHeightRid; + _readbackResult = null; + RenderingServer.CallOnRenderThread(Callable.From(ReadbackTextureOnRenderThread)); + RenderingServer.ForceSync(); + + byte[]? raw = _readbackResult; + if (raw is null || raw.Length < DeltaTexSize * DeltaTexSize * 8) + { + return false; + } + + float pixelsPerMeter = InnerTexelSpan / _tileSize; + float px = GutterCenterOffset + (cx - tile.OriginX) * pixelsPerMeter; + float py = GutterCenterOffset + (cz - tile.OriginZ) * pixelsPerMeter; + float fx = Math.Clamp(px - 0.5f, 0f, DeltaTexSize - 1.0001f); + float fy = Math.Clamp(py - 0.5f, 0f, DeltaTexSize - 1.0001f); - float fx = Math.Clamp(px - 0.5f, 0f, ViewportSize - 1.0001f); - float fy = Math.Clamp(py - 0.5f, 0f, ViewportSize - 1.0001f); int x0 = (int)MathF.Floor(fx); int y0 = (int)MathF.Floor(fy); - int x1 = Math.Min(x0 + 1, ViewportSize - 1); - int y1 = Math.Min(y0 + 1, ViewportSize - 1); + int x1 = Math.Min(x0 + 1, DeltaTexSize - 1); + int y1 = Math.Min(y0 + 1, DeltaTexSize - 1); float txFrac = fx - x0; float tyFrac = fy - y0; - var c00 = img.GetPixel(x0, y0); - if (c00.A < 0.5f) + float ReadHalfR(int x, int y) { - return false; + int byteOff = (y * DeltaTexSize + x) * 8; + return (float)BitConverter.ToHalf(raw, byteOff); } - var c10 = img.GetPixel(x1, y0); - var c01 = img.GetPixel(x0, y1); - var c11 = img.GetPixel(x1, y1); + float h00 = ReadHalfR(x0, y0); + float h10 = ReadHalfR(x1, y0); + float h01 = ReadHalfR(x0, y1); + float h11 = ReadHalfR(x1, y1); - float r = (c00.R * (1f - txFrac) + c10.R * txFrac) * (1f - tyFrac) + - (c01.R * (1f - txFrac) + c11.R * txFrac) * tyFrac; - bakedHeight = TerrainField.MinWorldHeight + Math.Clamp(r, 0f, 1f) * HeightSpan; + float deltaH = (h00 * (1f - txFrac) + h10 * txFrac) * (1f - tyFrac) + + (h01 * (1f - txFrac) + h11 * txFrac) * tyFrac; + + bakedHeight = Math.Clamp(baseH + deltaH, terrain.MapMinHeight, terrain.MapMaxHeight); return true; } - private void BuildTileGrid() + private void EnsureGridAllocated(TerrainField terrain, SionMapData? sionMap) { - for (int tz = 0; tz < TerrainField.TileGridCount; tz++) + bool needsRebuild = _tiles is null || + _gridCount != terrain.TileGridCount || + MathF.Abs(_tileSize - terrain.MapTileSize) > 0.01f; + + if (sionMap is not null) { - for (int tx = 0; tx < TerrainField.TileGridCount; tx++) + EnsureSionLayer0Resources(sionMap); + } + + if (needsRebuild) + { + if (_tiles is not null) { - var tile = new TileNode(); - - tile.HeightViewport = CreateOrthoViewport($"Tile_{tx}_{tz}_Height", useHdr: true, out var heightCanvas); - tile.HeightCanvas = heightCanvas; - heightCanvas.AddChild(CreateClearQuad(_heightClearMat, _white1x1)); - AddChild(tile.HeightViewport); - - tile.AlbedoViewport = CreateOrthoViewport($"Tile_{tx}_{tz}_Albedo", useHdr: false, out var albedoCanvas); - tile.AlbedoCanvas = albedoCanvas; - albedoCanvas.AddChild(CreateClearQuad(_albedoClearMat, _white1x1)); - AddChild(tile.AlbedoViewport); - - var mat = new ShaderMaterial { Shader = _surfaceShader }; - mat.SetShaderParameter("height_tex", tile.HeightViewport.GetTexture()); - mat.SetShaderParameter("albedo_tex", tile.AlbedoViewport.GetTexture()); - mat.SetShaderParameter("height_min", TerrainField.MinWorldHeight); - mat.SetShaderParameter("height_max", TerrainField.MaxWorldHeight); - mat.SetShaderParameter("tile_size", TerrainField.TileSize); - mat.SetShaderParameter("inner_span", InnerTexelSpan); - mat.SetShaderParameter("tex_size", (float)ViewportSize); - mat.SetShaderParameter("gutter_offset", GutterCenterOffset); - - float centerX = -TerrainField.HalfExtent + (tx + 0.5f) * TerrainField.TileSize; - float centerZ = -TerrainField.HalfExtent + (tz + 0.5f) * TerrainField.TileSize; - - tile.SurfaceMesh = new MeshInstance3D + for (int tz = 0; tz < _gridCount; tz++) { - Name = $"Tile_{tx}_{tz}_Mesh", - Mesh = _nearPlaneMesh, - MaterialOverride = mat, - Position = new Vector3(centerX, 0f, centerZ), - CustomAabb = new Aabb( - new Vector3(-TerrainField.TileSize * 0.5f, TerrainField.MinWorldHeight - 2f, -TerrainField.TileSize * 0.5f), - new Vector3(TerrainField.TileSize, HeightSpan + 4f, TerrainField.TileSize)) - }; - AddChild(tile.SurfaceMesh); + for (int tx = 0; tx < _gridCount; tx++) + { + var old = _tiles[tx, tz]; + if (old?.SurfaceMesh is not null && IsInstanceValid(old.SurfaceMesh)) + { + old.SurfaceMesh.QueueFree(); + } + } + } + } - _tiles[tx, tz] = tile; + _gridCount = terrain.TileGridCount; + _tileSize = terrain.MapTileSize; + _mapSize = terrain.MapSize; + + _nearPlaneMesh = new PlaneMesh + { + Size = new Vector2(_tileSize, _tileSize), + SubdivideWidth = 191, + SubdivideDepth = 191 + }; + _midPlaneMesh = new PlaneMesh + { + Size = new Vector2(_tileSize, _tileSize), + SubdivideWidth = 47, + SubdivideDepth = 47 + }; + _farPlaneMesh = new PlaneMesh + { + Size = new Vector2(_tileSize, _tileSize), + SubdivideWidth = 11, + SubdivideDepth = 11 + }; + + _tiles = new TileNode[_gridCount, _gridCount]; + for (int tz = 0; tz < _gridCount; tz++) + { + for (int tx = 0; tx < _gridCount; tx++) + { + float originX = -terrain.MapHalfExtent + tx * _tileSize; + float originZ = -terrain.MapHalfExtent + tz * _tileSize; + var mat = new ShaderMaterial { Shader = _surfaceShader }; + var mi = new MeshInstance3D + { + Name = $"Tile_{tx}_{tz}_Mesh", + Mesh = _nearPlaneMesh, + MaterialOverride = mat, + Position = new Vector3(originX + _tileSize * 0.5f, 0f, originZ + _tileSize * 0.5f) + }; + AddChild(mi); + + _tiles[tx, tz] = new TileNode + { + Tx = tx, + Tz = tz, + OriginX = originX, + OriginZ = originZ, + SurfaceMesh = mi, + SurfaceMat = mat + }; + } + } + } + + bool isSion = sionMap is not null; + float minY = terrain.MapMinHeight; + float maxY = terrain.MapMaxHeight; + float span = MathF.Max(1f, maxY - minY); + + for (int tz = 0; tz < _gridCount; tz++) + { + for (int tx = 0; tx < _gridCount; tx++) + { + var tile = _tiles![tx, tz]; + var mat = tile.SurfaceMat; + mat.SetShaderParameter("base_dem_tex", isSion && _sionDemTexRd is not null ? _sionDemTexRd : _zeroDem1x1Tex); + mat.SetShaderParameter("base_surface_tex", isSion && _sionSurfaceTex is not null ? _sionSurfaceTex : _whiteSurface1x1Tex); + mat.SetShaderParameter("base_mask_tex", isSion && _sionMaskTex is not null ? _sionMaskTex : _zeroMask1x1Tex); + mat.SetShaderParameter("delta_height_tex", _neutralDeltaHeightTex); + mat.SetShaderParameter("delta_albedo_tex", _neutralDeltaAlbedoTex); + mat.SetShaderParameter("dem_min_y", isSion ? _sionDemMinY : 0f); + mat.SetShaderParameter("dem_scale_span", isSion ? _sionDemScaleSpan : 0f); + mat.SetShaderParameter("dem_grid_res", isSion ? (float)sionMap!.Metadata.GridRes : 1f); + mat.SetShaderParameter("height_min", minY); + mat.SetShaderParameter("height_max", maxY); + mat.SetShaderParameter("map_size", _mapSize); + mat.SetShaderParameter("tile_origin_x", tile.OriginX); + mat.SetShaderParameter("tile_origin_z", tile.OriginZ); + mat.SetShaderParameter("tile_size", _tileSize); + mat.SetShaderParameter("inner_span", InnerTexelSpan); + mat.SetShaderParameter("tex_size", (float)DeltaTexSize); + mat.SetShaderParameter("gutter_center", GutterCenterOffset); + mat.SetShaderParameter("is_sion", isSion ? 1f : 0f); + + tile.SurfaceMesh.CustomAabb = new Aabb( + new Vector3(-_tileSize * 0.5f, minY - 2f, -_tileSize * 0.5f), + new Vector3(_tileSize, span + 4f, _tileSize)); } } } - private static SubViewport CreateOrthoViewport(string name, bool useHdr, out Node2D canvas) + private void EnsureSionLayer0Resources(SionMapData sionMap) { - var vp = new SubViewport + if (string.Equals(_loadedSionDir, sionMap.DirectoryPath, StringComparison.OrdinalIgnoreCase)) { - Name = name, - Size = new Vector2I(ViewportSize, ViewportSize), - Disable3D = true, - UseHdr2D = useHdr, - TransparentBg = false, - Snap2DTransformsToPixel = false, - Snap2DVerticesToPixel = false, - RenderTargetClearMode = SubViewport.ClearMode.Always, - RenderTargetUpdateMode = SubViewport.UpdateMode.Disabled - }; + return; + } + _loadedSionDir = sionMap.DirectoryPath; + _sionDemMinY = sionMap.BaseDemMinY; + _sionDemScaleSpan = 65535.0f * sionMap.BaseDemScale; - var cam = new Camera2D + string surfPath = Path.Combine(sionMap.DirectoryPath, sionMap.Metadata.SurfaceTexture); + if (!File.Exists(surfPath)) { - AnchorMode = Camera2D.AnchorModeEnum.FixedTopLeft, - Position = Vector2.Zero, - Enabled = true, - PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off, - ProcessCallback = Camera2D.Camera2DProcessCallback.Physics - }; - vp.AddChild(cam); + throw new FileNotFoundException($"Missing Sion terrain surface texture: {surfPath}", surfPath); + } + var surfImg = Image.LoadFromFile(surfPath) + ?? throw new InvalidOperationException($"Failed to decode Sion terrain surface texture: {surfPath}"); - canvas = new Node2D { Name = "Canvas" }; - vp.AddChild(canvas); - return vp; + var tintImg = (Image)surfImg.Duplicate(); + tintImg.Resize(GroundTintGridSize, GroundTintGridSize, Image.Interpolation.Bilinear); + var grid = new Color[GroundTintGridSize * GroundTintGridSize]; + for (int y = 0; y < GroundTintGridSize; y++) + { + for (int x = 0; x < GroundTintGridSize; x++) + { + Color c = tintImg.GetPixel(x, y); + grid[y * GroundTintGridSize + x] = new Color( + Math.Clamp(c.R + 0.11f, 0.20f, 0.90f), + Math.Clamp(c.G + 0.11f, 0.20f, 0.88f), + Math.Clamp(c.B + 0.10f, 0.18f, 0.84f), + 1.0f); + } + } + _groundTintGrid = grid; + _groundTintSizeM = sionMap.Metadata.SizeMeters; + + surfImg.GenerateMipmaps(); + _sionSurfaceTex = ImageTexture.CreateFromImage(surfImg); + + string maskName = string.IsNullOrWhiteSpace(sionMap.Metadata.SurfaceMaskTexture) + ? "terrain_surface_mask.png" + : sionMap.Metadata.SurfaceMaskTexture; + string maskPath = Path.Combine(sionMap.DirectoryPath, maskName); + if (File.Exists(maskPath)) + { + var maskImg = Image.LoadFromFile(maskPath); + if (maskImg is not null && !maskImg.IsEmpty()) + { + maskImg.GenerateMipmaps(); + _sionMaskTex = ImageTexture.CreateFromImage(maskImg); + } + } + + if (RenderingServer.GetRenderingDevice() is not null) + { + _sionDemTexRd ??= new Texture2Drd(); + byte[] demBytes = new byte[sionMap.BaseDem.Length * 2]; + Buffer.BlockCopy(sionMap.BaseDem, 0, demBytes, 0, demBytes.Length); + _pendingSionDemUpload = demBytes; + _pendingSionDemRes = sionMap.Metadata.GridRes; + RenderingServer.CallOnRenderThread(Callable.From(UploadSionDemOnRenderThread)); + } } - private void BakeTile(int tx, int tz, TileNode tile, TerrainField terrain) + private void EnqueueTileBake(int tx, int tz, TileNode tile, TerrainField terrain, bool isSion) { long t0 = RustToDust.Ymir.ArenaSession.PerfEnabled ? System.Diagnostics.Stopwatch.GetTimestamp() : 0; - float tileMinX = -TerrainField.HalfExtent + tx * TerrainField.TileSize; - float tileMinZ = -TerrainField.HalfExtent + tz * TerrainField.TileSize; IReadOnlyList indices = terrain.GetTileBrushIndices(tx, tz); - var brushes = terrain.Brushes; - - int hCount = 0; - int aCount = 0; - - for (int i = 0; i < indices.Count; i++) + if (indices.Count == 0 && isSion) { - var b = brushes[indices[i]]; - if (b.RadiusX <= 0.05f || b.RadiusZ <= 0.05f) - { - continue; - } - - float px = GutterCenterOffset + (b.X - tileMinX) * PixelsPerMeter; - float py = GutterCenterOffset + (b.Z - tileMinZ) * PixelsPerMeter; - float rxPx = b.RadiusX * PixelsPerMeter; - float rzPx = b.RadiusZ * PixelsPerMeter; - int kindInt = (int)b.Kind; - - // 1. Height+Material brush pass(es) - if (b.Kind == TerrainBrushKind.Crater) - { - // Crater uses subtractive pit + additive ejecta rim/scorch - SetQuad(tile.HeightCanvas, tile.HeightQuads, ref hCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateHeightBrushMat(_brushSubShader, kindInt, b.HeightDelta), _white1x1); - SetQuad(tile.HeightCanvas, tile.HeightQuads, ref hCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateHeightBrushMat(_brushAddShader, kindInt, b.HeightDelta), _white1x1); - } - else if (b.Kind == TerrainBrushKind.Track) - { - SetQuad(tile.HeightCanvas, tile.HeightQuads, ref hCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateHeightBrushMat(_brushSubShader, kindInt, b.HeightDelta), _white1x1); - SetQuad(tile.HeightCanvas, tile.HeightQuads, ref hCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateHeightBrushMat(_brushAddShader, kindInt, b.HeightDelta), _white1x1); - } - else if (b.Kind == TerrainBrushKind.Road || b.HeightDelta < 0f) - { - SetQuad(tile.HeightCanvas, tile.HeightQuads, ref hCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateHeightBrushMat(_brushSubShader, kindInt, b.HeightDelta), _white1x1); - } - else - { - SetQuad(tile.HeightCanvas, tile.HeightQuads, ref hCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateHeightBrushMat(_brushAddShader, kindInt, b.HeightDelta), _white1x1); - } - - // 2. Albedo brush pass - SetQuad(tile.AlbedoCanvas, tile.AlbedoQuads, ref aCount, px, py, rxPx, rzPx, b.RotationRad, GetOrCreateAlbedoBrushMat(kindInt, b.AlbedoR, b.AlbedoG, b.AlbedoB, b.HeightDelta), _white1x1); + // Untouched Sion tile: release LRU slot and bind shared 1x1 neutral delta texture + ReleaseTileSlot(tile); + tile.SurfaceMat.SetShaderParameter("delta_height_tex", _neutralDeltaHeightTex); + tile.SurfaceMat.SetShaderParameter("delta_albedo_tex", _neutralDeltaAlbedoTex); + return; } - HideUnusedQuads(tile.HeightQuads, hCount); - HideUnusedQuads(tile.AlbedoQuads, aCount); + int tileIdx = tz * _gridCount + tx; + LruSlot slot = AcquireLruSlot(tileIdx, tile); + tile.SurfaceMat.SetShaderParameter("delta_height_tex", slot.DeltaHeightTex); + tile.SurfaceMat.SetShaderParameter("delta_albedo_tex", slot.DeltaAlbedoTex); + + if (RenderingServer.GetRenderingDevice() is not null && !_rdFailed) + { + var brushes = terrain.Brushes; + var gpuList = new List(indices.Count); + for (int i = 0; i < indices.Count; i++) + { + var b = brushes[indices[i]]; + if (b.RadiusX <= 0.05f || b.RadiusZ <= 0.05f) + { + continue; + } + float invRx = 1f / MathF.Max(0.1f, b.RadiusX); + float invRz = 1f / MathF.Max(0.1f, b.RadiusZ); + float maxR = MathF.Max(0.1f, MathF.Max(b.RadiusX, b.RadiusZ)); + gpuList.Add(new GpuBrush + { + PosRot = new Vector4(b.X, b.Z, MathF.Cos(b.RotationRad), MathF.Sin(b.RotationRad)), + RadDelta = new Vector4(invRx, invRz, b.HeightDelta, maxR * maxR), + MatColor = new Vector4(b.AlbedoR, b.AlbedoG, b.AlbedoB, (float)(int)b.Kind) + }); + } + + lock (_jobLock) + { + _pendingJobs.Add(new PendingBakeJob + { + SlotIndex = slot.SlotIndex, + TileOriginX = tile.OriginX, + TileOriginZ = tile.OriginZ, + TileSize = _tileSize, + IsSion = isSion, + Brushes = gpuList.ToArray() + }); + } + } - tile.HeightViewport.RenderTargetUpdateMode = SubViewport.UpdateMode.Once; - tile.AlbedoViewport.RenderTargetUpdateMode = SubViewport.UpdateMode.Once; if (t0 != 0) { PerfBakeTileMs += (System.Diagnostics.Stopwatch.GetTimestamp() - t0) * 1000.0 / System.Diagnostics.Stopwatch.Frequency; @@ -437,94 +880,393 @@ public partial class TerrainRenderer : Node3D } } - private ShaderMaterial GetOrCreateHeightBrushMat(Shader shader, int kindInt, float heightDelta) + private LruSlot AcquireLruSlot(int tileIdx, TileNode tile) { - var key = (shader, kindInt, heightDelta); - if (!_heightBrushMatCache.TryGetValue(key, out var mat)) + _lruClock++; + if (tile.LruSlotIndex >= 0) { - mat = new ShaderMaterial { Shader = shader }; - mat.SetShaderParameter("brush_kind", kindInt); - mat.SetShaderParameter("height_delta", heightDelta); - mat.SetShaderParameter("height_span", HeightSpan); - _heightBrushMatCache[key] = mat; + var cur = _lruPool[tile.LruSlotIndex]; + if (cur.AssignedTileIndex == tileIdx) + { + cur.LastUsedSeq = _lruClock; + return cur; + } } - return mat; + + int bestIdx = -1; + ulong bestAge = ulong.MaxValue; + for (int i = 0; i < MaxGpuScarTiles; i++) + { + if (_lruPool[i].AssignedTileIndex < 0) + { + bestIdx = i; + break; + } + if (_lruPool[i].LastUsedSeq < bestAge) + { + bestAge = _lruPool[i].LastUsedSeq; + bestIdx = i; + } + } + + var chosen = _lruPool[bestIdx]; + if (chosen.AssignedTileIndex >= 0 && _tiles is not null) + { + int prevTileIdx = chosen.AssignedTileIndex; + int prevTx = prevTileIdx % _gridCount; + int prevTz = prevTileIdx / _gridCount; + if ((uint)prevTx < (uint)_gridCount && (uint)prevTz < (uint)_gridCount) + { + var evicted = _tiles[prevTx, prevTz]; + if (evicted.LruSlotIndex == bestIdx) + { + evicted.LruSlotIndex = -1; + evicted.BakedVisualVersion = -1; + evicted.BakedStructuralVersion = -1; + evicted.SurfaceMat.SetShaderParameter("delta_height_tex", _neutralDeltaHeightTex); + evicted.SurfaceMat.SetShaderParameter("delta_albedo_tex", _neutralDeltaAlbedoTex); + } + } + } + + chosen.AssignedTileIndex = tileIdx; + chosen.LastUsedSeq = _lruClock; + tile.LruSlotIndex = bestIdx; + return chosen; } - private ShaderMaterial GetOrCreateAlbedoBrushMat(int kindInt, float r, float g, float b, float heightDelta) + private void ReleaseTileSlot(TileNode tile) { - var key = (kindInt, r, g, b, heightDelta); - if (!_albedoBrushMatCache.TryGetValue(key, out var mat)) + if (tile.LruSlotIndex >= 0) { - mat = new ShaderMaterial { Shader = _brushAlbedoShader }; - mat.SetShaderParameter("brush_kind", kindInt); - mat.SetShaderParameter("brush_albedo", new Vector3(r, g, b)); - mat.SetShaderParameter("height_delta", heightDelta); - _albedoBrushMatCache[key] = mat; + var slot = _lruPool[tile.LruSlotIndex]; + if (slot.AssignedTileIndex == tile.Tz * _gridCount + tile.Tx) + { + slot.AssignedTileIndex = -1; + } + tile.LruSlotIndex = -1; } - return mat; } - private static Polygon2D CreateClearQuad(ShaderMaterial mat, ImageTexture whiteTex) + private void DispatchPendingJobsIfNeeded() { - return new Polygon2D + if (RenderingServer.GetRenderingDevice() is null || _rdFailed) { - Polygon = ClearQuadPoly, - UV = BrushUv, - Texture = whiteTex, - Material = mat + lock (_jobLock) + { + _pendingJobs.Clear(); + } + return; + } + + bool any; + lock (_jobLock) + { + any = _pendingJobs.Count > 0; + } + if (any) + { + _hasQueuedRdFlush = true; + RenderingServer.CallOnRenderThread(Callable.From(FlushPendingGpuBakesOnRenderThread)); + } + } + + private void UploadSionDemOnRenderThread() + { + RenderingDevice? rd = RenderingServer.GetRenderingDevice(); + byte[]? demBytes = _pendingSionDemUpload; + int res = _pendingSionDemRes; + _pendingSionDemUpload = null; + if (rd is null || demBytes is null || res <= 1) + { + return; + } + + if (_sionDemRid.IsValid) + { + if (_sionDemTexRd is not null) + { + _sionDemTexRd.TextureRdRid = new Rid(); + } + rd.FreeRid(_sionDemRid); + _sionDemRid = new Rid(); + } + + var fmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type2D, + Format = RenderingDevice.DataFormat.R16Unorm, + Width = (uint)res, + Height = (uint)res, + Depth = 1, + Mipmaps = 1, + ArrayLayers = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | RenderingDevice.TextureUsageBits.CanUpdateBit }; + var dataArr = new Godot.Collections.Array { demBytes }; + _sionDemRid = rd.TextureCreate(fmt, new RDTextureView(), dataArr); + if (_sionDemTexRd is not null && _sionDemRid.IsValid) + { + _sionDemTexRd.TextureRdRid = _sionDemRid; + } } - private static void SetQuad( - Node2D canvas, - List pool, - ref int index, - float px, float py, - float rxPx, float rzPx, - float rotationRad, - ShaderMaterial mat, - ImageTexture whiteTex) + private bool EnsureComputePipelineOnRenderThread(RenderingDevice rd) { - Polygon2D quad; - if (index < pool.Count) + if (_rdInitialized) { - quad = pool[index]; - quad.Position = new Vector2(px, py); - quad.Rotation = rotationRad; - quad.Scale = new Vector2(rxPx, rzPx); - quad.Material = mat; - if (!quad.Visible) - { - quad.Visible = true; - } + return true; } - else + if (_rdFailed) { - quad = new Polygon2D + return false; + } + + string source = Godot.FileAccess.GetFileAsString("res://terrain_tile_bake.glsl"); + if (string.IsNullOrWhiteSpace(source)) + { + GD.PrintErr("TerrainRenderer: missing compute shader res://terrain_tile_bake.glsl"); + _rdFailed = true; + return false; + } + + using var rdSrc = new RDShaderSource + { + Language = RenderingDevice.ShaderLanguage.Glsl, + SourceCompute = source + }; + using RDShaderSpirV spirv = rd.ShaderCompileSpirVFromSource(rdSrc, allowCache: true); + if (!string.IsNullOrEmpty(spirv.CompileErrorCompute)) + { + GD.PrintErr($"TerrainRenderer: SPIR-V compile error in terrain_tile_bake.glsl: {spirv.CompileErrorCompute}"); + _rdFailed = true; + return false; + } + + _bakeShaderRid = rd.ShaderCreateFromSpirV(spirv, "terrain_tile_bake"); + _bakePipeRid = rd.ComputePipelineCreate(_bakeShaderRid); + if (!_bakeShaderRid.IsValid || !_bakePipeRid.IsValid) + { + GD.PrintErr("TerrainRenderer: failed to create compute pipeline"); + _rdFailed = true; + return false; + } + + _brushSsboRid = rd.StorageBufferCreate(MaxSsboBrushes * BrushStrideBytes, new byte[MaxSsboBrushes * BrushStrideBytes]); + _rdInitialized = true; + return true; + } + + private void EnsureSlotRdAllocatedOnRenderThread(RenderingDevice rd, LruSlot slot) + { + if (slot.IsRdAllocated) + { + return; + } + + var hFmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type2D, + Format = RenderingDevice.DataFormat.R16G16B16A16Sfloat, + Width = DeltaTexSize, + Height = DeltaTexSize, + Depth = 1, + Mipmaps = 1, + ArrayLayers = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | + RenderingDevice.TextureUsageBits.StorageBit | + RenderingDevice.TextureUsageBits.CanCopyFromBit + }; + slot.DeltaHeightRid = rd.TextureCreate(hFmt, new RDTextureView()); + + var aFmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type2D, + Format = RenderingDevice.DataFormat.R8G8B8A8Unorm, + Width = DeltaTexSize, + Height = DeltaTexSize, + Depth = 1, + Mipmaps = 1, + ArrayLayers = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | RenderingDevice.TextureUsageBits.StorageBit + }; + slot.DeltaAlbedoRid = rd.TextureCreate(aFmt, new RDTextureView()); + + var uniforms = new Godot.Collections.Array + { + new RDUniform { - Position = new Vector2(px, py), - Rotation = rotationRad, - Scale = new Vector2(rxPx, rzPx), - Polygon = UnitQuadPoly, - UV = BrushUv, - Texture = whiteTex, - Material = mat + UniformType = RenderingDevice.UniformType.Image, + Binding = 0, + _Ids = new Godot.Collections.Array { slot.DeltaHeightRid } + }, + new RDUniform + { + UniformType = RenderingDevice.UniformType.Image, + Binding = 1, + _Ids = new Godot.Collections.Array { slot.DeltaAlbedoRid } + }, + new RDUniform + { + UniformType = RenderingDevice.UniformType.StorageBuffer, + Binding = 2, + _Ids = new Godot.Collections.Array { _brushSsboRid } + } + }; + slot.UniformSetRid = rd.UniformSetCreate(uniforms, _bakeShaderRid, 0); + slot.DeltaHeightTex.TextureRdRid = slot.DeltaHeightRid; + slot.DeltaAlbedoTex.TextureRdRid = slot.DeltaAlbedoRid; + slot.IsRdAllocated = true; + } + + private void FlushPendingGpuBakesOnRenderThread() + { + PendingBakeJob[] jobs; + lock (_jobLock) + { + if (_pendingJobs.Count == 0) + { + _hasQueuedRdFlush = false; + return; + } + jobs = _pendingJobs.ToArray(); + _pendingJobs.Clear(); + } + + RenderingDevice? rd = RenderingServer.GetRenderingDevice(); + if (rd is null || !EnsureComputePipelineOnRenderThread(rd)) + { + _hasQueuedRdFlush = false; + return; + } + + long t0 = RustToDust.Ymir.ArenaSession.PerfEnabled ? System.Diagnostics.Stopwatch.GetTimestamp() : 0; + + int totalBrushes = 0; + var brushStarts = new uint[jobs.Length]; + for (int j = 0; j < jobs.Length; j++) + { + int count = jobs[j].Brushes.Length; + if (totalBrushes + count > MaxSsboBrushes) + { + count = Math.Max(0, MaxSsboBrushes - totalBrushes); + } + brushStarts[j] = (uint)totalBrushes; + for (int b = 0; b < count; b++) + { + int byteOff = (totalBrushes + b) * BrushStrideBytes; + MemoryMarshal.Write(_ssboStagingBytes.AsSpan(byteOff, BrushStrideBytes), in jobs[j].Brushes[b]); + } + totalBrushes += count; + } + + if (totalBrushes > 0) + { + rd.BufferUpdate(_brushSsboRid, 0, (uint)(totalBrushes * BrushStrideBytes), _ssboStagingBytes); + } + + for (int j = 0; j < jobs.Length; j++) + { + EnsureSlotRdAllocatedOnRenderThread(rd, _lruPool[jobs[j].SlotIndex]); + } + + uint groups = (uint)((DeltaTexSize + 7) / 8); + long cl = rd.ComputeListBegin(); + rd.ComputeListBindComputePipeline(cl, _bakePipeRid); + for (int j = 0; j < jobs.Length; j++) + { + var job = jobs[j]; + var slot = _lruPool[job.SlotIndex]; + uint bCount = (uint)Math.Min(job.Brushes.Length, MaxSsboBrushes - (int)brushStarts[j]); + var push = new TileBakePush + { + TileOriginAndSpan = new Vector4(job.TileOriginX, job.TileOriginZ, job.TileSize, InnerTexelSpan), + BaseColorAndGutter = job.IsSion + ? new Vector4(0f, 0f, 0f, GutterStartIndex) + : new Vector4(DesertAlbedoClear.R, DesertAlbedoClear.G, DesertAlbedoClear.B, GutterStartIndex), + BrushStart = brushStarts[j], + BrushCount = bCount, + TexSize = DeltaTexSize, + IsSion = job.IsSion ? 1u : 0u }; - pool.Add(quad); - canvas.AddChild(quad); + MemoryMarshal.Write(_pushBytes, in push); + rd.ComputeListBindUniformSet(cl, slot.UniformSetRid, 0); + rd.ComputeListSetPushConstant(cl, _pushBytes, PushConstantBytes); + rd.ComputeListDispatch(cl, groups, groups, 1); + } + rd.ComputeListEnd(); + _hasQueuedRdFlush = false; + + if (t0 != 0) + { + PerfBakeTileMs += (System.Diagnostics.Stopwatch.GetTimestamp() - t0) * 1000.0 / System.Diagnostics.Stopwatch.Frequency; } - index++; } - private static void HideUnusedQuads(List pool, int usedCount) + private void ReadbackTextureOnRenderThread() { - for (int i = usedCount; i < pool.Count; i++) + RenderingDevice? rd = RenderingServer.GetRenderingDevice(); + if (rd is null || !_readbackTargetRid.IsValid) { - if (pool[i].Visible) - { - pool[i].Visible = false; - } + _readbackResult = null; + return; } + _readbackResult = rd.TextureGetData(_readbackTargetRid, 0); + } + + private void DisposeRdResourcesOnRenderThread() + { + RenderingDevice? rd = RenderingServer.GetRenderingDevice(); + if (rd is null) + { + return; + } + + for (int i = 0; i < _lruPool.Length; i++) + { + var slot = _lruPool[i]; + if (slot is null || !slot.IsRdAllocated) + { + continue; + } + slot.DeltaHeightTex.TextureRdRid = new Rid(); + slot.DeltaAlbedoTex.TextureRdRid = new Rid(); + if (slot.UniformSetRid.IsValid) rd.FreeRid(slot.UniformSetRid); + if (slot.DeltaHeightRid.IsValid) rd.FreeRid(slot.DeltaHeightRid); + if (slot.DeltaAlbedoRid.IsValid) rd.FreeRid(slot.DeltaAlbedoRid); + slot.UniformSetRid = new Rid(); + slot.DeltaHeightRid = new Rid(); + slot.DeltaAlbedoRid = new Rid(); + slot.IsRdAllocated = false; + } + + if (_sionDemTexRd is not null) + { + _sionDemTexRd.TextureRdRid = new Rid(); + } + if (_sionDemRid.IsValid) + { + rd.FreeRid(_sionDemRid); + _sionDemRid = new Rid(); + } + if (_brushSsboRid.IsValid) + { + rd.FreeRid(_brushSsboRid); + _brushSsboRid = new Rid(); + } + if (_bakePipeRid.IsValid) + { + rd.FreeRid(_bakePipeRid); + _bakePipeRid = new Rid(); + } + if (_bakeShaderRid.IsValid) + { + rd.FreeRid(_bakeShaderRid); + _bakeShaderRid = new Rid(); + } + _rdInitialized = false; } } diff --git a/client/UiFonts.cs b/client/UiFonts.cs new file mode 100644 index 0000000..c3aba41 --- /dev/null +++ b/client/UiFonts.cs @@ -0,0 +1,35 @@ +using Godot; + +namespace RustToDust.Client; + +/// +/// Central font accessor for custom Control._Draw() canvas calls. +/// Standard controls inherit gui/theme/custom_font from project.godot. +/// +internal static class UiFonts +{ + private const string RegularPath = "res://fonts/MonaspaceKrypton-Regular.otf"; + private const string SemiBoldPath = "res://fonts/MonaspaceKrypton-SemiBold.otf"; + private const string BoldPath = "res://fonts/MonaspaceKrypton-Bold.otf"; + + private static Font? _regular; + private static Font? _semiBold; + private static Font? _bold; + + public static Font Regular => _regular ??= LoadOrFallback(RegularPath, ThemeDB.FallbackFont); + public static Font SemiBold => _semiBold ??= LoadOrFallback(SemiBoldPath, Regular); + public static Font Bold => _bold ??= LoadOrFallback(BoldPath, SemiBold); + + private static Font LoadOrFallback(string path, Font fallback) + { + if (ResourceLoader.Exists(path)) + { + var loaded = GD.Load(path); + if (loaded is not null) + { + return loaded; + } + } + return fallback; + } +} diff --git a/client/VehicleAssetCache.cs b/client/VehicleAssetCache.cs index 4fc7c0a..8473599 100644 --- a/client/VehicleAssetCache.cs +++ b/client/VehicleAssetCache.cs @@ -132,9 +132,9 @@ public sealed class VehicleAssetCache : IDisposable public VehicleAssetCache() { + ClientAssets.EnsureAssetsRootRegistered(); _vehiclesDir = VehicleCatalogLoader.LocateVehiclesDirectory(); - string assetsDir = Directory.GetParent(_vehiclesDir)?.FullName - ?? throw new DirectoryNotFoundException($"Could not locate assets parent directory of '{_vehiclesDir}'."); + string assetsDir = ClientAssets.LocateAssetsDirectory(); _gearDir = Path.Combine(assetsDir, "gear"); if (!Directory.Exists(_gearDir)) { diff --git a/client/VolumetricCompositorEffect.cs b/client/VolumetricCompositorEffect.cs new file mode 100644 index 0000000..debe86c --- /dev/null +++ b/client/VolumetricCompositorEffect.cs @@ -0,0 +1,724 @@ +using System; +using System.Runtime.InteropServices; +using Godot; + +namespace RustToDust.Client; + +/// +/// 4-pass Forward+ Vulkan compute pipeline (PostSky) owning: +/// Pass 0: flow_field_step.glsl (camera-snapped 3m 64x24x64 RGBA16F ping-pong -> ) +/// Pass 1: volumetric_tile_cull.glsl (16x16 half-res tiles + 128-element Bitonic sort) +/// Pass 2: volumetric_raymarch.glsl (sorted monotonic sweep-line + Aetheria curl/triNoise + shock cavity + 2 shadow taps) +/// Pass 3: volumetric_composite.glsl (2x2 bilateral depth upsample pre-tonemap) +/// +public sealed partial class VolumetricCompositorEffect : CompositorEffect +{ + public const int FlowDimX = 64; + public const int FlowDimY = 24; + public const int FlowDimZ = 64; + public const float FlowVoxelSizeMeters = 3.0f; + public const int TileSizeHalfRes = 16; + public const int TileStrideBytes = 112; + public const int FrameUboBytes = 272; + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + private struct VolumetricFrameUbo + { + public Vector4 InvProj0, InvProj1, InvProj2, InvProj3; + public Vector4 CamPosTime; + public Vector4 CamRightAspect; + public Vector4 CamUpTanHalfFov; + public Vector4 CamFwdNearFar; + public Vector4 SunDirIntensity; + public Vector4 SunColorExt; + public Vector4 AmbientColorFog; + public Vector4 ViewportInfo; + public uint HalfW, HalfH, TilesX, FrameIndex; + public Vector4 FlowOriginVoxel; + public Vector4 FlowInvExtentDt; + public int DeltaX, DeltaY, DeltaZ, ImpulseCount; + public uint MaxSteps, MaxIter, IsFullRes, QualityPad; + } + + private readonly Texture3Drd _flowTexRd; + private VolumetricEmitterPool _emitterPool; + + // Atmosphere parameters updated from game thread via volatile/lock + private readonly object _atmoLock = new(); + private Vector3 _sunDir = new Vector3(0.45f, 0.55f, 0.70f).Normalized(); + private float _sunEnergy = 1.25f; + private Color _sunColor = Colors.White; + private Color _ambientColor = new(0.28f, 0.34f, 0.42f); + private float _globalExtinctionScale = 0.28f; + private VfxResolutionScale _resolutionScale = VfxResolutionScale.Half; + private VolumetricSamples _volumetricSamples = VolumetricSamples.Medium; + + // Render-thread RD state + private RenderingDevice? _rd; + private bool _rdInitialized; + private bool _rdFailed; + + private Rid _flowShaderRid, _flowPipeRid; + private Rid _cullShaderRid, _cullPipeRid; + private Rid _marchShaderRid, _marchPipeRid; + private Rid _compShaderRid, _compPipeRid; + + private readonly Rid[] _flowTexRids = new Rid[2]; + private int _flowReadIdx; + private Vector3I _prevFlowVoxelOrigin; + private bool _hasPrevFlowOrigin; + + private Rid _nearestSamplerRid; + private Rid _linearSamplerRid; + private Rid _frameUboRid; + private Rid _emitterSsboRid; + private Rid _impulseSsboRid; + private Rid _tileSsboRid; + private int _tileSsboCapacityTiles; + + private Rid _halfVolRid; + private Vector2I _halfVolSize; + private uint _frameCounter; + + // Pre-allocated CPU staging buffers (zero per-frame allocations) + private readonly byte[] _uboBytes = new byte[FrameUboBytes]; + private readonly byte[] _emitterUploadBytes = new byte[VolumetricEmitterPool.MaxEmitters * VolumetricEmitterPool.EmitterStrideBytes]; + private readonly byte[] _impulseUploadBytes = new byte[VolumetricEmitterPool.MaxFlowImpulses * VolumetricEmitterPool.ImpulseStrideBytes]; + + // Lightweight RD timestamp telemetry (populated when ProfilingEnabled == true) + public bool ProfilingEnabled { get; set; } + private ulong _lastSampledTimestampFrame = ulong.MaxValue; + public double LastFlowGpuMs { get; private set; } + public double LastCullGpuMs { get; private set; } + public double LastMarchGpuMs { get; private set; } + public double LastCompGpuMs { get; private set; } + public double LastTotalGpuMs => LastFlowGpuMs + LastCullGpuMs + LastMarchGpuMs + LastCompGpuMs; + public Vector2I LastMarchSize { get; private set; } + public int CurrentMaxSteps { get; private set; } = 10; + public int CurrentMaxIter { get; private set; } = 15; + + public VolumetricCompositorEffect() : this(new Texture3Drd(), new VolumetricEmitterPool()) + { + } + + public VolumetricCompositorEffect(Texture3Drd flowTexRd, VolumetricEmitterPool emitterPool) + { + _flowTexRd = flowTexRd; + _emitterPool = emitterPool; + EffectCallbackType = EffectCallbackTypeEnum.PostSky; + AccessResolvedColor = true; + AccessResolvedDepth = true; + Enabled = true; + } + + public void SetEmitterPool(VolumetricEmitterPool pool) + { + _emitterPool = pool ?? throw new ArgumentNullException(nameof(pool)); + } + + public void ApplyGraphicsSettings(GraphicsSettings settings) + { + ArgumentNullException.ThrowIfNull(settings); + lock (_atmoLock) + { + _resolutionScale = settings.VfxResolution; + _volumetricSamples = settings.VolumetricSamples; + } + } + + public void SetAtmosphere(Vector3 sunDir, float sunEnergy, Color sunColor, Color ambientColor, float extinctionScale = 0.28f) + { + lock (_atmoLock) + { + _sunDir = sunDir.LengthSquared() > 1e-5f ? sunDir.Normalized() : Vector3.Up; + _sunEnergy = MathF.Max(0.05f, sunEnergy); + _sunColor = sunColor; + _ambientColor = ambientColor; + _globalExtinctionScale = Math.Clamp(extinctionScale, 0.05f, 2.0f); + } + } + + public override void _RenderCallback(int effectCallbackType, RenderData renderData) + { + if (effectCallbackType != (int)EffectCallbackTypeEnum.PostSky || _rdFailed) + { + return; + } + + RenderingDevice? rd = RenderingServer.GetRenderingDevice(); + if (rd is null) + { + return; + } + + if (!_rdInitialized && !TryInitializeRd(rd)) + { + _rdFailed = true; + return; + } + + if (renderData.GetRenderSceneBuffers() is not RenderSceneBuffersRD sceneBuffers) + { + return; + } + + RenderSceneData sceneData = renderData.GetRenderSceneData(); + if (sceneData is null) + { + return; + } + + Vector2I fullSize = sceneBuffers.GetInternalSize(); + if (fullSize.X < 2 || fullSize.Y < 2) + { + return; + } + + VfxResolutionScale resScale; + VolumetricSamples volSamples; + Vector3 sunDir; + float sunEnergy; + Color sunCol, ambCol; + float extScale; + lock (_atmoLock) + { + resScale = _resolutionScale; + volSamples = _volumetricSamples; + sunDir = _sunDir; + sunEnergy = _sunEnergy; + sunCol = _sunColor; + ambCol = _ambientColor; + extScale = _globalExtinctionScale; + } + + bool isFullRes = resScale == VfxResolutionScale.Full; + float resFactor = GraphicsSettings.GetResolutionScaleFactor(resScale); + Vector2I marchSize = isFullRes + ? fullSize + : new Vector2I( + Math.Max(1, (int)MathF.Round(fullSize.X * resFactor)), + Math.Max(1, (int)MathF.Round(fullSize.Y * resFactor))); + int tilesX = Math.Max(1, (marchSize.X + TileSizeHalfRes - 1) / TileSizeHalfRes); + int tilesY = Math.Max(1, (marchSize.Y + TileSizeHalfRes - 1) / TileSizeHalfRes); + int totalTiles = tilesX * tilesY; + (int maxSteps, int maxIter) = GraphicsSettings.GetVolumetricStepBudget(volSamples); + + LastMarchSize = marchSize; + CurrentMaxSteps = maxSteps; + CurrentMaxIter = maxIter; + + EnsureHalfResAndTileBuffers(rd, marchSize, totalTiles); + + uint viewCount = Math.Max(1u, sceneData.GetViewCount()); + const uint view = 0u; + + Transform3D camXf = sceneData.GetCamTransform(); + Projection rawProj = sceneData.GetViewProjection(view); + + // Validate reverse-Z projection convention [1..0] + Vector4 testNear = rawProj * new Vector4(0f, 0f, -0.05f, 1f); + Projection revProj = (testNear.W != 0f && (testNear.Z / testNear.W) < 0f) + ? Projection.CreateDepthCorrection(flipY: false) * rawProj + : rawProj; + Projection invProj = revProj.Inverse(); + + Vector4 nearView = invProj * new Vector4(0f, 0f, 1f, 1f); + Vector4 farView = invProj * new Vector4(0f, 0f, 0f, 1f); + float zNear = MathF.Max(0.01f, MathF.Abs(nearView.W) > 1e-6f ? -nearView.Z / nearView.W : 0.05f); + float zFar = MathF.Abs(farView.W) > 1e-6f && (-farView.Z / farView.W) > zNear + 1f + ? -farView.Z / farView.W + : 4800f; + + float tanHalfFovY = 1f / MathF.Max(1e-4f, MathF.Abs(rawProj.Y.Y)); + float aspect = MathF.Abs(rawProj.Y.Y) / MathF.Max(1e-4f, MathF.Abs(rawProj.X.X)); + + Vector3 camPos = camXf.Origin; + Vector3 camRight = camXf.Basis.X.Normalized(); + Vector3 camUp = camXf.Basis.Y.Normalized(); + Vector3 camFwd = (-camXf.Basis.Z).Normalized(); + + _emitterPool.CopyRenderSnapshot( + _emitterUploadBytes, + _impulseUploadBytes, + out int emitterCount, + out int impulseCount, + out float elapsedTime, + out float dt); + + Vector3I newVoxelOrigin = new( + (int)MathF.Floor((camPos.X - 96f) / FlowVoxelSizeMeters), + (int)MathF.Floor((camPos.Y - 24f) / FlowVoxelSizeMeters), + (int)MathF.Floor((camPos.Z - 96f) / FlowVoxelSizeMeters)); + Vector3I flowDelta = _hasPrevFlowOrigin ? (newVoxelOrigin - _prevFlowVoxelOrigin) : Vector3I.Zero; + _prevFlowVoxelOrigin = newVoxelOrigin; + _hasPrevFlowOrigin = true; + + Vector3 flowOriginWorld = new( + newVoxelOrigin.X * FlowVoxelSizeMeters, + newVoxelOrigin.Y * FlowVoxelSizeMeters, + newVoxelOrigin.Z * FlowVoxelSizeMeters); + Vector3 flowInvExtent = new( + 1f / (FlowDimX * FlowVoxelSizeMeters), + 1f / (FlowDimY * FlowVoxelSizeMeters), + 1f / (FlowDimZ * FlowVoxelSizeMeters)); + + _frameCounter++; + var ubo = new VolumetricFrameUbo + { + InvProj0 = invProj.X, + InvProj1 = invProj.Y, + InvProj2 = invProj.Z, + InvProj3 = invProj.W, + CamPosTime = new Vector4(camPos.X, camPos.Y, camPos.Z, elapsedTime), + CamRightAspect = new Vector4(camRight.X, camRight.Y, camRight.Z, aspect), + CamUpTanHalfFov = new Vector4(camUp.X, camUp.Y, camUp.Z, tanHalfFovY), + CamFwdNearFar = new Vector4(camFwd.X, camFwd.Y, camFwd.Z, 0f), + SunDirIntensity = new Vector4(sunDir.X, sunDir.Y, sunDir.Z, sunEnergy), + SunColorExt = new Vector4(sunCol.R, sunCol.G, sunCol.B, extScale), + AmbientColorFog = new Vector4(ambCol.R, ambCol.G, ambCol.B, zNear), + ViewportInfo = new Vector4(fullSize.X, fullSize.Y, zFar, emitterCount), + HalfW = (uint)marchSize.X, + HalfH = (uint)marchSize.Y, + TilesX = (uint)tilesX, + FrameIndex = _frameCounter, + FlowOriginVoxel = new Vector4(flowOriginWorld.X, flowOriginWorld.Y, flowOriginWorld.Z, FlowVoxelSizeMeters), + FlowInvExtentDt = new Vector4(flowInvExtent.X, flowInvExtent.Y, flowInvExtent.Z, dt), + DeltaX = flowDelta.X, + DeltaY = flowDelta.Y, + DeltaZ = flowDelta.Z, + ImpulseCount = impulseCount, + MaxSteps = (uint)maxSteps, + MaxIter = (uint)maxIter, + IsFullRes = isFullRes ? 1u : 0u, + QualityPad = 0u + }; + + MemoryMarshal.Write(_uboBytes, in ubo); + rd.BufferUpdate(_frameUboRid, 0, FrameUboBytes, _uboBytes); + + if (emitterCount > 0) + { + uint emBytes = (uint)(emitterCount * VolumetricEmitterPool.EmitterStrideBytes); + rd.BufferUpdate(_emitterSsboRid, 0, emBytes, _emitterUploadBytes); + } + if (impulseCount > 0) + { + uint impBytes = (uint)(impulseCount * VolumetricEmitterPool.ImpulseStrideBytes); + rd.BufferUpdate(_impulseSsboRid, 0, impBytes, _impulseUploadBytes); + } + + int writeIdx = 1 - _flowReadIdx; + Rid prevFlowRid = _flowTexRids[_flowReadIdx]; + Rid nextFlowRid = _flowTexRids[writeIdx]; + + bool captureThisFrame = ProfilingEnabled && (_frameCounter & 7u) == 0u && _frameCounter >= 24u && rd.GetCapturedTimestampsCount() < 180; + if (ProfilingEnabled) + { + SamplePreviousFrameTimestamps(rd); + } + if (captureThisFrame) + { + rd.CaptureTimestamp("Cut10b_FlowStart"); + } + + // Compute pass list (Pass 0 always; Passes 1-3 whenever active emitters exist) + long computeList = rd.ComputeListBegin(); + + // Pass 0: flow_field_step (64x24x64 / 8x4x8 = 8x6x8 groups) + Rid flowSet = GetPass0UniformSet(prevFlowRid, nextFlowRid); + rd.ComputeListBindComputePipeline(computeList, _flowPipeRid); + rd.ComputeListBindUniformSet(computeList, flowSet, 0); + rd.ComputeListDispatch(computeList, 8, 6, 8); + + if (emitterCount > 0) + { + for (uint v = 0; v < viewCount; v++) + { + Rid colorLayer = sceneBuffers.GetColorLayer(v, false); + Rid depthLayer = sceneBuffers.GetDepthLayer(v, false); + if (!colorLayer.IsValid || !depthLayer.IsValid) + { + continue; + } + + // Pass 1: volumetric_tile_cull + rd.ComputeListAddBarrier(computeList); + if (captureThisFrame && v == 0) + { + rd.ComputeListEnd(); + rd.CaptureTimestamp("Cut10b_CullStart"); + computeList = rd.ComputeListBegin(); + } + + Rid cullSet = GetPass1UniformSet(depthLayer); + rd.ComputeListBindComputePipeline(computeList, _cullPipeRid); + rd.ComputeListBindUniformSet(computeList, cullSet, 0); + rd.ComputeListDispatch(computeList, (uint)tilesX, (uint)tilesY, 1); + + // Pass 2: volumetric_raymarch (reading freshly updated nextFlowRid!) + rd.ComputeListAddBarrier(computeList); + if (captureThisFrame && v == 0) + { + rd.ComputeListEnd(); + rd.CaptureTimestamp("Cut10b_MarchStart"); + computeList = rd.ComputeListBegin(); + } + + Rid marchSet = GetPass2UniformSet(depthLayer, nextFlowRid); + rd.ComputeListBindComputePipeline(computeList, _marchPipeRid); + rd.ComputeListBindUniformSet(computeList, marchSet, 0); + rd.ComputeListDispatch(computeList, (uint)tilesX, (uint)tilesY, 1); + + // Pass 3: volumetric_composite (2x2 bilateral depth upsample -> colorLayer) + rd.ComputeListAddBarrier(computeList); + if (captureThisFrame && v == 0) + { + rd.ComputeListEnd(); + rd.CaptureTimestamp("Cut10b_CompStart"); + computeList = rd.ComputeListBegin(); + } + + Rid compSet = GetPass3UniformSet(depthLayer, colorLayer); + rd.ComputeListBindComputePipeline(computeList, _compPipeRid); + rd.ComputeListBindUniformSet(computeList, compSet, 0); + uint compGroupsX = (uint)((fullSize.X + 15) / 16); + uint compGroupsY = (uint)((fullSize.Y + 15) / 16); + rd.ComputeListDispatch(computeList, compGroupsX, compGroupsY, 1); + } + } + + rd.ComputeListEnd(); + + if (captureThisFrame) + { + rd.CaptureTimestamp("Cut10b_End"); + } + + // Advance ping-pong & update global Texture3Drd + flow origin for GPUParticles3D + _flowReadIdx = writeIdx; + _flowTexRd.TextureRdRid = nextFlowRid; + RenderingServer.GlobalShaderParameterSet("rtd_flow_origin", flowOriginWorld); + RenderingServer.GlobalShaderParameterSet("rtd_flow_inv_extent", flowInvExtent); + } + + private void SamplePreviousFrameTimestamps(RenderingDevice rd) + { + uint count = rd.GetCapturedTimestampsCount(); + if (count == 0) + { + return; + } + + ulong tsFrame = rd.GetCapturedTimestampsFrame(); + if (tsFrame == _lastSampledTimestampFrame) + { + return; + } + _lastSampledTimestampFrame = tsFrame; + + ulong tFlow = 0, tCull = 0, tMarch = 0, tComp = 0, tEnd = 0; + for (uint i = 0; i < count; i++) + { + string name = rd.GetCapturedTimestampName(i); + switch (name) + { + case "Cut10b_FlowStart": tFlow = rd.GetCapturedTimestampGpuTime(i); break; + case "Cut10b_CullStart": tCull = rd.GetCapturedTimestampGpuTime(i); break; + case "Cut10b_MarchStart": tMarch = rd.GetCapturedTimestampGpuTime(i); break; + case "Cut10b_CompStart": tComp = rd.GetCapturedTimestampGpuTime(i); break; + case "Cut10b_End": tEnd = rd.GetCapturedTimestampGpuTime(i); break; + } + } + + // Godot 4.7 Vulkan GetCapturedTimestampGpuTime empirically returns nanoseconds (confirmed vs --gpu-profile; GodotSharp.xml's "microseconds" doc is stale) + if (tFlow > 0 && tEnd >= tFlow) + { + if (tCull > tFlow && tMarch > tCull && tComp > tMarch && tEnd >= tComp) + { + LastFlowGpuMs = (tCull - tFlow) / 1_000_000.0; + LastCullGpuMs = (tMarch - tCull) / 1_000_000.0; + LastMarchGpuMs = (tComp - tMarch) / 1_000_000.0; + LastCompGpuMs = (tEnd - tComp) / 1_000_000.0; + } + else + { + LastFlowGpuMs = (tEnd - tFlow) / 1_000_000.0; + LastCullGpuMs = 0.0; + LastMarchGpuMs = 0.0; + LastCompGpuMs = 0.0; + } + } + } + + private bool TryInitializeRd(RenderingDevice rd) + { + _rd = rd; + + if (!TryCompileCompute(rd, "res://flow_field_step.glsl", "flow_field_step", out _flowShaderRid, out _flowPipeRid) || + !TryCompileCompute(rd, "res://volumetric_tile_cull.glsl", "volumetric_tile_cull", out _cullShaderRid, out _cullPipeRid) || + !TryCompileCompute(rd, "res://volumetric_raymarch.glsl", "volumetric_raymarch", out _marchShaderRid, out _marchPipeRid) || + !TryCompileCompute(rd, "res://volumetric_composite.glsl", "volumetric_composite", out _compShaderRid, out _compPipeRid)) + { + return false; + } + + var nearestState = new RDSamplerState + { + MinFilter = RenderingDevice.SamplerFilter.Nearest, + MagFilter = RenderingDevice.SamplerFilter.Nearest, + RepeatU = RenderingDevice.SamplerRepeatMode.ClampToEdge, + RepeatV = RenderingDevice.SamplerRepeatMode.ClampToEdge, + RepeatW = RenderingDevice.SamplerRepeatMode.ClampToEdge + }; + _nearestSamplerRid = rd.SamplerCreate(nearestState); + + var linearState = new RDSamplerState + { + MinFilter = RenderingDevice.SamplerFilter.Linear, + MagFilter = RenderingDevice.SamplerFilter.Linear, + RepeatU = RenderingDevice.SamplerRepeatMode.ClampToEdge, + RepeatV = RenderingDevice.SamplerRepeatMode.ClampToEdge, + RepeatW = RenderingDevice.SamplerRepeatMode.ClampToEdge + }; + _linearSamplerRid = rd.SamplerCreate(linearState); + + var flowFmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type3D, + Format = RenderingDevice.DataFormat.R16G16B16A16Sfloat, + Width = FlowDimX, + Height = FlowDimY, + Depth = FlowDimZ, + Mipmaps = 1, + ArrayLayers = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | RenderingDevice.TextureUsageBits.StorageBit + }; + byte[] zero3d = new byte[FlowDimX * FlowDimY * FlowDimZ * 8]; + var initArr = new Godot.Collections.Array { zero3d }; + _flowTexRids[0] = rd.TextureCreate(flowFmt, new RDTextureView(), initArr); + _flowTexRids[1] = rd.TextureCreate(flowFmt, new RDTextureView(), initArr); + _flowReadIdx = 0; + _flowTexRd.TextureRdRid = _flowTexRids[0]; + + _frameUboRid = rd.UniformBufferCreate(FrameUboBytes, new byte[FrameUboBytes]); + _emitterSsboRid = rd.StorageBufferCreate( + (uint)(VolumetricEmitterPool.MaxEmitters * VolumetricEmitterPool.EmitterStrideBytes), + new byte[VolumetricEmitterPool.MaxEmitters * VolumetricEmitterPool.EmitterStrideBytes]); + _impulseSsboRid = rd.StorageBufferCreate( + (uint)(VolumetricEmitterPool.MaxFlowImpulses * VolumetricEmitterPool.ImpulseStrideBytes), + new byte[VolumetricEmitterPool.MaxFlowImpulses * VolumetricEmitterPool.ImpulseStrideBytes]); + + _rdInitialized = true; + return true; + } + + private static bool TryCompileCompute( + RenderingDevice rd, + string resPath, + string debugName, + out Rid shaderRid, + out Rid pipeRid) + { + shaderRid = new Rid(); + pipeRid = new Rid(); + + string source = FileAccess.GetFileAsString(resPath); + if (string.IsNullOrWhiteSpace(source)) + { + GD.PrintErr($"VolumetricCompositorEffect: missing compute shader '{resPath}'"); + return false; + } + + using var rdSrc = new RDShaderSource + { + Language = RenderingDevice.ShaderLanguage.Glsl, + SourceCompute = source + }; + using RDShaderSpirV spirv = rd.ShaderCompileSpirVFromSource(rdSrc, allowCache: true); + string err = spirv.CompileErrorCompute; + if (!string.IsNullOrEmpty(err)) + { + GD.PrintErr($"VolumetricCompositorEffect: SPIR-V compile error in '{resPath}': {err}"); + return false; + } + + shaderRid = rd.ShaderCreateFromSpirV(spirv, debugName); + if (!shaderRid.IsValid) + { + GD.PrintErr($"VolumetricCompositorEffect: ShaderCreateFromSpirV failed for '{resPath}'"); + return false; + } + pipeRid = rd.ComputePipelineCreate(shaderRid); + if (!pipeRid.IsValid) + { + GD.PrintErr($"VolumetricCompositorEffect: ComputePipelineCreate failed for '{resPath}'"); + return false; + } + return true; + } + + private void EnsureHalfResAndTileBuffers(RenderingDevice rd, Vector2I halfSize, int totalTiles) + { + if (!_halfVolRid.IsValid || _halfVolSize != halfSize) + { + if (_halfVolRid.IsValid) + { + rd.FreeRid(_halfVolRid); + } + var fmt = new RDTextureFormat + { + TextureType = RenderingDevice.TextureType.Type2D, + Format = RenderingDevice.DataFormat.R16G16B16A16Sfloat, + Width = (uint)halfSize.X, + Height = (uint)halfSize.Y, + Depth = 1, + Mipmaps = 1, + ArrayLayers = 1, + Samples = RenderingDevice.TextureSamples.Samples1, + UsageBits = RenderingDevice.TextureUsageBits.SamplingBit | RenderingDevice.TextureUsageBits.StorageBit + }; + _halfVolRid = rd.TextureCreate(fmt, new RDTextureView()); + _halfVolSize = halfSize; + } + + if (!_tileSsboRid.IsValid || _tileSsboCapacityTiles < totalTiles) + { + if (_tileSsboRid.IsValid) + { + rd.FreeRid(_tileSsboRid); + } + _tileSsboCapacityTiles = Math.Max(totalTiles, 2048); + uint sizeBytes = (uint)(_tileSsboCapacityTiles * TileStrideBytes); + _tileSsboRid = rd.StorageBufferCreate(sizeBytes, new byte[sizeBytes]); + } + } + + private Rid GetPass0UniformSet(Rid prevFlowRid, Rid nextFlowRid) + { + var u0 = new RDUniform { UniformType = RenderingDevice.UniformType.UniformBuffer, Binding = 0 }; + u0.AddId(_frameUboRid); + var u1 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 1 }; + u1.AddId(_impulseSsboRid); + var u2 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 2 }; + u2.AddId(_linearSamplerRid); + u2.AddId(prevFlowRid); + var u3 = new RDUniform { UniformType = RenderingDevice.UniformType.Image, Binding = 3 }; + u3.AddId(nextFlowRid); + return UniformSetCacheRD.GetCache(_flowShaderRid, 0, new Godot.Collections.Array { u0, u1, u2, u3 }); + } + + private Rid GetPass1UniformSet(Rid depthLayer) + { + var u0 = new RDUniform { UniformType = RenderingDevice.UniformType.UniformBuffer, Binding = 0 }; + u0.AddId(_frameUboRid); + var u1 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 1 }; + u1.AddId(_emitterSsboRid); + var u2 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 2 }; + u2.AddId(_tileSsboRid); + var u3 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 3 }; + u3.AddId(_nearestSamplerRid); + u3.AddId(depthLayer); + return UniformSetCacheRD.GetCache(_cullShaderRid, 0, new Godot.Collections.Array { u0, u1, u2, u3 }); + } + + private Rid GetPass2UniformSet(Rid depthLayer, Rid flowTexRid) + { + var u0 = new RDUniform { UniformType = RenderingDevice.UniformType.UniformBuffer, Binding = 0 }; + u0.AddId(_frameUboRid); + var u1 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 1 }; + u1.AddId(_emitterSsboRid); + var u2 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 2 }; + u2.AddId(_tileSsboRid); + var u3 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 3 }; + u3.AddId(_nearestSamplerRid); + u3.AddId(depthLayer); + var u4 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 4 }; + u4.AddId(_linearSamplerRid); + u4.AddId(flowTexRid); + var u5 = new RDUniform { UniformType = RenderingDevice.UniformType.Image, Binding = 5 }; + u5.AddId(_halfVolRid); + return UniformSetCacheRD.GetCache(_marchShaderRid, 0, new Godot.Collections.Array { u0, u1, u2, u3, u4, u5 }); + } + + private Rid GetPass3UniformSet(Rid depthLayer, Rid colorLayer) + { + var u0 = new RDUniform { UniformType = RenderingDevice.UniformType.UniformBuffer, Binding = 0 }; + u0.AddId(_frameUboRid); + var u1 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 1 }; + u1.AddId(_nearestSamplerRid); + u1.AddId(depthLayer); + var u2 = new RDUniform { UniformType = RenderingDevice.UniformType.SamplerWithTexture, Binding = 2 }; + u2.AddId(_nearestSamplerRid); + u2.AddId(_halfVolRid); + var u3 = new RDUniform { UniformType = RenderingDevice.UniformType.Image, Binding = 3 }; + u3.AddId(colorLayer); + var u4 = new RDUniform { UniformType = RenderingDevice.UniformType.StorageBuffer, Binding = 4 }; + u4.AddId(_tileSsboRid); + return UniformSetCacheRD.GetCache(_compShaderRid, 0, new Godot.Collections.Array { u0, u1, u2, u3, u4 }); + } + + public void DisposeRdResources() + { + if (!_rdInitialized || _rd is null) + { + return; + } + _rdInitialized = false; + Enabled = false; + + if (_flowTexRd is not null) + { + _flowTexRd.TextureRdRid = new Rid(); + } + + FreeIfValid(_rd, ref _flowTexRids[0]); + FreeIfValid(_rd, ref _flowTexRids[1]); + FreeIfValid(_rd, ref _halfVolRid); + FreeIfValid(_rd, ref _frameUboRid); + FreeIfValid(_rd, ref _emitterSsboRid); + FreeIfValid(_rd, ref _impulseSsboRid); + FreeIfValid(_rd, ref _tileSsboRid); + FreeIfValid(_rd, ref _nearestSamplerRid); + FreeIfValid(_rd, ref _linearSamplerRid); + + // Free shaders (automatically cleans up dependent pipelines in Godot RD) + _flowPipeRid = new Rid(); + _cullPipeRid = new Rid(); + _marchPipeRid = new Rid(); + _compPipeRid = new Rid(); + FreeIfValid(_rd, ref _flowShaderRid); + FreeIfValid(_rd, ref _cullShaderRid); + FreeIfValid(_rd, ref _marchShaderRid); + FreeIfValid(_rd, ref _compShaderRid); + + _rd = null; + } + + public override void _Notification(int what) + { + if (what != NotificationPredelete) + { + return; + } + + // Only release if still alive and not already cleaned up in AtmosphereSystem._ExitTree + if (_flowTexRd is not null) + { + _flowTexRd.TextureRdRid = new Rid(); + } + if (_rdInitialized && RenderingServer.GetRenderingDevice() is not null) + { + DisposeRdResources(); + } + } + + private static void FreeIfValid(RenderingDevice rd, ref Rid rid) + { + if (rid.IsValid) + { + rd.FreeRid(rid); + rid = new Rid(); + } + } +} diff --git a/client/VolumetricEmitterPool.cs b/client/VolumetricEmitterPool.cs new file mode 100644 index 0000000..b6d567b --- /dev/null +++ b/client/VolumetricEmitterPool.cs @@ -0,0 +1,1027 @@ +using System; +using System.Runtime.InteropServices; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// CPU authority for all volumetric smoke, fire, retro-plume, plasma, and thermal-pool emitters +/// (<= 128) plus 3D flow-field impulses (<= 64) consumed by . +/// Packs std430-aligned snapshots under a short lock for zero-allocation GPU upload. +/// +public sealed class VolumetricEmitterPool +{ + public const int MaxEmitters = 128; + public const int MaxFlowImpulses = 64; + public const int EmitterStrideBytes = 64; + public const int ImpulseStrideBytes = 48; + + public const uint EmitterSmoke = 0u; + public const uint EmitterFireball = 1u; + public const uint EmitterRetroPlume = 2u; + public const uint EmitterPlasmaBurst = 3u; + public const uint EmitterThermalPool = 4u; + + public const uint FlowShockShell = 0u; + public const uint FlowRetroDownwash = 1u; + public const uint FlowThermalUpdraft = 2u; + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + public struct GpuVolumetricEmitter + { + public float Ax, Ay, Az, RadiusA; + public float Bx, By, Bz, Temp; + public float DensityMult, RadiusB, FlowSpeed, PackedFlags; + public float R, G, B, Softness; + } + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + public struct GpuFlowImpulse + { + public float PosX, PosY, PosZ, Radius; + public float DirX, DirY, DirZ, Strength; + public float ShellThickness, ShockPressure, TypeBitsFloat, FalloffExp; + } + + private struct EmitterSlot + { + public bool Active; + public uint Type; + public int Priority; + public byte Seed; + public Vector3 StartPos; + public Vector3 EndPos; + public Vector3 VelStart; + public Vector3 VelEnd; + public float Drag; + public float Buoyancy; + public float RadiusA0; + public float RadiusA1; + public float RadiusB0; + public float RadiusB1; + public float Density0; + public float Density1; + public float Temp0; + public float Temp1; + public float FlowSpeed; + public float Softness; + public Color Tint0; + public Color Tint1; + public float Age; + public float Lifetime; + } + + private struct ImpulseSlot + { + public bool Active; + public uint Type; + public int Priority; + public Vector3 Pos; + public Vector3 Dir; + public float Radius0; + public float Radius1; + public float Strength0; + public float Strength1; + public float ShellThickness; + public float ShockPressure0; + public float ShockPressure1; + public float FalloffExp; + public float Age; + public float Lifetime; + } + + private readonly EmitterSlot[] _emitters = new EmitterSlot[MaxEmitters]; + private readonly ImpulseSlot[] _impulses = new ImpulseSlot[MaxFlowImpulses]; + + private readonly object _sync = new(); + private readonly byte[] _emitterBytes = new byte[MaxEmitters * EmitterStrideBytes]; + private readonly byte[] _impulseBytes = new byte[MaxFlowImpulses * ImpulseStrideBytes]; + private int _packedEmitterCount; + private int _packedImpulseCount; + private float _elapsedTime; + private float _lastStepDt = 1f / 60f; + private uint _rng = 0x51F29D4Bu; + private byte _seedSeq; + + public int ActiveEmitterCount { get; private set; } + public int ActiveImpulseCount { get; private set; } + + public void ClearAll() + { + Array.Clear(_emitters, 0, _emitters.Length); + Array.Clear(_impulses, 0, _impulses.Length); + ActiveEmitterCount = 0; + ActiveImpulseCount = 0; + lock (_sync) + { + _packedEmitterCount = 0; + _packedImpulseCount = 0; + Array.Clear(_emitterBytes, 0, _emitterBytes.Length); + Array.Clear(_impulseBytes, 0, _impulseBytes.Length); + } + } + + public void Step(float dt) + { + float stepDt = float.IsFinite(dt) && dt > 0f ? Math.Clamp(dt, 0f, 0.05f) : 0f; + _elapsedTime += stepDt; + + Span gpuEmitters = stackalloc GpuVolumetricEmitter[MaxEmitters]; + int emCount = 0; + for (int i = 0; i < MaxEmitters; i++) + { + ref EmitterSlot s = ref _emitters[i]; + if (!s.Active) + { + continue; + } + if (stepDt > 0f) + { + s.Age += stepDt; + if (s.Age >= s.Lifetime) + { + s.Active = false; + continue; + } + if (s.Drag > 0f) + { + float damp = MathF.Exp(-s.Drag * stepDt); + s.VelStart *= damp; + s.VelEnd *= damp; + } + s.VelStart.Y += s.Buoyancy * stepDt; + s.VelEnd.Y += s.Buoyancy * stepDt; + s.StartPos += s.VelStart * stepDt; + s.EndPos += s.VelEnd * stepDt; + } + + float t = Math.Clamp(s.Age / MathF.Max(0.01f, s.Lifetime), 0f, 1f); + float density = Mathf.Lerp(s.Density0, s.Density1, t); + // Smooth fade-out tail in last 25% of lifetime + if (t > 0.75f) + { + density *= 1f - (t - 0.75f) / 0.25f; + } + if (density <= 0.002f) + { + continue; + } + + float rA = MathF.Max(0.25f, Mathf.Lerp(s.RadiusA0, s.RadiusA1, t)); + float rB = MathF.Max(0.25f, Mathf.Lerp(s.RadiusB0, s.RadiusB1, t)); + float tempT = MathF.Pow(t, 1.45f); + float temp = MathF.Max(0f, Mathf.Lerp(s.Temp0, s.Temp1, tempT)); + Color tint = s.Tint0.Lerp(s.Tint1, t); + + uint ageByte = (uint)Math.Clamp((int)(t * 255f), 0, 255); + uint packedFlags = (s.Type & 0xFu) | (ageByte << 4) | ((uint)s.Seed << 12); + + gpuEmitters[emCount++] = new GpuVolumetricEmitter + { + Ax = s.StartPos.X, + Ay = s.StartPos.Y, + Az = s.StartPos.Z, + RadiusA = rA, + Bx = s.EndPos.X, + By = s.EndPos.Y, + Bz = s.EndPos.Z, + Temp = temp, + DensityMult = density, + RadiusB = rB, + FlowSpeed = s.FlowSpeed, + PackedFlags = BitConverter.UInt32BitsToSingle(packedFlags), + R = MathF.Max(0f, tint.R), + G = MathF.Max(0f, tint.G), + B = MathF.Max(0f, tint.B), + Softness = s.Softness + }; + } + + Span gpuImpulses = stackalloc GpuFlowImpulse[MaxFlowImpulses]; + int impCount = 0; + for (int i = 0; i < MaxFlowImpulses; i++) + { + ref ImpulseSlot s = ref _impulses[i]; + if (!s.Active) + { + continue; + } + if (stepDt > 0f) + { + s.Age += stepDt; + if (s.Age >= s.Lifetime) + { + s.Active = false; + continue; + } + } + + float t = Math.Clamp(s.Age / MathF.Max(0.01f, s.Lifetime), 0f, 1f); + float radius = MathF.Max(0.5f, Mathf.Lerp(s.Radius0, s.Radius1, t)); + float strength = Mathf.Lerp(s.Strength0, s.Strength1, t); + float pressure = MathF.Max(0f, Mathf.Lerp(s.ShockPressure0, s.ShockPressure1, t)); + + gpuImpulses[impCount++] = new GpuFlowImpulse + { + PosX = s.Pos.X, + PosY = s.Pos.Y, + PosZ = s.Pos.Z, + Radius = radius, + DirX = s.Dir.X, + DirY = s.Dir.Y, + DirZ = s.Dir.Z, + Strength = strength, + ShellThickness = s.ShellThickness, + ShockPressure = pressure, + TypeBitsFloat = BitConverter.UInt32BitsToSingle(s.Type), + FalloffExp = s.FalloffExp + }; + } + + ActiveEmitterCount = emCount; + ActiveImpulseCount = impCount; + + lock (_sync) + { + _packedEmitterCount = emCount; + _packedImpulseCount = impCount; + if (stepDt > 0f) + { + _lastStepDt = stepDt; + } + if (emCount > 0) + { + MemoryMarshal.AsBytes(gpuEmitters.Slice(0, emCount)).CopyTo(_emitterBytes); + } + if (impCount > 0) + { + MemoryMarshal.AsBytes(gpuImpulses.Slice(0, impCount)).CopyTo(_impulseBytes); + } + } + } + + public void CopyRenderSnapshot( + byte[] dstEmitters, + byte[] dstImpulses, + out int emitterCount, + out int impulseCount, + out float elapsedTime, + out float dt) + { + lock (_sync) + { + emitterCount = _packedEmitterCount; + impulseCount = _packedImpulseCount; + elapsedTime = _elapsedTime; + dt = _lastStepDt; + if (emitterCount > 0) + { + Buffer.BlockCopy(_emitterBytes, 0, dstEmitters, 0, emitterCount * EmitterStrideBytes); + } + if (impulseCount > 0) + { + Buffer.BlockCopy(_impulseBytes, 0, dstImpulses, 0, impulseCount * ImpulseStrideBytes); + } + } + } + + public void SpawnEmitter( + uint type, + Vector3 startPos, + Vector3 endPos, + Vector3 velStart, + Vector3 velEnd, + float radiusA0, + float radiusA1, + float radiusB0, + float radiusB1, + float density0, + float density1, + float temp0, + float temp1, + Color tint0, + Color tint1, + float lifetime, + float flowSpeed = 0.55f, + float softness = 0.36f, + float drag = 1.2f, + float buoyancy = 0.45f, + int priority = 5) + { + int slot = FindOrEvictEmitterSlot(priority); + if (slot < 0) + { + return; + } + _emitters[slot] = new EmitterSlot + { + Active = true, + Type = type, + Priority = priority, + Seed = _seedSeq++, + StartPos = startPos, + EndPos = endPos, + VelStart = velStart, + VelEnd = velEnd, + Drag = drag, + Buoyancy = buoyancy, + RadiusA0 = radiusA0, + RadiusA1 = radiusA1, + RadiusB0 = radiusB0, + RadiusB1 = radiusB1, + Density0 = density0, + Density1 = density1, + Temp0 = temp0, + Temp1 = temp1, + FlowSpeed = flowSpeed, + Softness = softness, + Tint0 = tint0, + Tint1 = tint1, + Age = 0f, + Lifetime = MathF.Max(0.05f, lifetime) + }; + ActiveEmitterCount = CountActiveEmitters(); + } + + public void SpawnFlowImpulse( + uint type, + Vector3 pos, + Vector3 dir, + float radius0, + float radius1, + float strength0, + float strength1, + float shellThickness, + float shockPressure0, + float shockPressure1, + float lifetime, + float falloffExp = 1.6f, + int priority = 5) + { + int slot = FindOrEvictImpulseSlot(priority); + if (slot < 0) + { + return; + } + _impulses[slot] = new ImpulseSlot + { + Active = true, + Type = type, + Priority = priority, + Pos = pos, + Dir = dir.LengthSquared() > 1e-5f ? dir.Normalized() : Vector3.Up, + Radius0 = radius0, + Radius1 = radius1, + Strength0 = strength0, + Strength1 = strength1, + ShellThickness = shellThickness, + ShockPressure0 = shockPressure0, + ShockPressure1 = shockPressure1, + FalloffExp = falloffExp, + Age = 0f, + Lifetime = MathF.Max(0.04f, lifetime) + }; + ActiveImpulseCount = CountActiveImpulses(); + } + + public void EmitChassisExplosion(Vector3 pos, float massKg, Color groundTint) + { + Color gLin = groundTint.SrgbToLinear(); + float scale = Math.Clamp(massKg / 2800f, 0.85f, 1.55f); + // Primary fireball -> rising billowing soot capsule (3.5s) + SpawnEmitter( + EmitterFireball, + startPos: pos + new Vector3(0f, 0.4f, 0f), + endPos: pos + new Vector3(NextSigned() * 0.4f, 2.2f * scale, NextSigned() * 0.4f), + velStart: new Vector3(NextSigned() * 0.6f, 1.4f, NextSigned() * 0.6f), + velEnd: new Vector3(NextSigned() * 0.9f, 3.8f * scale, NextSigned() * 0.9f), + radiusA0: 1.8f * scale, + radiusA1: 5.2f * scale, + radiusB0: 2.2f * scale, + radiusB1: 6.4f * scale, + density0: 2.35f, + density1: 0.80f, + temp0: 1.95f, + temp1: 0.10f, + tint0: new Color(0.10f, 0.08f, 0.07f), + tint1: new Color(0.05f, 0.048f, 0.048f), + lifetime: 3.4f, + flowSpeed: 0.85f, + softness: 0.42f, + drag: 0.95f, + buoyancy: 0.90f, + priority: 10); + + // Low ground dust skirt pushed outward by blast + SpawnEmitter( + EmitterSmoke, + startPos: pos - new Vector3(1.5f, 0.1f, 0f), + endPos: pos + new Vector3(1.5f, 0.2f, 0f), + velStart: Vector3.Up * 0.5f, + velEnd: Vector3.Up * 1.1f, + radiusA0: 2.4f * scale, + radiusA1: 6.8f * scale, + radiusB0: 2.4f * scale, + radiusB1: 6.8f * scale, + density0: 0.80f, + density1: 0.10f, + temp0: 0.30f, + temp1: 0f, + tint0: gLin * 0.85f, + tint1: gLin * 0.50f, + lifetime: 2.2f, + flowSpeed: 0.65f, + softness: 0.48f, + drag: 1.4f, + buoyancy: 0.25f, + priority: 9); + + // Expanding radial ShockShell (~90 m/s) + buoyant ThermalUpdraft column + SpawnFlowImpulse( + FlowShockShell, + pos, + Vector3.Up, + radius0: 1.6f * scale, + radius1: 24.0f * scale, + strength0: 90f, + strength1: 14f, + shellThickness: 3.4f, + shockPressure0: 1.4f, + shockPressure1: 0.0f, + lifetime: 0.40f, + priority: 10); + + SpawnFlowImpulse( + FlowThermalUpdraft, + pos, + Vector3.Up, + radius0: 5.5f * scale, + radius1: 8.5f * scale, + strength0: 13.5f, + strength1: 3.5f, + shellThickness: 0f, + shockPressure0: 0f, + shockPressure1: 0f, + lifetime: 3.2f, + priority: 9); + } + + public void EmitExplosiveHit(Vector3 pos, Vector3 normal, Color groundTint, WeaponVisualClass wClass, bool isRecoilless, bool isAirburst) + { + bool isPlasma = wClass == WeaponVisualClass.PlasmaPpc; + bool isSwarm = wClass == WeaponVisualClass.SwarmSmart; + bool isThermal = wClass == WeaponVisualClass.ThermalBeam; + float scale = isRecoilless || wClass == WeaponVisualClass.RocketSalvo + ? 1.35f + : (isAirburst ? 1.15f : (isThermal ? 0.58f : 0.90f)); + + uint type = (isPlasma || isSwarm || isThermal) ? EmitterPlasmaBurst : EmitterFireball; + Color gLin = groundTint.SrgbToLinear(); + Color tint0 = isPlasma + ? new Color(0.10f, 0.52f, 0.72f) + : isSwarm + ? new Color(0.24f, 0.62f, 0.14f) + : isThermal + ? new Color(0.12f, 0.22f, 0.28f) + : gLin * 0.30f + new Color(0.05f, 0.045f, 0.04f); + Color tint1 = new(0.05f, 0.048f, 0.045f); + + float temp0 = (isPlasma || isThermal) ? 1.65f : (isAirburst || isRecoilless || wClass == WeaponVisualClass.RocketSalvo ? 2.10f : 1.70f); + float life = (isRecoilless || wClass == WeaponVisualClass.RocketSalvo) ? 1.55f : (isThermal ? 0.50f : 0.95f); + + SpawnEmitter( + type, + startPos: pos + normal * 0.25f, + endPos: pos + normal * (1.2f * scale) + Vector3.Up * (0.9f * scale), + velStart: normal * 1.4f, + velEnd: normal * 2.4f + Vector3.Up * 1.8f, + radiusA0: 0.9f * scale, + radiusA1: 2.8f * scale, + radiusB0: 1.1f * scale, + radiusB1: 3.4f * scale, + density0: 1.85f, + density1: 0.26f, + temp0: temp0, + temp1: 0.0f, + tint0: tint0, + tint1: tint1, + lifetime: life, + flowSpeed: 0.75f, + softness: 0.42f, + drag: 1.4f, + buoyancy: 0.65f, + priority: isRecoilless ? 8 : 6); + + if (isRecoilless || wClass is WeaponVisualClass.RocketSalvo or WeaponVisualClass.PlasmaPpc or WeaponVisualClass.Explosive) + { + SpawnFlowImpulse( + FlowShockShell, + pos, + normal, + radius0: 0.8f, + radius1: 11.0f * scale, + strength0: 54f * scale, + strength1: 8f, + shellThickness: 2.4f, + shockPressure0: 1.05f, + shockPressure1: 0.0f, + lifetime: 0.26f, + priority: 7); + } + } + + public void EmitMuzzleBreechPuff(Vector3 start, Vector3 end, Color groundTint, WeaponVisualClass wClass, bool isRecoilless) + { + Vector3 dir = (end - start).LengthSquared() > 1e-4f ? (end - start).Normalized() : Vector3.Forward; + float scale = isRecoilless ? 1.25f : 0.85f; + Color gLin = groundTint.SrgbToLinear(); + Color smokeTint = new( + Mathf.Lerp(0.24f, gLin.R, 0.35f), + Mathf.Lerp(0.22f, gLin.G, 0.35f), + Mathf.Lerp(0.20f, gLin.B, 0.35f)); + + SpawnEmitter( + EmitterSmoke, + startPos: start + dir * 0.2f, + endPos: start + dir * (2.6f * scale), + velStart: dir * 2.8f + Vector3.Up * 0.8f, + velEnd: dir * 4.2f + Vector3.Up * 1.4f, + radiusA0: 0.48f * scale, + radiusA1: 1.55f * scale, + radiusB0: 0.75f * scale, + radiusB1: 2.15f * scale, + density0: 1.35f, + density1: 0.18f, + temp0: isRecoilless ? 0.65f : 0.35f, + temp1: 0f, + tint0: smokeTint, + tint1: smokeTint * 0.75f, + lifetime: isRecoilless ? 0.82f : 0.50f, + flowSpeed: 0.6f, + softness: 0.44f, + drag: 2.2f, + buoyancy: 0.55f, + priority: 6); + + if (isRecoilless || wClass == WeaponVisualClass.RocketSalvo) + { + // Backblast / recoil puff & impulse + SpawnFlowImpulse( + FlowShockShell, + start, + dir, + radius0: 0.6f, + radius1: 6.5f * scale, + strength0: 28f, + strength1: 4f, + shellThickness: 1.8f, + shockPressure0: 0.55f, + shockPressure1: 0f, + lifetime: 0.18f, + priority: 5); + } + } + + public void EmitOrdnanceDetonation(Vector3 pos, Color accentCol, float splashRadius) + { + float scale = Math.Clamp(splashRadius / 4.2f, 0.75f, 1.85f); + SpawnEmitter( + EmitterFireball, + startPos: pos, + endPos: pos + Vector3.Up * (1.8f * scale), + velStart: Vector3.Up * 1.4f, + velEnd: Vector3.Up * 3.2f, + radiusA0: 1.2f * scale, + radiusA1: 3.8f * scale, + radiusB0: 1.4f * scale, + radiusB1: 4.5f * scale, + density0: 2.15f, + density1: 0.42f, + temp0: 2.05f, + temp1: 0.10f, + tint0: accentCol * 0.32f + new Color(0.07f, 0.06f, 0.055f), + tint1: new Color(0.055f, 0.05f, 0.048f), + lifetime: 2.1f, + flowSpeed: 0.8f, + softness: 0.40f, + drag: 1.1f, + buoyancy: 0.85f, + priority: 9); + + SpawnFlowImpulse( + FlowShockShell, + pos, + Vector3.Up, + radius0: 1.0f, + radius1: Math.Clamp(splashRadius * 3.2f, 9f, 24f), + strength0: 76f, + strength1: 12f, + shellThickness: 2.8f, + shockPressure0: 1.25f, + shockPressure1: 0f, + lifetime: 0.34f, + priority: 9); + + SpawnFlowImpulse( + FlowThermalUpdraft, + pos, + Vector3.Up, + radius0: 3.5f * scale, + radius1: 6.0f * scale, + strength0: 9.5f, + strength1: 2.5f, + shellThickness: 0f, + shockPressure0: 0f, + shockPressure1: 0f, + lifetime: 2.2f, + priority: 7); + } + + public void EmitOrdnanceTrailCapsule(Vector3 tailPos, Vector3 pos, Vector3 vel, Color accentCol, bool isRocket) + { + if (ActiveEmitterCount >= 112) + { + return; + } + Vector3 back = vel.LengthSquared() > 1f ? -vel.Normalized() : Vector3.Up; + Vector3 segStart = pos; + Vector3 segEnd = pos.DistanceSquaredTo(tailPos) > 0.25f ? tailPos : pos + back * 2.2f; + SpawnEmitter( + isRocket ? EmitterFireball : EmitterSmoke, + startPos: segStart, + endPos: segEnd, + velStart: back * 1.4f + Vector3.Up * 0.5f, + velEnd: back * 0.8f + Vector3.Up * 1.1f, + radiusA0: isRocket ? 0.55f : 0.38f, + radiusA1: isRocket ? 1.85f : 1.15f, + radiusB0: isRocket ? 0.72f : 0.48f, + radiusB1: isRocket ? 2.25f : 1.35f, + density0: isRocket ? 0.92f : 0.58f, + density1: 0.06f, + temp0: isRocket ? 0.75f : 0.10f, + temp1: 0f, + tint0: isRocket ? new Color(0.62f, 0.56f, 0.50f) : accentCol * 0.65f, + tint1: new Color(0.32f, 0.30f, 0.28f), + lifetime: isRocket ? 0.95f : 0.55f, + flowSpeed: 0.65f, + softness: 0.46f, + drag: 1.6f, + buoyancy: 0.45f, + priority: 4); + } + + public void EmitThermalPoolPlume(Vector3 pos, float radius, Color accentCol) + { + if (ActiveEmitterCount >= 116) + { + return; + } + float r = Math.Clamp(radius * 0.55f, 1.4f, 4.5f); + SpawnEmitter( + EmitterThermalPool, + startPos: pos + new Vector3(NextSigned() * r * 0.45f, 0.2f, NextSigned() * r * 0.45f), + endPos: pos + new Vector3(NextSigned() * r * 0.35f, 2.8f, NextSigned() * r * 0.35f), + velStart: Vector3.Up * 1.1f, + velEnd: Vector3.Up * 2.2f, + radiusA0: r * 0.55f, + radiusA1: r * 0.85f, + radiusB0: r * 0.40f, + radiusB1: r * 0.95f, + density0: 0.78f, + density1: 0.10f, + temp0: 0.85f, + temp1: 0.15f, + tint0: accentCol, + tint1: accentCol * 0.55f, + lifetime: 0.75f, + flowSpeed: 0.75f, + softness: 0.45f, + drag: 1.0f, + buoyancy: 0.85f, + priority: 5); + + SpawnFlowImpulse( + FlowThermalUpdraft, + pos, + Vector3.Up, + radius0: radius, + radius1: radius * 1.15f, + strength0: 7.5f, + strength1: 7.5f, + shellThickness: 0f, + shockPressure0: 0f, + shockPressure1: 0f, + lifetime: 0.45f, + priority: 4); + } + + public void EmitPodReentryPlume(Vector3 podPos, Vector3 podVel, float heatGlow, bool isContender) + { + float scale = isContender ? 1.25f : 0.85f; + Vector3 upTrail = podVel.LengthSquared() > 1f ? -podVel.Normalized() : Vector3.Up; + SpawnEmitter( + EmitterRetroPlume, + startPos: podPos + upTrail * 0.8f, + endPos: podPos + upTrail * (4.5f * scale), + velStart: upTrail * 2.5f, + velEnd: upTrail * 4.0f, + radiusA0: 0.75f * scale, + radiusA1: 1.85f * scale, + radiusB0: 1.15f * scale, + radiusB1: 2.65f * scale, + density0: 0.90f, + density1: 0.08f, + temp0: 0.72f + heatGlow * 0.45f, + temp1: 0.04f, + tint0: new Color(0.55f, 0.42f, 0.34f), + tint1: new Color(0.28f, 0.26f, 0.25f), + lifetime: 0.42f, + flowSpeed: 0.90f, + softness: 0.42f, + drag: 1.6f, + buoyancy: 0.4f, + priority: isContender ? 7 : 4); + } + + public void EmitPodRetroPlume(Vector3 podBasePos, float agl, Color groundTint, bool isContender) + { + float scale = isContender ? 1.25f : 0.88f; + float jetLen = MathF.Min(12f * scale, MathF.Max(3.5f, agl * 0.6f)); + SpawnEmitter( + EmitterRetroPlume, + startPos: podBasePos, + endPos: podBasePos - new Vector3(0f, jetLen, 0f), + velStart: new Vector3(0f, -8f, 0f), + velEnd: new Vector3(NextSigned() * 2.5f, -4f, NextSigned() * 2.5f), + radiusA0: 0.85f * scale, + radiusA1: 1.6f * scale, + radiusB0: 1.65f * scale, + radiusB1: 3.4f * scale, + density0: 1.85f, + density1: 0.24f, + temp0: 1.55f, + temp1: 0.14f, + tint0: new Color(0.60f, 0.48f, 0.38f), + tint1: groundTint * 0.72f, + lifetime: 0.26f, + flowSpeed: 1.1f, + softness: 0.40f, + drag: 1.8f, + buoyancy: 0.2f, + priority: isContender ? 9 : 6); + + if (agl < 65f) + { + float washT = Math.Clamp(1f - agl / 65f, 0.20f, 1f); + Vector3 groundPos = podBasePos - new Vector3(0f, MathF.Max(0f, agl), 0f) + new Vector3(0f, 0.6f, 0f); + SpawnEmitter( + EmitterSmoke, + startPos: groundPos + new Vector3(-1.8f * scale, 0f, 0f), + endPos: groundPos + new Vector3(1.8f * scale, 0.4f, 0f), + velStart: new Vector3(-3.5f * washT, 1.1f, NextSigned() * 2.2f), + velEnd: new Vector3(3.5f * washT, 1.3f, NextSigned() * 2.2f), + radiusA0: 1.6f * scale, + radiusA1: 4.8f * scale * washT + 1.4f, + radiusB0: 1.6f * scale, + radiusB1: 4.8f * scale * washT + 1.4f, + density0: 0.82f * washT, + density1: 0.08f, + temp0: 0.10f, + temp1: 0f, + tint0: groundTint, + tint1: groundTint * 0.78f, + lifetime: 0.72f, + flowSpeed: 0.85f, + softness: 0.48f, + drag: 1.6f, + buoyancy: 0.35f, + priority: isContender ? 8 : 5); + + SpawnFlowImpulse( + FlowRetroDownwash, + groundPos, + Vector3.Down, + radius0: 14.0f * scale, + radius1: 18.0f * scale, + strength0: 42f * washT, + strength1: 30f * washT, + shellThickness: 0f, + shockPressure0: 0.65f * washT, + shockPressure1: 0.35f * washT, + lifetime: 0.14f, + priority: isContender ? 9 : 6); + } + } + + public void EmitPodTouchdownPlume(Vector3 pos, Vector3 normal, Color groundTint, bool isContender) + { + float scale = isContender ? 1.40f : 0.95f; + SpawnEmitter( + EmitterFireball, + startPos: pos + normal * 0.6f, + endPos: pos + normal * (2.6f * scale), + velStart: normal * 1.8f, + velEnd: normal * 3.4f, + radiusA0: 1.6f * scale, + radiusA1: 5.5f * scale, + radiusB0: 1.9f * scale, + radiusB1: 6.2f * scale, + density0: 1.85f, + density1: 0.30f, + temp0: 1.35f, + temp1: 0.0f, + tint0: groundTint * 0.82f, + tint1: groundTint * 0.55f, + lifetime: isContender ? 1.85f : 1.15f, + flowSpeed: 0.85f, + softness: 0.46f, + drag: 1.3f, + buoyancy: 0.65f, + priority: isContender ? 10 : 7); + + SpawnFlowImpulse( + FlowShockShell, + pos + normal * 0.4f, + normal, + radius0: 1.8f, + radius1: 22.0f * scale, + strength0: 68f * scale, + strength1: 12f, + shellThickness: 3.2f, + shockPressure0: 1.1f, + shockPressure1: 0f, + lifetime: 0.35f, + priority: 10); + } + + public void EmitThermalVentPlume(Vector3 pos, float thermalRatio) + { + if (ActiveEmitterCount >= 112) + { + return; + } + float heatT = Math.Clamp((thermalRatio - 0.85f) / 0.25f, 0f, 1f); + SpawnEmitter( + EmitterSmoke, + startPos: pos, + endPos: pos + new Vector3(0f, 1.4f, 0f), + velStart: new Vector3(NextSigned() * 0.6f, 2.2f, NextSigned() * 0.6f), + velEnd: new Vector3(NextSigned() * 0.8f, 3.0f, NextSigned() * 0.8f), + radiusA0: 0.45f, + radiusA1: 1.45f + heatT * 0.4f, + radiusB0: 0.55f, + radiusB1: 1.65f + heatT * 0.5f, + density0: 0.72f, + density1: 0.06f, + temp0: 0.25f + heatT * 0.45f, + temp1: 0f, + tint0: new Color(0.82f, 0.72f - heatT * 0.22f, 0.62f - heatT * 0.35f), + tint1: new Color(0.45f, 0.42f, 0.40f), + lifetime: 0.65f, + flowSpeed: 0.6f, + softness: 0.45f, + drag: 1.5f, + buoyancy: 0.75f, + priority: 4); + } + + public void EmitDamageSmokePlume(Vector3 pos, float coreHpRatio) + { + if (ActiveEmitterCount >= 112) + { + return; + } + float dmgT = Math.Clamp((0.35f - coreHpRatio) / 0.35f, 0f, 1f); + SpawnEmitter( + dmgT > 0.35f ? EmitterFireball : EmitterSmoke, + startPos: pos, + endPos: pos + new Vector3(0f, 1.8f, 0f), + velStart: new Vector3(NextSigned() * 0.5f, 2.1f, NextSigned() * 0.5f), + velEnd: new Vector3(NextSigned() * 0.8f, 3.2f, NextSigned() * 0.8f), + radiusA0: 0.62f, + radiusA1: 1.95f + dmgT * 0.65f, + radiusB0: 0.75f, + radiusB1: 2.35f + dmgT * 0.75f, + density0: 1.65f, + density1: 0.24f, + temp0: dmgT > 0.30f ? 0.85f + dmgT * 0.55f : 0.12f, + temp1: 0f, + tint0: new Color(0.11f, 0.10f, 0.095f), + tint1: new Color(0.06f, 0.06f, 0.06f), + lifetime: 0.95f, + flowSpeed: 0.7f, + softness: 0.42f, + drag: 1.1f, + buoyancy: 0.85f, + priority: 5); + } + + public void EmitFootstepOrTirePuff(Vector3 pos, Color groundTint, float scale) + { + // Strictly gated under 48 active emitters so combat explosions never drop slots and desert stays within GPU budget + if (ActiveEmitterCount >= 48) + { + return; + } + Color gLin = groundTint.SrgbToLinear(); + SpawnEmitter( + EmitterSmoke, + startPos: pos, + endPos: pos + new Vector3(NextSigned() * 0.4f, 0.45f, NextSigned() * 0.4f), + velStart: new Vector3(NextSigned() * 1.1f, 0.9f, NextSigned() * 1.1f), + velEnd: new Vector3(NextSigned() * 1.4f, 1.4f, NextSigned() * 1.4f), + radiusA0: 0.48f * scale, + radiusA1: 1.55f * scale, + radiusB0: 0.58f * scale, + radiusB1: 1.75f * scale, + density0: 0.38f, + density1: 0.04f, + temp0: 0f, + temp1: 0f, + tint0: gLin * 1.1f, + tint1: gLin * 0.75f, + lifetime: 0.44f, + flowSpeed: 0.45f, + softness: 0.50f, + drag: 2.0f, + buoyancy: 0.35f, + priority: 1); + } + + private int FindOrEvictEmitterSlot(int priority) + { + int oldestIdx = -1; + int lowestPri = int.MaxValue; + float oldestAge = -1f; + for (int i = 0; i < MaxEmitters; i++) + { + if (!_emitters[i].Active) + { + return i; + } + if (_emitters[i].Priority < lowestPri || + (_emitters[i].Priority == lowestPri && _emitters[i].Age > oldestAge)) + { + lowestPri = _emitters[i].Priority; + oldestAge = _emitters[i].Age; + oldestIdx = i; + } + } + return lowestPri <= priority ? oldestIdx : -1; + } + + private int FindOrEvictImpulseSlot(int priority) + { + int oldestIdx = -1; + int lowestPri = int.MaxValue; + float oldestAge = -1f; + for (int i = 0; i < MaxFlowImpulses; i++) + { + if (!_impulses[i].Active) + { + return i; + } + if (_impulses[i].Priority < lowestPri || + (_impulses[i].Priority == lowestPri && _impulses[i].Age > oldestAge)) + { + lowestPri = _impulses[i].Priority; + oldestAge = _impulses[i].Age; + oldestIdx = i; + } + } + return lowestPri <= priority ? oldestIdx : -1; + } + + private int CountActiveEmitters() + { + int count = 0; + for (int i = 0; i < MaxEmitters; i++) + { + if (_emitters[i].Active) count++; + } + return count; + } + + private int CountActiveImpulses() + { + int count = 0; + for (int i = 0; i < MaxFlowImpulses; i++) + { + if (_impulses[i].Active) count++; + } + return count; + } + + private float NextFloat() + { + uint x = _rng; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + _rng = x; + return (x & 0x00FFFFFFu) / 16777216f; + } + + private float NextSigned() => NextFloat() * 2f - 1f; +} diff --git a/client/export_presets.cfg b/client/export_presets.cfg new file mode 100644 index 0000000..4a70a59 --- /dev/null +++ b/client/export_presets.cfg @@ -0,0 +1,48 @@ +[preset.0] + +name="Windows Desktop" +platform="Windows Desktop" +runnable=true +advanced_options=false +dedicated_server=false +custom_features="" +export_filter="all_resources" +include_filter="*.glsl" +exclude_filter="tests/*,*.uid" +export_path="" +patches=PackedStringArray() +encryption_include_filters="" +encryption_exclude_filters="" +seed=0 +encrypt_pck=false +encrypt_directory=false +script_export_mode=2 + +[preset.0.options] + +custom_template/debug="" +custom_template/release="" +debug/export_console_wrapper=1 +binary_format/embed_pck=false +texture_format/s3tc_bptc=true +texture_format/etc2_astc=false +shader_baker/enabled=false +binary_format/architecture="x86_64" +codesign/enable=false +application/modify_resources=true +application/icon="" +application/console_wrapper_icon="" +application/icon_interpolation=4 +application/file_version="" +application/product_version="" +application/company_name="GameCult" +application/product_name="Rust to Dust" +application/file_description="Rust to Dust" +application/copyright="" +application/trademarks="" +application/export_angle=0 +application/export_d3d12=0 +application/d3d12_agility_sdk_multiarch=true +ssh_remote_deploy/enabled=false +dotnet/include_scripts_content=false +dotnet/include_debug_symbols=false diff --git a/client/film_grain.gdshader b/client/film_grain.gdshader index 3562d44..6f9cf5a 100644 --- a/client/film_grain.gdshader +++ b/client/film_grain.gdshader @@ -6,6 +6,7 @@ render_mode blend_mix; uniform sampler2D screen_tex : hint_screen_texture, filter_nearest; uniform float grain_strength : hint_range(0.0, 0.1) = 0.018; +uniform float post_gamma : hint_range(0.5, 2.5) = 1.32; float interleaved_gradient_noise(vec2 frag_xy, float frame_idx) { vec2 p = frag_xy + vec2(frame_idx * 17.0, frame_idx * 31.0); @@ -14,12 +15,13 @@ float interleaved_gradient_noise(vec2 frag_xy, float frame_idx) { void fragment() { vec4 src = texture(screen_tex, SCREEN_UV); + vec3 graded = pow(max(src.rgb, vec3(0.0)), vec3(post_gamma)); float frame_idx = mod(floor(fract(TIME * 0.001) * 60000.0), 64.0); float n = interleaved_gradient_noise(FRAGCOORD.xy, frame_idx); - float luma = dot(src.rgb, vec3(0.2126, 0.7152, 0.0722)); + float luma = dot(graded, vec3(0.2126, 0.7152, 0.0722)); float midtone_weight = smoothstep(0.02, 0.18, luma) * (1.0 - 0.65 * smoothstep(0.65, 1.0, luma)); - vec3 grained = clamp(src.rgb + vec3((n - 0.5) * 2.0 * grain_strength * midtone_weight), vec3(0.0), vec3(1.0)); + vec3 grained = clamp(graded + vec3((n - 0.5) * 2.0 * grain_strength * midtone_weight), vec3(0.0), vec3(1.0)); COLOR = vec4(grained, src.a); } diff --git a/client/flow_field_step.glsl b/client/flow_field_step.glsl new file mode 100644 index 0000000..3fbe2a0 --- /dev/null +++ b/client/flow_field_step.glsl @@ -0,0 +1,130 @@ +#version 450 + +layout(local_size_x = 8, local_size_y = 4, local_size_z = 8) in; + +struct FlowImpulse { + vec4 posRadius; + vec4 dirStrength; + vec4 shellParams; +}; + +layout(set = 0, binding = 0, std140) uniform VolumetricFrame { + mat4 invProj; + vec4 camPosTime; + vec4 camRightAspect; + vec4 camUpTanHalfFov; + vec4 camFwdNearFar; + vec4 sunDirIntensity; + vec4 sunColorExt; + vec4 ambientColorFog; + vec4 viewportInfo; + uvec4 tileGridParams; + vec4 flowOriginVoxel; + vec4 flowInvExtentDt; + ivec4 flowDeltaImpulse; + uvec4 qualityParams; +} u_frame; + +layout(set = 0, binding = 1, std430) readonly buffer FlowImpulseBuffer { + FlowImpulse impulses[]; +} u_impulses; + +layout(set = 0, binding = 2) uniform sampler3D u_prevFlow; +layout(set = 0, binding = 3, rgba16f) uniform writeonly image3D u_nextFlow; + +shared FlowImpulse sImp[64]; + +void main() { + uint tid = gl_LocalInvocationIndex; + uint impulseCount = min(uint(max(0, u_frame.flowDeltaImpulse.w)), 64u); + if (tid < impulseCount) { + sImp[tid] = u_impulses.impulses[tid]; + } + memoryBarrierShared(); + barrier(); + + ivec3 g = ivec3(gl_GlobalInvocationID.xyz); + const ivec3 gridDim = ivec3(64, 24, 64); + if (any(greaterThanEqual(g, gridDim))) { + return; + } + + float voxelSize = u_frame.flowOriginVoxel.w; + float dt = clamp(u_frame.flowInvExtentDt.w, 0.0, 0.05); + float elapsed = u_frame.camPosTime.w; + + // Gentle planetary wind that shifts subtly with time so idle smoke plumes breathe + vec3 ambientWind = vec3( + 1.25 + 0.35 * sin(elapsed * 0.23), + 0.18, + 0.55 + 0.25 * cos(elapsed * 0.19) + ); + + ivec3 prevIdx = g + u_frame.flowDeltaImpulse.xyz; + bool inPrev = all(greaterThanEqual(prevIdx, ivec3(0))) && all(lessThan(prevIdx, gridDim)); + vec3 prevVel = inPrev ? texelFetch(u_prevFlow, prevIdx, 0).rgb : ambientWind; + + vec3 srcUv = (vec3(prevIdx) + vec3(0.5) - (prevVel * dt) / voxelSize) / vec3(gridDim); + vec4 advected = (inPrev && all(greaterThanEqual(srcUv, vec3(0.0))) && all(lessThanEqual(srcUv, vec3(1.0)))) + ? textureLod(u_prevFlow, srcUv, 0.0) + : vec4(ambientWind, 0.0); + + vec3 vel = mix(ambientWind, advected.rgb, exp(-dt * 1.45)); + float shockP = advected.a * exp(-dt * 4.5); + + vec3 worldP = u_frame.flowOriginVoxel.xyz + (vec3(g) + vec3(0.5)) * voxelSize; + + for (uint i = 0u; i < impulseCount; i++) { + FlowImpulse imp = sImp[i]; + uint typeBits = floatBitsToUint(imp.shellParams.z); + float radius = max(0.5, imp.posRadius.w); + float strength = imp.dirStrength.w; + + if (typeBits == 0u) { + // ShockShell: expanding radial blast shell + vec3 delta = worldP - imp.posRadius.xyz; + float dist = length(delta); + float thick = max(1.5, imp.shellParams.x); + float dShell = (dist - radius) / thick; + if (abs(dShell) < 3.0) { + float shell = exp(-dShell * dShell); + vec3 rDir = dist > 0.05 ? delta / dist : vec3(0.0, 1.0, 0.0); + vel += rDir * (strength * shell); + shockP = max(shockP, imp.shellParams.y * shell); + } + } else if (typeBits == 1u) { + // RetroDownwash: radial ground deflection from pod retro thruster + vec3 d = worldP - imp.posRadius.xyz; + float rXZ = length(d.xz); + float rNorm = rXZ / radius; + float hNorm = abs(d.y) / max(3.0, radius * 0.55); + if (rNorm < 1.35 && hNorm < 1.35) { + float rFall = exp(-rNorm * rNorm * 1.6) * smoothstep(1.35, 0.08, rNorm); + float hFall = exp(-hNorm * hNorm * 1.4); + vec2 rXZDir = rXZ > 0.1 ? d.xz / rXZ : vec2(1.0, 0.0); + vec3 outDir = normalize(vec3(rXZDir.x, 0.28, rXZDir.y)); + float w = rFall * hFall; + vel += outDir * (strength * w); + shockP = max(shockP, imp.shellParams.y * w); + } + } else { + // ThermalUpdraft: buoyant rising column above fireballs & thermal pools + vec3 d = worldP - imp.posRadius.xyz; + float rXZ = length(d.xz); + float rNorm = rXZ / radius; + if (rNorm < 1.3 && d.y > -2.5 && d.y < radius * 2.8) { + float hFall = smoothstep(-2.5, 1.5, d.y) * smoothstep(radius * 2.8, 0.0, max(0.0, d.y)); + float colFall = exp(-rNorm * rNorm * 1.5) * hFall; + vel += vec3(0.0, strength * colFall, 0.0); + } + } + } + + float vLen = length(vel); + if (vLen > 120.0) { + vel *= 120.0 / vLen; + } + shockP = clamp(shockP, 0.0, 2.0); + + imageStore(u_nextFlow, g, vec4(vel, shockP)); +} diff --git a/client/fonts/MONASPACE_LICENSE.txt b/client/fonts/MONASPACE_LICENSE.txt new file mode 100644 index 0000000..1b82de9 --- /dev/null +++ b/client/fonts/MONASPACE_LICENSE.txt @@ -0,0 +1,93 @@ +Copyright (c) 2023, GitHub https://github.com/githubnext/monaspace +with Reserved Font Name "Monaspace", including subfamilies: "Argon", "Neon", "Xenon", "Radon", and "Krypton" + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting — in part or in whole — any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. \ No newline at end of file diff --git a/client/fonts/MonaspaceKrypton-Bold.otf b/client/fonts/MonaspaceKrypton-Bold.otf new file mode 100644 index 0000000..4fafd5f Binary files /dev/null and b/client/fonts/MonaspaceKrypton-Bold.otf differ diff --git a/client/fonts/MonaspaceKrypton-Bold.otf.import b/client/fonts/MonaspaceKrypton-Bold.otf.import new file mode 100644 index 0000000..11f4f1e --- /dev/null +++ b/client/fonts/MonaspaceKrypton-Bold.otf.import @@ -0,0 +1,36 @@ +[remap] + +importer="font_data_dynamic" +type="FontFile" +uid="uid://dlsxsr034f5sv" +path="res://.godot/imported/MonaspaceKrypton-Bold.otf-a6e22263037c0e08923dee8788f7d7d1.fontdata" + +[deps] + +source_file="res://fonts/MonaspaceKrypton-Bold.otf" +dest_files=["res://.godot/imported/MonaspaceKrypton-Bold.otf-a6e22263037c0e08923dee8788f7d7d1.fontdata"] + +[params] + +Rendering=null +antialiasing=1 +generate_mipmaps=false +disable_embedded_bitmaps=true +multichannel_signed_distance_field=false +msdf_pixel_range=8 +msdf_size=48 +allow_system_fallback=true +force_autohinter=false +modulate_color_glyphs=false +hinting=3 +subpixel_positioning=4 +keep_rounding_remainders=true +oversampling=0.0 +Fallbacks=null +fallbacks=[] +Compress=null +compress=true +preload=[] +language_support={} +script_support={} +opentype_features={} diff --git a/client/fonts/MonaspaceKrypton-Regular.otf b/client/fonts/MonaspaceKrypton-Regular.otf new file mode 100644 index 0000000..ce21874 Binary files /dev/null and b/client/fonts/MonaspaceKrypton-Regular.otf differ diff --git a/client/fonts/MonaspaceKrypton-Regular.otf.import b/client/fonts/MonaspaceKrypton-Regular.otf.import new file mode 100644 index 0000000..03294fe --- /dev/null +++ b/client/fonts/MonaspaceKrypton-Regular.otf.import @@ -0,0 +1,36 @@ +[remap] + +importer="font_data_dynamic" +type="FontFile" +uid="uid://1udxuivwq46s" +path="res://.godot/imported/MonaspaceKrypton-Regular.otf-879dc21ea909cad808c934de94044b6e.fontdata" + +[deps] + +source_file="res://fonts/MonaspaceKrypton-Regular.otf" +dest_files=["res://.godot/imported/MonaspaceKrypton-Regular.otf-879dc21ea909cad808c934de94044b6e.fontdata"] + +[params] + +Rendering=null +antialiasing=1 +generate_mipmaps=false +disable_embedded_bitmaps=true +multichannel_signed_distance_field=false +msdf_pixel_range=8 +msdf_size=48 +allow_system_fallback=true +force_autohinter=false +modulate_color_glyphs=false +hinting=3 +subpixel_positioning=4 +keep_rounding_remainders=true +oversampling=0.0 +Fallbacks=null +fallbacks=[] +Compress=null +compress=true +preload=[] +language_support={} +script_support={} +opentype_features={} diff --git a/client/fonts/MonaspaceKrypton-SemiBold.otf b/client/fonts/MonaspaceKrypton-SemiBold.otf new file mode 100644 index 0000000..8c9d680 Binary files /dev/null and b/client/fonts/MonaspaceKrypton-SemiBold.otf differ diff --git a/client/fonts/MonaspaceKrypton-SemiBold.otf.import b/client/fonts/MonaspaceKrypton-SemiBold.otf.import new file mode 100644 index 0000000..e76054a --- /dev/null +++ b/client/fonts/MonaspaceKrypton-SemiBold.otf.import @@ -0,0 +1,36 @@ +[remap] + +importer="font_data_dynamic" +type="FontFile" +uid="uid://270t27q6bpet" +path="res://.godot/imported/MonaspaceKrypton-SemiBold.otf-c294810382571aa26a9353cf57198e74.fontdata" + +[deps] + +source_file="res://fonts/MonaspaceKrypton-SemiBold.otf" +dest_files=["res://.godot/imported/MonaspaceKrypton-SemiBold.otf-c294810382571aa26a9353cf57198e74.fontdata"] + +[params] + +Rendering=null +antialiasing=1 +generate_mipmaps=false +disable_embedded_bitmaps=true +multichannel_signed_distance_field=false +msdf_pixel_range=8 +msdf_size=48 +allow_system_fallback=true +force_autohinter=false +modulate_color_glyphs=false +hinting=3 +subpixel_positioning=4 +keep_rounding_remainders=true +oversampling=0.0 +Fallbacks=null +fallbacks=[] +Compress=null +compress=true +preload=[] +language_support={} +script_support={} +opentype_features={} diff --git a/client/gpu_sparks_draw.gdshader b/client/gpu_sparks_draw.gdshader new file mode 100644 index 0000000..2441a07 --- /dev/null +++ b/client/gpu_sparks_draw.gdshader @@ -0,0 +1,151 @@ +shader_type spatial; +render_mode unshaded, cull_disabled, depth_draw_opaque; + +varying vec4 v_color; +varying vec2 v_uvCentered; +varying vec2 v_kite; +varying float v_ageNorm; +varying float v_type; +varying float v_camFade; + +void vertex() { + vec3 worldPos = MODEL_MATRIX[3].xyz; + vec3 velWorld = MODEL_MATRIX[0].xyz; + + float widthM = max(0.012, INSTANCE_CUSTOM.x); + float ageNorm = clamp(INSTANCE_CUSTOM.y / max(0.01, INSTANCE_CUSTOM.z), 0.0, 1.0); + float pType = floor(INSTANCE_CUSTOM.w + 0.001); + + v_color = COLOR; + v_ageNorm = ageNorm; + v_type = pType; + v_uvCentered = UV * 2.0 - vec2(1.0); + + // Kite-stretch trick: rotate quad coordinates 45 degrees so pointed ears align directly along velocity: + // (-1,-1) -> u=-1,v=0 (tail tip); (+1,+1) -> u=+1,v=0 (nose tip); (+1,-1)/(-1,+1) -> v=±1 (side ears) + float uKite = 0.5 * (v_uvCentered.x + v_uvCentered.y); + float vKite = 0.5 * (v_uvCentered.x - v_uvCentered.y); + v_kite = vec2(uKite, vKite); + + vec3 camRight = INV_VIEW_MATRIX[0].xyz; + vec3 camUp = INV_VIEW_MATRIX[1].xyz; + vec3 toCamVec = CAMERA_POSITION_WORLD - worldPos; + float toCamLen2 = dot(toCamVec, toCamVec); + float distToCam = sqrt(toCamLen2); + v_camFade = smoothstep(1.2, 2.8, distToCam); + if (distToCam < 1.2) { + MODELVIEW_MATRIX = VIEW_MATRIX; + VERTEX = worldPos; + } else { + vec3 toCam = toCamLen2 > 1e-6 ? toCamVec * inversesqrt(toCamLen2) : INV_VIEW_MATRIX[2].xyz; + + if (pType > 2.5) { + // Type 3: Stationary 4-point HDR muzzle starburst + float pulse = sin(ageNorm * 3.14159265); + float sz = min(widthM * (0.65 + 0.45 * pulse), distToCam * 0.032); + vec3 displacedWorld = worldPos + camRight * (v_uvCentered.x * sz) + camUp * (v_uvCentered.y * sz); + MODELVIEW_MATRIX = VIEW_MATRIX; + VERTEX = displacedWorld; + } else { + float speed = length(velWorld); + vec3 vProj = velWorld - toCam * dot(velWorld, toCam); + float vProjLen2 = dot(vProj, vProj); + vec3 axisWorld = vProjLen2 > 1e-4 ? vProj * inversesqrt(vProjLen2) : camRight; + vec3 rawPerp = cross(toCam, axisWorld); + float rawPerpLen2 = dot(rawPerp, rawPerp); + vec3 perpWorld = rawPerpLen2 > 1e-6 ? rawPerp * inversesqrt(rawPerpLen2) : camUp; + + float dist = distToCam; + float halfWidth; + float halfLen; + + if (pType > 1.5) { + // Type 2: Tiny flow-blown grit / dust mote + float minGritPx = dist * 0.0010; + halfWidth = max(clamp(widthM * (0.75 + 0.30 * ageNorm), 0.020, 0.055), minGritPx); + halfLen = halfWidth + clamp(speed * 0.006, 0.01, 0.09); + } else { + // Type 0 (VelocitySpark) & Type 1 (BuoyantEmber): crisp short punchy streaks (halfLen capped 0.04..0.16m) + float minSparkPx = dist * 0.0012; + halfWidth = max(clamp(widthM * mix(0.82, 0.38, ageNorm), 0.012, 0.030), minSparkPx); + float baseLen = clamp(halfWidth * 1.6 + speed * 0.008, 0.04, 0.16); + halfLen = max(halfWidth * 1.8, min(0.16, max(baseLen, minSparkPx * 2.6))); + } + + // Near-camera angular cap so sparks & dust motes at 1.8-2.5m never blow up into giant halftone spears + float maxAngLen = dist * 0.022; + halfLen = min(halfLen, maxAngLen); + halfWidth = min(halfWidth, maxAngLen * 0.32); + + vec3 displacedWorld = worldPos + axisWorld * (uKite * halfLen) + perpWorld * (vKite * halfWidth); + MODELVIEW_MATRIX = VIEW_MATRIX; + VERTEX = displacedWorld; + } + } +} + +void fragment() { + if (v_camFade < 0.02) { + discard; + } + float fade = (1.0 - v_ageNorm * v_ageNorm) * clamp(v_color.a, 0.0, 1.0) * v_camFade; + if (fade < 0.02) { + discard; + } + + // Temporally animated Interleaved Gradient Noise for stochastic opaque TAA coverage (depth_draw_opaque) + float frameIdx = mod(floor(TIME * 60.0), 64.0); + float dither = fract(52.9829189 * fract(dot(FRAGCOORD.xy + 5.588238 * frameIdx, vec2(0.06711056, 0.00583715)))); + + if (v_type > 2.5) { + // 4-point HDR muzzle starburst + float r = length(v_uvCentered); + if (r > 1.0) { + discard; + } + float cx = exp(-abs(v_uvCentered.y) * 9.5) * smoothstep(1.0, 0.05, abs(v_uvCentered.x)); + float cy = exp(-abs(v_uvCentered.x) * 9.5) * smoothstep(1.0, 0.05, abs(v_uvCentered.y)); + float core = smoothstep(0.55, 0.0, r); + float mask = max(core, max(cx, cy) * 0.90); + float coverage = clamp(mask * fade * 1.25, 0.0, 1.0); + if (coverage <= dither) { + discard; + } + ALBEDO = max(v_color.rgb, vec3(0.0)) * (1.0 + core * 0.95); + } else if (v_type > 1.5) { + // Flow-entrained grit / dust mote + float r = length(v_kite); + if (r > 0.92) { + discard; + } + float coverage = smoothstep(0.92, 0.14, r) * fade * 0.85; + if (coverage <= dither) { + discard; + } + ALBEDO = max(v_color.rgb, vec3(0.0)); + } else { + // Molten slag spark / ember: white-gold -> amber -> deep copper-orange cooling ramp + float rKite = length(vec2(v_kite.x, v_kite.y * 1.15)); + if (rKite > 1.0) { + discard; + } + float core = pow(clamp(1.0 - rKite, 0.0, 1.0), 1.45); + float hotCenter = smoothstep(0.50, 0.0, rKite); + float coverage = clamp(core * fade * 1.20, 0.0, 1.0); + if (coverage <= dither) { + discard; + } + + vec3 whiteGold = vec3(6.2, 4.2, 1.65); + vec3 moltenAmber = vec3(4.3, 1.85, 0.30); + vec3 copperEmber = vec3(1.85, 0.42, 0.05); + vec3 ramp = v_ageNorm < 0.38 + ? mix(whiteGold, moltenAmber, v_ageNorm / 0.38) + : mix(moltenAmber, copperEmber, clamp((v_ageNorm - 0.38) / 0.62, 0.0, 1.0)); + + // Subtle caller tint (20%) so plasma/thermal slag still reads predominantly as molten fire + vec3 tintRgb = max(v_color.rgb, vec3(0.0)); + vec3 moltenRgb = mix(ramp, tintRgb, 0.20); + ALBEDO = mix(moltenRgb, whiteGold * 1.15, hotCenter * (1.0 - 0.55 * v_ageNorm)); + } +} diff --git a/client/gpu_sparks_process.gdshader b/client/gpu_sparks_process.gdshader new file mode 100644 index 0000000..0a05bf2 --- /dev/null +++ b/client/gpu_sparks_process.gdshader @@ -0,0 +1,154 @@ +shader_type particles; +render_mode disable_velocity; + +global uniform sampler3D rtd_flow_field; +global uniform vec3 rtd_flow_origin; +global uniform vec3 rtd_flow_inv_extent; + +float tri(float x) { + return abs(fract(x) - 0.5); +} + +vec3 tri3(vec3 p) { + return vec3( + tri(p.z + tri(p.y)), + tri(p.z + tri(p.x)), + tri(p.y + tri(p.x)) + ); +} + +vec3 safeNorm(vec3 v) { + float l2 = dot(v, v); + return l2 > 1e-8 ? v * inversesqrt(l2) : vec3(0.0, 1.0, 0.0); +} + +vec3 aetheriaCurl(vec3 pos, float flowScale, float scrollSpeed, float t) { + vec3 field = pos / max(0.5, flowScale); + float s1 = t * scrollSpeed; + float s2 = t * scrollSpeed * 1.61803398875; + vec3 t1 = safeNorm(tri3(field - vec3(0.0, s1, 0.0))); + vec3 t2 = safeNorm(tri3(field * 1.61803398875 - vec3(0.0, s2, 0.0))); + return cross(t1, t2); +} + +uint hashU32(uint x) { + x ^= x >> 16u; + x *= 0x7FEB352Du; + x ^= x >> 15u; + x *= 0x846CA68Bu; + x ^= x >> 16u; + return x; +} + +float hash01(uint x) { + return float(hashU32(x) & 0x00FFFFFFu) / 16777216.0; +} + +void start() { + ACTIVE = true; + float pType = floor(CUSTOM.w + 0.001); + + if (pType > 2.5) { + // Type 3: MuzzleStarburst stays stationary at muzzle + VELOCITY = vec3(0.0); + TRANSFORM[0].xyz = vec3(1.0, 0.0, 0.0); + TRANSFORM[1].xyz = vec3(0.0, 1.0, 0.0); + TRANSFORM[2].xyz = vec3(0.0, 0.0, 1.0); + } else { + uint seed = INDEX ^ (NUMBER * 747796405u) ^ floatBitsToUint(TIME); + float r0 = hash01(seed + 1u); + float r1 = hash01(seed + 17u); + float r2 = hash01(seed + 53u); + float r3 = hash01(seed + 131u); + float r4 = hash01(seed + 257u); + float r5 = hash01(seed + 509u); + + // Wide log-normal speed dispersion (0.25x..2.8x) + 3D directional chaos to shatter radial shell fans + float gauss = (r0 + r1 - 1.0) * 1.45; + float speedMult = clamp(exp(gauss * 0.72), 0.25, 2.80); + float baseSpeed = length(VELOCITY); + vec3 dirJitter = vec3(r2 * 2.0 - 1.0, r4 * 2.0 - 1.0, r5 * 2.0 - 1.0); + VELOCITY = VELOCITY * speedMult + dirJitter * (baseSpeed * 0.30); + + // Sub-frame / burst-window birth offset (0..55ms) with immediate curl + gravity advection + float dt0 = r3 * 0.055; + vec3 curl0 = aetheriaCurl(TRANSFORM[3].xyz, 3.0, 0.90, TIME); + if (pType < 0.5) { + VELOCITY += curl0 * (18.0 * dt0); + VELOCITY.y -= 11.0 * dt0; + } else if (pType < 1.5) { + VELOCITY += curl0 * (14.0 * dt0); + VELOCITY.y += 2.6 * dt0; + } else { + VELOCITY += curl0 * (10.0 * dt0); + VELOCITY.y -= 1.2 * dt0; + } + TRANSFORM[3].xyz += VELOCITY * dt0; + CUSTOM.y = min(CUSTOM.z * 0.35, dt0 * 0.65); + + TRANSFORM[0].xyz = VELOCITY; + TRANSFORM[1].xyz = vec3(0.0, 1.0, 0.0); + TRANSFORM[2].xyz = vec3(0.0, 0.0, 1.0); + } +} + +void process() { + float age = CUSTOM.y + DELTA; + float maxLife = max(0.01, CUSTOM.z); + if (age >= maxLife) { + ACTIVE = false; + } else { + CUSTOM.y = age; + float pType = floor(CUSTOM.w + 0.001); + float drag = fract(CUSTOM.w) * 20.0; + + if (pType > 2.5) { + // Type 3: MuzzleStarburst (stationary HDR flash) + VELOCITY = vec3(0.0); + TRANSFORM[0].xyz = vec3(1.0, 0.0, 0.0); + TRANSFORM[1].xyz = vec3(0.0, 1.0, 0.0); + TRANSFORM[2].xyz = vec3(0.0, 0.0, 1.0); + } else { + vec3 worldPos = TRANSFORM[3].xyz; + vec3 flowUv = (worldPos - rtd_flow_origin) * rtd_flow_inv_extent; + vec4 flowSample = vec4(0.0); + if (all(greaterThanEqual(flowUv, vec3(0.0))) && all(lessThanEqual(flowUv, vec3(1.0)))) { + flowSample = textureLod(rtd_flow_field, flowUv, 0.0); + } + + vec3 flowVel = flowSample.rgb; + float shockP = flowSample.a; + vec3 curl = aetheriaCurl(worldPos, 3.2, 0.85, TIME); + + if (pType < 0.5) { + // Type 0: VelocitySpark (ballistic + wispy Tri3D curl streams + flow drag + shock kick) + VELOCITY += (flowVel - VELOCITY) * min(1.0, drag * DELTA); + VELOCITY += curl * (22.0 * DELTA); + VELOCITY.y -= 11.0 * DELTA; + if (shockP > 0.20) { + VELOCITY += flowVel * (shockP * 0.55 * DELTA); + } + } else if (pType < 1.5) { + // Type 1: BuoyantEmber (upward buoyancy + swirling Tri3D thermal streams) + VELOCITY += (flowVel - VELOCITY) * min(1.0, drag * DELTA); + VELOCITY += curl * (15.5 * DELTA); + VELOCITY.y += 3.0 * DELTA; + if (shockP > 0.20) { + VELOCITY += flowVel * (shockP * 0.70 * DELTA); + } + } else { + // Type 2: DustMote (heavily flow-entrained ground grit + curl wisps) + float dustDrag = max(drag, 3.2); + VELOCITY += (flowVel - VELOCITY) * min(1.0, dustDrag * DELTA); + VELOCITY += curl * (11.0 * DELTA); + VELOCITY.y -= 1.2 * DELTA; + } + + TRANSFORM[3].xyz += VELOCITY * DELTA; + // Pass world VELOCITY to gpu_sparks_draw.gdshader cleanly via MODEL_MATRIX[0] + TRANSFORM[0].xyz = VELOCITY; + TRANSFORM[1].xyz = vec3(0.0, 1.0, 0.0); + TRANSFORM[2].xyz = vec3(0.0, 0.0, 1.0); + } + } +} diff --git a/client/inventory_grid.gdshader b/client/inventory_grid.gdshader index fce4ae7..c77eb2d 100644 --- a/client/inventory_grid.gdshader +++ b/client/inventory_grid.gdshader @@ -2,12 +2,13 @@ shader_type canvas_item; render_mode blend_premul_alpha; // Port of Aetheria's UI/Inventory Grid shader to Godot 4 Forward+ Vulkan. -// Evaluates analytical corner-folded texel boxes for hull/hardpoint silhouettes, L-brackets, -// hairline rules, direct bilinear heat glow, hit-pulse flash, and 45-degree fracture hatching. +// Evaluates stateless interior cell fill: corner-folded texel masks, bilinear heat glow, +// hit-pulse flash, and 45-degree fracture hatching. Crisp vector frames, L-brackets, +// stripped X-marks, and Krypton labels are rendered by HbGpuCanvas on top. // // data_tex (3W x H, filter_nearest): // 3x + 0 : cell/item fill & armor tint (RGBA) -// 3x + 1 : border/bracket accent color (RGBA) +// 3x + 1 : reserved / accent tint // 3x + 2 : R = 8-bit neighbor mismatch mask (N,E,S,W,NE,SE,SW,NW) // G = flags (bit0=present, bit1=item, bit2=hover, bit3=damaged/stripped, bit4=compatible, bit5=border_radiator) // B = reserved (0) @@ -23,17 +24,9 @@ uniform sampler2D temp_tex : filter_linear, repeat_disable; uniform vec2 grid_size = vec2(4.0, 5.0); uniform vec2 rect_size = vec2(180.0, 225.0); -// Look parameters in Aetheria texel units -uniform float icon_texel = 1.51515; uniform float bg_texel = 1.0; -uniform float rule_inset = 1.5; -uniform float rule_width = 1.0; -uniform float arm_texels = 1.25; uniform float fill_inset = 2.6; uniform float softness = 1.0; -uniform float rule_alpha = 0.34; -uniform float bracket_alpha = 1.0; -uniform float fill_alpha = 0.14; const float FAR = 1000.0; @@ -45,7 +38,7 @@ float box_profile(float x, float lo, float hi, float soft) { return clamp(1.0 - outside / soft, 0.0, 1.0); } -float eval_layer(vec2 p, float cell_px, float texel, uint mask, bool is_item, bool is_icon, float aa_px) { +float eval_bg_mask(vec2 p, float cell_px, float texel, uint mask, float aa_px) { float t = min(texel, cell_px / 8.0); bool left = p.x < cell_px * 0.5; bool top = p.y >= cell_px * 0.5; @@ -69,36 +62,7 @@ float eval_layer(vec2 p, float cell_px, float texel, uint mask, bool is_item, bo if (concave) { f -= box_profile(x, -FAR, fill_inset - 0.5, soft) * box_profile(y, -FAR, fill_inset - 0.5, soft); } - f = clamp(f, 0.0, 1.0); - if (!is_icon) { - return f; - } - - float a = is_item ? fill_alpha * f : 0.0; - float ri = rule_inset; - float rlo = ri - (rule_width - 1.0) * 0.5; - float rhi = ri + (rule_width - 1.0) * 0.5; - float rx = box_profile(x, rlo, rhi, soft); - float ry = box_profile(y, rlo, rhi, soft); - float arms = arm_texels >= 1.0 ? 1.0 : 0.0; - - if (v) { - a += rule_alpha * ry * (h ? box_profile(x, ri, FAR, soft) : 1.0); - } - if (h) { - a += rule_alpha * rx * (v ? box_profile(y, ri + 1.0, FAR, soft) : 1.0); - } - if (v && h) { - a += (bracket_alpha - rule_alpha) * (ry * box_profile(x, ri, ri + arm_texels, soft) + arms * rx * box_profile(y, ri + 1.0, ri + arm_texels, soft)); - } else if (concave) { - a += bracket_alpha * (ry * box_profile(x, ri - arm_texels, ri, soft) + arms * rx * box_profile(y, ri - arm_texels, ri - 1.0, soft)); - } else if (!v && !h) { - // Faint cell subdivision hairline across matched internal cell boundaries - float sub_x = box_profile(x, 0.0, 0.65, soft); - float sub_y = box_profile(y, 0.0, 0.65, soft); - a += 0.14 * max(sub_x, sub_y); - } - return clamp(a, 0.0, 1.0); + return clamp(f, 0.0, 1.0); } vec3 thermal_ramp(float t) { @@ -136,7 +100,6 @@ void fragment() { float tex_w = safe_grid.x * 3.0; float ty = (cellf.y + 0.5) / safe_grid.y; vec4 cell_fill = textureLod(data_tex, vec2((cellf.x * 3.0 + 0.5) / tex_w, ty), 0.0); - vec4 border_accent = textureLod(data_tex, vec2((cellf.x * 3.0 + 1.5) / tex_w, ty), 0.0); vec4 meta = textureLod(data_tex, vec2((cellf.x * 3.0 + 2.5) / tex_w, ty), 0.0); uint mask = uint(round(meta.r * 255.0)); @@ -146,7 +109,6 @@ void fragment() { if ((flags & 1u) == 0u) { COLOR = vec4(0.0); } else { - bool is_item = (flags & 2u) != 0u; bool is_hover = (flags & 4u) != 0u; bool is_damaged = (flags & 8u) != 0u; bool is_compatible = (flags & 16u) != 0u; @@ -155,8 +117,7 @@ void fragment() { float plateau_stress = temp_sample.g; vec3 heat_col = thermal_ramp(norm_temp); - float a_bg = eval_layer(p, S, bg_texel, mask, false, false, aa_px) * cell_fill.a; - float a_rules = eval_layer(p, S, icon_texel, mask, is_item, true, aa_px); + float a_bg = eval_bg_mask(p, S, bg_texel, mask, aa_px) * cell_fill.a; // Intact vs stripped (Armor == 0) interior fill with always-active subtle bilinear heat glow on hot cells float hot_blend = smoothstep(0.05, 0.65, norm_temp) * 0.56; @@ -174,6 +135,10 @@ void fragment() { base_rgb += heat_col * (0.20 * norm_temp + 0.30 * overheat_glow); base_rgb = clamp(base_rgb, vec3(0.0), vec3(1.0)); + if (is_compatible) { + float pulse = 0.72 + 0.28 * sin(TIME * 6.5); + base_rgb = mix(base_rgb, vec3(0.96, 0.82, 0.30), 0.16 * pulse); + } if (is_hover) { base_rgb = mix(base_rgb, vec3(0.95, 0.94, 0.88), 0.16); } @@ -182,27 +147,8 @@ void fragment() { vec3 flash_col = vec3(1.0, 0.76, 0.38); base_rgb = clamp(mix(base_rgb, flash_col, hit_pulse * 0.85), vec3(0.0), vec3(1.0)); - vec3 accent_rgb = border_accent.rgb; - if (is_damaged) { - accent_rgb = mix(accent_rgb, vec3(0.92, 0.26, 0.18), 0.70); - } - if (is_compatible) { - float pulse = 0.72 + 0.28 * sin(TIME * 6.5); - accent_rgb = mix(accent_rgb, vec3(0.96, 0.82, 0.30), pulse); - a_rules = clamp(a_rules * 1.35, 0.0, 1.0); - } - if (is_hover) { - accent_rgb = mix(accent_rgb, vec3(1.0), 0.35); - a_rules = clamp(a_rules * 1.25, 0.0, 1.0); - } - accent_rgb = clamp(mix(accent_rgb, flash_col, hit_pulse * 0.90), vec3(0.0), vec3(1.0)); - - float icon_alpha = clamp(a_rules * border_accent.a, 0.0, 1.0); - vec3 icon_rgb = clamp(accent_rgb, vec3(0.0), vec3(1.0)); - - float out_a = clamp(icon_alpha + a_bg * (1.0 - icon_alpha), 0.0, 1.0); - vec3 out_rgb = min(icon_rgb * icon_alpha + base_rgb * a_bg * (1.0 - icon_alpha), vec3(out_a)); - out_rgb = max(out_rgb, vec3(0.0)); + float out_a = clamp(a_bg, 0.0, 1.0); + vec3 out_rgb = clamp(base_rgb, vec3(0.0), vec3(1.0)) * out_a; COLOR = vec4(out_rgb, out_a); } } diff --git a/client/particle_billboard.gdshader b/client/particle_billboard.gdshader deleted file mode 100644 index eb44cea..0000000 --- a/client/particle_billboard.gdshader +++ /dev/null @@ -1,108 +0,0 @@ -shader_type spatial; -render_mode unshaded, cull_disabled, blend_mix, depth_draw_never; - -// Forward+ Vulkan single-draw-call billboard particle shader for MultiMeshInstance3D. -// Zero texture binds; packs shape mode, normalized age, HDR emissive, and 2D rotation into INSTANCE_CUSTOM, -// and sRGB RGB tint (converted to linear in vertex()) + alpha fade into COLOR. -// -// INSTANCE_CUSTOM layout: -// x = mode (0.0 = soft wisp dust/smoke, 1.0 = 4-point HDR muzzle starburst, 2.0 = spark/ember streak, 3.0 = steam/fireball puff) -// y = age_norm (0.0..1.0) -// z = emissive (0.0..4.0+ HDR multiplier) -// w = rot_rad (2D billboard roll angle in radians) - -varying vec4 v_color; -varying vec4 v_custom; - -float hash21(vec2 p) { - p = fract(p * vec2(127.1, 311.7)); - p += dot(p, p + 34.43); - return fract(p.x * p.y); -} - -float soft_noise(vec2 p) { - return 0.5 + 0.25 * sin(p.x * 2.7 + p.y * 1.9) + 0.25 * cos(p.y * 2.3 - p.x * 1.7); -} - -vec3 srgb_to_linear(vec3 c) { - vec3 lo = c / 12.92; - vec3 hi = pow((c + vec3(0.055)) / 1.055, vec3(2.4)); - return mix(lo, hi, step(vec3(0.04045), c)); -} - -void vertex() { - v_color = vec4(srgb_to_linear(max(COLOR.rgb, vec3(0.0))), COLOR.a); - v_custom = INSTANCE_CUSTOM; - - float rot = INSTANCE_CUSTOM.w; - float c = cos(rot); - float s = sin(rot); - VERTEX.xy = vec2(VERTEX.x * c - VERTEX.y * s, VERTEX.x * s + VERTEX.y * c); - - vec3 world_pos = MODEL_MATRIX[3].xyz; - float sx = length(MODEL_MATRIX[0].xyz); - float sy = length(MODEL_MATRIX[1].xyz); - - MODELVIEW_MATRIX = VIEW_MATRIX * mat4( - vec4(INV_VIEW_MATRIX[0].xyz * sx, 0.0), - vec4(INV_VIEW_MATRIX[1].xyz * sy, 0.0), - vec4(INV_VIEW_MATRIX[2].xyz, 0.0), - vec4(world_pos, 1.0) - ); -} - -void fragment() { - vec2 centered = UV * 2.0 - vec2(1.0); - float r = length(centered); - if (r > 1.0) { - discard; - } - - float mode = floor(v_custom.x + 0.5); - float age_norm = clamp(v_custom.y, 0.0, 1.0); - float emissive = max(v_custom.z, 0.0); - - float shape_alpha = 0.0; - float core_mask = 0.0; - - if (mode < 0.5) { - // Mode 0: Soft wisp dust / smoke plume - float wisp = soft_noise(centered * 2.4 + vec2(v_custom.w * 1.7, age_norm * 1.5)); - float radial = smoothstep(1.0, 0.14, r + (wisp - 0.5) * 0.34); - shape_alpha = radial * (0.72 + 0.28 * wisp); - core_mask = smoothstep(0.65, 0.0, r) * 0.4; - } else if (mode < 1.5) { - // Mode 1: Crisp 4-point HDR muzzle starburst - float ax = abs(centered.x); - float ay = abs(centered.y); - float cross_x = exp(-ay * 10.5) * smoothstep(1.0, 0.08, ax); - float cross_y = exp(-ax * 10.5) * smoothstep(1.0, 0.08, ay); - float core = smoothstep(0.58, 0.0, r); - float flash = max(core, max(cross_x, cross_y) * 0.92); - shape_alpha = clamp(flash, 0.0, 1.0); - core_mask = clamp(core * 1.35 + (cross_x + cross_y) * 0.55, 0.0, 1.5); - } else if (mode < 2.5) { - // Mode 2: Elongated spark / hot shrapnel streak - vec2 stretched = vec2(centered.x * 1.0, centered.y * 2.6); - float sr = length(stretched); - float streak = smoothstep(1.0, 0.05, sr); - shape_alpha = streak * streak; - core_mask = smoothstep(0.75, 0.0, sr); - } else { - // Mode 3: Steam / fireball / thermal puff - float billow = soft_noise(centered * 3.1 - vec2(age_norm * 1.9, v_custom.w)); - float radial = smoothstep(1.0, 0.08, r + (billow - 0.5) * 0.26); - float hot_core = smoothstep(0.62, 0.0, r); - shape_alpha = radial; - core_mask = hot_core * (1.0 - age_norm * 0.55); - } - - float alpha = clamp(shape_alpha * v_color.a, 0.0, 1.0); - if (alpha < 0.005) { - discard; - } - - vec3 rgb = max(v_color.rgb, vec3(0.0)) * (1.0 + emissive * core_mask); - ALBEDO = rgb; - ALPHA = alpha; -} diff --git a/client/project.godot b/client/project.godot index d66247b..c4a58ec 100644 --- a/client/project.godot +++ b/client/project.godot @@ -20,6 +20,10 @@ window/stretch/mode="canvas_items" project/assembly_name="RustToDust.Client" +[gui] + +theme/custom_font="res://fonts/MonaspaceKrypton-Regular.otf" + [physics] ; Godot's physics is switched off: Ymir is the only physics world. ArenaSession ticks at 60 Hz. diff --git a/client/terrain_brush.gdshader b/client/terrain_brush.gdshader deleted file mode 100644 index ccbe36f..0000000 --- a/client/terrain_brush.gdshader +++ /dev/null @@ -1,67 +0,0 @@ -shader_type canvas_item; -render_mode blend_add; - -// Encodes positive height deltas into R ([-18m, +52m] => span 70m), -// roughness delta into G, scorch/track wear into B, and ALWAYS A = 1.0 -// (required for TransparentBg=false UseHdr2D=true blend equations in forward_plus). -uniform int brush_kind = 0; -uniform float height_delta = 0.0; -uniform float height_span = 70.0; - -void fragment() { - vec2 uv_local = UV * 2.0 - 1.0; - float u = uv_local.x; - float v = uv_local.y; - float r2 = u * u + v * v; - if (r2 >= 1.0) { - discard; - } - - float pos_dh = 0.0; - float pos_dg = 0.0; - float d_scorch = 0.0; - - if (brush_kind == 0) { - // DuneRidge (positive) - float env = 1.0 - r2; - env *= env; - float ridge = max(0.0, 1.0 - u * u); - float asym = 1.0 + 0.32 * u; - pos_dh = max(0.0, height_delta) * env * (0.35 + 0.65 * ridge) * asym; - pos_dg = 0.02 * env; - } else if (brush_kind == 1) { - // Mesa - float r = sqrt(r2); - float t = clamp((1.0 - r) / 0.45, 0.0, 1.0); - float plateau = t * t * (3.0 - 2.0 * t); - pos_dh = max(0.0, height_delta) * plateau; - } else if (brush_kind == 2) { - // SalvagePad (positive part) - float env = 1.0 - r2; - env *= env; - pos_dh = max(0.0, height_delta) * env; - pos_dg = 0.03 * env; - } else if (brush_kind == 4) { - // Crater ejecta rim + slag/scorch - float r = sqrt(r2); - float depth = abs(height_delta); - float rim_t = sin(3.14159265 * clamp((r - 0.55) / 0.45, 0.0, 1.0)); - pos_dh = 0.32 * depth * rim_t * rim_t; - pos_dg = 0.04 * (1.0 - r); - d_scorch = 0.78 * clamp(1.0 - r * 0.9, 0.0, 1.0); - } else if (brush_kind == 5) { - // Track wear - float env = 1.0 - r2; - env *= env; - d_scorch = 0.32 * env; - } else if (brush_kind == 6) { - // Scorch - float r = sqrt(r2); - float mask = clamp(1.0 - r, 0.0, 1.0); - mask = mask * mask; - pos_dg = 0.02 * mask; - d_scorch = 0.85 * mask; - } - - COLOR = vec4(pos_dh / height_span, pos_dg, d_scorch, 1.0); -} diff --git a/client/terrain_brush_albedo.gdshader b/client/terrain_brush_albedo.gdshader deleted file mode 100644 index 3b1cdf8..0000000 --- a/client/terrain_brush_albedo.gdshader +++ /dev/null @@ -1,73 +0,0 @@ -shader_type canvas_item; -render_mode blend_mix; - -uniform int brush_kind = 0; -uniform vec3 brush_albedo = vec3(0.72, 0.53, 0.33); -uniform float height_delta = 0.0; - -void fragment() { - vec2 uv_local = UV * 2.0 - 1.0; - float u = uv_local.x; - float v = uv_local.y; - float r2 = u * u + v * v; - if (r2 >= 1.0) { - discard; - } - - vec3 col = brush_albedo; - float alpha = 0.0; - - if (brush_kind == 0) { - // DuneRidge: windward sunlit crest vs dry wash - float env = 1.0 - r2; - env *= env; - float ridge = max(0.0, 1.0 - u * u); - col = mix(brush_albedo * 0.90, brush_albedo * 1.12, ridge); - alpha = env * 0.72; - } else if (brush_kind == 1) { - // Mesa: rust-basalt plateau + stratified skirt - float r = sqrt(r2); - float t = clamp((1.0 - r) / 0.45, 0.0, 1.0); - float plateau = t * t * (3.0 - 2.0 * t); - float cliff_band = clamp(1.0 - abs(r - 0.74) * 5.0, 0.0, 1.0); - col = mix(brush_albedo, brush_albedo * 0.68, cliff_band); - alpha = clamp(plateau + cliff_band * 0.5, 0.0, 0.94); - } else if (brush_kind == 2) { - // SalvagePad: compacted gravel & weathered concrete slab - float env = 1.0 - r2; - env *= env; - float border = smoothstep(0.75, 0.92, sqrt(r2)); - col = mix(brush_albedo, vec3(0.32, 0.28, 0.24), border * 0.45); - alpha = clamp(env * 1.15, 0.0, 0.88); - } else if (brush_kind == 3) { - // Road: twin packed dirt ruts running longitudinally along u (cross-track offset abs(v)) - float env = 1.0 - r2; - env *= env; - float rut = smoothstep(0.15, 0.45, abs(v)) * (1.0 - smoothstep(0.60, 0.92, abs(v))); - col = mix(brush_albedo, brush_albedo * 0.76, rut); - alpha = env * (0.45 + 0.35 * rut); - } else if (brush_kind == 4) { - // Crater: charred pit center + bright rust ejecta rim - float r = sqrt(r2); - float pit = clamp(1.0 - r / 0.62, 0.0, 1.0); - float rim = sin(3.14159265 * clamp((r - 0.55) / 0.45, 0.0, 1.0)); - vec3 ejecta = vec3(0.62, 0.38, 0.22); - col = mix(ejecta, brush_albedo, clamp(pit * 1.3, 0.0, 1.0)); - alpha = clamp(max(pit * 0.94, rim * rim * 0.72), 0.0, 0.95); - } else if (brush_kind == 5) { - // Track: twin tire ruts along local X - float env = 1.0 - r2; - env *= env; - float treads = smoothstep(0.18, 0.45, abs(v)) * (1.0 - smoothstep(0.62, 0.92, abs(v))); - col = brush_albedo; - alpha = env * treads * 0.62; - } else if (brush_kind == 6) { - // Scorch - float r = sqrt(r2); - float mask = clamp(1.0 - r, 0.0, 1.0); - col = brush_albedo; - alpha = mask * mask * 0.88; - } - - COLOR = vec4(col, alpha); -} diff --git a/client/terrain_brush_sub.gdshader b/client/terrain_brush_sub.gdshader deleted file mode 100644 index 660e195..0000000 --- a/client/terrain_brush_sub.gdshader +++ /dev/null @@ -1,41 +0,0 @@ -shader_type canvas_item; -render_mode blend_sub; - -// Encodes negative height deltas (crater pits, dry washes, road ruts, tire ruts) into R. -uniform int brush_kind = 0; -uniform float height_delta = 0.0; -uniform float height_span = 70.0; - -void fragment() { - vec2 uv_local = UV * 2.0 - 1.0; - float u = uv_local.x; - float v = uv_local.y; - float r2 = u * u + v * v; - if (r2 >= 1.0) { - discard; - } - - float neg_dh = 0.0; - float neg_dg = 0.0; - if (brush_kind == 0) { - // Dry wash (negative DuneRidge) - float env = 1.0 - r2; - env *= env; - float ridge = max(0.0, 1.0 - u * u); - float asym = 1.0 + 0.32 * u; - neg_dh = max(0.0, -height_delta) * env * (0.35 + 0.65 * ridge) * asym; - } else if (brush_kind == 2 || brush_kind == 3 || brush_kind == 5) { - // SalvagePad (<0), Road, Track rut - float env = 1.0 - r2; - env *= env; - neg_dh = max(0.0, -height_delta) * env; - } else if (brush_kind == 4) { - // Crater pit - float r = sqrt(r2); - float depth = abs(height_delta); - float pit_t = clamp(1.0 - r / 0.62, 0.0, 1.0); - neg_dh = depth * pit_t * pit_t * (3.0 - 2.0 * pit_t); - } - - COLOR = vec4(neg_dh / height_span, neg_dg, 0.0, 1.0); -} diff --git a/client/terrain_surface.gdshader b/client/terrain_surface.gdshader index 706c6db..0818af1 100644 --- a/client/terrain_surface.gdshader +++ b/client/terrain_surface.gdshader @@ -1,18 +1,29 @@ shader_type spatial; render_mode cull_back, depth_draw_opaque; -uniform sampler2D height_tex : filter_linear, repeat_disable; -uniform sampler2D albedo_tex : source_color, filter_linear, repeat_disable; +uniform sampler2D base_dem_tex : filter_linear, repeat_disable; +uniform sampler2D base_surface_tex : source_color, filter_linear_mipmap, repeat_disable; +uniform sampler2D base_mask_tex : filter_linear_mipmap, repeat_disable; +uniform sampler2D delta_height_tex : filter_linear, repeat_disable; +uniform sampler2D delta_albedo_tex : source_color, filter_linear, repeat_disable; + +uniform float dem_min_y = 0.0; +uniform float dem_scale_span = 0.0; +uniform float dem_grid_res = 6145.0; uniform float height_min = -18.0; uniform float height_max = 52.0; +uniform float map_size = 1536.0; +uniform float tile_origin_x = 0.0; +uniform float tile_origin_z = 0.0; uniform float tile_size = 192.0; -uniform float inner_span = 253.0; -uniform float tex_size = 256.0; -uniform float gutter_offset = 1.5; +uniform float inner_span = 384.0; +uniform float tex_size = 388.0; +uniform float gutter_center = 2.5; +uniform float is_sion = 0.0; +uniform float tile_quads = 192.0; +uniform vec4 neighbor_quads = vec4(192.0, 192.0, 192.0, 192.0); // (-X, +X, -Z, +Z) -float decode_height(float h_norm) { - return mix(height_min, height_max, clamp(h_norm, 0.0, 1.0)); -} +varying vec3 v_world_pos; float hash21(vec2 p) { p = fract(p * vec2(123.34, 456.21)); @@ -20,37 +31,117 @@ float hash21(vec2 p) { return fract(p.x * p.y); } +float value_noise(vec2 p) { + vec2 i = floor(p); + vec2 f = fract(p); + vec2 u = f * f * (3.0 - 2.0 * f); + float a = hash21(i); + float b = hash21(i + vec2(1.0, 0.0)); + float c = hash21(i + vec2(0.0, 1.0)); + float d = hash21(i + vec2(1.0, 1.0)); + return mix(mix(a, b, u.x), mix(c, d, u.x), u.y); +} + vec2 to_baked_uv(vec2 mesh_uv) { - return (mesh_uv * inner_span + gutter_offset) / tex_size; + return (mesh_uv * inner_span + gutter_center) / tex_size; +} + +float sample_total_height(vec2 mesh_uv) { + vec2 world_xz = vec2(tile_origin_x, tile_origin_z) + mesh_uv * tile_size; + float base_h = 0.0; + if (is_sion > 0.5) { + float max_idx = dem_grid_res - 1.0; + vec2 dem_uv = ((world_xz + map_size * 0.5) / map_size * max_idx + 0.5) / dem_grid_res; + base_h = dem_min_y + textureLod(base_dem_tex, dem_uv, 0.0).r * dem_scale_span; + } + float delta_h = textureLod(delta_height_tex, to_baked_uv(mesh_uv), 0.0).r; + return clamp(base_h + delta_h, height_min, height_max); +} + +float sample_edge_snapped_height(vec2 uv) { + // Zero T-junction cracks: if an adjacent tile is coarser, snap edge vertex height + // onto the exact linear segment connecting the neighbor's coarse edge vertices. + if (uv.x < 0.0005 && neighbor_quads.x < tile_quads - 0.5) { + float nq = neighbor_quads.x; + float t = uv.y * nq; + float i0 = floor(t); + float u0 = i0 / nq; + float u1 = min(1.0, (i0 + 1.0) / nq); + return mix(sample_total_height(vec2(0.0, u0)), sample_total_height(vec2(0.0, u1)), t - i0); + } + if (uv.x > 0.9995 && neighbor_quads.y < tile_quads - 0.5) { + float nq = neighbor_quads.y; + float t = uv.y * nq; + float i0 = floor(t); + float u0 = i0 / nq; + float u1 = min(1.0, (i0 + 1.0) / nq); + return mix(sample_total_height(vec2(1.0, u0)), sample_total_height(vec2(1.0, u1)), t - i0); + } + if (uv.y < 0.0005 && neighbor_quads.z < tile_quads - 0.5) { + float nq = neighbor_quads.z; + float t = uv.x * nq; + float i0 = floor(t); + float u0 = i0 / nq; + float u1 = min(1.0, (i0 + 1.0) / nq); + return mix(sample_total_height(vec2(u0, 0.0)), sample_total_height(vec2(u1, 0.0)), t - i0); + } + if (uv.y > 0.9995 && neighbor_quads.w < tile_quads - 0.5) { + float nq = neighbor_quads.w; + float t = uv.x * nq; + float i0 = floor(t); + float u0 = i0 / nq; + float u1 = min(1.0, (i0 + 1.0) / nq); + return mix(sample_total_height(vec2(u0, 1.0)), sample_total_height(vec2(u1, 1.0)), t - i0); + } + return sample_total_height(uv); } void vertex() { - float h_norm = textureLod(height_tex, to_baked_uv(UV), 0.0).r; - VERTEX.y += decode_height(h_norm); + float h = sample_edge_snapped_height(UV); + VERTEX.y += h; + v_world_pos = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz; } void fragment() { - vec2 uv_baked = to_baked_uv(UV); - float texel_step = 1.0 / tex_size; - float world_step = tile_size / inner_span; + float world_step = tile_size / inner_span; // 0.5m + float uv_step = world_step / tile_size; - float hL = decode_height(texture(height_tex, uv_baked - vec2(texel_step, 0.0)).r); - float hR = decode_height(texture(height_tex, uv_baked + vec2(texel_step, 0.0)).r); - float hD = decode_height(texture(height_tex, uv_baked - vec2(0.0, texel_step)).r); - float hU = decode_height(texture(height_tex, uv_baked + vec2(0.0, texel_step)).r); + float hL = sample_total_height(UV - vec2(uv_step, 0.0)); + float hR = sample_total_height(UV + vec2(uv_step, 0.0)); + float hD = sample_total_height(UV - vec2(0.0, uv_step)); + float hU = sample_total_height(UV + vec2(0.0, uv_step)); vec3 world_normal = normalize(vec3(hL - hR, 2.0 * world_step, hD - hU)); NORMAL = normalize((VIEW_MATRIX * vec4(world_normal, 0.0)).xyz); - vec4 mat = texture(height_tex, uv_baked); - vec3 alb = texture(albedo_tex, uv_baked).rgb; - - // Subtle desert sand grain so dunes read crisply under sunlight (multiplicative in linear HDR) - float grain = (hash21(floor(UV * 768.0)) - 0.5) * 0.045; + vec2 uv_baked = to_baked_uv(UV); + vec4 mat = texture(delta_height_tex, uv_baked); + vec3 delta_alb = texture(delta_albedo_tex, uv_baked).rgb; float scorch = clamp(mat.b, 0.0, 1.0); - alb = clamp(alb * (1.0 + grain * 1.4), 0.0, 1.0) * (1.0 - 0.30 * scorch); + + vec3 alb; + float rough = clamp(mat.g, 0.35, 1.0); + if (is_sion > 0.5) { + vec2 world_uv = (v_world_pos.xz + map_size * 0.5) / map_size; + vec3 base_col = texture(base_surface_tex, world_uv).rgb; + vec4 cls = texture(base_mask_tex, world_uv); + alb = mix(base_col, delta_alb, clamp(mat.a, 0.0, 1.0)); + + float dist = length((INV_VIEW_MATRIX * vec4(0.0, 0.0, 0.0, 1.0)).xyz - v_world_pos); + float near_fade = clamp(1.0 - smoothstep(140.0, 480.0, dist), 0.12, 1.0); + float macro = (value_noise(v_world_pos.xz * 0.28) - 0.5) * 0.07; + float grit = (hash21(floor(v_world_pos.xz * 8.0)) - 0.5) * 0.045; + alb = clamp(alb * (1.0 + macro * 1.4 + grit * 1.6 * near_fade), 0.0, 1.0) * (1.0 - 0.32 * scorch); + + float base_rough = cls.r * 0.94 + cls.g * 0.90 + cls.b * 0.80 + cls.a * 0.26; + float cls_sum = max(0.001, cls.r + cls.g + cls.b + cls.a); + rough = mix(clamp(base_rough / cls_sum, 0.26, 0.96), rough, clamp(mat.a, 0.0, 1.0)); + } else { + float grain = (hash21(floor(UV * 768.0)) - 0.5) * 0.045; + alb = clamp(delta_alb * (1.0 + grain * 1.4), 0.0, 1.0) * (1.0 - 0.30 * scorch); + } ALBEDO = alb; - ROUGHNESS = clamp(mat.g, 0.35, 1.0); + ROUGHNESS = rough; METALLIC = 0.02; } diff --git a/client/terrain_tile_bake.glsl b/client/terrain_tile_bake.glsl new file mode 100644 index 0000000..96b0c42 --- /dev/null +++ b/client/terrain_tile_bake.glsl @@ -0,0 +1,176 @@ +#version 450 + +layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in; + +struct GpuBrush { + vec4 posRot; // x, z, cosR, sinR + vec4 radDelta; // invRx, invRz, heightDelta, maxRadiusSq + vec4 matColor; // albedoR, albedoG, albedoB, float(kind) +}; + +layout(set = 0, binding = 0, rgba16f) uniform writeonly image2D u_delta_height; +layout(set = 0, binding = 1, rgba8) uniform writeonly image2D u_delta_albedo; + +layout(set = 0, binding = 2, std430) readonly buffer BrushBuffer { + GpuBrush brushes[]; +} u_brushes; + +layout(push_constant, std430) uniform TileBakeParams { + vec4 tileOriginAndSpan; // x=tileMinX, y=tileMinZ, z=tileSize(192), w=innerSpan(384) + vec4 baseColorAndGutter; // rgb=clearAlbedo, w=gutterStart(2.0) + uvec4 counts; // x=brushStart, y=brushCount, z=texSize(388), w=isSion +} u_params; + +void main() { + ivec2 gid = ivec2(gl_GlobalInvocationID.xy); + int texSize = int(u_params.counts.z); + if (gid.x >= texSize || gid.y >= texSize) { + return; + } + + float tileMinX = u_params.tileOriginAndSpan.x; + float tileMinZ = u_params.tileOriginAndSpan.y; + float tileSize = u_params.tileOriginAndSpan.z; + float innerSpan = u_params.tileOriginAndSpan.w; + float gutterStart = u_params.baseColorAndGutter.w; + + float stepM = tileSize / innerSpan; + float wx = tileMinX + (float(gid.x) - gutterStart) * stepM; + float wz = tileMinZ + (float(gid.y) - gutterStart) * stepM; + + bool isSion = u_params.counts.w != 0u; + uint brushStart = u_params.counts.x; + uint brushEnd = brushStart + u_params.counts.y; + + float totalDh = 0.0; + float totalDg = 0.0; + float totalScorch = 0.0; + vec3 albedoAcc = u_params.baseColorAndGutter.rgb; + float deltaBlendAcc = isSion ? 0.0 : 1.0; + + for (uint i = brushStart; i < brushEnd; i++) { + GpuBrush b = u_brushes.brushes[i]; + float dx = wx - b.posRot.x; + float dz = wz - b.posRot.y; + if (dx * dx + dz * dz >= b.radDelta.w) { + continue; + } + + float cosR = b.posRot.z; + float sinR = b.posRot.w; + float lx = dx * cosR + dz * sinR; + float lz = -dx * sinR + dz * cosR; + + float u = lx * b.radDelta.x; + float v = lz * b.radDelta.y; + float r2 = u * u + v * v; + if (r2 >= 1.0) { + continue; + } + + int kind = int(b.matColor.w + 0.5); + float heightDelta = b.radDelta.z; + vec3 bCol = b.matColor.rgb; + float dh = 0.0; + float dg = 0.0; + float dScorch = 0.0; + vec3 col = bCol; + float alpha = 0.0; + + if (kind == 0) { + // DuneRidge + float env = 1.0 - r2; + env *= env; + float ridge = max(0.0, 1.0 - u * u); + float asym = 1.0 + 0.32 * u; + dh = heightDelta * env * (0.35 + 0.65 * ridge) * asym; + if (heightDelta > 0.0) { + dg = 0.02 * env; + } + col = mix(bCol * 0.90, bCol * 1.12, ridge); + alpha = env * 0.72; + } else if (kind == 1) { + // Mesa + float r = sqrt(r2); + float t = clamp((1.0 - r) / 0.45, 0.0, 1.0); + float plateau = t * t * (3.0 - 2.0 * t); + dh = heightDelta * plateau; + float cliffBand = clamp(1.0 - abs(r - 0.74) * 5.0, 0.0, 1.0); + col = mix(bCol, bCol * 0.68, cliffBand); + alpha = clamp(plateau + cliffBand * 0.5, 0.0, 0.94); + } else if (kind == 2) { + // SalvagePad + float env = 1.0 - r2; + env *= env; + dh = heightDelta * env; + if (heightDelta > 0.0) { + dg = 0.03 * env; + } + float border = smoothstep(0.75, 0.92, sqrt(r2)); + col = mix(bCol, vec3(0.32, 0.28, 0.24), border * 0.45); + alpha = clamp(env * 1.15, 0.0, 0.88); + } else if (kind == 3) { + // Road + float env = 1.0 - r2; + env *= env; + dh = heightDelta * env; + float rut = smoothstep(0.15, 0.45, abs(v)) * (1.0 - smoothstep(0.60, 0.92, abs(v))); + col = mix(bCol, bCol * 0.76, rut); + alpha = env * (0.45 + 0.35 * rut); + } else if (kind == 4) { + // Crater + float r = sqrt(r2); + float depth = abs(heightDelta); + float pitT = clamp(1.0 - r / 0.62, 0.0, 1.0); + float pit = -depth * pitT * pitT * (3.0 - 2.0 * pitT); + float rimT = sin(3.14159265 * clamp((r - 0.55) / 0.45, 0.0, 1.0)); + float rim = 0.32 * depth * rimT * rimT; + dh = pit + rim; + dg = 0.04 * (1.0 - r); + dScorch = 0.78 * clamp(1.0 - r * 0.9, 0.0, 1.0); + vec3 ejecta = isSion ? vec3(0.34, 0.31, 0.27) : vec3(0.62, 0.38, 0.22); + col = mix(ejecta, bCol, clamp(pitT * 1.3, 0.0, 1.0)); + alpha = clamp(max(pitT * 0.94, rimT * rimT * 0.72), 0.0, 0.95); + } else if (kind == 5) { + // Track + float env = 1.0 - r2; + env *= env; + dh = heightDelta * env; + dScorch = 0.32 * env; + float treads = smoothstep(0.18, 0.45, abs(v)) * (1.0 - smoothstep(0.62, 0.92, abs(v))); + col = bCol; + alpha = env * treads * 0.62; + } else if (kind == 6) { + // Scorch + float r = sqrt(r2); + float mask = clamp(1.0 - r, 0.0, 1.0); + float mask2 = mask * mask; + dg = 0.02 * mask2; + dScorch = 0.85 * mask2; + col = bCol; + alpha = mask2 * 0.88; + } else if (kind == 7) { + // Rubble + float env = 1.0 - r2; + env *= env; + float mound = 0.72 + 0.28 * cos(u * 3.14159265 * 2.5); + dh = heightDelta * env * mound; + dg = 0.08 * env; + dScorch = 0.35 * env; + float chunk = fract(sin(dot(floor(vec2(wx, wz) * 1.5), vec2(12.9898, 78.233))) * 43758.5453); + col = mix(bCol * 0.80, bCol * 1.15, chunk); + alpha = clamp(env * 1.2, 0.0, 0.96); + } + + totalDh += dh; + totalDg += dg; + totalScorch += dScorch; + albedoAcc = mix(albedoAcc, col, alpha); + deltaBlendAcc = max(deltaBlendAcc, alpha); + } + + float roughness = clamp(0.88 + totalDg, 0.35, 1.0); + float scorch = clamp(totalScorch, 0.0, 1.0); + imageStore(u_delta_height, gid, vec4(totalDh, roughness, scorch, clamp(deltaBlendAcc, 0.0, 1.0))); + imageStore(u_delta_albedo, gid, vec4(clamp(albedoAcc, 0.0, 1.0), 1.0)); +} diff --git a/client/tests/HbGpuProbe.cs b/client/tests/HbGpuProbe.cs new file mode 100644 index 0000000..aa8187c --- /dev/null +++ b/client/tests/HbGpuProbe.cs @@ -0,0 +1,233 @@ +using System; +using System.IO; +using System.Threading.Tasks; +using Godot; +using RustToDust.HbGpu; + +namespace RustToDust.Client.Tests; + +/// +/// Cut 14a visual & headless verification probe for HbGpuCanvas (1 Vulkan draw call). +/// Run headless: Godot --headless --audio-driver Dummy --path client res://tests/HbGpuProbe.tscn +/// Run Vulkan: Godot --audio-driver Dummy --windowed --path client res://tests/HbGpuProbe.tscn -- --capture-proof=path.png +/// +public partial class HbGpuProbe : Control +{ + private HbGpuCanvas _canvas = null!; + private bool _done; + private int _frameCount; + private string? _capturePath; + + public override void _Ready() + { + foreach (string arg in OS.GetCmdlineUserArgs()) + { + if (arg.StartsWith("--capture-proof=", StringComparison.Ordinal)) + { + _capturePath = arg["--capture-proof=".Length..]; + } + } + _capturePath ??= System.Environment.GetEnvironmentVariable("RTD_HBGPU_PROOF_PNG"); + + var bg = new ColorRect + { + Color = new Color(0.05f, 0.065f, 0.085f, 1.0f), + MouseFilter = MouseFilterEnum.Ignore + }; + AddChild(bg); + bg.SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect); + + _canvas = new HbGpuCanvas + { + Name = "HbGpuCanvas", + ProfilingEnabled = true + }; + AddChild(_canvas); + _canvas.SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect); + + _ = RunVerificationAsync(); + } + + private async Task RunVerificationAsync() + { + try + { + // Render enough frames to warm Vulkan pipeline & collect RD GPU timestamps + int targetFrames = _canvas.IsVulkanActive ? 24 : 3; + for (int i = 0; i < targetFrames; i++) + { + SubmitShowcaseFrame(i); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + _frameCount++; + } + + if (_canvas.LastQuadCount <= 0) + { + Fail("Expected LastQuadCount > 0 after submitting HbGpu showcase frame."); + return; + } + + if (!_canvas.IsVulkanActive) + { + GD.Print($"HBGPU_PROBE PASS (headless null-RD): quads={_canvas.LastQuadCount}, frames={_frameCount}"); + Finish(0); + return; + } + + if (_canvas.LastDrawCallCount != 1) + { + Fail($"Expected LastDrawCallCount == 1 on Vulkan, got {_canvas.LastDrawCallCount}."); + return; + } + + if (!_canvas.TryReadbackRgba8(out byte[] rgba, out int w, out int h)) + { + Fail("HbGpuCanvas.TryReadbackRgba8 returned false on active Vulkan device."); + return; + } + + int nonZero = 0; + int premulViolations = 0; + for (int i = 0; i + 3 < rgba.Length; i += 4) + { + byte r = rgba[i]; + byte g = rgba[i + 1]; + byte b = rgba[i + 2]; + byte a = rgba[i + 3]; + if (a > 0) + { + nonZero++; + } + if (r > a || g > a || b > a) + { + premulViolations++; + } + } + + if (nonZero < 1500) + { + Fail($"Expected >= 1500 rendered pixels in HbGpu Texture2Drd, got {nonZero} ({w}x{h})."); + return; + } + + if (premulViolations != 0) + { + Fail($"Premultiplied alpha invariant violated on {premulViolations} pixels."); + return; + } + + if (!string.IsNullOrWhiteSpace(_capturePath)) + { + SubmitShowcaseFrame(_frameCount); + await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw); + Image? vpImg = GetViewport().GetTexture()?.GetImage(); + if (vpImg is null) + { + Fail("Viewport capture returned null Image."); + return; + } + string? dir = Path.GetDirectoryName(_capturePath); + if (!string.IsNullOrEmpty(dir)) + { + Directory.CreateDirectory(dir); + } + Error saveErr = vpImg.SavePng(_capturePath); + if (saveErr != Error.Ok) + { + Fail($"Failed to save proof PNG '{_capturePath}': {saveErr}"); + return; + } + } + + GD.Print( + $"HBGPU_PROBE PASS (Vulkan): size={w}x{h}, quads={_canvas.LastQuadCount}, " + + $"draw_calls={_canvas.LastDrawCallCount}, gpu_ms={_canvas.LastHbGpuMs:F4}, " + + $"non_zero_px={nonZero}, premul_violations={premulViolations}"); + Finish(0); + } + catch (Exception ex) + { + Fail(ex.ToString()); + } + } + + private void SubmitShowcaseFrame(int frameIndex) + { + Color amber = new(0.95f, 0.72f, 0.22f, 1.0f); + Color cyan = new(0.32f, 0.86f, 0.96f, 1.0f); + Color slate = new(0.78f, 0.84f, 0.90f, 1.0f); + Color panelBg = new(0.06f, 0.09f, 0.12f, 0.78f); + Color alert = new(0.96f, 0.28f, 0.22f, 1.0f); + Color emerald = new(0.28f, 0.90f, 0.56f, 1.0f); + + _canvas.BeginFrame(); + + // Top-left panel backdrop + crisp Krypton typography across weights/slants/sizes + _canvas.DrawRectFilled(40f, 36f, 680f, 224f, panelBg); + _canvas.DrawLineSegment(40f, 36f, 720f, 36f, 2f, amber); + _canvas.DrawLineSegment(40f, 260f, 720f, 260f, 1.5f, new Color(amber, 0.5f)); + + _canvas.DrawText("RUST TO DUST // HB-GPU VULKAN", 60f, 84f, 32f, amber, wght: 700f); + _canvas.DrawText("CHASSIS: RAPTOR-7 | ALT: 142.8m | SPD: 28.4m/s", 60f, 124f, 20f, slate, wght: 550f); + _canvas.DrawText("CALT / LIGA: -> ==> != <= >= // 0x4F2A", 60f, 158f, 18f, cyan, wght: 350f); + _canvas.DrawText("SLANT -9 DEG // STEM DARKENED ANALYTIC SLUG", 60f, 192f, 15f, emerald, wght: 400f, slnt: -9f); + _canvas.DrawText("11PX MICRO TELEMETRY: 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ", 60f, 226f, 11f, slate, wght: 250f); + + // Center crosshair reticle + dynamic cubic Bezier thermal heat arc + float cx = 640f; + float cy = 400f; + _canvas.DrawCircleFilled(cx, cy, 3.5f, amber); + _canvas.DrawLineSegment(cx - 28f, cy, cx - 10f, cy, 2.0f, cyan); + _canvas.DrawLineSegment(cx + 10f, cy, cx + 28f, cy, 2.0f, cyan); + _canvas.DrawLineSegment(cx, cy - 28f, cx, cy - 10f, 2.0f, cyan); + _canvas.DrawLineSegment(cx, cy + 10f, cx, cy + 28f, 2.0f, cyan); + + float heatSweep = -2.356f + (0.65f + 0.1f * MathF.Sin(frameIndex * 0.1f)) * 4.712f; + _canvas.DrawArcStrokeDynamic(cx, cy, 62f, 5.5f, -2.356f, heatSweep, amber); + _canvas.DrawArcStrokeDynamic(cx, cy, 82f, 4.0f, -0.34f, 0.34f, alert); + + // Target lock corner brackets (all 4 quadrants) + float bx0 = 860f, by0 = 280f, bx1 = 1040f, by1 = 460f; + _canvas.DrawTargetBracketCorner(bx0, by0, 26f, 3.5f, 0, alert); + _canvas.DrawTargetBracketCorner(bx1, by0, 26f, 3.5f, 1, alert); + _canvas.DrawTargetBracketCorner(bx1, by1, 26f, 3.5f, 2, alert); + _canvas.DrawTargetBracketCorner(bx0, by1, 26f, 3.5f, 3, alert); + _canvas.DrawText("LOCK: SPECTATOR-02 [318m]", bx0, by0 - 12f, 14f, alert, wght: 600f); + + // Offscreen directional arrows + _canvas.DrawDirectionalArrow(1160f, 560f, 28f, 0.55f, amber); + _canvas.DrawDirectionalArrow(120f, 560f, 28f, -2.45f, alert); + + // Radar circle, safe ring, LOS lock line, diamond blip & chevron + float rx = 1080f, ry = 160f, rr = 96f; + _canvas.DrawCircleFilled(rx, ry, rr, new Color(0.04f, 0.07f, 0.09f, 0.85f)); + _canvas.DrawCircleRing(rx, ry, rr, 2.5f, cyan); + _canvas.DrawCircleRing(rx, ry, rr * 0.58f, 1.5f, new Color(emerald, 0.75f)); + _canvas.DrawLineSegment(rx, ry, rx + 44f, ry - 52f, 1.5f, new Color(alert, 0.85f)); + _canvas.Writer.DrawBlob( + HbGpuVectorShapes.GetDiamondBlip(_canvas.Blobs), + rx + 44f, ry - 52f, + 0.012f, 0f, 0f, -0.012f, 0f, 0f, + alert.R, alert.G, alert.B, alert.A); + _canvas.Writer.DrawBlob( + HbGpuVectorShapes.GetChevronTriangle(_canvas.Blobs), + rx, ry, + 0.014f, 0f, 0f, -0.014f, 0f, 0f, + emerald.R, emerald.G, emerald.B, emerald.A); + + _canvas.EndFrameAndSubmit(); + } + + private void Fail(string msg) + { + GD.PrintErr("HBGPU_PROBE FAIL: " + msg); + Finish(1); + } + + private void Finish(int code) + { + if (_done) return; + _done = true; + GetTree().Quit(code); + } +} diff --git a/client/tests/HbGpuProbe.tscn b/client/tests/HbGpuProbe.tscn new file mode 100644 index 0000000..ee00a32 --- /dev/null +++ b/client/tests/HbGpuProbe.tscn @@ -0,0 +1,12 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://tests/HbGpuProbe.cs" id="1"] + +[node name="HbGpuProbe" type="Control"] +layout_mode = 3 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +script = ExtResource("1") diff --git a/client/tests/Smoke.cs b/client/tests/Smoke.cs index a7a47be..8b30805 100644 --- a/client/tests/Smoke.cs +++ b/client/tests/Smoke.cs @@ -203,11 +203,11 @@ public partial class Smoke : Node } } - // Regression check (Finding 4): 4-tile boundary crater at (0, 0) bakes all 4 tiles on Sync#1 (<= 0.20m error on all 4 quadrants) - // and passive Track throttling preserves DirtyTileMask until all tiles are baked without skipping via _rebakeCursor. + // Regression check: 4-tile boundary crater at (0, 0) bakes all 4 tiles on Sync#1 (<= 0.20m error on all 4 quadrants) + // and passive Track throttling (MaxDirtyRebakesPerSync=4) preserves pending visual versions until all tiles are baked without skipping via _rebakeCursor. { // Flush any lingering track rebakes first so baseline is clean - for (int flush = 0; flush < 32 && _main.Session.ViewState.Terrain.DirtyTileMask != 0UL; flush++) + for (int flush = 0; flush < 32 && _main.Terrain.CountPendingDirtyVisualTiles(_main.Session.ViewState.Terrain) > 0; flush++) { _main.Terrain.Sync(_main.Session.ViewState.Terrain); } @@ -229,8 +229,8 @@ public partial class Smoke : Node _main.Terrain.Sync(_main.Session.ViewState.Terrain); // Sync#1 Check(_main.Terrain.DirtyRebakes == rebakes4Before + 4, $"Expected 4-tile boundary crater at (0,0) to bake all 4 tiles on Sync#1, got {_main.Terrain.DirtyRebakes - rebakes4Before}"); - Check(_main.Session.ViewState.Terrain.StructuralDirtyTileMask == 0UL, - "Expected StructuralDirtyTileMask == 0 after Sync#1 on 4-tile boundary crater"); + Check(_main.Terrain.CountPendingDirtyVisualTiles(_main.Session.ViewState.Terrain) == 0, + "Expected 0 pending dirty tiles after Sync#1 on 4-tile boundary crater"); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); @@ -252,21 +252,23 @@ public partial class Smoke : Node } } - // Stamp 3 passive tracks in adjacent tiles so _rebakeCursor must advance across Sync#1 and Sync#2 without skipping + // Stamp 5 passive tracks in distinct tiles so _rebakeCursor advances across Sync#1 (4) and Sync#2 (1) without skipping int rebakesTrackBefore = _main.Terrain.DirtyRebakes; _main.Session.ViewState.Terrain.StampTrack(-480f, -480f, 0f, 2f, 3f); _main.Session.ViewState.Terrain.StampTrack(-288f, -480f, 0f, 2f, 3f); _main.Session.ViewState.Terrain.StampTrack(-96f, -480f, 0f, 2f, 3f); + _main.Session.ViewState.Terrain.StampTrack(96f, -480f, 0f, 2f, 3f); + _main.Session.ViewState.Terrain.StampTrack(288f, -480f, 0f, 2f, 3f); _main.Terrain.Sync(_main.Session.ViewState.Terrain); - Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 2, - $"Expected Sync#1 to throttle 3 passive tracks to 2 rebakes, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}"); - Check(_main.Session.ViewState.Terrain.DirtyTileMask != 0UL, - "Expected DirtyTileMask to stay non-zero while 1 passive track tile remains dirty"); + Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 4, + $"Expected Sync#1 to throttle 5 passive tracks to 4 rebakes, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}"); + Check(_main.Terrain.CountPendingDirtyVisualTiles(_main.Session.ViewState.Terrain) == 1, + "Expected 1 pending dirty track tile remaining after Sync#1"); _main.Terrain.Sync(_main.Session.ViewState.Terrain); - Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 3, - $"Expected Sync#2 to bake remaining 3rd passive track tile without _rebakeCursor skip, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}"); - Check(_main.Session.ViewState.Terrain.DirtyTileMask == 0UL, - "Expected DirtyTileMask == 0 after all passive track tiles baked"); + Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 5, + $"Expected Sync#2 to bake remaining 5th passive track tile without _rebakeCursor skip, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}"); + Check(_main.Terrain.CountPendingDirtyVisualTiles(_main.Session.ViewState.Terrain) == 0, + "Expected 0 pending dirty tiles after all passive track tiles baked"); } _main.SetPhysicsProcess(true); @@ -279,6 +281,7 @@ public partial class Smoke : Node await VerifyOrbitalDropSequenceAsync(); await VerifyCut7bModularOrdnanceAsync(); VerifyForwardPlusAtmosphere(); + await VerifyGpuSparksRenderAsync(isHeadless); } private async Task VerifyHudAndShadersAsync(bool isHeadless) @@ -286,15 +289,23 @@ public partial class Smoke : Node var invShader = _main.Hud.Schematic.ShaderMaterial.Shader; Check(invShader is not null && !string.IsNullOrWhiteSpace(invShader.Code), "inventory_grid.gdshader failed to load"); + Check(_main.Hud.HbCanvas is not null, "Expected Hud.HbCanvas to be initialized"); - int chromeCount = 0; - foreach (var mat in _main.Hud.GetChromeMaterials()) + // Warm up HUD HbGpuCanvas and verify steady-state Sync allocates zero managed bytes + _main.Hud.Sync(_main.Session); + _main.Hud.Sync(_main.Session); + _main.Hud.Sync(_main.Session); + Check(_main.Hud.HbCanvas!.LastQuadCount > 50, + $"Expected Hud.HbCanvas.LastQuadCount > 50 after Sync, got {_main.Hud.HbCanvas.LastQuadCount}"); + long gcBefore = GC.GetAllocatedBytesForCurrentThread(); + for (int i = 0; i < 16; i++) { - chromeCount++; - Check(mat.Shader is not null && !string.IsNullOrWhiteSpace(mat.Shader.Code), - $"panel_chrome.gdshader failed to load on HUD panel #{chromeCount}"); + _main.Hud.Sync(_main.Session); } - Check(chromeCount == 6, $"Expected 6 ChromePanel materials on HUD, got {chromeCount}"); + long gcAfter = GC.GetAllocatedBytesForCurrentThread(); + long gcDelta = gcAfter - gcBefore; + GD.Print($"SMOKE INFO: Steady-state Hud.Sync x16 managed allocs={gcDelta} B"); + Check(gcDelta == 0, $"Expected 0 B managed allocations across steady-state Hud.Sync x16, got {gcDelta} B"); // Pack a real Ironclad chassis with mounted modules, thermal gradient, stripped cell, and active hit-pulse var testGrid = new ChassisGrid(Catalog.Ironclad); @@ -487,7 +498,7 @@ public partial class Smoke : Node Check(raptorHoleScanned > 1000, $"Expected > 1000 inactive hole pixels scanned on Raptor, got {raptorHoleScanned}"); Check(raptorHoleLit == 0, $"Expected 0 lit/opaque pixels in inactive Raptor cell holes, got {raptorHoleLit}"); - // Finding 5 GPU check: LabelsOverlay redraws on temp-only change & compatibility highlights update when Cargo[0] swaps at unchanged index 0 + // Cut 14b GPU check: HbGpuCanvas overlay re-emits on temp-only change & compatibility highlights update when Cargo[0] swaps at unchanged index 0 { raptorGrid.Cargo.Clear(); Check(raptorGrid.TryAddCargo(Catalog.Autocannon), "Expected Autocannon in Raptor Cargo[0]"); @@ -495,8 +506,8 @@ public partial class Smoke : Node await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); - int drawCountBeforeTemp = vpGrid.LabelsDrawCount; - string? tagBeforeTemp = vpGrid.GetLastDrawnLabel("hp.engine.chest"); + int emitCountBeforeTemp = vpGrid.OverlayEmitCount; + string? tagBeforeTemp = vpGrid.GetLastEmittedLabel("hp.engine.chest"); var cargoImgWeapon = gridVp.GetTexture().GetImage(); // Temp-only change (no armor hit, no mount change) @@ -506,10 +517,10 @@ public partial class Smoke : Node await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); - int drawCountAfterTemp = vpGrid.LabelsDrawCount; - string? tagAfterTemp = vpGrid.GetLastDrawnLabel("hp.engine.chest"); - Check(drawCountAfterTemp > drawCountBeforeTemp, - $"Expected LabelsOverlay to redraw on temp-only change ({drawCountBeforeTemp} -> {drawCountAfterTemp})"); + int emitCountAfterTemp = vpGrid.OverlayEmitCount; + string? tagAfterTemp = vpGrid.GetLastEmittedLabel("hp.engine.chest"); + Check(emitCountAfterTemp > emitCountBeforeTemp, + $"Expected InventoryGridControl HbGpu overlay to re-emit on temp-only change ({emitCountBeforeTemp} -> {emitCountAfterTemp})"); Check(!string.Equals(tagBeforeTemp, tagAfterTemp, StringComparison.Ordinal), $"Expected engine temp label text to update on temp-only change ('{tagBeforeTemp}' -> '{tagAfterTemp}')"); @@ -524,47 +535,31 @@ public partial class Smoke : Node GD.Print($"SMOKE INFO: InventoryGrid Cargo[0] swap diff pixels={cargoDiff}, label '{tagBeforeTemp}'->'{tagAfterTemp}'"); Check(cargoDiff > 50, $"Expected Cargo[0] replacement at unchanged index 0 to update compatibility highlight pixels (>50), got {cargoDiff}"); + Check(vpGrid.StandaloneCanvas is { LastDrawCallCount: 1 }, + $"Expected standalone InventoryGridControl HbGpuCanvas to render in 1 draw call, got {vpGrid.StandaloneCanvas?.LastDrawCallCount ?? -1}"); } gridVp.QueueFree(); - // GPU verification for panel_chrome.gdshader - var chromeVp = new SubViewport - { - Size = new Vector2I(240, 120), - TransparentBg = true, - RenderTargetUpdateMode = SubViewport.UpdateMode.Always - }; - var chromeShader = GD.Load("res://panel_chrome.gdshader"); - var chromeMat = new ShaderMaterial { Shader = chromeShader }; - chromeMat.SetShaderParameter("rect_size", new Vector2(240f, 120f)); - chromeMat.SetShaderParameter("accent_color", Color.FromHtml("#e08a4a")); - var chromeImgTex = Image.CreateEmpty(1, 1, false, Image.Format.Rgba8); - chromeImgTex.SetPixel(0, 0, Colors.White); - var chromeRect = new TextureRect - { - Texture = ImageTexture.CreateFromImage(chromeImgTex), - Size = new Vector2(240f, 120f), - ExpandMode = TextureRect.ExpandModeEnum.IgnoreSize, - StretchMode = TextureRect.StretchModeEnum.Scale, - Material = chromeMat - }; - chromeVp.AddChild(chromeRect); - AddChild(chromeVp); - + // Cut 14b Vulkan single-draw-call verification on live Hud.HbCanvas + _main.Hud.Sync(_main.Session); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); - - var chromeImg = chromeVp.GetTexture().GetImage(); - int chromeOpaque = CountNonZeroAlphaPixels(chromeImg, 0.08f); - Color cornerPx = chromeImg.GetPixel(2, 2); - Color centerPx = chromeImg.GetPixel(120, 60); - GD.Print($"SMOKE INFO: panel_chrome GPU opaque={chromeOpaque}, corner={cornerPx}, center={centerPx}"); - Check(chromeOpaque > 10000, $"Expected > 10000 rendered pixels from panel_chrome.gdshader, got {chromeOpaque}"); - Check(cornerPx.R > centerPx.R + 0.25f, - $"Expected L-bracket corner pixel ({cornerPx}) to be accented brighter than panel center ({centerPx})"); - - chromeVp.QueueFree(); + var hudHb = _main.Hud.HbCanvas; + Check(hudHb.LastDrawCallCount == 1, $"Expected Hud.HbCanvas LastDrawCallCount == 1, got {hudHb.LastDrawCallCount}"); + Check(hudHb.TryReadbackRgba8(out byte[] hudRgba, out int hudW, out int hudH), + "Expected Hud.HbCanvas.TryReadbackRgba8 to succeed on Vulkan"); + int hudNonZero = 0; + int hudPremulViol = 0; + for (int i = 0; i + 3 < hudRgba.Length; i += 4) + { + byte r = hudRgba[i], g = hudRgba[i + 1], b = hudRgba[i + 2], a = hudRgba[i + 3]; + if (a > 0) hudNonZero++; + if (r > a || g > a || b > a) hudPremulViol++; + } + GD.Print($"SMOKE INFO: Hud.HbCanvas Vulkan {hudW}x{hudH} quads={hudHb.LastQuadCount}, drawCalls={hudHb.LastDrawCallCount}, nonZeroPx={hudNonZero}, premulViol={hudPremulViol}"); + Check(hudNonZero > 4000, $"Expected > 4000 rendered pixels in Hud.HbCanvas, got {hudNonZero}"); + Check(hudPremulViol == 0, $"Expected 0 premul violations in Hud.HbCanvas, got {hudPremulViol}"); } private async Task MaybeCapturePreviewAsync(bool isHeadless) @@ -1163,7 +1158,7 @@ public partial class Smoke : Node $"Expected PomDecalPool to hold >= 1 active decal, got {_main.Arena.PomDecals.ActiveCount}"); _main.Hud.PushTestHitArc(localC.X + 20f, localC.Z + 10f, WeaponVisualClass.Explosive); - Check(_main.Hud.ActiveHitArcCount >= 1, "Expected CrosshairOverlay to accept incoming hit arc"); + Check(_main.Hud.ActiveHitArcCount >= 1, "Expected Hud HbGpuCanvas to accept incoming hit arc"); } // 11. Finding 1: Merged MultiMeshPartPool meshes preserve real non-white material albedos and intact COLOR_0.R AO @@ -1236,11 +1231,34 @@ public partial class Smoke : Node $"Expected zero StandardMaterial3D duplicates, got {VehicleVisualInstance.PerfMaterialDupCount}"); } - // 12. Cut 5d-2: Unified SimEvent -> ParticlePool idempotency + OmniLight3D[4] cap + CameraJuice zero-idle-jitter + Hud X-flash & vignette + // 12. Cut 5d-2 + Cut 10b: Unified SimEvent -> GpuSparksSystem + VolumetricEmitterPool idempotency + OmniLight3D[2] cap + global rtd_flow_field + CameraJuice + Hud X-flash { var particles = _main.Arena.Particles; + var volumetrics = _main.Arena.Volumetrics; + var gpuSparks = _main.Arena.GpuSparks; particles.ClearAll(); - int beforeCount = particles.ActiveParticleCount; + volumetrics.ClearAll(); + gpuSparks.ClearAll(); + + // Verify Cut 10b structural subtraction & GPUParticles3D / global shader param wiring + Check(!FileAccess.FileExists("res://particle_billboard.gdshader"), + "Expected obsolete particle_billboard.gdshader to be deleted"); + int particleMmiCount = 0; + foreach (Node ch in particles.GetChildren()) + { + if (ch is MultiMeshInstance3D) particleMmiCount++; + } + Check(particleMmiCount == 0, + $"Expected zero MultiMeshInstance3D nodes inside collapsed ParticlePool, found {particleMmiCount}"); + Check(gpuSparks.ParticlesNode.Amount == GpuSparksSystem.Capacity && gpuSparks.ParticlesNode.AmountRatio == 0.0f, + $"Expected GpuSparksSystem Amount={GpuSparksSystem.Capacity} AmountRatio=0.0f, got {gpuSparks.ParticlesNode.Amount} ratio={gpuSparks.ParticlesNode.AmountRatio}"); + + Check(AtmosphereSystem.AreFlowGlobalsRegistered, + "Expected global rtd_flow_* shader parameters registered in AtmosphereSystem"); + + int beforeSparks = gpuSparks.TotalEmittedCount; + int beforeVol = volumetrics.ActiveEmitterCount; + int beforeImp = volumetrics.ActiveImpulseCount; int tracerId = _main.Session.ViewState.AllocateTracerId(); var localC = _main.Session.LocalContender; @@ -1265,15 +1283,17 @@ public partial class Smoke : Node var simBatch = new List { shotEvent }; var emptyFootsteps = new List(); _main.Arena.ConsumeEvents(_main.Session, simBatch, emptyFootsteps, 0f, _main.SampleCurrentMapGroundTint); - int afterFirst = particles.ActiveParticleCount; - Check(afterFirst == beforeCount + 5, - $"Expected recoilless ShotFiredEvent #{tracerId} to spawn 1 muzzle starburst + 4 smoke puffs (+5 particles), got +{afterFirst - beforeCount}"); + int afterSparks = gpuSparks.TotalEmittedCount; + int afterVol = volumetrics.ActiveEmitterCount; + int afterImp = volumetrics.ActiveImpulseCount; + Check(afterSparks >= beforeSparks + 1 && afterVol >= beforeVol + 1 && afterImp >= beforeImp + 1, + $"Expected recoilless ShotFiredEvent #{tracerId} to emit GPU muzzle flash/sparks (+{afterSparks - beforeSparks}), volumetric breech puff (+{afterVol - beforeVol}), and flow impulse (+{afterImp - beforeImp})"); // Re-consume with dt=0: idempotent TracerId dedupe must NOT double-emit _main.Arena.ConsumeEvents(_main.Session, simBatch, emptyFootsteps, 0f, _main.SampleCurrentMapGroundTint); _main.Arena.ConsumeEvents(_main.Session, simBatch, emptyFootsteps, 0f, _main.SampleCurrentMapGroundTint); - Check(particles.ActiveParticleCount == afterFirst, - $"Expected duplicate ShotFiredEvent #{tracerId} across dt=0 frames to spawn once, got {afterFirst} -> {particles.ActiveParticleCount}"); + Check(gpuSparks.TotalEmittedCount == afterSparks && volumetrics.ActiveEmitterCount == afterVol && volumetrics.ActiveImpulseCount == afterImp, + $"Expected duplicate ShotFiredEvent #{tracerId} across dt=0 frames to spawn once, got sparks {afterSparks}->{gpuSparks.TotalEmittedCount}, vol {afterVol}->{volumetrics.ActiveEmitterCount}"); // OmniLight3D[2] pool strictly capped at <= 2 active lights even under 12 simultaneous flashes particles.ClearAll(); @@ -1291,8 +1311,10 @@ public partial class Smoke : Node Check(particles.FlashLightPoolSize == 2 && particles.ActiveFlashLightCount <= 2 && particles.PeakFlashLightCount <= 2, $"Expected OmniLight3D pool capped at <= 2, got active={particles.ActiveFlashLightCount} peak={particles.PeakFlashLightCount}"); - // Far walker footstep pulse (>70m static LOD, <=110m) still emits terrain-tinted dust in ParticlePool + // Far walker footstep pulse (>70m static LOD, <=110m) emits GPU dust motes + optional volumetric puff particles.ClearAll(); + volumetrics.ClearAll(); + gpuSparks.ClearAll(); var farStep = new FootstepPulse( IsContender: true, EntityId: 99, @@ -1302,9 +1324,11 @@ public partial class Smoke : Node LoadG: 1.25f, WorldPos: new System.Numerics.Vector3(pPos.X + 85f, pPos.Y, pPos.Z)); _main.Arena.ConsumeEvents(_main.Session, Array.Empty(), new[] { farStep }, 0f, _main.SampleCurrentMapGroundTint); - Check(particles.ActiveParticleCount >= 3, - $"Expected far walker (85m > 70m static LOD) footstep to emit dust puffs, got {particles.ActiveParticleCount}"); + Check(gpuSparks.TotalEmittedCount >= 4 && volumetrics.ActiveEmitterCount >= 1, + $"Expected far walker (85m > 70m static LOD) footstep to emit GPU dust motes ({gpuSparks.TotalEmittedCount}) + volumetric puff ({volumetrics.ActiveEmitterCount})"); particles.ClearAll(); + volumetrics.ClearAll(); + gpuSparks.ClearAll(); // CameraJuiceState zero-idle-jitter & ComputeCenterScreenAim invariance under trauma var juice = _main.CameraJuice; @@ -1598,10 +1622,14 @@ public partial class Smoke : Node Check(audio.CountActiveUiVoicesForClip("mech_quick_bolt") == 1, $"Expected first ContenderLoadoutEvent (1 -> 2) after ResetForSession to play mech_quick_bolt, got {audio.CountActiveUiVoicesForClip("mech_quick_bolt")}"); - // Finding 3: Out-of-PVS deaths spawn zero phantom particles, lights, or audio + // Finding 3: Out-of-PVS deaths spawn zero phantom volumetric emitters, GPU sparks, lights, or audio audio.ResetForSession(_main.Session); var particles3 = _main.Arena.Particles; + var volumetrics3 = _main.Arena.Volumetrics; + var gpuSparks3 = _main.Arena.GpuSparks; particles3.ClearAll(); + volumetrics3.ClearAll(); + gpuSparks3.ClearAll(); var hiddenSession = new HiddenRemoteDeathsSession(_main.Session); var spec0 = _main.Session.ViewState.Spectators.Spectators[0]; var hiddenDeaths = new ISimEvent[] @@ -1612,9 +1640,11 @@ public partial class Smoke : Node particles3.ConsumeEvents(hiddenSession, hiddenDeaths, listener, hasCam: true, _main.SampleCurrentMapGroundTint); particles3.AdvanceAndCommit(0f); audio.ConsumeSimEvents(hiddenSession, hiddenDeaths, listener); - Check(particles3.ActiveParticleCount == 0 && particles3.ActiveFlashLightCount == 0 && audio.ActiveOneShotVoiceCount == 0, - $"Expected out-of-PVS deaths to spawn 0 VFX/SFX, got particles={particles3.ActiveParticleCount} lights={particles3.ActiveFlashLightCount} voices={audio.ActiveOneShotVoiceCount}"); + Check(gpuSparks3.TotalEmittedCount == 0 && volumetrics3.ActiveEmitterCount == 0 && particles3.ActiveFlashLightCount == 0 && audio.ActiveOneShotVoiceCount == 0, + $"Expected out-of-PVS deaths to spawn 0 VFX/SFX, got sparks={gpuSparks3.TotalEmittedCount} vol={volumetrics3.ActiveEmitterCount} lights={particles3.ActiveFlashLightCount} voices={audio.ActiveOneShotVoiceCount}"); particles3.ClearAll(); + volumetrics3.ClearAll(); + gpuSparks3.ClearAll(); GD.Print($"SMOKE INFO: Audio verified (haven={audio.Bank.HavenClipCount}, proc={audio.Bank.ProceduralClipCount}, dummy={audio.IsDummyAudio}, kestrelPitch={kestrelPitch:F3}, bastionPitch={bastionPitch:F3})"); } @@ -1833,12 +1863,21 @@ public partial class Smoke : Node var sionState = _main.Session.ViewState; Check(_main.MapKind == ArenaMapKind.Sion && sionState.MapKind == ArenaMapKind.Sion, "Expected Sion map kind after Reset"); - Check(_main.SionMap.Visible && !_main.Terrain.Visible, "Expected SionMapRenderer visible and Desert TerrainRenderer hidden"); + Check(_main.Terrain.Visible && _main.SionMap.Visible, "Expected unified TerrainRenderer and SionMapRenderer buildings visible on Sion"); + Check(_main.Terrain.BakedTileCount == 256, $"Expected 256 unified Sion terrain tiles (16x16), got {_main.Terrain.BakedTileCount}"); + Check(_main.Terrain.ActiveGpuScarSlots == 0, $"Expected 0 active GPU scar slots on clean Sion start, got {_main.Terrain.ActiveGpuScarSlots}"); Check(_main.SionMap.IsBuilt, "Expected SionMapRenderer.IsBuilt == true"); - Check(_main.SionMap.TerrainChunkCount == 36, $"Expected 36 Sion terrain chunks, got {_main.SionMap.TerrainChunkCount}"); 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}"); @@ -1882,14 +1921,31 @@ public partial class Smoke : Node float disp = MathF.Sqrt((player.X - startX) * (player.X - startX) + (player.Z - startZ) * (player.Z - startZ)); Check(disp > 1.5f, $"Expected player displacement > 1.5m on Sion after 30 frames, got {disp:F2}m"); - Color inBoundsTint = _main.SionMap.SampleGroundTint(player.X, player.Z); - Color outBoundsTint = _main.SionMap.SampleGroundTint(9999f, 9999f); + Color inBoundsTint = _main.Terrain.SampleGroundTint(player.X, player.Z); + Color outBoundsTint = _main.Terrain.SampleGroundTint(9999f, 9999f); Check(float.IsFinite(inBoundsTint.R) && float.IsFinite(inBoundsTint.G) && float.IsFinite(inBoundsTint.B) && inBoundsTint.R > 0.1f, $"Expected valid Sion SampleGroundTint at player pos, got {inBoundsTint}"); Check(MathF.Abs(outBoundsTint.R - 0.56f) < 0.01f && MathF.Abs(outBoundsTint.G - 0.53f) < 0.01f, $"Expected neutral alpine fallback tint outside Sion bounds, got {outBoundsTint}"); - GD.Print($"SMOKE INFO: Sion verified (chunks={_main.SionMap.TerrainChunkCount}, tiles={_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}))"); + // Verify live crater brush on Sion allocates sparse GPU scar slot & depresses GPU height + float sionCpuPre = sionState.Terrain.SampleHeight(player.X, player.Z); + sionState.Terrain.StampCrater(player.X, player.Z, radius: 5.0f, depth: 1.5f); + _main.Terrain.Sync(sionState.Terrain, sionState.SionMap); + Check(_main.Terrain.ActiveGpuScarSlots >= 1, $"Expected >= 1 active GPU scar slot on Sion after crater, got {_main.Terrain.ActiveGpuScarSlots}"); + if (DisplayServer.GetName() != "headless") + { + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + Check(_main.Terrain.TrySampleBakedHeight(player.X, player.Z, out float sionGpuPost), + "Expected TrySampleBakedHeight to succeed on Sion crater tile"); + float sionCpuPost = sionState.Terrain.SampleHeight(player.X, player.Z); + Check(MathF.Abs(sionGpuPost - sionCpuPost) <= 0.25f, + $"Expected Sion GPU crater height ({sionGpuPost:F3}m) to match CPU ({sionCpuPost:F3}m) within 0.25m"); + Check(sionGpuPost < sionCpuPre - 0.8f, + $"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}, 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() @@ -1935,9 +1991,12 @@ public partial class Smoke : Node bool sawRetroBurn = false; bool sawGearEarlyTouchdown = false; + bool sawWideDropFov = false; int touchdownTick = -1; int debrisAtTouchdown = 0; + Check(session.ViewState.SquadSize == 3, $"Expected Solo Sion default SquadSize == 3, got {session.ViewState.SquadSize}"); + _main.SetScriptedInput(new PlayerInput( Throttle: 1f, Steer: 0f, @@ -1947,7 +2006,7 @@ public partial class Smoke : Node InteractPickup: false, Brake: false)); - for (int tick = 0; tick < 620; tick++) + for (int tick = 0; tick < 2000; tick++) { var tickInp = _main.Session.LocalContender.IsInDropPod ? new PlayerInput(1f, 0f, player.X, player.Z + 120f, false, false, false) @@ -1960,26 +2019,40 @@ public partial class Smoke : Node session.DrainSimEvents(evs); _main.Arena.ConsumeEvents(session, evs, Array.Empty(), 1f / 60f, _main.SampleCurrentMapGroundTint); _main.CameraJuice.ConsumeEvents(evs, session.LocalContenderId, new System.Numerics.Vector3(player.X, player.Y, player.Z), session); - _main.Audio.UpdateFrame(session, evs, Array.Empty(), _main.Camera.GlobalPosition, 1f / 60f, 1f); - _main.Hud.Sync(session); - - if (tick == 270) // t = 4.5s: gear pods should have landed while player is still falling - { - sawGearEarlyTouchdown = session.ViewState.GroundDrops.Count >= 35 && player.IsInDropPod; - } + OrbitalPodPhase podPhase = OrbitalPodPhase.Freefall; + float dropHorizSpeed = player.Speed; if (player.IsInDropPod) { foreach (var pod in session.ActivePods) { - if (pod.PodKind == OrbitalPodKind.Contender && pod.ContenderId == player.Id && pod.Phase == OrbitalPodPhase.RetroBurn) + if (pod.PodKind == OrbitalPodKind.Contender && pod.ContenderId == player.Id) { - sawRetroBurn = true; + podPhase = pod.Phase; + dropHorizSpeed = MathF.Sqrt(pod.VelX * pod.VelX + pod.VelZ * pod.VelZ); + if (pod.Phase == OrbitalPodPhase.RetroBurn) + { + sawRetroBurn = true; + } break; } } } - else if (touchdownTick < 0 && player.IsGroundedActive) + _main.CameraJuice.Update(1f / 60f, dropHorizSpeed, player.Grid.Spec.IsVtol, player.IsInDropPod, podPhase); + if (player.IsInDropPod && (CameraJuiceState.BaseFovDeg + _main.CameraJuice.FovOffsetDeg) >= 80f) + { + sawWideDropFov = true; + } + + _main.Audio.UpdateFrame(session, evs, Array.Empty(), _main.Camera.GlobalPosition, 1f / 60f, 1f); + _main.Hud.Sync(session); + + if (!sawGearEarlyTouchdown && session.ViewState.GroundDrops.Count >= 35 && player.IsInDropPod) + { + sawGearEarlyTouchdown = true; + } + + if (!player.IsInDropPod && touchdownTick < 0 && player.IsGroundedActive) { touchdownTick = tick; debrisAtTouchdown = _main.Arena.Debris.ActiveCount; @@ -1987,9 +2060,10 @@ public partial class Smoke : Node } } - Check(sawGearEarlyTouchdown, $"Expected >= 35 Wave 0 gear drops on ground at t=4.5s while player still in pod (drops={session.ViewState.GroundDrops.Count}, inPod={player.IsInDropPod})"); + Check(sawGearEarlyTouchdown, $"Expected >= 35 Wave 0 gear drops on ground while player still in pod (drops={session.ViewState.GroundDrops.Count}, inPod={player.IsInDropPod})"); Check(sawRetroBurn, "Expected local player pod to enter RetroBurn phase"); - Check(touchdownTick > 240 && touchdownTick < 620, $"Expected player pod touchdown in (240, 620) ticks, got {touchdownTick}"); + Check(sawWideDropFov, $"Expected wide drop-camera FOV >= 80 deg during Freefall, peak offset={_main.CameraJuice.FovOffsetDeg:F2}"); + Check(touchdownTick > 1000 && touchdownTick < 2000, $"Expected Sion 1620m player pod touchdown in (1000, 2000) ticks, got {touchdownTick}"); Check(debrisAtTouchdown >= 4, $"Expected >= 4 blown-off petals in DebrisSystem on touchdown, got {debrisAtTouchdown}"); Check(VehicleVisualInstance.PerfMaterialDupCount == 0, $"Expected 0 material duplicates during orbital drop, got {VehicleVisualInstance.PerfMaterialDupCount}"); @@ -2167,9 +2241,8 @@ public partial class Smoke : Node _main.Hud.SimulateCellHover(new Vector2I(pWeaponHpSpec.X, pWeaponHpSpec.Y), pWeaponHpSpec); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); - int chromeCount = 0; - foreach (var _ in _main.Hud.GetChromeMaterials()) chromeCount++; - Check(chromeCount == 6, $"Expected 6 HUD chrome panels, got {chromeCount}"); + Check(_main.Hud.HbCanvas.LastQuadCount > 50, + $"Expected Hud.HbCanvas.LastQuadCount > 50 in Garage mode, got {_main.Hud.HbCanvas.LastQuadCount}"); Check(_main.Hud.HoverLabelText.Contains(sabotDream.ManufacturerLabel) && _main.Hud.HoverLabelText.Contains('\n'), $"Expected 2-line Borderlands hover tooltip with manufacturer badge, got: {_main.Hud.HoverLabelText}"); Check(_main.Hud.GarageDetailsText.Contains(sabotDream.SummaryLine1) && _main.Hud.GarageDetailsText.Contains(sabotDream.SummaryLine2), @@ -2202,8 +2275,9 @@ public partial class Smoke : Node { sim.SetContenderPose(cIdx, 480f + cIdx * 12f, 480f); } + int enemyIdx = sim.State.SquadSize > 1 ? sim.State.SquadSize : 1; sim.SetContenderPose(0, 0f, 0f, 0f); - sim.SetContenderPose(1, 0f, 125f, MathF.PI); // target Anvil/rival 125m ahead + sim.SetContenderPose(enemyIdx, 0f, 125f, MathF.PI); // target Anvil/rival 125m ahead (non-ally) int audioShotsBefore = _main.Audio.Total3DPlaysRequested; bool sawMirrorRocket = false; @@ -2356,6 +2430,74 @@ public partial class Smoke : Node GD.Print($"SMOKE INFO: Cut 8 Forward+ verified (method={method}, sionZenithT={sionBaked.ZenithTransmittanceMean:F4}, desertZenithT={desertBaked.ZenithTransmittanceMean:F4}, desertHaze=({desertBaked.HazeColor.R:F3},{desertBaked.HazeColor.G:F3},{desertBaked.HazeColor.B:F3}), sionHaze=({sionBaked.HazeColor.R:F3},{sionBaked.HazeColor.G:F3},{sionBaked.HazeColor.B:F3}), grainLayer={atmo.FilmGrainLayer.Layer})"); } + private async Task VerifyGpuSparksRenderAsync(bool isHeadless) + { + if (isHeadless) + { + return; + } + + var sparkVp = new SubViewport + { + Size = new Vector2I(128, 128), + OwnWorld3D = true, + TransparentBg = true, + RenderTargetUpdateMode = SubViewport.UpdateMode.Always + }; + var env = new Godot.Environment + { + BackgroundMode = Godot.Environment.BGMode.Color, + BackgroundColor = new Color(0f, 0f, 0f, 0f) + }; + sparkVp.AddChild(new WorldEnvironment { Environment = env }); + var cam = new Camera3D + { + Position = new Vector3(0f, 0f, 5.5f), + Current = true + }; + sparkVp.AddChild(cam); + var sparks = new GpuSparksSystem { Name = "SmokeSparkProbe" }; + sparkVp.AddChild(sparks); + AddChild(sparkVp); + cam.LookAt(Vector3.Zero, Vector3.Up); + sparks.EnsureInitialized(); + + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var idleImg = sparkVp.GetTexture().GetImage(); + int idleLit = CountNonZeroAlphaPixels(idleImg, 0.05f); + Check(idleLit == 0, $"Expected 0 rendered spark pixels with AmountRatio=0.0f before EmitParticle, got {idleLit}"); + + sparks.EmitSparkBurst(Vector3.Zero, Vector3.Up, 128, new Color(4.5f, 2.5f, 0.75f, 1.0f), 8.0f, 0.05f); + sparks.EmitMuzzleStarburst(Vector3.Zero, new Color(5.0f, 3.0f, 1.0f, 1.0f), 0.75f, 0.14f); + + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + + var activeImg = sparkVp.GetTexture().GetImage(); + int brightPixels = 0; + int w = activeImg.GetWidth(); + int h = activeImg.GetHeight(); + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + Color c = activeImg.GetPixel(x, y); + float lum = c.R * 0.2126f + c.G * 0.7152f + c.B * 0.0722f; + if (c.A > 0.05f && lum > 0.35f) + { + brightPixels++; + } + } + } + GD.Print($"SMOKE INFO: GpuSparksSystem Vulkan render probe idleLit={idleLit} brightPixels={brightPixels}"); + Check(brightPixels > 25, $"Expected > 25 bright HDR spark pixels after EmitSparkBurst (start() ACTIVE=true), got {brightPixels}"); + + sparkVp.QueueFree(); + await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); + } + private void CheckFinitePositiveLut(string label, Image img, int expectedW, int expectedH) { Check(img.GetFormat() == Image.Format.Rgbah, $"Expected {label} format Rgbah, got {img.GetFormat()}"); 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..59ca2d4 --- /dev/null +++ b/client/tree_impostor.gdshader @@ -0,0 +1,151 @@ +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; + 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; + vec3 local_flow = vec3(0.0); + if (in_flow > 0.001) { + vec4 fs = textureLod(rtd_flow_field, clamp(flow_uv, vec3(0.0), vec3(1.0)), 0.0); + vec3 flow_local = (inverse(MODEL_MATRIX) * vec4(fs.rgb, 0.0)).xyz; + local_flow = flow_local * ((0.04 + fs.a * 0.10) * in_flow * top_w); + } + vec3 amb_local_raw = (inverse(MODEL_MATRIX) * vec4(ambient_wind_dir, 0.0)).xyz; + float amb_len = length(amb_local_raw); + vec3 ambient_local = amb_len > 1e-5 ? amb_local_raw / amb_len : vec3(1.0, 0.0, 0.0); + offset += ambient_local * (sway * mix(1.0, 0.5, in_flow)) + local_flow; + + 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/client/volumetric_capsule_beam.gdshader b/client/volumetric_capsule_beam.gdshader new file mode 100644 index 0000000..0f3330e --- /dev/null +++ b/client/volumetric_capsule_beam.gdshader @@ -0,0 +1,155 @@ +shader_type spatial; +render_mode unshaded, cull_front, blend_mix, depth_draw_never, depth_test_disabled; + +uniform sampler2D depth_tex : hint_depth_texture, filter_nearest; + +varying flat vec4 v_color; +varying flat vec4 v_custom; +varying flat vec3 v_ro; +varying flat float v_radius; +varying flat float v_halfLen; +varying vec3 v_fragCap; + +void vertex() { + v_color = COLOR; + v_custom = INSTANCE_CUSTOM; + + vec3 eX = normalize(MODEL_MATRIX[0].xyz); + vec3 eY = normalize(MODEL_MATRIX[1].xyz); + vec3 eZ = normalize(MODEL_MATRIX[2].xyz); + v_radius = max(0.005, 0.5 * length(MODEL_MATRIX[0].xyz)); + v_halfLen = max(0.0, 0.5 * length(MODEL_MATRIX[2].xyz) - v_radius); + + vec3 mid = MODEL_MATRIX[3].xyz; + mat3 invR = transpose(mat3(eX, eY, eZ)); + v_ro = invR * (CAMERA_POSITION_WORLD - mid); + + vec3 worldVert = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz; + v_fragCap = invR * (worldVert - mid); +} + +bool hitSphere(vec3 oc, vec3 rd, float r2, out float t0, out float t1) { + float b = dot(oc, rd); + float c = dot(oc, oc) - r2; + float disc = b * b - c; + if (disc <= 0.0) { + return false; + } + float sq = sqrt(disc); + t0 = -b - sq; + t1 = -b + sq; + return true; +} + +bool hitLocalCapsule(vec3 ro, vec3 rd, float h, float r, out float outEnter, out float outExit) { + float r2 = r * r; + if (h < 0.005) { + return hitSphere(ro, rd, r2, outEnter, outExit); + } + + outEnter = 1e9; + outExit = -1e9; + bool hit = false; + + float s0, s1; + if (hitSphere(ro - vec3(0.0, 0.0, -h), rd, r2, s0, s1)) { + outEnter = min(outEnter, s0); + outExit = max(outExit, s1); + hit = true; + } + if (hitSphere(ro - vec3(0.0, 0.0, h), rd, r2, s0, s1)) { + outEnter = min(outEnter, s0); + outExit = max(outExit, s1); + hit = true; + } + + // Infinite Z-axis cylinder x^2 + y^2 <= r^2 clipped to z in [-h, +h] + float a = dot(rd.xy, rd.xy); + float b = dot(ro.xy, rd.xy); + float c = dot(ro.xy, ro.xy) - r2; + float disc = b * b - a * c; + if (disc >= 0.0 && a > 1e-6) { + float sq = sqrt(disc); + float ct0 = (-b - sq) / a; + float ct1 = (-b + sq) / a; + if (abs(rd.z) > 1e-6) { + float tz0 = (-h - ro.z) / rd.z; + float tz1 = (h - ro.z) / rd.z; + ct0 = max(ct0, min(tz0, tz1)); + ct1 = min(ct1, max(tz0, tz1)); + if (ct1 > ct0) { + outEnter = min(outEnter, ct0); + outExit = max(outExit, ct1); + hit = true; + } + } else if (abs(ro.z) <= h) { + outEnter = min(outEnter, ct0); + outExit = max(outExit, ct1); + hit = true; + } + } + + return hit && (outExit > outEnter); +} + +void fragment() { + vec3 rd = normalize(v_fragCap - v_ro); + + float tEnter, tExit; + if (!hitLocalCapsule(v_ro, rd, v_halfLen, v_radius, tEnter, tExit)) { + discard; + } + tEnter = max(0.0, tEnter); + if (tExit <= tEnter) { + discard; + } + + float rawDepth = texture(depth_tex, SCREEN_UV).r; + float tScene = 1e6; + if (rawDepth > 0.0) { + vec4 viewPos = INV_PROJECTION_MATRIX * vec4(SCREEN_UV * 2.0 - 1.0, rawDepth, 1.0); + tScene = length(viewPos.xyz / viewPos.w); + } + + float tClipExit = min(tExit, tScene); + if (tClipExit <= tEnter) { + discard; + } + float depthFade = clamp((tScene - tEnter) / max(0.06, v_radius * 0.45), 0.0, 1.0); + + // Closest approach between clamped ray segment [tEnter, tClipExit] and capsule axis z in [-h, +h] + float xy2 = dot(rd.xy, rd.xy); + float tCyl = xy2 > 1e-6 ? -dot(v_ro.xy, rd.xy) / xy2 : 0.5 * (tEnter + tClipExit); + float tBest = clamp(tCyl, tEnter, tClipExit); + float s = v_ro.z + tBest * rd.z; + if (abs(s) > v_halfLen) { + s = clamp(s, -v_halfLen, v_halfLen); + tBest = clamp(-dot(v_ro - vec3(0.0, 0.0, s), rd), tEnter, tClipExit); + s = clamp(v_ro.z + tBest * rd.z, -v_halfLen, v_halfLen); + } + + vec3 pRay = v_ro + rd * tBest; + float dMin = length(pRay - vec3(0.0, 0.0, s)); + float rFrac = clamp(dMin / v_radius, 0.0, 1.0); + float chord = sqrt(max(0.0, 1.0 - rFrac * rFrac)); + + float coreSharpness = max(1.0, v_custom.x); + float coreFrac = clamp(v_custom.y, 0.08, 0.85); + float core = pow(clamp(1.0 - smoothstep(0.0, coreFrac, rFrac), 0.0, 1.0), coreSharpness); + float sheath = pow(chord, 1.75); + + // Basis.LookingAt puts -Z forward: start (tail) is at +v_halfLen, end (head) is at -v_halfLen + float tailT = v_halfLen > 0.01 ? clamp(0.5 - 0.5 * (s / v_halfLen), 0.0, 1.0) : 1.0; + float axial = mix(1.0, smoothstep(0.0, 0.78, tailT), v_custom.z * step(0.01, v_halfLen)); + float pulse = v_custom.w > 0.0 ? (0.88 + 0.12 * sin(s * 2.4 + TIME * v_custom.w)) : 1.0; + + vec3 hotCore = vec3(3.8, 3.8, 4.0); + vec3 rgb = mix(max(v_color.rgb, vec3(0.0)), hotCore, core * 0.82) * (0.45 + 0.55 * chord) * pulse; + float alpha = clamp(max(core, sheath * 0.85) * axial * depthFade * v_color.a, 0.0, 1.0); + if (alpha < 0.005) { + discard; + } + + ALBEDO = rgb; + ALPHA = alpha; +} diff --git a/client/volumetric_composite.glsl b/client/volumetric_composite.glsl new file mode 100644 index 0000000..327bb28 --- /dev/null +++ b/client/volumetric_composite.glsl @@ -0,0 +1,152 @@ +#version 450 + +layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in; + +#define MAX_TILE_EMITTERS 24u + +struct TileData { + uint count; + float minDepth; + float maxDepth; + uint _pad; + uint packedKeys[MAX_TILE_EMITTERS]; +}; + +layout(set = 0, binding = 0, std140) uniform VolumetricFrame { + mat4 invProj; + vec4 camPosTime; + vec4 camRightAspect; + vec4 camUpTanHalfFov; + vec4 camFwdNearFar; + vec4 sunDirIntensity; + vec4 sunColorExt; + vec4 ambientColorFog; + vec4 viewportInfo; + uvec4 tileGridParams; + vec4 flowOriginVoxel; + vec4 flowInvExtentDt; + ivec4 flowDeltaImpulse; + uvec4 qualityParams; +} u_frame; + +layout(set = 0, binding = 1) uniform sampler2D u_depthTex; +layout(set = 0, binding = 2) uniform sampler2D u_halfVolTex; +layout(set = 0, binding = 3, rgba16f) uniform image2D u_colorImg; +layout(set = 0, binding = 4, std430) readonly buffer TileBuffer { + TileData tiles[]; +} u_tiles; + +float linearizeReverseZ(float rawDepth) { + if (rawDepth <= 0.0) { + return u_frame.viewportInfo.z; + } + float zN = u_frame.ambientColorFog.w; + float zF = u_frame.viewportInfo.z; + return (zN * zF) / max(1e-5, zN + rawDepth * (zF - zN)); +} + +float marchQuadMaxDepth(ivec2 mpx, ivec2 marchRes, ivec2 fullRes) { + vec2 ratio = vec2(fullRes) / vec2(marchRes); + ivec2 px0 = clamp(ivec2(floor(vec2(mpx) * ratio)), ivec2(0), fullRes - ivec2(1)); + ivec2 px1 = clamp(ivec2(ceil(vec2(mpx + ivec2(1)) * ratio)) - ivec2(1), px0, fullRes - ivec2(1)); + float dMax = 0.0; + for (int sy = px0.y; sy <= px1.y; sy++) { + for (int sx = px0.x; sx <= px1.x; sx++) { + dMax = max(dMax, linearizeReverseZ(texelFetch(u_depthTex, ivec2(sx, sy), 0).r)); + } + } + return dMax; +} + +void main() { + ivec2 fullRes = ivec2(u_frame.viewportInfo.xy); + ivec2 px = ivec2(gl_GlobalInvocationID.xy); + if (any(greaterThanEqual(px, fullRes))) { + return; + } + + ivec2 marchRes = ivec2(u_frame.tileGridParams.xy); + uint tilesX = u_frame.tileGridParams.z; + bool isFullRes = u_frame.qualityParams.z != 0u; + + vec4 vol; + if (isFullRes) { + ivec2 tileCoord = px / 16; + uint tileIdx = uint(tileCoord.y) * tilesX + uint(tileCoord.x); + if (u_tiles.tiles[tileIdx].count == 0u) { + return; + } + // Direct 1:1 full-res sample bypassing 2x2 bilateral upsample + vol = texelFetch(u_halfVolTex, min(px, marchRes - ivec2(1)), 0); + } else { + vec2 scaleToMarch = vec2(marchRes) / vec2(fullRes); + vec2 hCoord = (vec2(px) + vec2(0.5)) * scaleToMarch - vec2(0.5); + ivec2 h0 = clamp(ivec2(floor(hCoord)), ivec2(0), marchRes - ivec2(1)); + ivec2 h1 = min(h0 + ivec2(1), marchRes - ivec2(1)); + + ivec2 t0 = h0 / 16; + ivec2 t1 = h1 / 16; + if (all(equal(t0, t1))) { + uint tileIdx = uint(t0.y) * tilesX + uint(t0.x); + if (u_tiles.tiles[tileIdx].count == 0u) { + return; + } + } else { + uint anyCount = + u_tiles.tiles[uint(t0.y) * tilesX + uint(t0.x)].count + + u_tiles.tiles[uint(t0.y) * tilesX + uint(t1.x)].count + + u_tiles.tiles[uint(t1.y) * tilesX + uint(t0.x)].count + + u_tiles.tiles[uint(t1.y) * tilesX + uint(t1.x)].count; + if (anyCount == 0u) { + return; + } + } + + float dFull = linearizeReverseZ(texelFetch(u_depthTex, px, 0).r); + vec2 f = clamp(hCoord - vec2(h0), vec2(0.0), vec2(1.0)); + + float depthScale = max(0.45, 0.055 * dFull); + vec4 volSum = vec4(0.0); + float wSum = 0.0; + float wRawSum = 0.0; + float minMarchDepth = 1e9; + + ivec2 offsets[4] = ivec2[4](ivec2(0, 0), ivec2(1, 0), ivec2(0, 1), ivec2(1, 1)); + float spatialW[4] = float[4]( + (1.0 - f.x) * (1.0 - f.y), + f.x * (1.0 - f.y), + (1.0 - f.x) * f.y, + f.x * f.y + ); + + for (int i = 0; i < 4; i++) { + ivec2 hp = min(h0 + offsets[i], marchRes - ivec2(1)); + vec4 vSample = texelFetch(u_halfVolTex, hp, 0); + float dMarch = marchQuadMaxDepth(hp, marchRes, fullRes); + minMarchDepth = min(minMarchDepth, dMarch); + float wDepth = exp(-abs(dFull - dMarch) / depthScale); + float wRaw = spatialW[i] * wDepth; + wRawSum += wRaw; + float w = max(1e-5, wRaw); + volSum += vSample * w; + wSum += w; + } + + // Thin foreground occluder (spark/edge strictly in front of ALL 4 march-res background depth taps): + // do not smear background smoke over it + if (wRawSum < 1e-3 && dFull < minMarchDepth * 0.92) { + return; + } + + vol = volSum / max(1e-5, wSum); + } + + // Skip write when completely transparent + if (vol.a > 0.999 && dot(vol.rgb, vol.rgb) < 1e-7) { + return; + } + + vec4 scene = imageLoad(u_colorImg, px); + scene.rgb = scene.rgb * clamp(vol.a, 0.0, 1.0) + max(vol.rgb, vec3(0.0)); + imageStore(u_colorImg, px, scene); +} diff --git a/client/volumetric_raymarch.glsl b/client/volumetric_raymarch.glsl new file mode 100644 index 0000000..63e61aa --- /dev/null +++ b/client/volumetric_raymarch.glsl @@ -0,0 +1,540 @@ +#version 450 + +layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in; + +#define MAX_TILE_EMITTERS 24u + +struct VolumetricEmitter { + vec4 posRadius; + vec4 endRadiusTemp; + vec4 params; + vec4 tintSoftness; +}; + +struct TileData { + uint count; + float minDepth; + float maxDepth; + uint _pad; + uint packedKeys[MAX_TILE_EMITTERS]; +}; + +layout(set = 0, binding = 0, std140) uniform VolumetricFrame { + mat4 invProj; + vec4 camPosTime; + vec4 camRightAspect; + vec4 camUpTanHalfFov; + vec4 camFwdNearFar; + vec4 sunDirIntensity; + vec4 sunColorExt; + vec4 ambientColorFog; + vec4 viewportInfo; + uvec4 tileGridParams; + vec4 flowOriginVoxel; + vec4 flowInvExtentDt; + ivec4 flowDeltaImpulse; + uvec4 qualityParams; +} u_frame; + +layout(set = 0, binding = 1, std430) readonly buffer EmitterBuffer { + VolumetricEmitter emitters[]; +} u_emitters; + +layout(set = 0, binding = 2, std430) readonly buffer TileBuffer { + TileData tiles[]; +} u_tiles; + +layout(set = 0, binding = 3) uniform sampler2D u_depthTex; +layout(set = 0, binding = 4) uniform sampler3D u_flowField; +layout(set = 0, binding = 5, rgba16f) uniform writeonly image2D u_halfVol; + +shared uint sTileCount; +shared VolumetricEmitter sEmitters[MAX_TILE_EMITTERS]; + +float linearizeReverseZ(float rawDepth) { + if (rawDepth <= 0.0) { + return u_frame.viewportInfo.z; + } + float zN = u_frame.ambientColorFog.w; + float zF = u_frame.viewportInfo.z; + return (zN * zF) / max(1e-5, zN + rawDepth * (zF - zN)); +} + +vec3 computeRayDirWorld(vec2 fullUv, out float invCosView) { + vec2 ndcXY = fullUv * 2.0 - 1.0; + float tanY = u_frame.camUpTanHalfFov.w; + float aspect = u_frame.camRightAspect.w; + vec3 viewVec = vec3(ndcXY.x * aspect * tanY, (1.0 - 2.0 * fullUv.y) * tanY, -1.0); + invCosView = length(viewVec); + return normalize(u_frame.camRightAspect.xyz * viewVec.x + + u_frame.camUpTanHalfFov.xyz * viewVec.y + + u_frame.camFwdNearFar.xyz); +} + +// --- Aetheria Volumetric.cginc math (ported cleanly with NaN-safe normalize) --- +float tri(float x) { + return abs(fract(x) - 0.5); +} + +vec3 tri3(vec3 p) { + return vec3( + tri(p.z + tri(p.y)), + tri(p.z + tri(p.x)), + tri(p.y + tri(p.x)) + ); +} + +vec3 safeNorm(vec3 v) { + float l2 = dot(v, v); + return l2 > 1e-8 ? v * inversesqrt(l2) : vec3(0.0, 1.0, 0.0); +} + +vec3 Tri3D(vec3 P, vec3 PGolden) { + vec3 t1 = safeNorm(tri3(P)); + vec3 t2 = safeNorm(tri3(PGolden)); + return cross(t1, t2); +} + +float triNoise3d(vec3 p, float flowTime) { + float z = 1.4; + float rz = 0.001; + vec3 bp = p; + for (int i = 0; i < 2; i++) { + vec3 dg = tri3(bp * 2.0); + p += dg + flowTime; + bp *= 1.8; + z *= 1.5; + p *= 1.2; + rz += tri(p.z + tri(p.x + tri(p.y))) / z; + bp += 0.14; + } + return rz; +} + +vec3 aetheriaFlow(vec3 pos, float flowScale, float scrollSpeed, float time) { + vec3 field = pos / max(0.5, flowScale); + float s1 = time * scrollSpeed; + float s2 = time * scrollSpeed * 1.61803398875; + vec3 fl = Tri3D(field - vec3(0.0, s1, 0.0), field * 1.61803398875 - vec3(0.0, s2, 0.0)); + fl.y *= 0.5; + return fl; +} + +bool intersectSphere(vec3 oc, vec3 rd, float r2, out float t0, out float t1) { + float b = dot(oc, rd); + float c = dot(oc, oc) - r2; + float disc = b * b - c; + if (disc <= 0.0) { + return false; + } + float sq = sqrt(disc); + t0 = -b - sq; + t1 = -b + sq; + return true; +} + +bool intersectCapsule(vec3 ro, vec3 rd, vec3 A, vec3 B, float R, out float outNear, out float outFar) { + float r2 = R * R; + vec3 ba = B - A; + float baba = dot(ba, ba); + if (baba < 0.0025) { + return intersectSphere(ro - A, rd, r2, outNear, outFar); + } + + outNear = 1e9; + outFar = -1e9; + bool hit = false; + + float s0, s1; + if (intersectSphere(ro - A, rd, r2, s0, s1)) { + outNear = min(outNear, s0); + outFar = max(outFar, s1); + hit = true; + } + if (intersectSphere(ro - B, rd, r2, s0, s1)) { + outNear = min(outNear, s0); + outFar = max(outFar, s1); + hit = true; + } + + vec3 oa = ro - A; + float bard = dot(ba, rd); + float baoa = dot(ba, oa); + float rdoa = dot(rd, oa); + float oaoa = dot(oa, oa); + float a = baba - bard * bard; + float b = baba * rdoa - baoa * bard; + float c = baba * oaoa - baoa * baoa - r2 * baba; + float h = b * b - a * c; + if (h >= 0.0 && a > 1e-6) { + float sq = sqrt(h); + float ct0 = (-b - sq) / a; + float ct1 = (-b + sq) / a; + if (abs(bard) > 1e-6) { + float tEnd0 = -baoa / bard; + float tEnd1 = (baba - baoa) / bard; + float tCapMin = min(tEnd0, tEnd1); + float tCapMax = max(tEnd0, tEnd1); + ct0 = max(ct0, tCapMin); + ct1 = min(ct1, tCapMax); + if (ct1 > ct0) { + outNear = min(outNear, ct0); + outFar = max(outFar, ct1); + hit = true; + } + } else if (baoa >= 0.0 && baoa <= baba) { + outNear = min(outNear, ct0); + outFar = max(outFar, ct1); + hit = true; + } + } + return hit && (outFar > outNear); +} + +vec3 blackbodyRamp(float temp) { + // Tuned for AgX (TonemapAgxWhite=6.0) + GlowHdrThreshold=1.0: blazing white-gold cores -> molten orange-red edges + vec3 c0 = vec3(0.55, 0.04, 0.003); + vec3 c1 = vec3(1.85, 0.28, 0.015); + vec3 c2 = vec3(3.60, 0.92, 0.075); + vec3 c3 = vec3(5.60, 2.35, 0.34); + vec3 c4 = vec3(7.60, 4.45, 1.35); + if (temp < 0.35) return mix(c0, c1, smoothstep(0.10, 0.35, temp)); + if (temp < 0.72) return mix(c1, c2, (temp - 0.35) / 0.37); + if (temp < 1.10) return mix(c2, c3, (temp - 0.72) / 0.38); + return mix(c3, c4, clamp((temp - 1.10) / 0.50, 0.0, 1.0)); +} + +float hgPhase(float cosTheta, float g) { + float g2 = g * g; + float denom = max(0.05, 1.0 + g2 - 2.0 * g * cosTheta); + return (1.0 - g2) / (12.5663706 * pow(denom, 1.5)); +} + +void main() { + uint tid = gl_LocalInvocationIndex; + ivec2 tileCoord = ivec2(gl_WorkGroupID.xy); + uint tilesX = u_frame.tileGridParams.z; + uint tileIdx = uint(tileCoord.y) * tilesX + uint(tileCoord.x); + + if (tid == 0u) { + sTileCount = min(u_tiles.tiles[tileIdx].count, MAX_TILE_EMITTERS); + } + memoryBarrierShared(); + barrier(); + + ivec2 marchRes = ivec2(u_frame.tileGridParams.xy); + ivec2 px = ivec2(gl_GlobalInvocationID.xy); + + // Empty-tile fast exit (uniform across workgroup) + if (sTileCount == 0u) { + if (all(lessThan(px, marchRes))) { + imageStore(u_halfVol, px, vec4(0.0, 0.0, 0.0, 1.0)); + } + return; + } + + if (tid < sTileCount) { + uint eIdx = u_tiles.tiles[tileIdx].packedKeys[tid] & 0x7Fu; + sEmitters[tid] = u_emitters.emitters[eIdx]; + } + memoryBarrierShared(); + barrier(); + + if (any(greaterThanEqual(px, marchRes))) { + return; + } + + ivec2 fullRes = ivec2(u_frame.viewportInfo.xy); + bool isFullRes = u_frame.qualityParams.z != 0u; + float dMax = 0.0; + if (isFullRes) { + ivec2 sp = min(px, fullRes - ivec2(1)); + dMax = linearizeReverseZ(texelFetch(u_depthTex, sp, 0).r); + } else { + vec2 ratio = vec2(fullRes) / vec2(marchRes); + ivec2 px0 = clamp(ivec2(floor(vec2(px) * ratio)), ivec2(0), fullRes - ivec2(1)); + ivec2 px1 = clamp(ivec2(ceil(vec2(px + ivec2(1)) * ratio)) - ivec2(1), px0, fullRes - ivec2(1)); + for (int sy = px0.y; sy <= px1.y; sy++) { + for (int sx = px0.x; sx <= px1.x; sx++) { + float linD = linearizeReverseZ(texelFetch(u_depthTex, ivec2(sx, sy), 0).r); + dMax = max(dMax, linD); + } + } + } + + vec2 fullUv = (vec2(px) + vec2(0.5)) / vec2(marchRes); + float invCosView; + vec3 rd = computeRayDirWorld(fullUv, invCosView); + vec3 ro = u_frame.camPosTime.xyz; + float tSceneMax = dMax * invCosView; + + // Exact per-pixel capsule intersections sorted ascending by t0 for monotonic sweep-line + uint hitPack[MAX_TILE_EMITTERS]; + float hitT1[MAX_TILE_EMITTERS]; + uint hitCount = 0u; + float tEndMax = 0.0; + + for (uint k = 0u; k < sTileCount; k++) { + VolumetricEmitter em = sEmitters[k]; + float rBound = max(em.posRadius.w, em.params.y) * 1.95; + float t0, t1; + if (intersectCapsule(ro, rd, em.posRadius.xyz, em.endRadiusTemp.xyz, rBound, t0, t1)) { + t0 = max(2.0, t0); + t1 = min(tSceneMax, t1); + if (t1 > t0 + 1e-3) { + uint key = (floatBitsToUint(t0) & 0xFFFFFFE0u) | (k & 0x1Fu); + uint ins = hitCount; + while (ins > 0u && hitPack[ins - 1u] > key) { + hitPack[ins] = hitPack[ins - 1u]; + hitT1[ins] = hitT1[ins - 1u]; + ins--; + } + hitPack[ins] = key; + hitT1[ins] = t1; + hitCount++; + tEndMax = max(tEndMax, t1); + } + } + } + + if (hitCount == 0u) { + imageStore(u_halfVol, px, vec4(0.0, 0.0, 0.0, 1.0)); + return; + } + + // Interleaved Gradient Noise temporal jitter + float frameF = float(u_frame.tileGridParams.w & 63u); + float ign = fract(52.9829189 * fract(dot(vec2(px) + 5.588238 * frameF, vec2(0.06711056, 0.00583715)))); + + float elapsed = u_frame.camPosTime.w; + vec3 sunDir = u_frame.sunDirIntensity.xyz; + float cosTheta = dot(rd, sunDir); + float phase = mix(hgPhase(cosTheta, 0.68), hgPhase(cosTheta, -0.25), 0.22); + vec3 sunRad = u_frame.sunColorExt.rgb * u_frame.sunDirIntensity.w; + vec3 ambRad = u_frame.ambientColorFog.rgb; + float extScale = u_frame.sunColorExt.w; + + vec3 L = vec3(0.0); + float T = 1.0; + uint nextIdx = 0u; + uint activeMask = 0u; + float t = 0.0; + int steps = 0; + int iter = 0; + int maxSteps = clamp(int(u_frame.qualityParams.x), 1, 64); + int maxIter = clamp(max(int(u_frame.qualityParams.y), maxSteps * 2), 1, 96); + float stepScale = 10.0 / max(float(maxSteps), 1.0); + + while ((nextIdx < hitCount || activeMask != 0u) && t < tEndMax && T >= 0.03 && steps < maxSteps && iter < maxIter) { + // Empty-space jump directly to nextIdx's t0 whenever no emitter is currently active + if (activeMask == 0u) { + float minNext = uintBitsToFloat(hitPack[nextIdx] & 0xFFFFFFE0u); + float nextT1 = hitT1[nextIdx]; + float chord = max(0.0, nextT1 - minNext); + float dsLeap = max(0.16, max(0.42, 0.32 + 0.014 * minNext) * stepScale); + float jitter = ign * min(dsLeap, max(0.05, chord * 0.45)); + t = min(max(t, minNext) + jitter, tEndMax - 1e-4); + if (t >= tEndMax) { + break; + } + } + + float ds = max(0.16, max(0.42, 0.32 + 0.014 * t) * stepScale); + float tLo = t - 0.5 * ds; + float tHi = t + 0.5 * ds; + + // Monotonic sweep-line admission: advance nextIdx forward, never re-scanning earlier entries + while (nextIdx < hitCount) { + float b0 = uintBitsToFloat(hitPack[nextIdx] & 0xFFFFFFE0u); + if (b0 > tHi) { + break; + } + if (hitT1[nextIdx] >= tLo) { + activeMask |= (1u << nextIdx); + } + nextIdx++; + } + + // Retire emitters already exited + uint amCheck = activeMask; + while (amCheck != 0u) { + int bit = findLSB(amCheck); + amCheck &= amCheck - 1u; + if (hitT1[bit] < tLo) { + activeMask &= ~(1u << uint(bit)); + } + } + + if (activeMask == 0u) { + continue; + } + + // Near-camera fade (2.0..6.8m) so lens-adjacent plumes never blind the viewport or stall raymarching + if (t >= 2.0) { + float nearFade = smoothstep(2.0, 6.8, t); + float emitNearFade = smoothstep(2.5, 8.5, t); + if (nearFade > 0.001) { + vec3 worldPos = ro + rd * t; + bool hasFlow = false; + vec4 flowSample = vec4(0.0); + float shock = 0.0; + vec3 stepCurl = vec3(0.0); + + float rhoSum = 0.0; + vec3 albedoSum = vec3(0.0); + vec3 radialSum = vec3(0.0); + float tempSum = 0.0; + float noiseSum = 0.0; + float plasmaSum = 0.0; + + uint am = activeMask; + while (am != 0u) { + int hitSlot = findLSB(am); + am &= am - 1u; + uint k = hitPack[hitSlot] & 0x1Fu; + VolumetricEmitter em = sEmitters[k]; + + uint flags = floatBitsToUint(em.params.w); + uint emType = flags & 0xFu; + float ageNorm = float((flags >> 4u) & 0xFFu) / 255.0; + float seed = float((flags >> 12u) & 0xFFu) * 0.371; + + float rA = em.posRadius.w; + float rB = em.params.y; + float radAvg = max(0.35, 0.5 * (rA + rB)); + + vec3 A = em.posRadius.xyz; + vec3 B = em.endRadiusTemp.xyz; + vec3 ab = B - A; + float ab2 = dot(ab, ab); + + // Conservative squared-distance guard BEFORE sampling 3D flow texture or Tri3D curl (matches 1.95 * rad rBound) + float preSegT = ab2 > 1e-5 ? clamp(dot(worldPos - A, ab) / ab2, 0.0, 1.0) : 0.0; + float preRad = mix(rA, rB, preSegT); + vec3 preDelta = worldPos - (A + ab * preSegT); + float rGuard = 1.15 * preRad + 0.80 * radAvg; + if (dot(preDelta, preDelta) > rGuard * rGuard) { + continue; + } + + if (!hasFlow) { + vec3 flowUv = (worldPos - u_frame.flowOriginVoxel.xyz) * u_frame.flowInvExtentDt.xyz; + flowSample = (all(greaterThanEqual(flowUv, vec3(0.0))) && all(lessThanEqual(flowUv, vec3(1.0)))) + ? textureLod(u_flowField, flowUv, 0.0) + : vec4(0.0); + shock = clamp(flowSample.a, 0.0, 1.5); + stepCurl = aetheriaFlow(worldPos - flowSample.rgb * 0.20, 11.0, 0.68, elapsed); + hasFlow = true; + } + + // Uncuffed 3D flow advection + wind/buoyancy shear + age-grown Tri3D curl bounded inside rBound (1.95 * rad) + vec3 flowOffset = flowSample.rgb * (0.28 + 0.45 * ageNorm); + float advSegT = ab2 > 1e-5 ? clamp(dot((worldPos - flowOffset) - A, ab) / ab2, 0.0, 1.0) : 0.0; + flowOffset += vec3(flowSample.r, 0.0, flowSample.b) * (0.32 * advSegT * (0.35 + ageNorm)); + float fOffLen = length(flowOffset); + if (fOffLen > 0.62 * radAvg) { + flowOffset *= (0.62 * radAvg) / fOffLen; + } + vec3 advectedPos = worldPos - flowOffset; + + float curlScale = mix(0.24, 0.46, clamp(ageNorm * 1.1 + advSegT * 0.45, 0.0, 1.0)) * radAvg; + vec3 evalPos = advectedPos + stepCurl * curlScale; + + float segT = ab2 > 1e-5 ? clamp(dot(evalPos - A, ab) / ab2, 0.0, 1.0) : 0.0; + vec3 closest = A + ab * segT; + float taper = ab2 > 0.15 ? mix(1.02, 0.78, segT) : 1.0; + float rad = mix(rA, rB, segT) * taper; + vec3 radialVec = evalPos - closest; + float distNorm = length(radialVec) / max(0.15, rad); + + if (distNorm < 1.16) { + // True Aetheria gradient-offset pattern (Volumetric.cginc:210-215): + // triNoise3d ONLY offsets the smooth radial SDF gradient by a small centered displacement << 1.0 + vec3 nCoord = (evalPos / max(1.4, rad * 0.95)) * 0.32 + vec3(seed); + float n1 = triNoise3d(nCoord, elapsed * 0.32); + float n2 = triNoise3d(nCoord * 3.6, elapsed * 0.52); + float dispAmp = 0.35 + 0.65 * clamp(distNorm, 0.0, 1.0); + float disp = ((n1 - 0.45 * n2) - 0.11) * 0.88 * dispAmp; + float warpedDist = clamp(distNorm - disp, 0.0, 1.2); + + if (warpedDist < 1.0) { + float softness = clamp(em.tintSoftness.a, 0.18, 0.75); + float falloffEdge = mix(0.04, 0.14, softness); + float profile = 1.0 - smoothstep(falloffEdge, 1.0, warpedDist); + float rho_k = profile * em.params.x * nearFade; + + // Shock-front cavity carving + adiabatic compression rim + rho_k *= clamp(1.0 - shock * 0.42, 0.32, 1.0) * (1.0 + 0.45 * smoothstep(0.2, 0.9, shock)); + + if (rho_k > 1e-4) { + rhoSum += rho_k; + albedoSum += em.tintSoftness.rgb * rho_k; + radialSum += safeNorm(radialVec + vec3(0.0, 0.28 * rad, 0.0)) * rho_k; + + // Tight radial temperature falloff: outer shell cools to un-emissive rolling soot + float coreRadial = pow(clamp(1.0 - warpedDist, 0.0, 1.0), 2.35); + float localTemp = max(em.endRadiusTemp.w * coreRadial, shock * 0.22); + tempSum += localTemp * rho_k; + noiseSum += clamp((n1 - 0.45 * n2) * 2.5 + 0.25, 0.0, 1.0) * rho_k; + if (emType == 3u || emType == 4u) { + plasmaSum += rho_k; + } + } + } + } + } + + if (rhoSum > 0.002) { + float rawDens = rhoSum; + float coreTemp = tempSum / rhoSum; + float stepNoise = noiseSum / rhoSum; + vec3 albedo = albedoSum / rhoSum; + vec3 localUpOrRadial = safeNorm(radialSum); + + // Layer 1 & 2: Aetheria inverse-density charcoal soot contour (CloudShader.shader:96-97 / Volumetric.cginc:234) + // Dense interiors stay deep velvety charcoal soot; rimBoost (1.65) applies strictly to thin outer sunlit vapor edges + float sootContour = 1.0 / (1.0 + 4.6 * rawDens); + float sunAlignment = clamp(dot(localUpOrRadial, sunDir), -1.0, 1.0); + float rimBias = max(0.0, sunAlignment); + float rimFactor = 1.0 + 0.65 * smoothstep(0.25, 0.72, sootContour); + vec3 sunlitEdgeTint = mix(albedo, albedo * 1.35 + vec3(0.045, 0.040, 0.036), sootContour * smoothstep(0.10, 0.78, max(0.0, sunAlignment) + phase)); + float vaporEdgeFade = smoothstep(0.0, 0.08, rawDens); + vec3 skyBounce = max(0.0, localUpOrRadial.y) * 0.08 * ambRad; + vec3 scatterLum = sunlitEdgeTint * (sootContour * vaporEdgeFade * rimFactor) * (sunRad * (rimBias + phase * 2.6) + skyBounce); + + // Layer 3: Sharp turbulent core-only combustion peeking through dark soot crevices + vec3 plasmaEmit = vec3(0.0); + float coreSignal = coreTemp * (0.85 + 0.30 * stepNoise); + float coreGate = smoothstep(0.72, 1.05, coreSignal); + if (coreGate > 0.001) { + float coreGlow = pow(clamp(rawDens, 0.0, 1.4), 2.15) * coreGate; + vec3 bb = blackbodyRamp(coreTemp); + float plasmaMix = plasmaSum / rhoSum; + if (plasmaMix > 0.01) { + bb = mix(bb, albedo * (1.55 + 2.05 * coreTemp), 0.75 * plasmaMix); + } + plasmaEmit = bb * (coreGlow * 5.0) * emitNearFade; + } + + float sigmaT = rawDens * extScale; + float stepTrans = exp(-sigmaT * ds); + // CloudShader.shader:96-97: do NOT multiply scatterLum by sigmaT before dividing by sigmaT + float integDivExt = sigmaT > 1e-4 ? (1.0 - stepTrans) / sigmaT : ds; + vec3 stepLight = (scatterLum + plasmaEmit) * integDivExt * nearFade; + L += T * stepLight; + T *= stepTrans; + steps++; + if (T < 0.03) { + T = 0.0; + break; + } + } + } + } + + t += ds; + iter++; + } + + imageStore(u_halfVol, px, vec4(min(L, vec3(24.0)), clamp(T, 0.0, 1.0))); +} diff --git a/client/volumetric_tile_cull.glsl b/client/volumetric_tile_cull.glsl new file mode 100644 index 0000000..2ca2c59 --- /dev/null +++ b/client/volumetric_tile_cull.glsl @@ -0,0 +1,214 @@ +#version 450 + +layout(local_size_x = 16, local_size_y = 16, local_size_z = 1) in; + +#define MAX_TILE_EMITTERS 24u + +struct VolumetricEmitter { + vec4 posRadius; + vec4 endRadiusTemp; + vec4 params; + vec4 tintSoftness; +}; + +struct TileData { + uint count; + float minDepth; + float maxDepth; + uint _pad; + uint packedKeys[MAX_TILE_EMITTERS]; +}; + +layout(set = 0, binding = 0, std140) uniform VolumetricFrame { + mat4 invProj; + vec4 camPosTime; + vec4 camRightAspect; + vec4 camUpTanHalfFov; + vec4 camFwdNearFar; + vec4 sunDirIntensity; + vec4 sunColorExt; + vec4 ambientColorFog; + vec4 viewportInfo; + uvec4 tileGridParams; + vec4 flowOriginVoxel; + vec4 flowInvExtentDt; + ivec4 flowDeltaImpulse; + uvec4 qualityParams; +} u_frame; + +layout(set = 0, binding = 1, std430) readonly buffer EmitterBuffer { + VolumetricEmitter emitters[]; +} u_emitters; + +layout(set = 0, binding = 2, std430) writeonly buffer TileBuffer { + TileData tiles[]; +} u_tiles; + +layout(set = 0, binding = 3) uniform sampler2D u_depthTex; + +shared uint sMinDepthBits; +shared uint sMaxDepthBits; +shared uint sTileCount; +shared uint sKeys[128]; + +float linearizeReverseZ(float rawDepth) { + if (rawDepth <= 0.0) { + return u_frame.viewportInfo.z; + } + float zN = u_frame.ambientColorFog.w; + float zF = u_frame.viewportInfo.z; + return (zN * zF) / max(1e-5, zN + rawDepth * (zF - zN)); +} + +void main() { + uint tid = gl_LocalInvocationIndex; + ivec2 tileCoord = ivec2(gl_WorkGroupID.xy); + uint tilesX = u_frame.tileGridParams.z; + uint tileIdx = uint(tileCoord.y) * tilesX + uint(tileCoord.x); + + if (tid == 0u) { + sMinDepthBits = 0x7F7FFFFFu; + sMaxDepthBits = 0u; + sTileCount = 0u; + } + if (tid < 128u) { + sKeys[tid] = 0xFFFFFFFFu; + } + memoryBarrierShared(); + barrier(); + + ivec2 marchRes = ivec2(u_frame.tileGridParams.xy); + ivec2 fullRes = ivec2(u_frame.viewportInfo.xy); + ivec2 mx = ivec2(gl_GlobalInvocationID.xy); + bool isFullRes = u_frame.qualityParams.z != 0u; + + float dMin = u_frame.viewportInfo.z; + float dMax = 0.0; + if (all(lessThan(mx, marchRes))) { + if (isFullRes) { + ivec2 sp = min(mx, fullRes - ivec2(1)); + float linD = linearizeReverseZ(texelFetch(u_depthTex, sp, 0).r); + dMin = linD; + dMax = linD; + } else { + vec2 ratio = vec2(fullRes) / vec2(marchRes); + ivec2 px0 = clamp(ivec2(floor(vec2(mx) * ratio)), ivec2(0), fullRes - ivec2(1)); + ivec2 px1 = clamp(ivec2(ceil(vec2(mx + ivec2(1)) * ratio)) - ivec2(1), px0, fullRes - ivec2(1)); + for (int sy = px0.y; sy <= px1.y; sy++) { + for (int sx = px0.x; sx <= px1.x; sx++) { + float rawD = texelFetch(u_depthTex, ivec2(sx, sy), 0).r; + float linD = linearizeReverseZ(rawD); + dMin = min(dMin, linD); + dMax = max(dMax, linD); + } + } + } + atomicMin(sMinDepthBits, floatBitsToUint(max(0.0, dMin))); + atomicMax(sMaxDepthBits, floatBitsToUint(max(0.0, dMax))); + } + memoryBarrierShared(); + barrier(); + + float tileMinDepth = uintBitsToFloat(sMinDepthBits); + float tileMaxDepth = uintBitsToFloat(sMaxDepthBits); + if (tileMaxDepth <= 0.0) { + tileMaxDepth = u_frame.viewportInfo.z; + } + + // Tile frustum bounds in view space (view looks down -Z, +X right, +Y up) + vec2 uv0 = vec2(tileCoord * 16) / vec2(marchRes); + vec2 uv1 = min(vec2((tileCoord + ivec2(1)) * 16) / vec2(marchRes), vec2(1.0)); + + float tanY = u_frame.camUpTanHalfFov.w; + float aspect = u_frame.camRightAspect.w; + float x0 = (uv0.x * 2.0 - 1.0) * aspect * tanY; + float x1 = (uv1.x * 2.0 - 1.0) * aspect * tanY; + float yTop = (1.0 - 2.0 * uv0.y) * tanY; + float yBot = (1.0 - 2.0 * uv1.y) * tanY; + + vec3 nLeft = normalize(vec3(-1.0, 0.0, -x0)); + vec3 nRight = normalize(vec3(1.0, 0.0, x1)); + vec3 nTop = normalize(vec3(0.0, 1.0, yTop)); + vec3 nBot = normalize(vec3(0.0, -1.0, -yBot)); + + uint emitterCount = min(uint(max(0.0, u_frame.viewportInfo.w + 0.5)), 128u); + if (tid < emitterCount) { + VolumetricEmitter em = u_emitters.emitters[tid]; + float rA = em.posRadius.w; + float rB = em.params.y; + float rBound = max(rA, rB) * 1.95; + + vec3 wA = em.posRadius.xyz - u_frame.camPosTime.xyz; + vec3 wB = em.endRadiusTemp.xyz - u_frame.camPosTime.xyz; + + vec3 camR = u_frame.camRightAspect.xyz; + vec3 camU = u_frame.camUpTanHalfFov.xyz; + vec3 camF = u_frame.camFwdNearFar.xyz; + + // View-space coordinates: +X right, +Y up, -Z forward + vec3 vA = vec3(dot(wA, camR), dot(wA, camU), -dot(wA, camF)); + vec3 vB = vec3(dot(wB, camR), dot(wB, camU), -dot(wB, camF)); + + float dMinEm = min(-vA.z - rBound, -vB.z - rBound); + float dMaxEm = max(-vA.z + rBound, -vB.z + rBound); + + // Reject only behind camera or completely behind tileMaxDepth (NEVER clip against tileMinDepth!) + bool visible = (dMaxEm > 0.0) && (dMinEm < tileMaxDepth); + if (visible) { + if (dot(vA, nLeft) > rBound && dot(vB, nLeft) > rBound) visible = false; + else if (dot(vA, nRight) > rBound && dot(vB, nRight) > rBound) visible = false; + else if (dot(vA, nTop) > rBound && dot(vB, nTop) > rBound) visible = false; + else if (dot(vA, nBot) > rBound && dot(vB, nBot) > rBound) visible = false; + } + + if (visible) { + vec3 ab = vB - vA; + float ab2 = dot(ab, ab); + float segT = ab2 > 1e-5 ? clamp(dot(-vA, ab) / ab2, 0.0, 1.0) : 0.0; + vec3 closest = vA + ab * segT; + float tMinConservative = max(0.0, length(closest) - rBound); + uint packedKey = (floatBitsToUint(tMinConservative) & 0xFFFFFF80u) | (tid & 0x7Fu); + uint slot = atomicAdd(sTileCount, 1u); + if (slot < 128u) { + sKeys[slot] = packedKey; + } + } + } + memoryBarrierShared(); + barrier(); + + // Adaptive Bitonic sort (skip when <= 1; sort smallest power-of-2 >= count up to 128) + uint count = sTileCount; + if (count > 1u) { + uint sortN = count <= 16u ? 16u : (count <= 32u ? 32u : (count <= 64u ? 64u : 128u)); + for (uint k = 2u; k <= sortN; k <<= 1u) { + for (uint j = k >> 1u; j > 0u; j >>= 1u) { + if (tid < sortN) { + uint ixj = tid ^ j; + if (ixj > tid) { + bool ascending = ((tid & k) == 0u); + uint a = sKeys[tid]; + uint b = sKeys[ixj]; + if ((a > b) == ascending) { + sKeys[tid] = b; + sKeys[ixj] = a; + } + } + } + memoryBarrierShared(); + barrier(); + } + } + } + + if (tid == 0u) { + uint outCount = min(sTileCount, MAX_TILE_EMITTERS); + u_tiles.tiles[tileIdx].count = outCount; + u_tiles.tiles[tileIdx].minDepth = tileMinDepth; + u_tiles.tiles[tileIdx].maxDepth = tileMaxDepth; + u_tiles.tiles[tileIdx]._pad = 0u; + } + if (tid < MAX_TILE_EMITTERS) { + u_tiles.tiles[tileIdx].packedKeys[tid] = sKeys[tid]; + } +} diff --git a/native/rtd_hbgpu/CMakeLists.txt b/native/rtd_hbgpu/CMakeLists.txt new file mode 100644 index 0000000..60f55e7 --- /dev/null +++ b/native/rtd_hbgpu/CMakeLists.txt @@ -0,0 +1,89 @@ +cmake_minimum_required(VERSION 3.22) + +project(rtd_hbgpu VERSION 0.1.0 LANGUAGES C CXX) + +set(CMAKE_POSITION_INDEPENDENT_CODE ON) + +if(MSVC) + set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +endif() + +# Resolve pinned HarfBuzz 15.2.0 source +set(RTD_HARFBUZZ_DIR "" CACHE PATH "Path to HarfBuzz 15.2.0 source directory") +if(NOT RTD_HARFBUZZ_DIR AND DEFINED ENV{RTD_HARFBUZZ_DIR} AND EXISTS "$ENV{RTD_HARFBUZZ_DIR}/CMakeLists.txt") + set(RTD_HARFBUZZ_DIR "$ENV{RTD_HARFBUZZ_DIR}") +elseif(NOT RTD_HARFBUZZ_DIR AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/../../extern/harfbuzz/CMakeLists.txt") + set(RTD_HARFBUZZ_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../extern/harfbuzz") +elseif(NOT RTD_HARFBUZZ_DIR AND EXISTS "F:/aeth-wt/text-probe-gpu-build2/src/harfbuzz/CMakeLists.txt") + set(RTD_HARFBUZZ_DIR "F:/aeth-wt/text-probe-gpu-build2/src/harfbuzz") +endif() + +# Minimal HarfBuzz configuration: zero ICU/FreeType/Cairo/Glib/Subset/Raster/Vector bloat +set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) +set(HB_HAVE_CAIRO OFF CACHE BOOL "" FORCE) +set(HB_HAVE_FREETYPE OFF CACHE BOOL "" FORCE) +set(HB_HAVE_GRAPHITE2 OFF CACHE BOOL "" FORCE) +set(HB_HAVE_GLIB OFF CACHE BOOL "" FORCE) +set(HB_HAVE_ICU OFF CACHE BOOL "" FORCE) +set(HB_HAVE_GOBJECT OFF CACHE BOOL "" FORCE) +set(HB_HAVE_INTROSPECTION OFF CACHE BOOL "" FORCE) +set(HB_HAVE_CORETEXT OFF CACHE BOOL "" FORCE) +set(HB_HAVE_UNISCRIBE OFF CACHE BOOL "" FORCE) +set(HB_HAVE_GDI OFF CACHE BOOL "" FORCE) +set(HB_HAVE_DIRECTWRITE OFF CACHE BOOL "" FORCE) +set(HB_BUILD_UTILS OFF CACHE BOOL "" FORCE) +set(HB_BUILD_SUBSET OFF CACHE BOOL "" FORCE) +set(HB_BUILD_RASTER OFF CACHE BOOL "" FORCE) +set(HB_BUILD_VECTOR OFF CACHE BOOL "" FORCE) +set(HB_BUILD_GPU ON CACHE BOOL "" FORCE) +set(HB_BUILD_GPU_DEMO OFF CACHE STRING "" FORCE) + +if(RTD_HARFBUZZ_DIR AND EXISTS "${RTD_HARFBUZZ_DIR}/CMakeLists.txt") + add_subdirectory("${RTD_HARFBUZZ_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/harfbuzz" EXCLUDE_FROM_ALL) +else() + include(FetchContent) + FetchContent_Declare( + harfbuzz + URL "https://github.com/harfbuzz/harfbuzz/releases/download/15.2.0/harfbuzz-15.2.0.tar.xz" + URL_HASH SHA256=e2ec49090744383cdbe7df808c1cedaafba06a97be8dc4211fe546ba585f12cb + ) + FetchContent_MakeAvailable(harfbuzz) +endif() + +add_library(rtd_hbgpu SHARED rtd_hbgpu.c) +target_link_libraries(rtd_hbgpu PRIVATE harfbuzz-gpu harfbuzz) +target_include_directories(rtd_hbgpu + PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include" + PRIVATE "${harfbuzz_SOURCE_DIR}/src" +) +if(RTD_HARFBUZZ_DIR) + target_include_directories(rtd_hbgpu PRIVATE "${RTD_HARFBUZZ_DIR}/src") +endif() + +target_compile_features(rtd_hbgpu PRIVATE c_std_17) +target_compile_definitions(rtd_hbgpu PRIVATE RTD_HBGPU_EXPORTS) + +if(MSVC) + set_property(TARGET rtd_hbgpu PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + target_compile_options(harfbuzz PRIVATE $<$:/O2 /GL /Gy>) + target_compile_options(harfbuzz-gpu PRIVATE $<$:/O2 /GL /Gy>) + target_compile_options(rtd_hbgpu PRIVATE $<$:/O2 /GL /Gy>) + target_link_options(rtd_hbgpu PRIVATE $<$:/OPT:REF /OPT:ICF /LTCG>) +elseif(CMAKE_C_COMPILER_ID MATCHES "GNU|Clang") + target_compile_options(rtd_hbgpu PRIVATE $<$:-O2 -ffunction-sections -fdata-sections>) + if(NOT APPLE) + target_link_options(rtd_hbgpu PRIVATE $<$:-Wl,--gc-sections>) + endif() +endif() + +set_target_properties(rtd_hbgpu PROPERTIES + C_VISIBILITY_PRESET hidden + CXX_VISIBILITY_PRESET hidden + VISIBILITY_INLINES_HIDDEN ON + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/$" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/$" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" +) +if(MINGW) + set_property(TARGET rtd_hbgpu PROPERTY PREFIX "") +endif() diff --git a/native/rtd_hbgpu/include/rtd_hbgpu.h b/native/rtd_hbgpu/include/rtd_hbgpu.h new file mode 100644 index 0000000..e8fa720 --- /dev/null +++ b/native/rtd_hbgpu/include/rtd_hbgpu.h @@ -0,0 +1,124 @@ +#ifndef RTD_HBGPU_H +#define RTD_HBGPU_H + +#include + +#ifdef _WIN32 + #ifdef RTD_HBGPU_EXPORTS + #define RTD_HBGPU_API __declspec(dllexport) + #else + #define RTD_HBGPU_API __declspec(dllimport) + #endif +#else + #if defined(__GNUC__) || defined(__clang__) + #define RTD_HBGPU_API __attribute__((visibility("default"))) + #else + #define RTD_HBGPU_API + #endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct rtd_hb_font rtd_hb_font; + +typedef struct rtd_hb_font_metrics { + int32_t upem; + int32_t ascender; + int32_t descender; + int32_t line_gap; +} rtd_hb_font_metrics; + +typedef struct rtd_hb_shaped_glyph { + uint32_t glyph_id; + uint32_t cluster; + int32_t x_advance; + int32_t y_advance; + int32_t x_offset; + int32_t y_offset; +} rtd_hb_shaped_glyph; + +typedef struct rtd_hb_extents { + int32_t min_x; + int32_t min_y; + int32_t max_x; + int32_t max_y; +} rtd_hb_extents; + +enum { + RTD_HB_STAGE_VERTEX = 0, + RTD_HB_STAGE_FRAGMENT = 1 +}; + +enum { + RTD_HB_SHADER_SHARED = 0, + RTD_HB_SHADER_DRAW = 1 +}; + +enum { + RTD_HB_FEAT_NONE = 0, + RTD_HB_FEAT_CALT = 1u << 0, + RTD_HB_FEAT_LIGA = 1u << 1, + RTD_HB_FEAT_DEFAULT = RTD_HB_FEAT_CALT | RTD_HB_FEAT_LIGA +}; + +enum { + RTD_HB_VERB_MOVE = 0, /* 2 args: x, y */ + RTD_HB_VERB_LINE_TO = 1, /* 2 args: x, y */ + RTD_HB_VERB_QUAD_TO = 2, /* 4 args: cx, cy, x, y */ + RTD_HB_VERB_CUBIC_TO = 3, /* 6 args: c1x, c1y, c2x, c2y, x, y */ + RTD_HB_VERB_CLOSE = 4, /* 0 args */ + RTD_HB_VERB_LINE = 5, /* 7 args: x0, y0, w0, x1, y1, w1, cap (0=butt,1=square) */ + RTD_HB_VERB_RECT = 6, /* 5 args: x, y, w, h, stroke_width (NaN or <0 = filled) */ + RTD_HB_VERB_CIRCLE = 7 /* 4 args: cx, cy, r, stroke_width (NaN or <0 = filled) */ +}; + +RTD_HBGPU_API const char* rtd_hb_version_string(void); + +RTD_HBGPU_API const char* rtd_hb_shader_source(uint32_t stage, uint32_t kind); + +RTD_HBGPU_API rtd_hb_font* rtd_hb_font_create( + const uint8_t* ttf, + uint32_t len, + uint32_t face_index, + rtd_hb_font_metrics* out_metrics); + +RTD_HBGPU_API rtd_hb_font* rtd_hb_font_create_variant( + const rtd_hb_font* base_font, + float wght, + float wdth, + float slnt); + +RTD_HBGPU_API void rtd_hb_font_destroy(rtd_hb_font* f); + +RTD_HBGPU_API uint32_t rtd_hb_shape_utf16( + rtd_hb_font* f, + const uint16_t* utf16, + uint32_t char_len, + uint32_t feature_flags, + rtd_hb_shaped_glyph* out, + uint32_t cap); + +RTD_HBGPU_API int32_t rtd_hb_encode_glyph( + rtd_hb_font* f, + uint32_t glyph_id, + int16_t* out_rgba16i, + uint32_t cap_texels, + rtd_hb_extents* out_ext); + +RTD_HBGPU_API int32_t rtd_hb_encode_path( + uint32_t design_upem, + const uint8_t* verbs, + uint32_t n_verbs, + const float* args, + uint32_t n_args, + int16_t* out_rgba16i, + uint32_t cap_texels, + rtd_hb_extents* out_ext); + +#ifdef __cplusplus +} +#endif + +#endif /* RTD_HBGPU_H */ diff --git a/native/rtd_hbgpu/rtd_hbgpu.c b/native/rtd_hbgpu/rtd_hbgpu.c new file mode 100644 index 0000000..f5ffb2c --- /dev/null +++ b/native/rtd_hbgpu/rtd_hbgpu.c @@ -0,0 +1,348 @@ +#include "rtd_hbgpu.h" + +#include "hb.h" +#include "hb-gpu.h" +#include "hb-ot.h" + +#include +#include +#include + +struct rtd_hb_font { + hb_face_t* face; + hb_font_t* font; + hb_buffer_t* buf; + hb_gpu_draw_t* draw; +}; + +static void fill_extents(const hb_glyph_extents_t* ext, rtd_hb_extents* out_ext) { + if (!out_ext) return; + out_ext->min_x = ext->x_bearing; + out_ext->max_y = ext->y_bearing; + out_ext->max_x = ext->x_bearing + ext->width; + out_ext->min_y = ext->y_bearing + ext->height; +} + +static int32_t finalize_draw_blob( + hb_gpu_draw_t* draw, + int16_t* out_rgba16i, + uint32_t cap_texels, + rtd_hb_extents* out_ext) +{ + hb_glyph_extents_t hb_ext; + memset(&hb_ext, 0, sizeof(hb_ext)); + + hb_blob_t* blob = hb_gpu_draw_encode(draw, &hb_ext); + if (!blob) { + return -1; + } + + unsigned int byte_len = 0; + const char* data = hb_blob_get_data(blob, &byte_len); + fill_extents(&hb_ext, out_ext); + + if (byte_len == 0) { + hb_gpu_draw_recycle_blob(draw, blob); + return 0; + } + + if ((byte_len & 7u) != 0u) { + hb_gpu_draw_recycle_blob(draw, blob); + return -1; + } + + uint32_t texels = byte_len >> 3u; + if (texels > cap_texels || !out_rgba16i) { + hb_gpu_draw_recycle_blob(draw, blob); + return -(int32_t)texels; + } + + memcpy(out_rgba16i, data, byte_len); + hb_gpu_draw_recycle_blob(draw, blob); + return (int32_t)texels; +} + +RTD_HBGPU_API const char* rtd_hb_version_string(void) { + return hb_version_string(); +} + +RTD_HBGPU_API const char* rtd_hb_shader_source(uint32_t stage, uint32_t kind) { + hb_gpu_shader_stage_t hb_stage; + if (stage == RTD_HB_STAGE_VERTEX) { + hb_stage = HB_GPU_SHADER_STAGE_VERTEX; + } else if (stage == RTD_HB_STAGE_FRAGMENT) { + hb_stage = HB_GPU_SHADER_STAGE_FRAGMENT; + } else { + return NULL; + } + + if (kind == RTD_HB_SHADER_SHARED) { + return hb_gpu_shader_source(hb_stage, HB_GPU_SHADER_LANG_GLSL); + } + if (kind == RTD_HB_SHADER_DRAW) { + return hb_gpu_draw_shader_source(hb_stage, HB_GPU_SHADER_LANG_GLSL); + } + return NULL; +} + +RTD_HBGPU_API rtd_hb_font* rtd_hb_font_create( + const uint8_t* ttf, + uint32_t len, + uint32_t face_index, + rtd_hb_font_metrics* out_metrics) +{ + if (!ttf || len == 0) return NULL; + + hb_blob_t* blob = hb_blob_create((const char*)ttf, len, HB_MEMORY_MODE_DUPLICATE, NULL, NULL); + if (!blob || hb_blob_get_length(blob) == 0) { + if (blob) hb_blob_destroy(blob); + return NULL; + } + + hb_face_t* face = hb_face_create(blob, face_index); + hb_blob_destroy(blob); + if (!face || face == hb_face_get_empty()) { + if (face) hb_face_destroy(face); + return NULL; + } + + hb_font_t* font = hb_font_create(face); + hb_buffer_t* buf = hb_buffer_create(); + hb_gpu_draw_t* draw = hb_gpu_draw_create_or_fail(); + if (!font || !buf || !draw) { + if (draw) hb_gpu_draw_destroy(draw); + if (buf) hb_buffer_destroy(buf); + if (font) hb_font_destroy(font); + hb_face_destroy(face); + return NULL; + } + + rtd_hb_font* out = (rtd_hb_font*)calloc(1, sizeof(rtd_hb_font)); + if (!out) { + hb_gpu_draw_destroy(draw); + hb_buffer_destroy(buf); + hb_font_destroy(font); + hb_face_destroy(face); + return NULL; + } + + out->face = face; + out->font = font; + out->buf = buf; + out->draw = draw; + + if (out_metrics) { + hb_font_extents_t fe; + memset(&fe, 0, sizeof(fe)); + hb_font_get_h_extents(font, &fe); + out_metrics->upem = (int32_t)hb_face_get_upem(face); + out_metrics->ascender = fe.ascender; + out_metrics->descender = fe.descender; + out_metrics->line_gap = fe.line_gap; + } + + return out; +} + +RTD_HBGPU_API rtd_hb_font* rtd_hb_font_create_variant( + const rtd_hb_font* base_font, + float wght, + float wdth, + float slnt) +{ + if (!base_font || !base_font->face) return NULL; + + hb_face_t* face = hb_face_reference(base_font->face); + hb_font_t* font = hb_font_create(face); + hb_buffer_t* buf = hb_buffer_create(); + hb_gpu_draw_t* draw = hb_gpu_draw_create_or_fail(); + if (!font || !buf || !draw) { + if (draw) hb_gpu_draw_destroy(draw); + if (buf) hb_buffer_destroy(buf); + if (font) hb_font_destroy(font); + hb_face_destroy(face); + return NULL; + } + + hb_variation_t vars[3] = { + { HB_TAG('w', 'g', 'h', 't'), wght }, + { HB_TAG('w', 'd', 't', 'h'), wdth }, + { HB_TAG('s', 'l', 'n', 't'), slnt } + }; + hb_font_set_variations(font, vars, 3); + + rtd_hb_font* out = (rtd_hb_font*)calloc(1, sizeof(rtd_hb_font)); + if (!out) { + hb_gpu_draw_destroy(draw); + hb_buffer_destroy(buf); + hb_font_destroy(font); + hb_face_destroy(face); + return NULL; + } + + out->face = face; + out->font = font; + out->buf = buf; + out->draw = draw; + return out; +} + +RTD_HBGPU_API void rtd_hb_font_destroy(rtd_hb_font* f) { + if (!f) return; + if (f->draw) hb_gpu_draw_destroy(f->draw); + if (f->buf) hb_buffer_destroy(f->buf); + if (f->font) hb_font_destroy(f->font); + if (f->face) hb_face_destroy(f->face); + free(f); +} + +RTD_HBGPU_API uint32_t rtd_hb_shape_utf16( + rtd_hb_font* f, + const uint16_t* utf16, + uint32_t char_len, + uint32_t feature_flags, + rtd_hb_shaped_glyph* out, + uint32_t cap) +{ + if (!f || !f->font || !f->buf) return 0; + if (char_len == 0 || !utf16) return 0; + + hb_buffer_clear_contents(f->buf); + hb_buffer_add_utf16(f->buf, utf16, (int)char_len, 0, (int)char_len); + hb_buffer_guess_segment_properties(f->buf); + + hb_feature_t feats[2] = { + { HB_TAG('c', 'a', 'l', 't'), (feature_flags & RTD_HB_FEAT_CALT) ? 1u : 0u, HB_FEATURE_GLOBAL_START, HB_FEATURE_GLOBAL_END }, + { HB_TAG('l', 'i', 'g', 'a'), (feature_flags & RTD_HB_FEAT_LIGA) ? 1u : 0u, HB_FEATURE_GLOBAL_START, HB_FEATURE_GLOBAL_END } + }; + hb_shape(f->font, f->buf, feats, 2); + + unsigned int count = 0; + const hb_glyph_info_t* infos = hb_buffer_get_glyph_infos(f->buf, &count); + const hb_glyph_position_t* pos = hb_buffer_get_glyph_positions(f->buf, &count); + + if (out && cap > 0) { + uint32_t to_copy = count < cap ? count : cap; + for (uint32_t i = 0; i < to_copy; i++) { + out[i].glyph_id = infos[i].codepoint; + out[i].cluster = infos[i].cluster; + out[i].x_advance = pos[i].x_advance; + out[i].y_advance = pos[i].y_advance; + out[i].x_offset = pos[i].x_offset; + out[i].y_offset = pos[i].y_offset; + } + } + + return count; +} + +RTD_HBGPU_API int32_t rtd_hb_encode_glyph( + rtd_hb_font* f, + uint32_t glyph_id, + int16_t* out_rgba16i, + uint32_t cap_texels, + rtd_hb_extents* out_ext) +{ + if (!f || !f->font || !f->draw) return -1; + + hb_gpu_draw_clear(f->draw); + hb_gpu_draw_glyph(f->draw, f->font, glyph_id); + return finalize_draw_blob(f->draw, out_rgba16i, cap_texels, out_ext); +} + +RTD_HBGPU_API int32_t rtd_hb_encode_path( + uint32_t design_upem, + const uint8_t* verbs, + uint32_t n_verbs, + const float* args, + uint32_t n_args, + int16_t* out_rgba16i, + uint32_t cap_texels, + rtd_hb_extents* out_ext) +{ + if (!verbs || n_verbs == 0 || design_upem == 0) return -1; + + hb_gpu_draw_t* draw = hb_gpu_draw_create_or_fail(); + if (!draw) return -1; + + hb_gpu_draw_set_scale(draw, (int)design_upem, (int)design_upem); + hb_draw_funcs_t* dfuncs = hb_gpu_draw_get_funcs(draw); + hb_draw_state_t st = HB_DRAW_STATE_DEFAULT; + + uint32_t arg_idx = 0; + for (uint32_t i = 0; i < n_verbs; i++) { + switch (verbs[i]) { + case RTD_HB_VERB_MOVE: + if (arg_idx + 2u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + hb_draw_move_to(dfuncs, draw, &st, args[arg_idx], args[arg_idx + 1]); + arg_idx += 2u; + break; + + case RTD_HB_VERB_LINE_TO: + if (arg_idx + 2u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + hb_draw_line_to(dfuncs, draw, &st, args[arg_idx], args[arg_idx + 1]); + arg_idx += 2u; + break; + + case RTD_HB_VERB_QUAD_TO: + if (arg_idx + 4u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + hb_draw_quadratic_to(dfuncs, draw, &st, + args[arg_idx], args[arg_idx + 1], + args[arg_idx + 2], args[arg_idx + 3]); + arg_idx += 4u; + break; + + case RTD_HB_VERB_CUBIC_TO: + if (arg_idx + 6u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + hb_draw_cubic_to(dfuncs, draw, &st, + args[arg_idx], args[arg_idx + 1], + args[arg_idx + 2], args[arg_idx + 3], + args[arg_idx + 4], args[arg_idx + 5]); + arg_idx += 6u; + break; + + case RTD_HB_VERB_CLOSE: + hb_draw_close_path(dfuncs, draw, &st); + break; + + case RTD_HB_VERB_LINE: + if (arg_idx + 7u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + hb_draw_line(dfuncs, draw, &st, + args[arg_idx], args[arg_idx + 1], args[arg_idx + 2], + args[arg_idx + 3], args[arg_idx + 4], args[arg_idx + 5], + args[arg_idx + 6] >= 0.5f ? HB_DRAW_LINE_CAP_SQUARE : HB_DRAW_LINE_CAP_BUTT); + arg_idx += 7u; + break; + + case RTD_HB_VERB_RECT: { + if (arg_idx + 5u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + float sw = args[arg_idx + 4]; + if (sw < 0.0f) sw = NAN; + hb_draw_rectangle(dfuncs, draw, &st, + args[arg_idx], args[arg_idx + 1], + args[arg_idx + 2], args[arg_idx + 3], sw); + arg_idx += 5u; + break; + } + + case RTD_HB_VERB_CIRCLE: { + if (arg_idx + 4u > n_args || !args) { hb_gpu_draw_destroy(draw); return -1; } + float sw = args[arg_idx + 3]; + if (sw < 0.0f) sw = NAN; + hb_draw_circle(dfuncs, draw, &st, + args[arg_idx], args[arg_idx + 1], + args[arg_idx + 2], sw); + arg_idx += 4u; + break; + } + + default: + hb_gpu_draw_destroy(draw); + return -1; + } + } + + int32_t res = finalize_draw_blob(draw, out_rgba16i, cap_texels, out_ext); + hb_gpu_draw_destroy(draw); + return res; +} diff --git a/src/RustToDust.Core/ArenaScarLedger.cs b/src/RustToDust.Core/ArenaScarLedger.cs new file mode 100644 index 0000000..f7d79b5 --- /dev/null +++ b/src/RustToDust.Core/ArenaScarLedger.cs @@ -0,0 +1,399 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Linq; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using MessagePack; + +namespace RustToDust.Core +{ + [MessagePackObject] + public sealed class TerrainScarEntry + { + [Key(0)] public byte Kind { get; set; } + [Key(1)] public float X { get; set; } + [Key(2)] public float Z { get; set; } + [Key(3)] public float Radius { get; set; } + [Key(4)] public float Depth { get; set; } + [Key(5)] public float Yaw { get; set; } + [Key(6)] public uint Rgb8 { get; set; } + [Key(7), CultElementId] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class BuildingScarEntry + { + [Key(0)] public ushort BldgId { get; set; } + [Key(1)] public ulong CollapsedMask { get; set; } + [Key(2)] public ulong DamagedMask { get; set; } + [Key(3), CultElementId(nameof(BldgId))] public string ElementId { get; set; } = string.Empty; + } + + [MessagePackObject] + public sealed class TreeScarEntry + { + [Key(0)] public ushort TreeId { get; set; } + [Key(1)] public byte State { get; set; } + [Key(2), CultElementId(nameof(TreeId))] public string ElementId { get; set; } = string.Empty; + } + + [CultDocument("rtd.arena_scar_ledger", "1"), MessagePackObject] + public sealed class ArenaScarLedgerSnapshot + { + [CultName, Key(0)] public string AssetFingerprint { get; set; } = string.Empty; + [Key(1)] public List Terrain { get; set; } = new(); + [Key(2)] public List Buildings { get; set; } = new(); + [Key(3)] public List Trees { get; set; } = new(); + [Key(4)] public uint LedgerRevision { get; set; } + } + + public sealed class ArenaScarLedger + { + public const int MaxPersistentTerrainScars = 4096; + public const float CraterCoalesceRadiusMeters = TerrainField.CraterCoalesceRadiusMeters; + + private readonly List _terrain = new(); + private readonly Dictionary _buildings = new(); + private readonly Dictionary _trees = new(); + + public ArenaScarLedger(string assetFingerprint = "") + { + AssetFingerprint = assetFingerprint; + } + + public string AssetFingerprint { get; set; } + public uint LedgerRevision { get; private set; } + public bool IsDirty { get; set; } + public IReadOnlyList Terrain => _terrain; + public IReadOnlyDictionary Buildings => _buildings; + public IReadOnlyDictionary Trees => _trees; + + public void RecordTerrainStamp(TerrainStampEvent stamp) => + RecordTerrainStamp(stamp.Kind, stamp.X, stamp.Z, stamp.Radius, stamp.Depth, stamp.Yaw); + + public void RecordTerrainStamp(byte kind, float x, float z, float radius, float depth, float yaw, uint rgb8 = 0) + { + var stampKind = (TerrainStampKind)kind; + if (stampKind == TerrainStampKind.Track) + { + return; + } + + if (stampKind == TerrainStampKind.Crater) + { + radius = Math.Clamp(radius, 1.2f, 16f); + depth = Math.Clamp(MathF.Abs(depth), 0.15f, 4.5f); + } + + float coalesceSq = CraterCoalesceRadiusMeters * CraterCoalesceRadiusMeters; + if (stampKind == TerrainStampKind.Crater || stampKind == TerrainStampKind.Scorch) + { + for (int i = _terrain.Count - 1; i >= 0; i--) + { + var existing = _terrain[i]; + if (existing.Kind != kind) + { + continue; + } + float dx = existing.X - x; + float dz = existing.Z - z; + if (dx * dx + dz * dz < coalesceSq) + { + existing.Radius = MathF.Max(existing.Radius, radius); + existing.Depth = MathF.Max(existing.Depth, depth); + LedgerRevision++; + IsDirty = true; + return; + } + } + } + + if (_terrain.Count >= MaxPersistentTerrainScars) + { + int evictIdx = -1; + for (int i = 0; i < _terrain.Count; i++) + { + if (_terrain[i].Kind == (byte)TerrainStampKind.Scorch) + { + evictIdx = i; + break; + } + } + _terrain.RemoveAt(evictIdx >= 0 ? evictIdx : 0); + } + + _terrain.Add(new TerrainScarEntry + { + Kind = kind, + X = x, + Z = z, + Radius = radius, + Depth = depth, + Yaw = yaw, + Rgb8 = rgb8 + }); + LedgerRevision++; + 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(); + _buildings.Clear(); + _trees.Clear(); + LedgerRevision++; + IsDirty = true; + } + + public ArenaScarLedgerSnapshot ToSnapshot() + { + var snap = new ArenaScarLedgerSnapshot + { + AssetFingerprint = AssetFingerprint, + LedgerRevision = LedgerRevision, + Terrain = new List(_terrain.Count), + Buildings = new List(_buildings.Count), + Trees = new List(_trees.Count) + }; + for (int i = 0; i < _terrain.Count; i++) + { + var t = _terrain[i]; + snap.Terrain.Add(new TerrainScarEntry + { + Kind = t.Kind, + X = t.X, + Z = t.Z, + Radius = t.Radius, + Depth = t.Depth, + Yaw = t.Yaw, + Rgb8 = t.Rgb8 + }); + } + foreach (var b in _buildings.Values) + { + snap.Buildings.Add(new BuildingScarEntry + { + BldgId = b.BldgId, + CollapsedMask = b.CollapsedMask, + DamagedMask = b.DamagedMask + }); + } + foreach (var tr in _trees.Values) + { + snap.Trees.Add(new TreeScarEntry + { + TreeId = tr.TreeId, + State = tr.State + }); + } + return snap; + } + + public void LoadFromSnapshot(ArenaScarLedgerSnapshot snapshot) + { + _terrain.Clear(); + _buildings.Clear(); + _trees.Clear(); + + if (!string.IsNullOrEmpty(AssetFingerprint) && + !string.Equals(snapshot.AssetFingerprint, AssetFingerprint, StringComparison.Ordinal)) + { + return; + } + + for (int i = 0; i < snapshot.Terrain.Count && i < MaxPersistentTerrainScars; i++) + { + var t = snapshot.Terrain[i]; + _terrain.Add(new TerrainScarEntry + { + Kind = t.Kind, + X = t.X, + Z = t.Z, + Radius = t.Radius, + Depth = t.Depth, + Yaw = t.Yaw, + Rgb8 = t.Rgb8 + }); + } + for (int i = 0; i < snapshot.Buildings.Count; i++) + { + var b = snapshot.Buildings[i]; + _buildings[b.BldgId] = new BuildingScarEntry + { + BldgId = b.BldgId, + CollapsedMask = b.CollapsedMask, + DamagedMask = b.DamagedMask + }; + } + for (int i = 0; i < snapshot.Trees.Count; i++) + { + var tr = snapshot.Trees[i]; + _trees[tr.TreeId] = new TreeScarEntry + { + TreeId = tr.TreeId, + State = tr.State + }; + } + LedgerRevision = snapshot.LedgerRevision; + IsDirty = false; + } + + public void ApplyToTerrain(TerrainField terrain) + { + for (int i = 0; i < _terrain.Count; i++) + { + var t = _terrain[i]; + switch ((TerrainStampKind)t.Kind) + { + case TerrainStampKind.Crater: + terrain.StampCrater(t.X, t.Z, t.Radius, t.Depth); + break; + case TerrainStampKind.Scorch: + terrain.StampScorch(t.X, t.Z, t.Radius); + break; + case TerrainStampKind.Rubble: + terrain.StampRubble(t.X, t.Z, t.Radius, t.Depth, t.Yaw); + break; + } + } + } + + public static byte[] CompressSnapshot(ArenaScarLedgerSnapshot snapshot) + { + byte[] raw = MessagePackSerializer.Serialize(snapshot); + using var ms = new MemoryStream(); + using (var zlib = new ZLibStream(ms, CompressionLevel.Optimal, leaveOpen: true)) + { + zlib.Write(raw, 0, raw.Length); + } + return ms.ToArray(); + } + + public static ArenaScarLedgerSnapshot DecompressSnapshot(byte[] compressed) + { + using var src = new MemoryStream(compressed); + using var zlib = new ZLibStream(src, CompressionMode.Decompress); + using var dst = new MemoryStream(); + zlib.CopyTo(dst); + return MessagePackSerializer.Deserialize(dst.ToArray()); + } + } + + public static class ArenaScarLedgerStore + { + public static CultDocumentRegistry Registry { get; } = + CultDocumentRegistry.ForTypes(new[] { typeof(ArenaScarLedgerSnapshot) }); + + public static CultRecordKey LedgerKey(string profile = "default") => new("scars:" + profile); + + public static string GetDefaultPath(ArenaMapKind mapKind, string profile = "default") + { + string baseDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + if (string.IsNullOrWhiteSpace(baseDir)) + { + baseDir = AppContext.BaseDirectory; + } + string mapTag = mapKind == ArenaMapKind.Sion ? "sion" : "desert"; + string safeProfile = string.IsNullOrWhiteSpace(profile) ? "default" : profile.Trim(); + return Path.Combine(baseDir, "RustToDust", "scars", $"{mapTag}_scars_{safeProfile}.cultcache"); + } + + public static CultCache Open(string path, bool writable = false) + { + var options = new CultCacheOpenOptions + { + Registry = Registry, + ReadOnly = !writable, + FlushOnDispose = false, + StoreFlushOnDispose = false, + UseDirectoryStore = false + }; + return CultCacheMessagePack.Create(path, options); + } + + public static ArenaScarLedgerSnapshot Load(string path, string expectedAssetFingerprint) + { + if (string.IsNullOrWhiteSpace(path) || !File.Exists(path)) + { + return new ArenaScarLedgerSnapshot { AssetFingerprint = expectedAssetFingerprint }; + } + + try + { + using var cache = Open(path, writable: false); + var records = cache.GetAll().ToArray(); + if (records.Length == 0) + { + return new ArenaScarLedgerSnapshot { AssetFingerprint = expectedAssetFingerprint }; + } + + var snap = records[0]; + if (!string.IsNullOrEmpty(expectedAssetFingerprint) && + !string.Equals(snap.AssetFingerprint, expectedAssetFingerprint, StringComparison.Ordinal)) + { + return new ArenaScarLedgerSnapshot { AssetFingerprint = expectedAssetFingerprint }; + } + return snap; + } + catch + { + return new ArenaScarLedgerSnapshot { AssetFingerprint = expectedAssetFingerprint }; + } + } + + public static void Save(string path, ArenaScarLedgerSnapshot snapshot, string profile = "default") + { + if (snapshot is null) throw new ArgumentNullException(nameof(snapshot)); + if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("Path cannot be empty.", nameof(path)); + + string fullPath = Path.GetFullPath(path); + string dir = Path.GetDirectoryName(fullPath) ?? "."; + Directory.CreateDirectory(dir); + + string workspace = fullPath + "." + Guid.NewGuid().ToString("N") + ".tmp"; + string tempFile = Path.Combine(workspace, "scars.cultcache"); + try + { + Directory.CreateDirectory(workspace); + using (var cache = Open(tempFile, writable: true)) + { + cache.UpsertAsync(typeof(ArenaScarLedgerSnapshot), snapshot, LedgerKey(profile)).GetAwaiter().GetResult(); + cache.FlushAsync().GetAwaiter().GetResult(); + } + + if (File.Exists(fullPath)) + { + File.Replace(tempFile, fullPath, null); + } + else + { + File.Move(tempFile, fullPath); + } + } + finally + { + if (Directory.Exists(workspace)) + { + Directory.Delete(workspace, recursive: true); + } + } + } + } +} diff --git a/src/RustToDust.Core/AssetPathResolver.cs b/src/RustToDust.Core/AssetPathResolver.cs new file mode 100644 index 0000000..fc3f730 --- /dev/null +++ b/src/RustToDust.Core/AssetPathResolver.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace RustToDust.Core +{ + public static class AssetPathResolver + { + private static readonly object Gate = new(); + private static string? _explicitAssetsRoot; + + /// + /// Registers an explicit assets root directory (for example, + /// Path.Combine(OS.GetExecutablePath().GetBaseDir(), "assets") in exported Godot builds). + /// Checked after RTD_ASSETS_DIR and before ancestor probing. + /// + public static void RegisterAssetsRoot(string? assetsDirectory) + { + if (string.IsNullOrWhiteSpace(assetsDirectory)) + { + return; + } + + lock (Gate) + { + _explicitAssetsRoot = Path.GetFullPath(assetsDirectory); + } + } + + public static string LocateSubdirectory( + string relativeSubpath, + Func validator, + string missingDescription) + { + string? envRoot = Environment.GetEnvironmentVariable("RTD_ASSETS_DIR"); + if (!string.IsNullOrWhiteSpace(envRoot)) + { + string envCandidate = Path.Combine(envRoot, relativeSubpath); + if (validator(envCandidate)) + { + return Path.GetFullPath(envCandidate); + } + } + + string? registeredRoot; + lock (Gate) + { + registeredRoot = _explicitAssetsRoot; + } + if (!string.IsNullOrWhiteSpace(registeredRoot)) + { + string regCandidate = Path.Combine(registeredRoot, relativeSubpath); + if (validator(regCandidate)) + { + return Path.GetFullPath(regCandidate); + } + } + + foreach (string start in GetProbeStartDirectories()) + { + var dir = new DirectoryInfo(Path.GetFullPath(start)); + while (dir is not null) + { + string candidate = Path.Combine(dir.FullName, "assets", relativeSubpath); + if (validator(candidate)) + { + return Path.GetFullPath(candidate); + } + dir = dir.Parent; + } + } + + throw new DirectoryNotFoundException( + $"Could not locate 'assets/{relativeSubpath.Replace('\\', '/')}' {missingDescription} from BaseDirectory '{AppContext.BaseDirectory}' or CurrentDirectory '{Directory.GetCurrentDirectory()}'."); + } + + public static string LocateAssetsRoot() + { + string vehiclesDir = VehicleCatalogLoader.LocateVehiclesDirectory(); + return Directory.GetParent(vehiclesDir)?.FullName + ?? throw new DirectoryNotFoundException($"Could not locate assets parent directory of '{vehiclesDir}'."); + } + + private static IEnumerable GetProbeStartDirectories() + { + string? processDir = !string.IsNullOrWhiteSpace(Environment.ProcessPath) + ? Path.GetDirectoryName(Environment.ProcessPath) + : null; + + foreach (string? start in new[] { AppContext.BaseDirectory, processDir, Directory.GetCurrentDirectory() }) + { + if (!string.IsNullOrWhiteSpace(start) && Directory.Exists(start)) + { + yield return start; + } + } + } + } +} diff --git a/src/RustToDust.Core/GridChassis.cs b/src/RustToDust.Core/GridChassis.cs index 029e6d6..ffa48dd 100644 --- a/src/RustToDust.Core/GridChassis.cs +++ b/src/RustToDust.Core/GridChassis.cs @@ -889,6 +889,14 @@ namespace RustToDust.Core UpdateMountedTelemetry(); } + public void ApplyReplicatedCoreHpRatio(float coreHpRatio, bool alive) + { + if (MaxCoreHp <= 0f) return; + CoreHp = alive + ? MathF.Max(0.01f, Math.Clamp(coreHpRatio, 0f, 1f) * MaxCoreHp) + : 0f; + } + public void ApplyReplicatedThermal(ReadOnlySpan quantizedCellTemps, ReadOnlySpan mountedTemps, ReadOnlySpan mountedCooldowns) { int idx = 0; diff --git a/src/RustToDust.Core/IClientArenaSession.cs b/src/RustToDust.Core/IClientArenaSession.cs index 95942dd..04eef6f 100644 --- a/src/RustToDust.Core/IClientArenaSession.cs +++ b/src/RustToDust.Core/IClientArenaSession.cs @@ -58,7 +58,9 @@ namespace RustToDust.Core bool RequestEquipCargo(int cargoIndex, string hardpointId); void RequestNewMatch(int seed, ArenaMapKind mapKind); bool SetLobbyReady(bool ready) => false; - bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) => false; + bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) => RequestLobbyConfig(seed, mapKind, LobbyState?.SquadSize ?? 3); + bool RequestLobbyConfig(int seed, ArenaMapKind mapKind, byte squadSize) => false; + bool RequestLobbySquad(byte targetSquadId) => false; bool RequestLobbyStart() => false; (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha); diff --git a/src/RustToDust.Core/MatchRules.cs b/src/RustToDust.Core/MatchRules.cs index 898fb35..8591b0d 100644 --- a/src/RustToDust.Core/MatchRules.cs +++ b/src/RustToDust.Core/MatchRules.cs @@ -370,7 +370,7 @@ namespace RustToDust.Core for (int j = 0; j < state.Contenders.Count; j++) { var other = state.Contenders[j]; - if (other.Id == ai.Id || !other.IsGroundedActive) + if (other.Id == ai.Id || state.AreAllies(ai.Id, other.Id) || !other.IsGroundedActive) { continue; } @@ -869,6 +869,52 @@ namespace RustToDust.Core state.OrbitalDrop.CheckFinalRingCutoff(); bool canRespawn = state.OrbitalDrop.CanAnyWaitingContenderRespawn(); + if (state.SquadSize > 1) + { + uint aliveSquadMask = 0; + ContenderState? lowestActive = null; + ContenderState? lowestWaiting = null; + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (c.Alive) + { + if (c.SquadId < 32) + { + aliveSquadMask |= 1u << c.SquadId; + } + if (lowestActive is null || c.Id < lowestActive.Id) + { + lowestActive = c; + } + } + else if (c.WaitingForRespawn && canRespawn) + { + if (c.SquadId < 32) + { + aliveSquadMask |= 1u << c.SquadId; + } + if (lowestWaiting is null || c.Id < lowestWaiting.Id) + { + lowestWaiting = c; + } + } + } + + int survivingSquads = BitOperations.PopCount(aliveSquadMask); + if (survivingSquads <= 1) + { + var winner = lowestActive ?? lowestWaiting; + state.Phase = MatchPhase.Completed; + state.WinnerContenderId = winner?.Id; + if (winner is not null) + { + state.Broadcast.EmitVictory(state.Time, winner.Id, state.MapKind); + } + } + return; + } + int aliveCount = 0; int waitingCount = 0; ContenderState? survivor = null; diff --git a/src/RustToDust.Core/MatchState.cs b/src/RustToDust.Core/MatchState.cs index f537aba..d8da973 100644 --- a/src/RustToDust.Core/MatchState.cs +++ b/src/RustToDust.Core/MatchState.cs @@ -17,25 +17,34 @@ namespace RustToDust.Core public string Callsign { get; set; } = string.Empty; public bool IsHuman { get; set; } public bool IsReady { get; set; } + public byte SquadId { get; set; } } public sealed class LobbyState { public const float DefaultCountdownSeconds = 5.0f; - public LobbyState(int contenderCount, ArenaMapKind mapKind, int seed, int? hostSlotId = null, int minHumansToAutoStart = 1) + public LobbyState( + int contenderCount, + ArenaMapKind mapKind, + int seed, + int? hostSlotId = null, + int minHumansToAutoStart = 1, + byte squadSize = 3) { SelectedMap = mapKind; SelectedSeed = seed; HostSlotId = hostSlotId; MinHumansToAutoStart = Math.Max(1, minHumansToAutoStart); + SquadSize = (byte)Math.Clamp((int)squadSize, 1, 4); Slots = new LobbySlotState[contenderCount]; for (int i = 0; i < contenderCount; i++) { Slots[i] = new LobbySlotState { SlotId = i, - Callsign = $"Contender {i + 1:00}" + Callsign = $"Contender {i + 1:00}", + SquadId = SquadSize > 1 ? (byte)(i / SquadSize) : (byte)i }; } } @@ -46,6 +55,7 @@ namespace RustToDust.Core public bool ForceLaunched { get; set; } public ArenaMapKind SelectedMap { get; set; } public int SelectedSeed { get; set; } + public byte SquadSize { get; set; } = 3; public LobbySlotState[] Slots { get; } } @@ -205,6 +215,7 @@ namespace RustToDust.Core public int Id { get; } public string Name { get; set; } public bool IsHuman { get; set; } + public byte SquadId { get; set; } public ChassisGrid Grid { get; set; } public ContenderLifecycle Lifecycle { get; set; } = ContenderLifecycle.Active; public int RespawnsRemaining { get; set; } = 1; @@ -336,26 +347,46 @@ namespace RustToDust.Core private readonly List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)> _pendingLootTargets; private readonly List<(int ContenderId, float X, float Z, float Yaw)> _pendingContenderTargets; - public MatchState(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool skipInitialDrop = false, bool startInLobby = false) + public MatchState( + int seed = 42, + ArenaMapKind mapKind = ArenaMapKind.Desert, + bool skipInitialDrop = false, + bool startInLobby = false, + byte squadSize = 1, + ArenaScarLedgerSnapshot? initialScars = null) { Seed = seed; MapKind = mapKind; + SquadSize = (byte)Math.Clamp((int)squadSize, 1, 4); _pendingSkipInitialDrop = skipInitialDrop; Rng = new Random(seed); Broadcast = new BroadcastFeed(); OrbitalDrop = new OrbitalDropSystem(this); + _pendingContenderTargets = new List<(int ContenderId, float X, float Z, float Yaw)>(ContenderCount); List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)> lootTargets; if (mapKind == ArenaMapKind.Sion) { SionMap = SionMapLoader.Load(); - Terrain = TerrainField.LoadHeightmap( + if (SionMap.Trees.Count > 0) + { + SionTrees = new SionTreeDestructionState(SionMap.Trees); + } + Terrain = TerrainField.LoadSharedHeightmap( SionMap.Metadata.SizeMeters, SionMap.Metadata.GridRes, - SionMap.Heights, + SionMap.Metadata.TileGrid, + SionMap.BaseDem, + SionMap.BaseDemMinY, + SionMap.BaseDemScale, SionMap.Metadata.MinY, SionMap.Metadata.MaxY, (ulong)seed); + ScarLedger = new ArenaScarLedger(SionMap.AssetFingerprint); + if (initialScars is not null) + { + ApplyPersistentScars(initialScars); + } Spectators = new SpectatorRing( seed + 101, SpectatorRing.DefaultSpectatorCount, @@ -369,6 +400,8 @@ namespace RustToDust.Core SionMap.Metadata.MaxY + 140f); SeatSpectatorsOnSion(); SpawnContendersSion(); + AssignDefaultSquadIds(); + ApplySquadFormationTargets(); lootTargets = BuildInitialLootTargetsSion(); } else @@ -376,24 +409,25 @@ namespace RustToDust.Core Spectators = new SpectatorRing(seed + 101); var rawCover = BuildCoverBoxes(); Terrain = TerrainField.Generate((ulong)seed, rawCover); + ScarLedger = new ArenaScarLedger($"desert:{seed}"); + if (initialScars is not null) + { + ApplyPersistentScars(initialScars); + } ArenaCoverBoxes = SeatBoxesOnTerrain(rawCover, Terrain); ArenaBoundaryBoxes = BuildBoundaryBoxes(ArenaHalfExtent, -48f, 72f); SpawnContenders(); + AssignDefaultSquadIds(); + ApplySquadFormationTargets(); lootTargets = BuildInitialLootTargetsDesert(); } _pendingLootTargets = lootTargets; - _pendingContenderTargets = new List<(int ContenderId, float X, float Z, float Yaw)>(Contenders.Count); - for (int i = 0; i < Contenders.Count; i++) - { - var c = Contenders[i]; - _pendingContenderTargets.Add((c.Id, c.X, c.Z, c.Yaw)); - } if (startInLobby) { Phase = MatchPhase.Lobby; - Lobby = new LobbyState(ContenderCount, mapKind, seed); + Lobby = new LobbyState(ContenderCount, mapKind, seed, squadSize: SquadSize); for (int i = 0; i < Contenders.Count; i++) { Contenders[i].Lifecycle = ContenderLifecycle.Deploying; @@ -434,7 +468,12 @@ namespace RustToDust.Core { Lobby.CountdownSeconds = null; Lobby.ForceLaunched = false; + for (int i = 0; i < Contenders.Count && i < Lobby.Slots.Length; i++) + { + Contenders[i].SquadId = SquadSize > 1 ? Lobby.Slots[i].SquadId : (byte)i; + } } + ApplySquadFormationTargets(); if (_pendingSkipInitialDrop) { @@ -460,7 +499,49 @@ namespace RustToDust.Core public int Seed { get; } public ArenaMapKind MapKind { get; } + public byte SquadSize { get; } public SionMapData? SionMap { get; } + + public bool AreAllies(int contenderA, int contenderB) => + SquadSize > 1 && + contenderA >= 0 && contenderA < Contenders.Count && + contenderB >= 0 && contenderB < Contenders.Count && + Contenders[contenderA].SquadId == Contenders[contenderB].SquadId; + + public ContenderState? GetSquadLeader(byte squadId) + { + ContenderState? best = null; + for (int i = 0; i < Contenders.Count; i++) + { + var c = Contenders[i]; + if (c.SquadId != squadId) continue; + if (best is null || (c.IsHuman && !best.IsHuman) || (c.IsHuman == best.IsHuman && c.Id < best.Id)) + { + best = c; + } + } + return best; + } + + public int GetSquadMemberRank(int contenderId) + { + if (contenderId < 0 || contenderId >= Contenders.Count || SquadSize <= 1) + { + return 0; + } + var target = Contenders[contenderId]; + int rank = 0; + for (int i = 0; i < Contenders.Count; i++) + { + var c = Contenders[i]; + if (c.Id == target.Id || c.SquadId != target.SquadId) continue; + if ((c.IsHuman && !target.IsHuman) || (c.IsHuman == target.IsHuman && c.Id < target.Id)) + { + rank++; + } + } + return rank; + } public Random Rng { get; } public float Time { get; set; } public MatchPhase Phase { get; set; } = MatchPhase.Active; @@ -468,7 +549,62 @@ namespace RustToDust.Core public int? WinnerContenderId { get; set; } 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) + { + switch ((TerrainStampKind)stamp.Kind) + { + case TerrainStampKind.Crater: + Terrain.StampCrater(stamp.X, stamp.Z, stamp.Radius, stamp.Depth); + break; + case TerrainStampKind.Scorch: + Terrain.StampScorch(stamp.X, stamp.Z, stamp.Radius); + break; + case TerrainStampKind.Track: + Terrain.StampTrack(stamp.X, stamp.Z, stamp.Yaw, stamp.Radius, stamp.Length); + return; + case TerrainStampKind.Rubble: + Terrain.StampRubble(stamp.X, stamp.Z, stamp.Radius, stamp.Depth, stamp.Yaw); + break; + } + if (recordInLedger) + { + ScarLedger.RecordTerrainStamp(stamp); + } + } + + public void RepairArenaScars() + { + Terrain.ClearDynamicScars(); + SionTrees?.RepairAll(); + ScarLedger.Clear(); + } + + public bool IsSolidBuildingAtXz(float x, float z, float padding = 0f) => + SionMap is not null && SionMap.IsInsideAnyBuildingXz(x, z, padding); public SpectatorRing Spectators { get; } public List GroundDrops { get; } = new(); public List Tracers { get; } = new(); @@ -1297,6 +1433,354 @@ namespace RustToDust.Core } } + public static (float FwdOffset, float SideOffset, float AltStagger) GetSquadFormationOffset(int rank) => rank switch + { + 0 => (8f, 0f, 0f), + 1 => (-6f, -16f, 6f), + 2 => (-6f, 16f, 6f), + 3 => (-20f, 0f, 12f), + _ => (-20f - (rank - 3) * 14f, 0f, 12f + (rank - 3) * 6f) + }; + + private void AssignDefaultSquadIds() + { + for (int i = 0; i < Contenders.Count; i++) + { + Contenders[i].SquadId = SquadSize > 1 ? (byte)(i / SquadSize) : (byte)i; + } + } + + public void ApplySquadFormationTargets() + { + _pendingContenderTargets.Clear(); + if (SquadSize <= 1) + { + for (int i = 0; i < Contenders.Count; i++) + { + var c = Contenders[i]; + c.SquadId = (byte)i; + _pendingContenderTargets.Add((c.Id, c.X, c.Z, c.Yaw)); + } + return; + } + + var squadsById = new Dictionary>(); + for (int i = 0; i < Contenders.Count; i++) + { + var c = Contenders[i]; + if (!squadsById.TryGetValue(c.SquadId, out var list)) + { + list = new List(SquadSize); + squadsById[c.SquadId] = list; + } + list.Add(c); + } + + byte slot0Squad = Contenders.Count > 0 ? Contenders[0].SquadId : (byte)0; + var squadGroups = new List<(byte SquadId, List Members)>(squadsById.Count); + foreach (var kv in squadsById) + { + kv.Value.Sort(static (a, b) => + { + int humanCmp = (b.IsHuman ? 1 : 0).CompareTo(a.IsHuman ? 1 : 0); + return humanCmp != 0 ? humanCmp : a.Id.CompareTo(b.Id); + }); + squadGroups.Add((kv.Key, kv.Value)); + } + squadGroups.Sort((a, b) => + { + if (a.SquadId == slot0Squad && b.SquadId != slot0Squad) return -1; + if (b.SquadId == slot0Squad && a.SquadId != slot0Squad) return 1; + return a.SquadId.CompareTo(b.SquadId); + }); + + int squadCount = squadGroups.Count; + Span<(float X, float Z, float Yaw)> anchors = stackalloc (float X, float Z, float Yaw)[squadCount]; + var squadRng = new Random(Seed ^ (SquadSize * 7919)); + const float minAnchorSepSq = 220f * 220f; + + static float MinAnchorDistSq(ReadOnlySpan<(float X, float Z, float Yaw)> placed, int count, float x, float z) + { + float minSq = float.PositiveInfinity; + for (int k = 0; k < count; k++) + { + float dx = x - placed[k].X; + float dz = z - placed[k].Z; + float d2 = dx * dx + dz * dz; + if (d2 < minSq) minSq = d2; + } + return minSq; + } + + if (MapKind == ArenaMapKind.Sion && SionMap is not null) + { + var leader0 = squadGroups[0].Members[0]; + float pad0 = MathF.Max(leader0.Grid.Spec.HalfWidth, leader0.Grid.Spec.HalfLength) + 2.0f; + (float px, float pz) = FindClearSionPoint(-60f, 360f, pad0, minNy: 0.84f, maxSearchRadius: 120f); + float pYaw = MathF.Atan2(150f - px, -260f - pz); + anchors[0] = (px, pz, pYaw); + + for (int s = 1; s < squadCount; s++) + { + var leader = squadGroups[s].Members[0]; + float pad = MathF.Max(leader.Grid.Spec.HalfWidth, leader.Grid.Spec.HalfLength) + 2.0f; + float ax = 0f, az = 0f; + bool found = false; + float bestX = 0f, bestZ = 0f, bestMinDistSq = -1f; + + for (int attempt = 0; attempt < 48; attempt++) + { + float angle = attempt == 0 + ? ((s - 1) / (float)Math.Max(1, squadCount - 1)) * MathF.Tau + (float)(squadRng.NextDouble() - 0.5) * 0.25f + : (float)(squadRng.NextDouble() * MathF.Tau); + float r = attempt < 24 + ? (260f + (float)squadRng.NextDouble() * 640f) + : (440f + (float)squadRng.NextDouble() * 480f); + (float cx, float cz) = FindClearSionPoint( + MathF.Cos(angle) * r, + MathF.Sin(angle) * r, + pad, + minNy: 0.84f, + maxSearchRadius: 280f, + avoidContenders: false); + float d2 = MinAnchorDistSq(anchors, s, cx, cz); + if (d2 > bestMinDistSq) + { + bestMinDistSq = d2; + bestX = cx; + bestZ = cz; + } + if (d2 >= minAnchorSepSq) + { + ax = cx; + az = cz; + found = true; + break; + } + } + + if (!found) + { + float[] scanRadii = { 900f, 780f, 640f, 500f }; + for (int rIdx = 0; rIdx < scanRadii.Length && !found; rIdx++) + { + float r = scanRadii[rIdx]; + for (int a = 0; a < 36; a++) + { + float ang = (a / 36f) * MathF.Tau; + (float cx, float cz) = FindClearSionPoint( + MathF.Cos(ang) * r, + MathF.Sin(ang) * r, + pad, + minNy: 0.84f, + maxSearchRadius: 240f, + avoidContenders: false); + if (MinAnchorDistSq(anchors, s, cx, cz) >= minAnchorSepSq) + { + ax = cx; + az = cz; + found = true; + break; + } + } + } + } + + if (!found) + { + ax = bestX; + az = bestZ; + } + anchors[s] = (ax, az, MathF.Atan2(-ax, -az)); + } + } + else + { + const float minR = 210f; + const float maxR = 540f; + const float ringSpan = maxR - minR; + + for (int s = 0; s < squadCount; s++) + { + float ax = 0f, az = 0f; + bool found = false; + float bestX = 0f, bestZ = 0f, bestMinDistSq = -1f; + float sectorAngle = (s / (float)Math.Max(1, squadCount)) * MathF.Tau; + + for (int attempt = 0; attempt < 64; attempt++) + { + float angle = attempt < 12 + ? sectorAngle + (float)(squadRng.NextDouble() - 0.5) * (attempt == 0 ? 0.16f : 0.42f) + : (float)(squadRng.NextDouble() * MathF.Tau); + float baseR = attempt < 32 + ? (350f + (float)squadRng.NextDouble() * (maxR - 350f)) + : (minR + (float)squadRng.NextDouble() * ringSpan); + float cx = MathF.Cos(angle) * baseR; + float cz = MathF.Sin(angle) * baseR; + + for (int step = 0; step < 8; step++) + { + var (_, ny, _) = Terrain.SampleNormal(cx, cz); + if (ny >= 0.94f && !IsNearCoverBox(cx, cz, 8f)) + { + break; + } + float r = minR + ((baseR - minR + step * 37f) % ringSpan); + cx = MathF.Cos(angle) * r; + cz = MathF.Sin(angle) * r; + } + + if (IsNearCoverBox(cx, cz, 4f)) continue; + + float d2 = MinAnchorDistSq(anchors, s, cx, cz); + if (d2 > bestMinDistSq) + { + bestMinDistSq = d2; + bestX = cx; + bestZ = cz; + } + if (d2 >= minAnchorSepSq) + { + ax = cx; + az = cz; + found = true; + break; + } + } + + if (!found) + { + for (float r = maxR; r >= 200f && !found; r -= 20f) + { + for (int a = 0; a < 48; a++) + { + float ang = sectorAngle + (a / 48f) * MathF.Tau; + float cx = MathF.Cos(ang) * r; + float cz = MathF.Sin(ang) * r; + if (!IsNearCoverBox(cx, cz, 4f) && MinAnchorDistSq(anchors, s, cx, cz) >= minAnchorSepSq) + { + ax = cx; + az = cz; + found = true; + break; + } + } + } + } + + if (!found) + { + ax = bestX; + az = bestZ; + } + anchors[s] = (ax, az, MathF.Atan2(-ax, -az)); + } + } + + Span<(float X, float Z)> placed = stackalloc (float X, float Z)[Contenders.Count]; + int placedCount = 0; + + for (int s = 0; s < squadCount; s++) + { + var (ax, az, aYaw) = anchors[s]; + float sinY = MathF.Sin(aYaw); + float cosY = MathF.Cos(aYaw); + var members = squadGroups[s].Members; + + for (int k = 0; k < members.Count; k++) + { + var c = members[k]; + var (fwdOff, sideOff, _) = GetSquadFormationOffset(k); + float rawX = ax + sinY * fwdOff - cosY * sideOff; + float rawZ = az + cosY * fwdOff + sinY * sideOff; + float pad = MathF.Max(c.Grid.Spec.HalfWidth, c.Grid.Spec.HalfLength) + 2.0f; + + var (tx, tz) = FindClearSquadMemberPoint(rawX, rawZ, pad, placed, placedCount); + placed[placedCount++] = (tx, tz); + + c.X = tx; + c.Z = tz; + c.Yaw = aYaw; + c.Y = Terrain.SampleHeight(tx, tz) + c.Grid.Spec.HalfHeight + 0.15f; + c.AimY = c.Y; + c.SnapPreviousPose(); + c.ResetAimTracker(aYaw); + } + } + + for (int i = 0; i < Contenders.Count; i++) + { + var c = Contenders[i]; + _pendingContenderTargets.Add((c.Id, c.X, c.Z, c.Yaw)); + } + } + + private (float X, float Z) FindClearSquadMemberPoint( + float rawX, + float rawZ, + float pad, + ReadOnlySpan<(float X, float Z)> placed, + int placedCount) + { + float maxB = Terrain.MapHalfExtent - 28f; + float baseX = Math.Clamp(rawX, -maxB, maxB); + float baseZ = Math.Clamp(rawZ, -maxB, maxB); + + if (IsClearSquadMemberCandidate(baseX, baseZ, pad, maxB, minNy: 0.76f, placed, placedCount)) + { + return (baseX, baseZ); + } + + for (int pass = 0; pass < 2; pass++) + { + float minNy = pass == 0 ? 0.76f : 0f; + for (float r = 4f; r <= 120f; r += 4f) + { + for (int a = 0; a < 16; a++) + { + float ang = (a / 16f) * MathF.Tau; + float cx = Math.Clamp(baseX + MathF.Cos(ang) * r, -maxB, maxB); + float cz = Math.Clamp(baseZ + MathF.Sin(ang) * r, -maxB, maxB); + if (IsClearSquadMemberCandidate(cx, cz, pad, maxB, minNy, placed, placedCount)) + { + return (cx, cz); + } + } + } + } + + return FindClearDropPoint(baseX, baseZ, pad); + } + + private bool IsClearSquadMemberCandidate( + float cx, + float cz, + float pad, + float maxB, + float minNy, + ReadOnlySpan<(float X, float Z)> placed, + int placedCount) + { + const float minMemberSepSq = 14.5f * 14.5f; + if (MathF.Abs(cx) > maxB || MathF.Abs(cz) > maxB) return false; + if (MapKind == ArenaMapKind.Sion && SionMap is not null) + { + if (SionMap.IsInsideAnyBuildingXz(cx, cz, pad)) return false; + if (minNy > 0f && Terrain.SampleNormal(cx, cz).Ny < minNy) return false; + } + else if (IsNearCoverBox(cx, cz, pad)) + { + return false; + } + for (int k = 0; k < placedCount; k++) + { + float dx = cx - placed[k].X; + float dz = cz - placed[k].Z; + if (dx * dx + dz * dz < minMemberSepSq) return false; + } + return true; + } + private List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)> BuildInitialLootTargetsSion() { var targets = new List<(float X, float Z, ChassisSpec? Chassis, ModuleSpec? Module)>(40); diff --git a/src/RustToDust.Core/OrbitalDropSystem.cs b/src/RustToDust.Core/OrbitalDropSystem.cs index a94a2b4..3d36dc5 100644 --- a/src/RustToDust.Core/OrbitalDropSystem.cs +++ b/src/RustToDust.Core/OrbitalDropSystem.cs @@ -69,7 +69,7 @@ namespace RustToDust.Core public static class DropWaveConfig { - public static readonly float[] WaveTimes = { 0f, 75f, 155f, 235f }; + public static readonly float[] WaveTimes = { 0f, 85f, 165f, 245f }; public const int MaxRespawnWave = 2; public const float SionCutoffRadius = 580f; public const float DesertCutoffRadius = 260f; @@ -91,29 +91,35 @@ namespace RustToDust.Core float PodFootRadius, float SafetyMarginM) { - public static readonly OrbitalPodPreset Contender = new( - StartAltAgl: 410f, - InitialVelY: -28.0f, - TerminalSpeed: 78.0f, - NominalRetroAccel: 105.0f, - TargetTouchdownSpeed: 2.2f, - SteerAccel: 28.0f, - FreefallHorizDrag: 0.90f, + public static OrbitalPodPreset GetContender(ArenaMapKind mapKind) => new( + StartAltAgl: mapKind == ArenaMapKind.Sion ? 1620.0f : 840.0f, + InitialVelY: -24.0f, + TerminalSpeed: 62.0f, + NominalRetroAccel: 125.0f, + TargetTouchdownSpeed: 2.1f, + SteerAccel: 118.0f, + FreefallHorizDrag: 0.95f, BurnHorizDrag: 4.5f, PodFootRadius: 1.65f, SafetyMarginM: 4.0f); - public static readonly OrbitalPodPreset Gear = new( - StartAltAgl: 260f, - InitialVelY: -52.0f, - TerminalSpeed: 90.0f, + public static OrbitalPodPreset GetGear(ArenaMapKind mapKind) => new( + StartAltAgl: mapKind == ArenaMapKind.Sion ? 1580.0f : 740.0f, + InitialVelY: -44.0f, + TerminalSpeed: 68.0f, NominalRetroAccel: 140.0f, - TargetTouchdownSpeed: 2.2f, - SteerAccel: 0f, - FreefallHorizDrag: 0.90f, + TargetTouchdownSpeed: 2.1f, + SteerAccel: 0.0f, + FreefallHorizDrag: 0.95f, BurnHorizDrag: 4.5f, PodFootRadius: 1.1f, SafetyMarginM: 3.5f); + + public static float GetStartAltAgl(OrbitalPodKind kind, ArenaMapKind mapKind) => + kind == OrbitalPodKind.Contender ? GetContender(mapKind).StartAltAgl : GetGear(mapKind).StartAltAgl; + + public static readonly OrbitalPodPreset Contender = GetContender(ArenaMapKind.Desert); + public static readonly OrbitalPodPreset Gear = GetGear(ArenaMapKind.Desert); } public sealed class OrbitalPod @@ -278,37 +284,65 @@ namespace RustToDust.Core } } - float xCand = Math.Clamp(pod.X + vxNext * dt, -maxBound, maxBound); - float zCand = Math.Clamp(pod.Z + vzNext * dt, -maxBound, maxBound); + float targetX = Math.Clamp(pod.X + vxNext * dt, -maxBound, maxBound); + float targetZ = Math.Clamp(pod.Z + vzNext * dt, -maxBound, maxBound); + float candDx = targetX - pod.X; + float candDz = targetZ - pod.Z; + float candDist = MathF.Sqrt(candDx * candDx + candDz * candDz); + int subSteps = Math.Clamp((int)MathF.Ceiling(candDist / 0.75f), 1, 4); - // Lateral Building Wall & Stepped-Roof Guard: reject/slide horizontal moves that violate stopping altitude or disallowed roof entry - DropSurfaceSample sampleNext = surfaceQuery(xCand, zCand, preset.PodFootRadius, pod.Y + 1.0f); - if (IsBlockedHorizontalMove(pod, sampleNow, sampleNext, surfaceNow, hStop)) + // Lateral Building Wall & Stepped-Roof Guard: swept <= 0.75m horizontal sub-steps reject/slide before wall entry + float curX = pod.X; + float curZ = pod.Z; + DropSurfaceSample curSample = sampleNow; + float curSurfaceY = surfaceNow; + float subDt = dt / subSteps; + + for (int s = 0; s < subSteps; s++) { - DropSurfaceSample slideX = surfaceQuery(xCand, pod.Z, preset.PodFootRadius, pod.Y + 1.0f); - DropSurfaceSample slideZ = surfaceQuery(pod.X, zCand, preset.PodFootRadius, pod.Y + 1.0f); - if (!IsBlockedHorizontalMove(pod, sampleNow, slideX, surfaceNow, hStop)) + float stepX = Math.Clamp(curX + vxNext * subDt, -maxBound, maxBound); + float stepZ = Math.Clamp(curZ + vzNext * subDt, -maxBound, maxBound); + DropSurfaceSample stepSample = surfaceQuery(stepX, stepZ, preset.PodFootRadius, pod.Y + 1.0f); + if (IsBlockedHorizontalMove(pod, curSample, stepSample, curSurfaceY, hStop)) { - zCand = pod.Z; - vzNext = 0f; - sampleNext = slideX; - } - else if (!IsBlockedHorizontalMove(pod, sampleNow, slideZ, surfaceNow, hStop)) - { - xCand = pod.X; - vxNext = 0f; - sampleNext = slideZ; + DropSurfaceSample slideX = surfaceQuery(stepX, curZ, preset.PodFootRadius, pod.Y + 1.0f); + DropSurfaceSample slideZ = surfaceQuery(curX, stepZ, preset.PodFootRadius, pod.Y + 1.0f); + if (!IsBlockedHorizontalMove(pod, curSample, slideX, curSurfaceY, hStop)) + { + curX = stepX; + vzNext = 0f; + curSample = slideX; + } + else if (!IsBlockedHorizontalMove(pod, curSample, slideZ, curSurfaceY, hStop)) + { + curZ = stepZ; + vxNext = 0f; + curSample = slideZ; + } + else + { + vxNext = 0f; + vzNext = 0f; + break; + } } else { - xCand = pod.X; - zCand = pod.Z; - vxNext = 0f; - vzNext = 0f; - sampleNext = sampleNow; + curX = stepX; + curZ = stepZ; + curSample = stepSample; } + + float subTerrain = terrain.SampleHeight(curX, curZ); + curSurfaceY = curSample.IsBuildingRoof + ? MathF.Max(subTerrain, curSample.SurfaceY) + : subTerrain; } + float xCand = curX; + float zCand = curZ; + DropSurfaceSample sampleNext = curSample; + float terrainNext = terrain.SampleHeight(xCand, zCand); float surfaceNext = sampleNext.IsBuildingRoof ? MathF.Max(terrainNext, sampleNext.SurfaceY) @@ -623,9 +657,17 @@ namespace RustToDust.Core { CancelContenderPod(c.Id); - var preset = OrbitalPodPreset.Contender; + var preset = OrbitalPodPreset.GetContender(_state.MapKind); float groundY = ResolveGroundSurfaceY(targetX, targetZ, preset.PodFootRadius, surfaceQuery); - float stagger = ((c.Id % 3) - 1) * 6f; + float stagger; + if (_state.SquadSize > 1) + { + (_, _, stagger) = MatchState.GetSquadFormationOffset(_state.GetSquadMemberRank(c.Id)); + } + else + { + stagger = ((c.Id % 3) - 1) * 6f; + } float startY = groundY + preset.StartAltAgl + stagger; var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yaw); @@ -708,7 +750,7 @@ namespace RustToDust.Core ModuleSpec? module, DropSurfaceQuery surfaceQuery) { - var preset = OrbitalPodPreset.Gear; + var preset = OrbitalPodPreset.GetGear(_state.MapKind); float groundY = ResolveGroundSurfaceY(targetX, targetZ, preset.PodFootRadius, surfaceQuery); float startY = groundY + preset.StartAltAgl; float yaw = (float)((_nextPodId * 1.17f) % MathF.Tau); @@ -849,23 +891,106 @@ namespace RustToDust.Core return; } - // AI steers gently toward nearest unpicked GroundDrop within 180m or inward away from ring perimeter + // Squad V-chevron formation-follow above 140m AGL (only while leader is also above 140m split altitude) + if (_state.SquadSize > 1 && pod.LastAgl > 140f) + { + var leader = _state.GetSquadLeader(ai.SquadId); + if (leader is not null && leader.Id != ai.Id && leader.IsInDropPod && leader.ActivePodId.HasValue) + { + var leaderPod = FindPodById(leader.ActivePodId.Value); + if (leaderPod is not null && leaderPod.Phase == OrbitalPodPhase.Freefall && leaderPod.LastAgl > 140f) + { + Vector2 fwd = new(leaderPod.LookForwardX, leaderPod.LookForwardZ); + if (fwd.LengthSquared() < 1e-4f) + { + fwd = new Vector2(MathF.Sin(leaderPod.Yaw), MathF.Cos(leaderPod.Yaw)); + } + else + { + fwd = Vector2.Normalize(fwd); + } + Vector2 right = new(-fwd.Y, fwd.X); + int rank = _state.GetSquadMemberRank(ai.Id); + var (fwdOff, sideOff, _) = MatchState.GetSquadFormationOffset(rank); + float relFwd = fwdOff - 8f; + float formWorldX = fwd.X * relFwd + right.X * sideOff; + float formWorldZ = fwd.Y * relFwd + right.Y * sideOff; + + float fdx = (leaderPod.X + formWorldX) - pod.X; + float fdz = (leaderPod.Z + formWorldZ) - pod.Z; + float fDist = MathF.Sqrt(fdx * fdx + fdz * fdz); + if (fDist > 1.5f) + { + pod.LookForwardX = fdx / fDist; + pod.LookForwardZ = fdz / fDist; + pod.Yaw = MathF.Atan2(pod.LookForwardX, pod.LookForwardZ); + pod.SteerForwardCmd = Math.Clamp(fDist * 0.08f, 0f, 1f); + pod.SteerRightCmd = 0f; + } + else + { + pod.SteerForwardCmd = 0f; + pod.SteerRightCmd = 0f; + } + return; + } + } + } + + // Below 140m AGL (or FFA): split cleanly onto clear ground >= 12m from squadmates float goalX = 0f; float goalZ = 0f; bool hasGoal = false; + bool urgentSplit = false; float safeLimit = MathF.Max(40f, _state.Spectators.SafeRadius - 35f); float distFromCenter = MathF.Sqrt(pod.X * pod.X + pod.Z * pod.Z); - if (distFromCenter > safeLimit) + + if (_state.SquadSize > 1) + { + bool tooCloseNow = IsTooCloseToSquadmate(ai, pod.X, pod.Z, 15.5f, out float repulseX, out float repulseZ); + float predX = pod.X + pod.VelX * 0.65f; + float predZ = pod.Z + pod.VelZ * 0.65f; + bool tooClosePred = !tooCloseNow && IsTooCloseToSquadmate(ai, predX, predZ, 15.0f, out repulseX, out repulseZ, lookaheadSec: 0.65f); + bool tooCloseToAlly = tooCloseNow || tooClosePred; + + var surfNow = _state.DefaultDropSurfaceQuery(pod.X, pod.Z, OrbitalPodPreset.GetContender(_state.MapKind).PodFootRadius, pod.Y + 1.0f); + bool overInvalidBuilding = surfNow.IsInsideBuildingFootprint || (surfNow.IsBuildingRoof && !pod.AllowFlatRoofLanding); + if (tooCloseToAlly || overInvalidBuilding) + { + urgentSplit = tooCloseToAlly; + float seekX = tooCloseToAlly ? repulseX : pod.X; + float seekZ = tooCloseToAlly ? repulseZ : pod.Z; + var (cx, cz) = FindClearDropPointAvoidingSquadmates( + ai, + seekX, + seekZ, + 4.5f, + 15.5f, + _state.DefaultDropSurfaceQuery, + pod.AllowFlatRoofLanding); + goalX = cx; + goalZ = cz; + hasGoal = true; + } + } + + if (!hasGoal && distFromCenter > safeLimit) { hasGoal = true; } - else + else if (!hasGoal) { float bestSq = 180f * 180f; for (int i = 0; i < _state.GroundDrops.Count; i++) { var d = _state.GroundDrops[i]; if (d.PickedUp) continue; + if (_state.SquadSize > 1 && + (IsTooCloseToSquadmate(ai, d.X, d.Z, 16.0f, out _, out _) || + IsGroundDropClaimedBySquadmate(ai, pod, d.X, d.Z))) + { + continue; + } float dx = d.X - pod.X; float dz = d.Z - pod.Z; float d2 = dx * dx + dz * dz; @@ -884,11 +1009,14 @@ namespace RustToDust.Core float dx = goalX - pod.X; float dz = goalZ - pod.Z; float len = MathF.Sqrt(dx * dx + dz * dz); - if (len > 4f) + float minLen = urgentSplit ? 0.5f : 4f; + if (len > minLen) { pod.LookForwardX = dx / len; pod.LookForwardZ = dz / len; - pod.SteerForwardCmd = 0.65f; + pod.SteerForwardCmd = urgentSplit + ? Math.Clamp(len * 0.15f, 0.5f, 1.0f) + : Math.Clamp(len * 0.035f, 0.2f, 0.55f); pod.SteerRightCmd = 0f; return; } @@ -898,6 +1026,144 @@ namespace RustToDust.Core pod.SteerRightCmd = 0f; } + private (float X, float Z) FindClearDropPointAvoidingSquadmates( + ContenderState self, + float targetX, + float targetZ, + float pad, + float minSepM, + DropSurfaceQuery surfaceQuery, + bool allowFlatRoofLanding) + { + float footRadius = OrbitalPodPreset.GetContender(_state.MapKind).PodFootRadius; + var (cx, cz) = _state.FindClearDropPoint(targetX, targetZ, pad); + if (!IsTooCloseToSquadmate(self, cx, cz, minSepM, out _, out _)) + { + var surf0 = surfaceQuery(cx, cz, footRadius, _state.Terrain.SampleHeight(cx, cz) + 250f); + if (!surf0.IsInsideBuildingFootprint && !(surf0.IsBuildingRoof && !allowFlatRoofLanding)) + { + return (cx, cz); + } + } + + float baseAngle = self.Id * 2.1f; + float[] radii = { 16f, 24f, 34f, 46f, 60f }; + for (int rIdx = 0; rIdx < radii.Length; rIdx++) + { + float radius = radii[rIdx]; + for (int k = 0; k < 12; k++) + { + float ang = baseAngle + k * (MathF.Tau / 12f); + float rawX = targetX + MathF.Cos(ang) * radius; + float rawZ = targetZ + MathF.Sin(ang) * radius; + var (candX, candZ) = _state.FindClearDropPoint(rawX, rawZ, pad); + if (IsTooCloseToSquadmate(self, candX, candZ, minSepM, out _, out _)) + { + continue; + } + var surf = surfaceQuery(candX, candZ, footRadius, _state.Terrain.SampleHeight(candX, candZ) + 250f); + if (surf.IsInsideBuildingFootprint || (surf.IsBuildingRoof && !allowFlatRoofLanding)) + { + continue; + } + return (candX, candZ); + } + } + + return (cx, cz); + } + + private bool IsGroundDropClaimedBySquadmate(ContenderState self, OrbitalPod selfPod, float dropX, float dropZ) + { + float selfDx = dropX - selfPod.X; + float selfDz = dropZ - selfPod.Z; + float selfDistSq = selfDx * selfDx + selfDz * selfDz; + + for (int i = 0; i < _activePods.Count; i++) + { + var otherPod = _activePods[i]; + if (otherPod.PodKind != OrbitalPodKind.Contender || otherPod.ContenderId == self.Id) continue; + if (!_state.AreAllies(self.Id, otherPod.ContenderId)) continue; + float odx = dropX - otherPod.X; + float odz = dropZ - otherPod.Z; + float otherDistSq = odx * odx + odz * odz; + if (otherDistSq < selfDistSq - 1e-2f || + (MathF.Abs(otherDistSq - selfDistSq) <= 1e-2f && otherPod.ContenderId < self.Id)) + { + return true; + } + } + return false; + } + + private bool IsTooCloseToSquadmate( + ContenderState self, + float x, + float z, + float minSepM, + out float escapeX, + out float escapeZ, + float lookaheadSec = 0f) + { + escapeX = x; + escapeZ = z; + float minSepSq = minSepM * minSepM; + bool any = false; + int closeCount = 0; + float sumRx = 0f; + float sumRz = 0f; + float singleOtherX = x; + float singleOtherZ = z; + + void Accumulate(int otherId, float ox, float oz) + { + float dx = x - ox; + float dz = z - oz; + float d2 = dx * dx + dz * dz; + if (d2 < minSepSq) + { + float dist = MathF.Sqrt(d2); + float nx = dist > 0.1f ? dx / dist : MathF.Cos((self.Id + otherId + 1) * 2.1f); + float nz = dist > 0.1f ? dz / dist : MathF.Sin((self.Id + otherId + 1) * 2.1f); + float weight = MathF.Max(1f, minSepM - dist + 2f); + sumRx += nx * weight; + sumRz += nz * weight; + singleOtherX = ox; + singleOtherZ = oz; + closeCount++; + any = true; + } + } + + for (int i = 0; i < _activePods.Count; i++) + { + var otherPod = _activePods[i]; + if (otherPod.PodKind != OrbitalPodKind.Contender || otherPod.ContenderId == self.Id) continue; + if (!_state.AreAllies(self.Id, otherPod.ContenderId)) continue; + Accumulate(otherPod.ContenderId, otherPod.X + otherPod.VelX * lookaheadSec, otherPod.Z + otherPod.VelZ * lookaheadSec); + } + + for (int i = 0; i < _state.Contenders.Count; i++) + { + var c = _state.Contenders[i]; + if (c.Id == self.Id || !c.Alive || c.IsInDropPod) continue; + if (!_state.AreAllies(self.Id, c.Id)) continue; + Accumulate(c.Id, c.X, c.Z); + } + + if (any) + { + float rLen = MathF.Sqrt(sumRx * sumRx + sumRz * sumRz); + float rx = rLen > 1e-4f ? sumRx / rLen : MathF.Cos(self.Id * 2.1f); + float rz = rLen > 1e-4f ? sumRz / rLen : MathF.Sin(self.Id * 2.1f); + float anchorX = closeCount == 1 ? singleOtherX : x; + float anchorZ = closeCount == 1 ? singleOtherZ : z; + escapeX = anchorX + rx * (minSepM + 4.5f); + escapeZ = anchorZ + rz * (minSepM + 4.5f); + } + return any; + } + public void ApplyPlayerSteerInput(ContenderState human, DropSurfaceQuery? surfaceQuery = null) { if (!human.IsInDropPod || !human.ActivePodId.HasValue) @@ -954,12 +1220,24 @@ namespace RustToDust.Core for (int i = _activePods.Count - 1; i >= 0; i--) { var pod = _activePods[i]; + DropClearPointQuery clearQuery = _state.FindClearDropPoint; if (pod.PodKind == OrbitalPodKind.Contender && pod.ContenderId >= 0 && pod.ContenderId < _state.Contenders.Count) { var c = _state.Contenders[pod.ContenderId]; pod.AllowFlatRoofLanding = c.IsHuman && _state.MapKind == ArenaMapKind.Sion; + if (_state.SquadSize > 1) + { + clearQuery = (qx, qz, qpad) => FindClearDropPointAvoidingSquadmates( + c, + qx, + qz, + qpad, + 14.5f, + surfaceQuery, + pod.AllowFlatRoofLanding); + } } bool touched = OrbitalDropKinematics.StepPod( @@ -967,7 +1245,7 @@ namespace RustToDust.Core dt, _state.Terrain, surfaceQuery, - _state.FindClearDropPoint, + clearQuery, out bool retroBurnStarted, out DropSurfaceSample touchSample); @@ -1197,8 +1475,21 @@ namespace RustToDust.Core { if (emitEvents && !touchSample.IsBuildingRoof) { - _state.Terrain.StampCrater(pod.X, pod.Z, pod.PodKind == OrbitalPodKind.Contender ? 3.4f : 2.1f, 0.32f); - _state.Terrain.StampScorch(pod.X, pod.Z, pod.PodKind == OrbitalPodKind.Contender ? 4.2f : 2.6f); + _state.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = pod.X, + Z = pod.Z, + Radius = pod.PodKind == OrbitalPodKind.Contender ? 3.4f : 2.1f, + Depth = 0.32f + }); + _state.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Scorch, + X = pod.X, + Z = pod.Z, + Radius = pod.PodKind == OrbitalPodKind.Contender ? 4.2f : 2.6f + }); } // Re-sample ground height after crater stamp diff --git a/src/RustToDust.Core/SimEvents.cs b/src/RustToDust.Core/SimEvents.cs index 84211fb..980a2df 100644 --- a/src/RustToDust.Core/SimEvents.cs +++ b/src/RustToDust.Core/SimEvents.cs @@ -8,7 +8,8 @@ namespace RustToDust.Core { Crater = 0, Scorch = 1, - Track = 2 + Track = 2, + Rubble = 3 } public enum SlotControlReason : byte @@ -34,6 +35,8 @@ 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 { } @@ -252,6 +255,7 @@ namespace RustToDust.Core [Key(8)] public ContenderLoadoutEvent Loadout { get; set; } = new(); [Key(9)] public byte LifecycleByte { get; set; } [Key(10)] public byte RespawnsRemaining { get; set; } + [Key(11)] public byte SquadId { get; set; } } [MessagePackObject] @@ -320,6 +324,9 @@ namespace RustToDust.Core [Key(13)] public bool RespawnCutoffReached { get; set; } [Key(14)] public List ActivePods { get; set; } = new(); [Key(15)] public LobbySnapshotDto? Lobby { get; set; } + [Key(16)] public byte SquadSize { get; set; } = 1; + [Key(17)] public byte[]? ContenderSquadIds { get; set; } + [Key(18)] public byte[]? PersistentScars { get; set; } } [MessagePackObject] @@ -329,6 +336,7 @@ namespace RustToDust.Core [Key(1)] public string Callsign { get; set; } = string.Empty; [Key(2)] public bool IsHuman { get; set; } [Key(3)] public bool IsReady { get; set; } + [Key(4)] public byte SquadId { get; set; } } [MessagePackObject] @@ -341,6 +349,7 @@ namespace RustToDust.Core [Key(4)] public byte SelectedMap { get; set; } [Key(5)] public int SelectedSeed { get; set; } [Key(6)] public List Slots { get; set; } = new(); + [Key(7)] public byte SquadSize { get; set; } = 3; } [MessagePackObject] @@ -375,6 +384,8 @@ namespace RustToDust.Core [Union(11, typeof(LobbyStartCmdMsg))] [Union(12, typeof(LobbySnapshotMsg))] [Union(13, typeof(ClientKeepaliveMsg))] + [Union(14, typeof(LobbySquadCmdMsg))] + [Union(15, typeof(RepairArenaCmdMsg))] public interface ISchemaWireMessage { } @@ -470,6 +481,14 @@ namespace RustToDust.Core [Key(0)] public uint ReqSeq { get; set; } [Key(1)] public int Seed { get; set; } [Key(2)] public byte MapKind { get; set; } + [Key(3)] public byte SquadSize { get; set; } = 3; + } + + [MessagePackObject] + public sealed class LobbySquadCmdMsg : ISchemaWireMessage + { + [Key(0)] public uint ReqSeq { get; set; } + [Key(1)] public byte TargetSquadId { get; set; } } [MessagePackObject] @@ -485,6 +504,28 @@ 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 + { + [Key(0)] public uint LedgerRevision { get; set; } + } + + [MessagePackObject] + public sealed class RepairArenaCmdMsg : ISchemaWireMessage + { + [Key(0)] public uint ReqSeq { get; set; } + } + [MessagePackObject] public sealed class ClientKeepaliveMsg : ISchemaWireMessage { diff --git a/src/RustToDust.Core/SionMapLoader.cs b/src/RustToDust.Core/SionMapLoader.cs index 2e4b3dc..3981bb0 100644 --- a/src/RustToDust.Core/SionMapLoader.cs +++ b/src/RustToDust.Core/SionMapLoader.cs @@ -2,6 +2,7 @@ using System; using System.Buffers.Binary; using System.Collections.Generic; using System.IO; +using System.IO.Compression; using System.Numerics; using System.Text.Json; @@ -29,7 +30,14 @@ namespace RustToDust.Core float MinY, float MaxY, string SurfaceTexture, - IReadOnlyList Tiles); + IReadOnlyList Tiles, + string DemAssetHash = "", + string HeightmapFile = "heightmap_05m.u16z", + float HeightmapMinY = 0f, + float HeightmapScale = 1f, + string SurfaceMaskTexture = "terrain_surface_mask.png", + int BuildingTileGrid = 6, + float BuildingTileSizeMeters = 512f); public readonly record struct SionBuildingAabb( string Id, @@ -76,7 +84,7 @@ namespace RustToDust.Core { private const int SpatialGridRes = 64; - private readonly float[] _heights; + private readonly ushort[] _baseDem; private readonly SionBuildingAabb[] _buildings; private readonly List[] _cellBuildings; private readonly float[] _cellMinGroundY; @@ -87,15 +95,27 @@ namespace RustToDust.Core internal SionMapData( string directoryPath, SionMetadata metadata, - float[] heights, + ushort[] baseDem, + float baseDemMinY, + float baseDemScale, SionBuildingAabb[] buildings, - SionCollisionMesh[] collisionMeshes) + SionCollisionMesh[] collisionMeshes, + SionTreeCatalog? trees = null) { DirectoryPath = directoryPath; Metadata = metadata; - _heights = heights; + _baseDem = baseDem; + BaseDemMinY = baseDemMinY; + BaseDemScale = baseDemScale; _buildings = buildings; CollisionMeshes = collisionMeshes; + Trees = trees ?? SionTreeCatalog.Empty; + string baseFingerprint = !string.IsNullOrWhiteSpace(metadata.DemAssetHash) + ? $"sion:{metadata.DemAssetHash}" + : $"sion:{metadata.GridRes}:{metadata.CellSizeMeters:F3}"; + AssetFingerprint = !string.IsNullOrEmpty(Trees.AssetHash) + ? $"{baseFingerprint}:trees:{Trees.AssetHash}" + : baseFingerprint; _halfExtent = metadata.SizeMeters * 0.5f; _cellSize = metadata.SizeMeters / SpatialGridRes; @@ -131,9 +151,14 @@ namespace RustToDust.Core public string DirectoryPath { get; } public SionMetadata Metadata { get; } - public ReadOnlySpan Heights => _heights; + public ushort[] BaseDem => _baseDem; + public float BaseDemMinY { get; } + public float BaseDemScale { get; } + public string AssetFingerprint { get; } + 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) { @@ -320,45 +345,16 @@ namespace RustToDust.Core private static readonly object CacheLock = new(); private static readonly Dictionary Cache = new(StringComparer.OrdinalIgnoreCase); - public static string LocateSionDirectory() - { - string? envRoot = Environment.GetEnvironmentVariable("RTD_ASSETS_DIR"); - if (!string.IsNullOrWhiteSpace(envRoot)) - { - string envSion = Path.Combine(envRoot, "maps", "sion"); - if (IsValidSionDirectory(envSion)) - { - return Path.GetFullPath(envSion); - } - } - - foreach (string start in new[] { AppContext.BaseDirectory, Directory.GetCurrentDirectory() }) - { - if (string.IsNullOrWhiteSpace(start) || !Directory.Exists(start)) - { - continue; - } - - var dir = new DirectoryInfo(Path.GetFullPath(start)); - while (dir is not null) - { - string candidate = Path.Combine(dir.FullName, "assets", "maps", "sion"); - if (IsValidSionDirectory(candidate)) - { - return Path.GetFullPath(candidate); - } - dir = dir.Parent; - } - } - - throw new DirectoryNotFoundException( - $"Could not locate 'assets/maps/sion' containing metadata.json and heightmap.f32 from BaseDirectory '{AppContext.BaseDirectory}' or CurrentDirectory '{Directory.GetCurrentDirectory()}'."); - } + public static string LocateSionDirectory() => + AssetPathResolver.LocateSubdirectory( + Path.Combine("maps", "sion"), + IsValidSionDirectory, + "containing metadata.json and heightmap_05m.u16z"); private static bool IsValidSionDirectory(string dir) => Directory.Exists(dir) && File.Exists(Path.Combine(dir, "metadata.json")) && - File.Exists(Path.Combine(dir, "heightmap.f32")) && + File.Exists(Path.Combine(dir, "heightmap_05m.u16z")) && File.Exists(Path.Combine(dir, "buildings_manifest.json")); public static SionMapData Load(string? sionDirectory = null) @@ -373,7 +369,12 @@ namespace RustToDust.Core } var meta = LoadMetadata(Path.Combine(root, "metadata.json")); - float[] heights = LoadHeightmap(Path.Combine(root, "heightmap.f32"), meta.GridRes); + string hmFile = string.IsNullOrWhiteSpace(meta.HeightmapFile) ? "heightmap_05m.u16z" : meta.HeightmapFile; + ushort[] baseDem = LoadHeightmapU16z( + Path.Combine(root, hmFile), + meta.GridRes, + out float demMinY, + out float demScale); SionBuildingAabb[] buildings = LoadBuildingsManifest(Path.Combine(root, "buildings_manifest.json")); var colMeshes = new SionCollisionMesh[meta.Tiles.Count]; for (int i = 0; i < meta.Tiles.Count; i++) @@ -383,7 +384,12 @@ namespace RustToDust.Core colMeshes[i] = LoadRcolFile(colPath, t.Tx, t.Tz); } - var data = new SionMapData(root, meta, heights, 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; @@ -424,29 +430,82 @@ namespace RustToDust.Core MinY: r.GetProperty("minY").GetSingle(), MaxY: r.GetProperty("maxY").GetSingle(), SurfaceTexture: r.GetProperty("surfaceTexture").GetString() ?? "terrain_surface.png", - Tiles: tiles); + Tiles: tiles, + DemAssetHash: r.TryGetProperty("demAssetHash", out var dh) ? (dh.GetString() ?? "") : "", + HeightmapFile: r.TryGetProperty("heightmapFile", out var hf) ? (hf.GetString() ?? "heightmap_05m.u16z") : "heightmap_05m.u16z", + HeightmapMinY: r.TryGetProperty("heightmapMinY", out var hmin) ? hmin.GetSingle() : 0f, + HeightmapScale: r.TryGetProperty("heightmapScale", out var hsc) ? hsc.GetSingle() : 1f, + SurfaceMaskTexture: r.TryGetProperty("surfaceMaskTexture", out var sm) ? (sm.GetString() ?? "terrain_surface_mask.png") : "terrain_surface_mask.png", + BuildingTileGrid: r.TryGetProperty("buildingTileGrid", out var btg) ? btg.GetInt32() : 6, + BuildingTileSizeMeters: r.TryGetProperty("buildingTileSizeMeters", out var bts) ? bts.GetSingle() : 512f); } - private static float[] LoadHeightmap(string path, int gridRes) + private static ushort[] LoadHeightmapU16z(string path, int expectedGridRes, out float minY, out float scale) { - byte[] raw = File.ReadAllBytes(path); - int expectedCount = gridRes * gridRes; - if (raw.Length != expectedCount * 4) + byte[] fileBytes = File.ReadAllBytes(path); + if (fileBytes.Length < 24) { - throw new InvalidDataException( - $"Expected heightmap.f32 byte length {expectedCount * 4} ({gridRes}x{gridRes}), got {raw.Length}."); + throw new InvalidDataException($"Heightmap file '{path}' too small ({fileBytes.Length} bytes)."); } - var heights = new float[expectedCount]; - ReadOnlySpan span = raw; - for (int i = 0; i < expectedCount; i++) + ReadOnlySpan hdr = fileBytes.AsSpan(0, 24); + if (hdr[0] != (byte)'R' || hdr[1] != (byte)'D' || hdr[2] != (byte)'H' || hdr[3] != (byte)'M') { - float v = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(i * 4, 4)); - if (!float.IsFinite(v)) + throw new InvalidDataException($"Invalid RDHM magic in '{path}'."); + } + + uint version = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(4, 4)); + if (version != 2) + { + throw new InvalidDataException($"Unsupported RDHM version {version} in '{path}'."); + } + + int gridRes = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(8, 4))); + if (gridRes != expectedGridRes) + { + throw new InvalidDataException($"RDHM gridRes mismatch in '{path}': header={gridRes}, metadata={expectedGridRes}."); + } + + minY = BinaryPrimitives.ReadSingleLittleEndian(hdr.Slice(12, 4)); + scale = BinaryPrimitives.ReadSingleLittleEndian(hdr.Slice(16, 4)); + int rawByteCount = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(20, 4))); + int expectedSamples = gridRes * gridRes; + if (rawByteCount != expectedSamples * 2) + { + throw new InvalidDataException($"RDHM rawByteCount mismatch in '{path}': {rawByteCount} != {expectedSamples * 2}."); + } + + byte[] raw = new byte[rawByteCount]; + using (var ms = new MemoryStream(fileBytes, 24, fileBytes.Length - 24, writable: false)) + using (var zlib = new ZLibStream(ms, CompressionMode.Decompress)) + { + int totalRead = 0; + while (totalRead < rawByteCount) { - throw new InvalidDataException($"Non-finite heightmap value at index {i}: {v}"); + int read = zlib.Read(raw, totalRead, rawByteCount - totalRead); + if (read <= 0) + { + throw new InvalidDataException($"Unexpected EOF decompressing RDHM payload in '{path}' at {totalRead}/{rawByteCount}."); + } + totalRead += read; + } + } + + var heights = new ushort[expectedSamples]; + ReadOnlySpan span = raw; + for (int r = 0; r < gridRes; r++) + { + int rowStart = r * gridRes; + ushort pred = r > 0 ? heights[(r - 1) * gridRes] : (ushort)0; + for (int c = 0; c < gridRes; c++) + { + int idx = rowStart + c; + ushort zz = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(idx * 2, 2)); + short d = unchecked((short)((zz >> 1) ^ -(zz & 1))); + ushort val = unchecked((ushort)(pred + d)); + heights[idx] = val; + pred = val; } - heights[i] = v; } return heights; } diff --git a/src/RustToDust.Core/SionTreeField.cs b/src/RustToDust.Core/SionTreeField.cs new file mode 100644 index 0000000..542e043 --- /dev/null +++ b/src/RustToDust.Core/SionTreeField.cs @@ -0,0 +1,539 @@ +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.IO; +using System.Numerics; +using System.Security.Cryptography; + +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(), string.Empty); + + public SionTreeCatalog(SionTreePlacement[] trees, string assetHash = "") + { + _trees = trees ?? throw new ArgumentNullException(nameof(trees)); + AssetHash = assetHash ?? string.Empty; + 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 string AssetHash { get; } + 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; + } + + string assetHash = Convert.ToHexString(SHA256.HashData(raw)).Substring(0, 16).ToLowerInvariant(); + return new SionTreeCatalog(trees, assetHash); + } + } + + /// + /// 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 = 3_200f; + + private readonly SionTreeCatalog _catalog; + private readonly byte[] _packedStates; + private readonly int[] _tileColVersions = new int[SionTreeCatalog.TileCount]; + private readonly Dictionary _treeDamage = new(); + + 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]++; + } + } + } + + _treeDamage.Clear(); + 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; + } + + if (blastDamage < 25f || (t.TrunkRadiusM >= 0.50f && blastDamage < 45f)) + { + continue; + } + + float dist = MathF.Sqrt(distSq); + float shellDist = MathF.Max(0f, dist - t.TrunkRadiusM); + float atten = MathF.Max(0f, 1f - shellDist / effectiveRadius); + float impulse = blastDamage * atten; + if (impulse <= 0f) + { + continue; + } + float snapThreshold = t.TrunkRadiusM >= 0.50f + ? 85f + t.TrunkRadiusM * 240f + : 35f + t.TrunkRadiusM * 180f; + float totalDmg = _treeDamage.TryGetValue(t.TreeId, out float prevDmg) + ? prevDmg + impulse + : impulse; + + SionTreeState targetState = cur; + if ((dist <= snapCoreRadius && blastDamage >= 65f) || totalDmg >= snapThreshold) + { + targetState = SionTreeState.Snapped; + _treeDamage.Remove(t.TreeId); + } + else + { + _treeDamage[t.TreeId] = totalDmg; + if (cur == SionTreeState.Intact) + { + 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.Core/SpectatorRing.cs b/src/RustToDust.Core/SpectatorRing.cs index 258befa..a53acb9 100644 --- a/src/RustToDust.Core/SpectatorRing.cs +++ b/src/RustToDust.Core/SpectatorRing.cs @@ -124,7 +124,7 @@ namespace RustToDust.Core { public const float InitialRadius = 560f; public const float MinRadius = 85f; - public const float GraceDuration = 30f; + public const float GraceDuration = 45f; public const float ShrinkDuration = 360f; public const int DefaultSpectatorCount = 56; public const float TargetMemoryDuration = 4.0f; diff --git a/src/RustToDust.Core/TerrainField.cs b/src/RustToDust.Core/TerrainField.cs index faa3738..e207104 100644 --- a/src/RustToDust.Core/TerrainField.cs +++ b/src/RustToDust.Core/TerrainField.cs @@ -11,7 +11,8 @@ namespace RustToDust.Core Road, Crater, Track, - Scorch + Scorch, + Rubble } public readonly record struct TerrainBrush( @@ -34,14 +35,15 @@ namespace RustToDust.Core { public const float ArenaSize = 1536f; public const float HalfExtent = 768f; - public const int TileGridCount = 8; - public const float TileSize = ArenaSize / TileGridCount; // 192m + public const int DesertTileGridCount = 8; + public const float TileSize = ArenaSize / DesertTileGridCount; // 192m private const int AccelGridCount = 64; private const int AccelCellCount = AccelGridCount * AccelGridCount; public const float MinWorldHeight = -18f; public const float MaxWorldHeight = 52f; public const float HeightSpan = MaxWorldHeight - MinWorldHeight; // 70m public const int MaxDynamicDecals = 256; + public const float CraterCoalesceRadiusMeters = 0.75f; private readonly record struct BrushPrecomp( float CosR, @@ -64,21 +66,33 @@ namespace RustToDust.Core private readonly List _brushes = new(); private readonly List _brushPrecomps = new(); - private readonly List[,] _tileBrushIndices = new List[TileGridCount, TileGridCount]; + private readonly List[,] _tileBrushIndices; private readonly List[] _cellBrushIndices = new List[AccelCellCount]; private readonly float[] _cellMaxHeight = new float[AccelCellCount]; private readonly float[] _cellBaseMaxHeight = new float[AccelCellCount]; private readonly Queue _dynamicDecalSlots = new(); private float[]? _heightmap; + private ushort[]? _sharedU16Heights; + private float _baseMinY; + private float _baseScale; + private readonly float[]?[,] _scarredTileHeights; private int _nextBrushId = 1; - public TerrainField(ulong seed) + public TerrainField(ulong seed, int tileGridCount = DesertTileGridCount) { - Seed = seed; - TileVersions = new int[TileGridCount, TileGridCount]; - for (int tz = 0; tz < TileGridCount; tz++) + if (tileGridCount <= 0) { - for (int tx = 0; tx < TileGridCount; tx++) + throw new ArgumentOutOfRangeException(nameof(tileGridCount)); + } + Seed = seed; + TileGridCount = tileGridCount; + StructuralTileVersions = new int[tileGridCount, tileGridCount]; + VisualTileVersions = new int[tileGridCount, tileGridCount]; + _tileBrushIndices = new List[tileGridCount, tileGridCount]; + _scarredTileHeights = new float[tileGridCount, tileGridCount][]; + for (int tz = 0; tz < tileGridCount; tz++) + { + for (int tx = 0; tx < tileGridCount; tx++) { _tileBrushIndices[tx, tz] = new List(32); } @@ -90,6 +104,7 @@ namespace RustToDust.Core } public ulong Seed { get; } + public int TileGridCount { get; } public bool IsHeightmapMode { get; private set; } public float MapSize { get; private set; } = ArenaSize; public float MapHalfExtent { get; private set; } = HalfExtent; @@ -98,11 +113,15 @@ namespace RustToDust.Core public float MapMaxHeight { get; private set; } = MaxWorldHeight; public int HeightmapRes { get; private set; } public float HeightmapCellSize { get; private set; } + public int PhysicsTileResolution => IsHeightmapMode ? ((HeightmapRes - 1) / TileGridCount + 1) : 0; + public ushort[]? SharedU16Heights => _sharedU16Heights; + public float BaseMinY => _baseMinY; + public float BaseScale => _baseScale; private float AccelCellSize => MapSize / AccelGridCount; public IReadOnlyList Brushes => _brushes; - public int[,] TileVersions { get; } - public ulong DirtyTileMask { get; private set; } - public ulong StructuralDirtyTileMask { get; private set; } + public int[,] StructuralTileVersions { get; } + public int[,] VisualTileVersions { get; } + public int[,] TileVersions => VisualTileVersions; public static TerrainField LoadHeightmap( float sizeMeters, @@ -125,12 +144,13 @@ namespace RustToDust.Core throw new ArgumentException($"Expected {gridRes * gridRes} height samples, got {heights.Length}.", nameof(heights)); } - var field = new TerrainField(seed) + int tileGridCount = Math.Max(1, (int)MathF.Round(sizeMeters / TileSize)); + var field = new TerrainField(seed, tileGridCount) { IsHeightmapMode = true, MapSize = sizeMeters, MapHalfExtent = sizeMeters * 0.5f, - MapTileSize = sizeMeters / TileGridCount, + MapTileSize = sizeMeters / tileGridCount, MapMinHeight = minY - 8f, MapMaxHeight = maxY + 4f, HeightmapRes = gridRes, @@ -138,9 +158,58 @@ namespace RustToDust.Core _heightmap = heights.ToArray() }; - float half = field.MapHalfExtent; - float cellSize = field.AccelCellSize; - float invDemStep = 1f / field.HeightmapCellSize; + field.InitializeAccelGridFromHeightmap(gridRes); + return field; + } + + public static TerrainField LoadSharedHeightmap( + float sizeMeters, + int gridRes, + int tileGridCount, + ushort[] sharedU16Heights, + float baseMinY, + float baseScale, + float worldMinY, + float worldMaxY, + ulong seed = 0UL) + { + if (sizeMeters <= 0f || !float.IsFinite(sizeMeters)) + { + throw new ArgumentOutOfRangeException(nameof(sizeMeters)); + } + if (gridRes < 2) + { + throw new ArgumentOutOfRangeException(nameof(gridRes)); + } + if (sharedU16Heights is null || sharedU16Heights.Length != gridRes * gridRes) + { + throw new ArgumentException($"Expected {gridRes * gridRes} u16 height samples, got {sharedU16Heights?.Length ?? 0}.", nameof(sharedU16Heights)); + } + + var field = new TerrainField(seed, tileGridCount) + { + IsHeightmapMode = true, + MapSize = sizeMeters, + MapHalfExtent = sizeMeters * 0.5f, + MapTileSize = sizeMeters / tileGridCount, + MapMinHeight = worldMinY - 8f, + MapMaxHeight = worldMaxY + 4f, + HeightmapRes = gridRes, + HeightmapCellSize = sizeMeters / (gridRes - 1), + _sharedU16Heights = sharedU16Heights, + _baseMinY = baseMinY, + _baseScale = baseScale + }; + + field.InitializeAccelGridFromHeightmap(gridRes); + return field; + } + + private void InitializeAccelGridFromHeightmap(int gridRes) + { + float half = MapHalfExtent; + float cellSize = AccelCellSize; + float invDemStep = 1f / HeightmapCellSize; for (int cz = 0; cz < AccelGridCount; cz++) { @@ -162,7 +231,9 @@ namespace RustToDust.Core int row = iz * gridRes; for (int ix = ix0; ix <= ix1; ix++) { - float h = field._heightmap[row + ix]; + float h = _sharedU16Heights is not null + ? _baseMinY + _sharedU16Heights[row + ix] * _baseScale + : _heightmap![row + ix]; if (h > cellMax) { cellMax = h; @@ -172,8 +243,8 @@ namespace RustToDust.Core int cellIdx = cz * AccelGridCount + cx; float boundedMax = float.IsNegativeInfinity(cellMax) ? 0f : cellMax + 0.05f; - field._cellBaseMaxHeight[cellIdx] = boundedMax; - field._cellMaxHeight[cellIdx] = boundedMax; + _cellBaseMaxHeight[cellIdx] = boundedMax; + _cellMaxHeight[cellIdx] = boundedMax; } } @@ -181,23 +252,12 @@ namespace RustToDust.Core { for (int tx = 0; tx < TileGridCount; tx++) { - field.TileVersions[tx, tz] = 1; - field.DirtyTileMask |= 1UL << (tz * TileGridCount + tx); + StructuralTileVersions[tx, tz] = 1; + VisualTileVersions[tx, tz] = 1; } } - - return field; } - public void ClearDirtyMask() - { - DirtyTileMask = 0UL; - StructuralDirtyTileMask = 0UL; - } - - public void ClearStructuralDirtyTile(int tx, int tz) => - StructuralDirtyTileMask &= ~(1UL << (tz * TileGridCount + tx)); - public IReadOnlyList GetTileBrushIndices(int tx, int tz) => _tileBrushIndices[tx, tz]; public static TerrainField Generate(ulong seed, IReadOnlyList coverBoxes) @@ -400,12 +460,12 @@ namespace RustToDust.Core } // Bump all initial tile versions to 1 so clients detect initial bake needed - for (int tz = 0; tz < TileGridCount; tz++) + for (int tz = 0; tz < field.TileGridCount; tz++) { - for (int tx = 0; tx < TileGridCount; tx++) + for (int tx = 0; tx < field.TileGridCount; tx++) { - field.TileVersions[tx, tz] = 1; - field.DirtyTileMask |= 1UL << (tz * TileGridCount + tx); + field.StructuralTileVersions[tx, tz] = 1; + field.VisualTileVersions[tx, tz] = 1; } } @@ -416,6 +476,40 @@ namespace RustToDust.Core { float clampedR = Math.Clamp(radius, 1.2f, 16f); float clampedDepth = Math.Clamp(MathF.Abs(depth), 0.15f, 4.5f); + + const float coalesceSq = CraterCoalesceRadiusMeters * CraterCoalesceRadiusMeters; + for (int i = _brushes.Count - 1; i >= 0; i--) + { + var existing = _brushes[i]; + if (existing.Kind != TerrainBrushKind.Crater || !existing.Dynamic) + { + continue; + } + + float dx = existing.X - x; + float dz = existing.Z - z; + if (dx * dx + dz * dz < coalesceSq) + { + float newR = MathF.Max(existing.RadiusX, clampedR); + float existingDepth = MathF.Abs(existing.HeightDelta); + float newDepth = MathF.Max(existingDepth, clampedDepth); + if (newR > existing.RadiusX || newDepth > existingDepth) + { + UnregisterBrushFromTiles(i, in existing); + var updated = existing with + { + RadiusX = newR, + RadiusZ = newR, + HeightDelta = -newDepth + }; + _brushes[i] = updated; + _brushPrecomps[i] = BrushPrecomp.From(in updated); + RegisterBrushInTiles(i, in updated, incrementTileVersion: true); + } + return; + } + } + AddBrush(new TerrainBrush( Id: 0, Kind: TerrainBrushKind.Crater, @@ -433,6 +527,27 @@ namespace RustToDust.Core Dynamic: true)); } + public void StampRubble(float x, float z, float radius, float heightDelta, float yaw = 0f) + { + float clampedR = Math.Clamp(radius, 1.5f, 18f); + float clampedH = Math.Clamp(MathF.Abs(heightDelta), 0.15f, 2.5f); + AddBrush(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.Rubble, + X: x, + Z: z, + RotationRad: yaw, + RadiusX: clampedR, + RadiusZ: clampedR, + HeightDelta: clampedH, + Roughness: 0.97f, + Metallic: 0.05f, + AlbedoR: 0.42f, + AlbedoG: 0.39f, + AlbedoB: 0.35f, + Dynamic: true)); + } + public void StampTrack(float x, float z, float yaw, float width, float length) { SetDynamicDecal(new TerrainBrush( @@ -472,13 +587,30 @@ namespace RustToDust.Core Dynamic: true)); } - public float SampleHeight(float x, float z) + public float SampleBaseHeight(float x, float z) { float half = MapHalfExtent; float cx = Math.Clamp(x, -half, half); float cz = Math.Clamp(z, -half, half); - float h = 0f; + if (_sharedU16Heights is not null) + { + int res = HeightmapRes; + float fx = Math.Clamp((cx + half) / HeightmapCellSize, 0f, res - 1f); + float fz = Math.Clamp((cz + half) / HeightmapCellSize, 0f, res - 1f); + int ix = Math.Clamp((int)fx, 0, res - 2); + int iz = Math.Clamp((int)fz, 0, res - 2); + float tx = Math.Clamp(fx - ix, 0f, 1f); + float tz = Math.Clamp(fz - iz, 0f, 1f); + int row0 = iz * res; + int row1 = row0 + res; + float h00 = _baseMinY + _sharedU16Heights[row0 + ix] * _baseScale; + float h10 = _baseMinY + _sharedU16Heights[row0 + ix + 1] * _baseScale; + float h01 = _baseMinY + _sharedU16Heights[row1 + ix] * _baseScale; + float h11 = _baseMinY + _sharedU16Heights[row1 + ix + 1] * _baseScale; + return (h00 * (1f - tx) + h10 * tx) * (1f - tz) + (h01 * (1f - tx) + h11 * tx) * tz; + } + if (_heightmap is not null) { int res = HeightmapRes; @@ -494,21 +626,194 @@ namespace RustToDust.Core float h10 = _heightmap[row0 + ix + 1]; float h01 = _heightmap[row1 + ix]; float h11 = _heightmap[row1 + ix + 1]; - h = (h00 * (1f - tx) + h10 * tx) * (1f - tz) + (h01 * (1f - tx) + h11 * tx) * tz; + return (h00 * (1f - tx) + h10 * tx) * (1f - tz) + (h01 * (1f - tx) + h11 * tx) * tz; } - WorldToAccelCell(cx, cz, out int acx, out int acz); - var indices = _cellBrushIndices[acz * AccelGridCount + acx]; - for (int i = 0; i < indices.Count; i++) + return 0f; + } + + public float SampleHeight(float x, float z) + { + float half = MapHalfExtent; + float cx = Math.Clamp(x, -half, half); + float cz = Math.Clamp(z, -half, half); + + float h = SampleBaseHeight(cx, cz); + + if (_brushes.Count > 0) { - int idx = indices[i]; - var b = _brushes[idx]; - h += EvaluateBrushHeightFast(in b, _brushPrecomps[idx], cx, cz); + WorldToAccelCell(cx, cz, out int acx, out int acz); + var indices = _cellBrushIndices[acz * AccelGridCount + acx]; + for (int i = 0; i < indices.Count; i++) + { + int idx = indices[i]; + var b = _brushes[idx]; + h += EvaluateBrushHeightFast(in b, _brushPrecomps[idx], cx, cz); + } } return Math.Clamp(h, MapMinHeight, MapMaxHeight); } + public void ExtractTilePhysicsHeights(int tx, int tz, Span dst, out float minY, out float maxY) + { + if ((uint)tx >= (uint)TileGridCount || (uint)tz >= (uint)TileGridCount) + { + throw new ArgumentOutOfRangeException(nameof(tx)); + } + if (!IsHeightmapMode) + { + throw new InvalidOperationException("ExtractTilePhysicsHeights requires heightmap mode."); + } + + int samplesPerTile = (HeightmapRes - 1) / TileGridCount; + int side = samplesPerTile + 1; + int count = side * side; + if (dst.Length < count) + { + throw new ArgumentException($"Destination span too small: need {count}, got {dst.Length}.", nameof(dst)); + } + + int gx0 = tx * samplesPerTile; + int gz0 = tz * samplesPerTile; + var tileBrushes = _tileBrushIndices[tx, tz]; + bool hasStructuralBrushes = false; + for (int i = 0; i < tileBrushes.Count; i++) + { + var k = _brushes[tileBrushes[i]].Kind; + if (k != TerrainBrushKind.Track && k != TerrainBrushKind.Scorch) + { + hasStructuralBrushes = true; + break; + } + } + + float minVal = float.PositiveInfinity; + float maxVal = float.NegativeInfinity; + float half = MapHalfExtent; + float step = HeightmapCellSize; + int res = HeightmapRes; + + for (int lz = 0; lz < side; lz++) + { + int gz = gz0 + lz; + int globalRow = gz * res + gx0; + int localRow = lz * side; + float wz = -half + gz * step; + + for (int lx = 0; lx < side; lx++) + { + float h = _sharedU16Heights is not null + ? _baseMinY + _sharedU16Heights[globalRow + lx] * _baseScale + : _heightmap![globalRow + lx]; + + if (hasStructuralBrushes) + { + float wx = -half + (gx0 + lx) * step; + for (int bi = 0; bi < tileBrushes.Count; bi++) + { + int bIdx = tileBrushes[bi]; + var b = _brushes[bIdx]; + if (b.Kind == TerrainBrushKind.Track || b.Kind == TerrainBrushKind.Scorch) + { + continue; + } + h += EvaluateBrushHeightFast(in b, _brushPrecomps[bIdx], wx, wz); + } + } + + float clamped = Math.Clamp(h, MapMinHeight, MapMaxHeight); + dst[localRow + lx] = clamped; + if (clamped < minVal) minVal = clamped; + if (clamped > maxVal) maxVal = clamped; + } + } + + if (hasStructuralBrushes) + { + var cached = _scarredTileHeights[tx, tz]; + if (cached is null || cached.Length != count) + { + cached = new float[count]; + _scarredTileHeights[tx, tz] = cached; + } + dst.Slice(0, count).CopyTo(cached); + } + else + { + _scarredTileHeights[tx, tz] = null; + } + + minY = float.IsPositiveInfinity(minVal) ? 0f : minVal; + maxY = float.IsNegativeInfinity(maxVal) ? 0f : maxVal; + } + + public void ClearDynamicScars() + { + if (_brushes.Count == 0) + { + return; + } + + bool anyDynamic = false; + var staticBrushes = new List(_brushes.Count); + for (int i = 0; i < _brushes.Count; i++) + { + if (_brushes[i].Dynamic) + { + anyDynamic = true; + GetBrushTileBounds(_brushes[i], out int minTx, out int maxTx, out int minTz, out int maxTz); + bool isStructural = _brushes[i].Kind != TerrainBrushKind.Track && _brushes[i].Kind != TerrainBrushKind.Scorch; + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + VisualTileVersions[tx, tz]++; + if (isStructural) + { + StructuralTileVersions[tx, tz]++; + } + _scarredTileHeights[tx, tz] = null; + } + } + } + else + { + staticBrushes.Add(_brushes[i]); + } + } + + if (!anyDynamic) + { + return; + } + + _brushes.Clear(); + _brushPrecomps.Clear(); + _dynamicDecalSlots.Clear(); + for (int tz = 0; tz < TileGridCount; tz++) + { + for (int tx = 0; tx < TileGridCount; tx++) + { + _tileBrushIndices[tx, tz].Clear(); + } + } + for (int c = 0; c < AccelCellCount; c++) + { + _cellBrushIndices[c].Clear(); + _cellMaxHeight[c] = _cellBaseMaxHeight[c]; + } + + for (int i = 0; i < staticBrushes.Count; i++) + { + int idx = _brushes.Count; + var b = staticBrushes[i]; + _brushes.Add(b); + _brushPrecomps.Add(BrushPrecomp.From(in b)); + RegisterBrushInTiles(idx, in b, incrementTileVersion: false); + } + } + public (float Nx, float Ny, float Nz) SampleNormal(float x, float z) { const float eps = 0.5f; @@ -723,6 +1028,13 @@ namespace RustToDust.Core float rim = (0.32f * depth) * rimT * rimT; return pit + rim; } + case TerrainBrushKind.Rubble: + { + float env = 1f - r2; + env *= env; + float mound = 0.72f + 0.28f * MathF.Cos(u * MathF.PI * 2.5f); + return b.HeightDelta * env * mound; + } default: return 0f; } @@ -854,6 +1166,12 @@ namespace RustToDust.Core case TerrainBrushKind.Crater: cellMaxPositiveHeight = 0.33f * MathF.Abs(b.HeightDelta); break; + case TerrainBrushKind.Rubble: + { + float env = 1f - minR2; + cellMaxPositiveHeight = MathF.Max(0f, b.HeightDelta) * env * env; + break; + } default: cellMaxPositiveHeight = 0f; break; @@ -889,12 +1207,11 @@ namespace RustToDust.Core _tileBrushIndices[tx, tz].Add(index); if (incrementTileVersion) { - TileVersions[tx, tz]++; - ulong bit = 1UL << (tz * TileGridCount + tx); - DirtyTileMask |= bit; + VisualTileVersions[tx, tz]++; if (isStructural) { - StructuralDirtyTileMask |= bit; + StructuralTileVersions[tx, tz]++; + _scarredTileHeights[tx, tz] = null; } } } @@ -928,12 +1245,11 @@ namespace RustToDust.Core for (int tx = minTx; tx <= maxTx; tx++) { _tileBrushIndices[tx, tz].Remove(index); - TileVersions[tx, tz]++; - ulong bit = 1UL << (tz * TileGridCount + tx); - DirtyTileMask |= bit; + VisualTileVersions[tx, tz]++; if (isStructural) { - StructuralDirtyTileMask |= bit; + StructuralTileVersions[tx, tz]++; + _scarredTileHeights[tx, tz] = null; } } } @@ -997,8 +1313,8 @@ namespace RustToDust.Core { float nx = (x + HalfExtent) / TileSize; float nz = (z + HalfExtent) / TileSize; - tx = Math.Clamp((int)MathF.Floor(nx), 0, TileGridCount - 1); - tz = Math.Clamp((int)MathF.Floor(nz), 0, TileGridCount - 1); + tx = Math.Clamp((int)MathF.Floor(nx), 0, DesertTileGridCount - 1); + tz = Math.Clamp((int)MathF.Floor(nz), 0, DesertTileGridCount - 1); } private static bool IsBrushClearOfCover(in TerrainBrush candidate, IReadOnlyList coverBoxes) diff --git a/src/RustToDust.Core/VehicleCatalogLoader.cs b/src/RustToDust.Core/VehicleCatalogLoader.cs index 3336ffe..06a472c 100644 --- a/src/RustToDust.Core/VehicleCatalogLoader.cs +++ b/src/RustToDust.Core/VehicleCatalogLoader.cs @@ -7,40 +7,11 @@ namespace RustToDust.Core { public static class VehicleCatalogLoader { - public static string LocateVehiclesDirectory() - { - string? envRoot = Environment.GetEnvironmentVariable("RTD_ASSETS_DIR"); - if (!string.IsNullOrWhiteSpace(envRoot)) - { - string envVehicles = Path.Combine(envRoot, "vehicles"); - if (HasVehiclePackages(envVehicles)) - { - return Path.GetFullPath(envVehicles); - } - } - - foreach (string start in new[] { AppContext.BaseDirectory, Directory.GetCurrentDirectory() }) - { - if (string.IsNullOrWhiteSpace(start) || !Directory.Exists(start)) - { - continue; - } - - var dir = new DirectoryInfo(Path.GetFullPath(start)); - while (dir is not null) - { - string candidate = Path.Combine(dir.FullName, "assets", "vehicles"); - if (HasVehiclePackages(candidate)) - { - return candidate; - } - dir = dir.Parent; - } - } - - throw new DirectoryNotFoundException( - $"Could not locate 'assets/vehicles' containing vehicle.cc packages from BaseDirectory '{AppContext.BaseDirectory}' or CurrentDirectory '{Directory.GetCurrentDirectory()}'."); - } + public static string LocateVehiclesDirectory() => + AssetPathResolver.LocateSubdirectory( + "vehicles", + HasVehiclePackages, + "containing vehicle.cc packages"); private static bool HasVehiclePackages(string vehiclesDir) { diff --git a/src/RustToDust.HbGpu/HbGpuAtlasAllocator.cs b/src/RustToDust.HbGpu/HbGpuAtlasAllocator.cs new file mode 100644 index 0000000..c9d2f83 --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuAtlasAllocator.cs @@ -0,0 +1,175 @@ +using System; +using System.Runtime.InteropServices; + +namespace RustToDust.HbGpu; + +/// +/// Manages texel offsets inside the single 262,144-texel (2.0 MiB) RGBA16I GPU atlas: +/// - Persistent zone: [0 .. 229,376) with a 75% (172,032) watermark reset trigger. +/// - Dynamic scratch ring: [229,376 .. 262,144). +/// Queues uploads into pre-allocated staging storage for zero-GC render-thread commits. +/// +public sealed class HbGpuAtlasAllocator +{ + public const uint TotalTexels = 262_144; + public const uint PersistentCapacity = 229_376; + public const uint PersistentResetWatermark = 172_032; // 75% of PersistentCapacity + public const uint DynamicBase = PersistentCapacity; + public const uint DynamicCapacity = TotalTexels - PersistentCapacity; // 32,768 + public const int BytesPerTexel = 8; + public const int TotalBytes = (int)(TotalTexels * BytesPerTexel); + + public struct UploadChunk + { + public uint AtlasTexelOffset; + public uint ShortOffset; + public uint TexelCount; + } + + private readonly short[] _pendingShorts = new short[TotalTexels * 4]; + private readonly UploadChunk[] _pendingChunks = new UploadChunk[2048]; + private uint _pendingShortCursor; + private int _pendingChunkCount; + + public uint PersistentCursor { get; private set; } + public uint DynamicCursor { get; private set; } + public uint Epoch { get; private set; } = 1; + + public bool NeedsPersistentReset => PersistentCursor > PersistentResetWatermark; + + public int PendingChunkCount => _pendingChunkCount; + + public ReadOnlySpan PendingShortPool => _pendingShorts; + + public ReadOnlySpan PendingChunks => _pendingChunks.AsSpan(0, _pendingChunkCount); + + public void ResetPersistent() + { + PersistentCursor = 0; + Epoch++; + } + + public uint AllocatePersistent(ReadOnlySpan rgba16iShorts) + { + if (rgba16iShorts.IsEmpty || (rgba16iShorts.Length & 3) != 0) + { + throw new ArgumentException("Texel data must be a non-empty multiple of 4 shorts.", nameof(rgba16iShorts)); + } + + uint texels = (uint)(rgba16iShorts.Length >> 2); + if (PersistentCursor + texels > PersistentCapacity) + { + throw new InvalidOperationException( + $"Persistent atlas overflow: cursor={PersistentCursor}, needed={texels}, cap={PersistentCapacity}."); + } + + uint atlasOffset = PersistentCursor; + PersistentCursor += texels; + QueueUpload(atlasOffset, rgba16iShorts, texels); + return atlasOffset; + } + + public uint AllocateDynamic(ReadOnlySpan rgba16iShorts) + { + if (rgba16iShorts.IsEmpty || (rgba16iShorts.Length & 3) != 0) + { + throw new ArgumentException("Texel data must be a non-empty multiple of 4 shorts.", nameof(rgba16iShorts)); + } + + uint texels = (uint)(rgba16iShorts.Length >> 2); + if (texels > DynamicCapacity) + { + throw new InvalidOperationException( + $"Dynamic blob ({texels} texels) exceeds DynamicCapacity ({DynamicCapacity})."); + } + + if (DynamicCursor + texels > DynamicCapacity) + { + DynamicCursor = 0; + } + + uint atlasOffset = DynamicBase + DynamicCursor; + DynamicCursor += texels; + QueueUpload(atlasOffset, rgba16iShorts, texels); + return atlasOffset; + } + + private void QueueUpload(uint atlasOffset, ReadOnlySpan rgba16iShorts, uint texels) + { + if (_pendingChunkCount >= _pendingChunks.Length || + _pendingShortCursor + (uint)rgba16iShorts.Length > (uint)_pendingShorts.Length) + { + // Should never happen in normal HUD usage; reset pending ring head safely if overwhelmed without draining. + throw new InvalidOperationException("Atlas pending upload staging buffer full before render-thread drain."); + } + + rgba16iShorts.CopyTo(_pendingShorts.AsSpan((int)_pendingShortCursor)); + _pendingChunks[_pendingChunkCount++] = new UploadChunk + { + AtlasTexelOffset = atlasOffset, + ShortOffset = _pendingShortCursor, + TexelCount = texels + }; + _pendingShortCursor += (uint)rgba16iShorts.Length; + } + + /// + /// Copies all pending upload chunks into a caller-owned staging byte[] at index 0 + /// and invokes uploadCallback(atlasByteOffset, byteCount). Zero allocations when callback is cached. + /// + public int DrainChunks(byte[] stagingBuffer, Action uploadCallback) + { + int count = _pendingChunkCount; + if (count == 0) + { + return 0; + } + + for (int i = 0; i < count; i++) + { + UploadChunk c = _pendingChunks[i]; + uint byteCount = c.TexelCount * BytesPerTexel; + if (byteCount > (uint)stagingBuffer.Length) + { + throw new InvalidOperationException($"Upload chunk ({byteCount} B) exceeds staging buffer ({stagingBuffer.Length} B)."); + } + Buffer.BlockCopy(_pendingShorts, (int)(c.ShortOffset * sizeof(short)), stagingBuffer, 0, (int)byteCount); + uploadCallback(c.AtlasTexelOffset * BytesPerTexel, byteCount); + } + + _pendingChunkCount = 0; + _pendingShortCursor = 0; + return count; + } + + /// + /// Copies all pending upload chunks into a full 2 MiB mirror buffer at their atlas byte offsets. + /// Returns how many chunks were drained. Zero allocations. + /// + public int DrainToMirror(byte[] atlasMirrorBytes) + { + int count = _pendingChunkCount; + if (count == 0) + { + return 0; + } + + for (int i = 0; i < count; i++) + { + UploadChunk c = _pendingChunks[i]; + int dstOffset = (int)(c.AtlasTexelOffset * BytesPerTexel); + int byteCount = (int)(c.TexelCount * BytesPerTexel); + Buffer.BlockCopy(_pendingShorts, (int)(c.ShortOffset * sizeof(short)), atlasMirrorBytes, dstOffset, byteCount); + } + + _pendingChunkCount = 0; + _pendingShortCursor = 0; + return count; + } + + public void ClearPending() + { + _pendingChunkCount = 0; + _pendingShortCursor = 0; + } +} diff --git a/src/RustToDust.HbGpu/HbGpuBlobCache.cs b/src/RustToDust.HbGpu/HbGpuBlobCache.cs new file mode 100644 index 0000000..368c07a --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuBlobCache.cs @@ -0,0 +1,200 @@ +using System; +using System.Collections.Generic; + +namespace RustToDust.HbGpu; + +/// +/// Encodes and caches RGBA16I Slug blobs for font glyphs and static/dynamic vector shapes +/// using a pre-allocated 65,536-short (128 KiB) scratch buffer. +/// +public sealed unsafe class HbGpuBlobCache +{ + public const int ScratchShortsCapacity = 65_536; + public const uint ScratchTexelsCapacity = ScratchShortsCapacity / 4; // 16,384 texels + + private readonly HbGpuAtlasAllocator _atlas; + private readonly Dictionary _glyphBlobs = new(512); + private readonly Dictionary _vectorBlobs = new(64); + private readonly short[] _scratchShorts = new short[ScratchShortsCapacity]; + private bool _persistentOverflowPending; + + public HbGpuBlobCache(HbGpuAtlasAllocator atlas) + { + _atlas = atlas ?? throw new ArgumentNullException(nameof(atlas)); + } + + public HbGpuAtlasAllocator Atlas => _atlas; + + public int CachedGlyphCount => _glyphBlobs.Count; + + public int CachedVectorCount => _vectorBlobs.Count; + + public bool IsPersistentOverflowPending => _persistentOverflowPending; + + public bool EnsureBudgetOrReset() + { + if (!_atlas.NeedsPersistentReset && !_persistentOverflowPending) + { + return false; + } + + _atlas.ResetPersistent(); + _glyphBlobs.Clear(); + _vectorBlobs.Clear(); + _persistentOverflowPending = false; + return true; + } + + public CachedBlob GetOrEncodeGlyph( + HbGpuFontCache fonts, + byte fontId, + uint glyphId, + ushort qWght, + ushort qWdth, + short qSlnt) + { + var key = new GlyphBlobKey(fontId, glyphId, qWght, qWdth, qSlnt); + if (_glyphBlobs.TryGetValue(key, out CachedBlob cached)) + { + return cached; + } + + IntPtr fontHandle = fonts.GetOrCreateStyle(new HbGpuStyleKey(fontId, qWght, qWdth, qSlnt)); + int texelCount; + RtdHbExtents ext; + fixed (short* dst = _scratchShorts) + { + texelCount = HbGpuNative.EncodeGlyph(fontHandle, glyphId, dst, ScratchTexelsCapacity, out ext); + } + + if (texelCount < 0) + { + throw new InvalidOperationException($"rtd_hb_encode_glyph failed for glyph {glyphId} (code {texelCount})."); + } + + CachedBlob blob; + if (texelCount == 0) + { + blob = new CachedBlob(0, 0, 0, 0, 0, 0, IsEmpty: true); + } + else + { + if (_atlas.PersistentCursor + (uint)texelCount > HbGpuAtlasAllocator.PersistentCapacity) + { + // Never wipe persistent atlas mid-frame while earlier quads reference pre-reset offsets. + // Flag for reset at next BeginFrame() and skip overflow glyphs cleanly for this frame. + _persistentOverflowPending = true; + return new CachedBlob(0, 0, 0, 0, 0, 0, IsEmpty: true); + } + + uint offset = _atlas.AllocatePersistent(_scratchShorts.AsSpan(0, texelCount * 4)); + blob = new CachedBlob( + offset, + checked((short)ext.MinX), + checked((short)ext.MinY), + checked((short)ext.MaxX), + checked((short)ext.MaxY), + (uint)texelCount, + IsEmpty: false); + } + + _glyphBlobs[key] = blob; + return blob; + } + + public bool TryGetStaticPath(VectorBlobKey key, out CachedBlob cached) => + _vectorBlobs.TryGetValue(key, out cached); + + public CachedBlob GetOrEncodeStaticPath( + VectorBlobKey key, + uint designUpem, + ReadOnlySpan verbs, + ReadOnlySpan args) + { + if (_vectorBlobs.TryGetValue(key, out CachedBlob cached)) + { + return cached; + } + + int texelCount = EncodePathIntoScratch(designUpem, verbs, args, out RtdHbExtents ext); + CachedBlob blob; + if (texelCount == 0) + { + blob = new CachedBlob(0, 0, 0, 0, 0, 0, IsEmpty: true); + } + else + { + if (_atlas.PersistentCursor + (uint)texelCount > HbGpuAtlasAllocator.PersistentCapacity) + { + // Never wipe persistent atlas mid-frame while earlier quads reference pre-reset offsets. + _persistentOverflowPending = true; + return new CachedBlob(0, 0, 0, 0, 0, 0, IsEmpty: true); + } + + uint offset = _atlas.AllocatePersistent(_scratchShorts.AsSpan(0, texelCount * 4)); + blob = new CachedBlob( + offset, + checked((short)ext.MinX), + checked((short)ext.MinY), + checked((short)ext.MaxX), + checked((short)ext.MaxY), + (uint)texelCount, + IsEmpty: false); + } + + _vectorBlobs[key] = blob; + return blob; + } + + public CachedBlob EncodeDynamicPath( + uint designUpem, + ReadOnlySpan verbs, + ReadOnlySpan args) + { + int texelCount = EncodePathIntoScratch(designUpem, verbs, args, out RtdHbExtents ext); + if (texelCount == 0) + { + return new CachedBlob(0, 0, 0, 0, 0, 0, IsEmpty: true); + } + + uint offset = _atlas.AllocateDynamic(_scratchShorts.AsSpan(0, texelCount * 4)); + return new CachedBlob( + offset, + checked((short)ext.MinX), + checked((short)ext.MinY), + checked((short)ext.MaxX), + checked((short)ext.MaxY), + (uint)texelCount, + IsEmpty: false); + } + + private int EncodePathIntoScratch( + uint designUpem, + ReadOnlySpan verbs, + ReadOnlySpan args, + out RtdHbExtents ext) + { + int texelCount; + fixed (byte* vPtr = verbs) + fixed (float* aPtr = args) + fixed (short* dst = _scratchShorts) + { + texelCount = HbGpuNative.EncodePath( + designUpem, + vPtr, + (uint)verbs.Length, + aPtr, + (uint)args.Length, + dst, + ScratchTexelsCapacity, + out ext); + } + + if (texelCount < 0) + { + throw new InvalidOperationException($"rtd_hb_encode_path failed (code {texelCount})."); + } + + return texelCount; + } +} diff --git a/src/RustToDust.HbGpu/HbGpuCommandWriter.cs b/src/RustToDust.HbGpu/HbGpuCommandWriter.cs new file mode 100644 index 0000000..77fa213 --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuCommandWriter.cs @@ -0,0 +1,247 @@ +using System; + +namespace RustToDust.HbGpu; + +/// +/// Zero-allocation CPU quad builder and text shaper writing 80-byte HbGpuQuadInstance records. +/// +public sealed unsafe class HbGpuCommandWriter +{ + public const int MaxQuads = 4096; + public const int ShapingScratchCapacity = 1024; + + private readonly HbGpuQuadInstance[] _quads = new HbGpuQuadInstance[MaxQuads]; + private readonly RtdHbShapedGlyph[] _shapedScratch = new RtdHbShapedGlyph[ShapingScratchCapacity]; + + public int QuadCount { get; private set; } + + public ReadOnlySpan Quads => _quads.AsSpan(0, QuadCount); + + public HbGpuQuadInstance[] RawBuffer => _quads; + + public void BeginFrame() + { + QuadCount = 0; + } + + public static uint PackClipCoord(float minVal, float maxVal) + { + ushort lo = (ushort)Math.Clamp((int)MathF.Floor(minVal), 0, 65535); + ushort hi = (ushort)Math.Clamp((int)MathF.Ceiling(maxVal), 0, 65535); + return (uint)lo | ((uint)hi << 16); + } + + public static void PackClipRect( + float x, float y, float w, float h, + out uint clipMinPacked, + out uint clipMaxPacked) + { + ushort x0 = (ushort)Math.Clamp((int)MathF.Floor(x), 0, 65535); + ushort y0 = (ushort)Math.Clamp((int)MathF.Floor(y), 0, 65535); + ushort x1 = (ushort)Math.Clamp((int)MathF.Ceiling(x + w), 0, 65535); + ushort y1 = (ushort)Math.Clamp((int)MathF.Ceiling(y + h), 0, 65535); + clipMinPacked = (uint)x0 | ((uint)y0 << 16); + clipMaxPacked = (uint)x1 | ((uint)y1 << 16); + } + + public bool TryAddQuad(in HbGpuQuadInstance quad) + { + if (QuadCount >= MaxQuads) + { + return false; + } + + _quads[QuadCount++] = quad; + return true; + } + + public void DrawBlob( + in CachedBlob blob, + float screenX, + float screenY, + float m00, + float m01, + float m10, + float m11, + float anchorEmX, + float anchorEmY, + float r, + float g, + float b, + float a, + bool stemDarken = false, + uint clipMinPacked = 0, + uint clipMaxPacked = HbGpuQuadInstance.Unclipped, + uint extraFlags = 0u) + { + if (!blob.IsValid || QuadCount >= MaxQuads) + { + return; + } + + _quads[QuadCount++] = new HbGpuQuadInstance + { + EmMinX = blob.MinX, + EmMinY = blob.MinY, + EmMaxX = blob.MaxX, + EmMaxY = blob.MaxY, + AnchorEmX = anchorEmX, + AnchorEmY = anchorEmY, + ScreenX = screenX, + ScreenY = screenY, + M00 = m00, + M01 = m01, + M10 = m10, + M11 = m11, + ColorR = r, + ColorG = g, + ColorB = b, + ColorA = a, + AtlasTexelOffset = blob.AtlasOffset, + Flags = (stemDarken ? HbGpuQuadInstance.FlagStemDarken : 0u) | extraFlags, + ClipMinPacked = clipMinPacked, + ClipMaxPacked = clipMaxPacked + }; + } + + public float MeasureTextWidth( + ReadOnlySpan text, + float fontSizePx, + HbGpuFontCache fonts, + byte fontId = 0, + float wght = 200f, + float wdth = 100f, + float slnt = 0f, + HbGpuFeatureFlags features = HbGpuFeatureFlags.Default) + { + if (text.IsEmpty) + { + return 0f; + } + + HbGpuStyleKey styleKey = HbGpuStyleKey.FromAxes(fontId, wght, wdth, slnt); + IntPtr fontHandle = fonts.GetOrCreateStyle(styleKey); + int upem = fonts.GetMetrics(fontId).Upem; + float scale = fontSizePx / upem; + + uint glyphCount; + fixed (char* textPtr = text) + fixed (RtdHbShapedGlyph* outPtr = _shapedScratch) + { + glyphCount = HbGpuNative.ShapeUtf16( + fontHandle, + textPtr, + (uint)text.Length, + (uint)features, + outPtr, + (uint)_shapedScratch.Length); + } + + int count = (int)Math.Min(glyphCount, (uint)_shapedScratch.Length); + int adv = 0; + for (int i = 0; i < count; i++) + { + adv += _shapedScratch[i].XAdvance; + } + + return adv * scale; + } + + /// + /// Shapes UTF-16 text directly and appends glyph quads. (x, baselineY) is the pen baseline origin in logical pixels (Y-down). + /// Returns the total horizontal advance in logical pixels. + /// + public float DrawTextUtf16( + ReadOnlySpan text, + float x, + float baselineY, + float fontSizePx, + float r, + float g, + float b, + float a, + HbGpuFontCache fonts, + HbGpuBlobCache blobs, + byte fontId = 0, + float wght = 200f, + float wdth = 100f, + float slnt = 0f, + HbGpuFeatureFlags features = HbGpuFeatureFlags.Default, + bool stemDarken = true, + uint clipMinPacked = 0, + uint clipMaxPacked = HbGpuQuadInstance.Unclipped) + { + if (text.IsEmpty) + { + return 0f; + } + + HbGpuStyleKey styleKey = HbGpuStyleKey.FromAxes(fontId, wght, wdth, slnt); + IntPtr fontHandle = fonts.GetOrCreateStyle(styleKey); + int upem = fonts.GetMetrics(fontId).Upem; + float scale = fontSizePx / upem; + + uint glyphCount; + fixed (char* textPtr = text) + fixed (RtdHbShapedGlyph* outPtr = _shapedScratch) + { + glyphCount = HbGpuNative.ShapeUtf16( + fontHandle, + textPtr, + (uint)text.Length, + (uint)features, + outPtr, + (uint)_shapedScratch.Length); + } + + int count = (int)Math.Min(glyphCount, (uint)_shapedScratch.Length); + float penX = x; + float penY = baselineY; + + for (int i = 0; i < count; i++) + { + RtdHbShapedGlyph sg = _shapedScratch[i]; + CachedBlob blob = blobs.GetOrEncodeGlyph( + fonts, + fontId, + sg.GlyphId, + styleKey.QWght, + styleKey.QWdth, + styleKey.QSlnt); + + if (blob.IsValid && QuadCount < MaxQuads) + { + float gx = penX + sg.XOffset * scale; + float gy = penY - sg.YOffset * scale; // Y-up font offset -> Y-down screen + _quads[QuadCount++] = new HbGpuQuadInstance + { + EmMinX = blob.MinX, + EmMinY = blob.MinY, + EmMaxX = blob.MaxX, + EmMaxY = blob.MaxY, + AnchorEmX = 0f, + AnchorEmY = 0f, + ScreenX = gx, + ScreenY = gy, + M00 = scale, + M01 = 0f, + M10 = 0f, + M11 = -scale, + ColorR = r, + ColorG = g, + ColorB = b, + ColorA = a, + AtlasTexelOffset = blob.AtlasOffset, + Flags = stemDarken ? HbGpuQuadInstance.FlagStemDarken : 0u, + ClipMinPacked = clipMinPacked, + ClipMaxPacked = clipMaxPacked + }; + } + + penX += sg.XAdvance * scale; + penY -= sg.YAdvance * scale; + } + + return penX - x; + } +} diff --git a/src/RustToDust.HbGpu/HbGpuFontCache.cs b/src/RustToDust.HbGpu/HbGpuFontCache.cs new file mode 100644 index 0000000..a40500d --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuFontCache.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace RustToDust.HbGpu; + +/// +/// Owns loaded font faces and lazy quantized-axis (wght, wdth, slnt) hb_font_t* handles. +/// Avoids per-frame hb_font_set_variations thrash. +/// +public sealed unsafe class HbGpuFontCache : IDisposable +{ + private readonly Dictionary _baseFaces = new(); + private readonly Dictionary _metrics = new(); + private readonly Dictionary _styles = new(); + private bool _disposed; + + public byte RegisterFontFromFile(byte fontId, string path, uint faceIndex = 0) + { + ObjectDisposedException.ThrowIf(_disposed, this); + byte[] bytes = File.ReadAllBytes(path); + return RegisterFont(fontId, bytes, faceIndex); + } + + public byte RegisterFont(byte fontId, ReadOnlySpan ttfBytes, uint faceIndex = 0) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (ttfBytes.IsEmpty) + { + throw new ArgumentException("Font bytes cannot be empty.", nameof(ttfBytes)); + } + + if (_baseFaces.TryGetValue(fontId, out IntPtr existing) && existing != IntPtr.Zero) + { + throw new InvalidOperationException($"FontId {fontId} is already registered."); + } + + fixed (byte* ptr = ttfBytes) + { + IntPtr baseHandle = HbGpuNative.FontCreate(ptr, (uint)ttfBytes.Length, faceIndex, out RtdHbFontMetrics metrics); + if (baseHandle == IntPtr.Zero) + { + throw new InvalidOperationException($"rtd_hb_font_create failed for FontId {fontId}."); + } + + _baseFaces[fontId] = baseHandle; + _metrics[fontId] = metrics; + } + + return fontId; + } + + public RtdHbFontMetrics GetMetrics(byte fontId) => _metrics[fontId]; + + public bool TryGetMetrics(byte fontId, out RtdHbFontMetrics metrics) => + _metrics.TryGetValue(fontId, out metrics); + + public IntPtr GetOrCreateStyle(HbGpuStyleKey key) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_styles.TryGetValue(key, out IntPtr handle)) + { + return handle; + } + + if (!_baseFaces.TryGetValue(key.FontId, out IntPtr baseHandle)) + { + throw new KeyNotFoundException($"FontId {key.FontId} is not registered in HbGpuFontCache."); + } + + float wght = key.QWght; + float wdth = key.QWdth * 0.1f; + float slnt = key.QSlnt * 0.1f; + IntPtr variant = HbGpuNative.FontCreateVariant(baseHandle, wght, wdth, slnt); + if (variant == IntPtr.Zero) + { + throw new InvalidOperationException($"rtd_hb_font_create_variant failed for {key}."); + } + + _styles[key] = variant; + return variant; + } + + public IntPtr GetOrCreateStyle(byte fontId, float wght, float wdth, float slnt) => + GetOrCreateStyle(HbGpuStyleKey.FromAxes(fontId, wght, wdth, slnt)); + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + + foreach (IntPtr handle in _styles.Values) + { + if (handle != IntPtr.Zero) + { + HbGpuNative.FontDestroy(handle); + } + } + _styles.Clear(); + + foreach (IntPtr baseHandle in _baseFaces.Values) + { + if (baseHandle != IntPtr.Zero) + { + HbGpuNative.FontDestroy(baseHandle); + } + } + _baseFaces.Clear(); + _metrics.Clear(); + } +} diff --git a/src/RustToDust.HbGpu/HbGpuNative.cs b/src/RustToDust.HbGpu/HbGpuNative.cs new file mode 100644 index 0000000..9e55941 --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuNative.cs @@ -0,0 +1,66 @@ +using System; +using System.Runtime.InteropServices; + +namespace RustToDust.HbGpu; + +public static unsafe class HbGpuNative +{ + public const string LibraryName = "rtd_hbgpu"; + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_version_string")] + private static extern IntPtr NativeVersionString(); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_shader_source")] + private static extern IntPtr NativeShaderSource(uint stage, uint kind); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_font_create")] + public static extern IntPtr FontCreate( + byte* ttf, + uint len, + uint faceIndex, + out RtdHbFontMetrics outMetrics); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_font_create_variant")] + public static extern IntPtr FontCreateVariant( + IntPtr baseFont, + float wght, + float wdth, + float slnt); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_font_destroy")] + public static extern void FontDestroy(IntPtr font); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_shape_utf16")] + public static extern uint ShapeUtf16( + IntPtr font, + char* utf16, + uint charLen, + uint featureFlags, + RtdHbShapedGlyph* outGlyphs, + uint cap); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_encode_glyph")] + public static extern int EncodeGlyph( + IntPtr font, + uint glyphId, + short* outRgba16i, + uint capTexels, + out RtdHbExtents outExt); + + [DllImport(LibraryName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "rtd_hb_encode_path")] + public static extern int EncodePath( + uint designUpem, + byte* verbs, + uint nVerbs, + float* args, + uint nArgs, + short* outRgba16i, + uint capTexels, + out RtdHbExtents outExt); + + public static string GetVersionString() => + Marshal.PtrToStringUTF8(NativeVersionString()) ?? string.Empty; + + public static string GetShaderSource(HbGpuShaderStage stage, HbGpuShaderKind kind) => + Marshal.PtrToStringUTF8(NativeShaderSource((uint)stage, (uint)kind)) ?? string.Empty; +} diff --git a/src/RustToDust.HbGpu/HbGpuTypes.cs b/src/RustToDust.HbGpu/HbGpuTypes.cs new file mode 100644 index 0000000..07fc309 --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuTypes.cs @@ -0,0 +1,152 @@ +using System; +using System.Runtime.InteropServices; + +namespace RustToDust.HbGpu; + +[StructLayout(LayoutKind.Sequential)] +public struct RtdHbFontMetrics +{ + public int Upem; + public int Ascender; + public int Descender; + public int LineGap; +} + +[StructLayout(LayoutKind.Sequential)] +public struct RtdHbShapedGlyph +{ + public uint GlyphId; + public uint Cluster; + public int XAdvance; + public int YAdvance; + public int XOffset; + public int YOffset; +} + +[StructLayout(LayoutKind.Sequential)] +public struct RtdHbExtents +{ + public int MinX; + public int MinY; + public int MaxX; + public int MaxY; +} + +/// +/// 80-byte GPU quad instance matching the std430 SSBO layout in HbGpuCanvas. +/// +[StructLayout(LayoutKind.Sequential, Pack = 4)] +public struct HbGpuQuadInstance +{ + public float EmMinX; + public float EmMinY; + public float EmMaxX; + public float EmMaxY; + + public float AnchorEmX; + public float AnchorEmY; + public float ScreenX; + public float ScreenY; + + public float M00; + public float M01; + public float M10; + public float M11; + + public float ColorR; + public float ColorG; + public float ColorB; + public float ColorA; + + public uint AtlasTexelOffset; + public uint Flags; + public uint ClipMinPacked; + public uint ClipMaxPacked; + + public const uint FlagStemDarken = 1u; + public const uint FlagSolidRect = 2u; + public const uint Unclipped = 0xFFFFFFFFu; +} + +[Flags] +public enum HbGpuFeatureFlags : uint +{ + None = 0u, + Calt = 1u << 0, + Liga = 1u << 1, + Default = Calt | Liga +} + +public enum HbGpuPathVerb : byte +{ + Move = 0, + LineTo = 1, + QuadTo = 2, + CubicTo = 3, + Close = 4, + Line = 5, + Rect = 6, + Circle = 7 +} + +public enum HbGpuShaderStage : uint +{ + Vertex = 0, + Fragment = 1 +} + +public enum HbGpuShaderKind : uint +{ + Shared = 0, + Draw = 1 +} + +public enum VectorShapeKind : ushort +{ + UnitFilledRect = 1, + UnitCircleFill = 2, + UnitRingStroke = 3, + CornerLBracket = 4, + TargetBracketCorner = 5, + DirectionalArrow = 6, + ChevronTriangle = 7, + DiamondBlip = 8, + HitMarkerArm = 9, + StrippedHatchX = 10, + PanelFrame = 11, + HardpointBracket = 12, + ThermalHeatArc = 13, + IncomingHitArc = 14, + Custom = 100 +} + +public readonly record struct HbGpuStyleKey(byte FontId, ushort QWght, ushort QWdth, short QSlnt) +{ + public static ushort QuantizeWeight(float wght) => + (ushort)Math.Clamp((int)MathF.Round(wght), 100, 1000); + + public static ushort QuantizeWidth(float wdth) => + (ushort)Math.Clamp((int)MathF.Round(wdth * 10f), 500, 2000); + + public static short QuantizeSlant(float slnt) => + (short)Math.Clamp((int)MathF.Round(slnt * 10f), -200, 200); + + public static HbGpuStyleKey FromAxes(byte fontId, float wght, float wdth, float slnt) => + new(fontId, QuantizeWeight(wght), QuantizeWidth(wdth), QuantizeSlant(slnt)); +} + +public readonly record struct GlyphBlobKey(byte FontId, uint GlyphId, ushort QWght, ushort QWdth, short QSlnt); + +public readonly record struct VectorBlobKey(VectorShapeKind Kind, ushort ParamA, ushort ParamB, uint ParamC = 0); + +public readonly record struct CachedBlob( + uint AtlasOffset, + short MinX, + short MinY, + short MaxX, + short MaxY, + uint TexelCount, + bool IsEmpty) +{ + public bool IsValid => TexelCount > 0 && !IsEmpty; +} diff --git a/src/RustToDust.HbGpu/HbGpuVectorShapes.cs b/src/RustToDust.HbGpu/HbGpuVectorShapes.cs new file mode 100644 index 0000000..6ec2ebe --- /dev/null +++ b/src/RustToDust.HbGpu/HbGpuVectorShapes.cs @@ -0,0 +1,254 @@ +using System; + +namespace RustToDust.HbGpu; + +/// +/// Encodes canonical UI/HUD vector primitives into HarfBuzz hb-gpu RGBA16I blobs +/// in a 1000-unit design space ([-500 .. +500] or [0 .. 1000]). +/// +public static class HbGpuVectorShapes +{ + public const uint DesignUpem = 1000u; + + private static readonly byte[] RectVerbs = { (byte)HbGpuPathVerb.Rect }; + private static readonly float[] UnitFilledRectArgs = { -500f, -500f, 1000f, 1000f, float.NaN }; + + private static readonly byte[] CircleVerbs = { (byte)HbGpuPathVerb.Circle }; + private static readonly float[] UnitFilledCircleArgs = { 0f, 0f, 500f, float.NaN }; + + // L-corner bracket centered around (0,0) pointing into (+X, +Y), design space 1000x1000 + // Thickness paramB in thousandths (e.g. 100 = 10% of arm length) + private static readonly byte[] CornerBracketVerbs = + { + (byte)HbGpuPathVerb.Move, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.Close + }; + + // Equilateral/tactical chevron pointing +Y (Y-up in design space -> -Y in Y-down screen) + private static readonly byte[] ChevronVerbs = + { + (byte)HbGpuPathVerb.Move, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.LineTo, + (byte)HbGpuPathVerb.Close + }; + private static readonly float[] ChevronArgs = + { + 0f, 500f, + 420f, -380f, + 0f, -140f, + -420f, -380f + }; + + // Solid directional arrow pointing +Y in design space + private static readonly float[] ArrowArgs = + { + 0f, 520f, + 400f, -360f, + 0f, -180f, + -400f, -360f + }; + + // Diamond blip centered at (0,0) + private static readonly float[] DiamondArgs = + { + 0f, 500f, + 500f, 0f, + 0f, -500f, + -500f, 0f + }; + + public static CachedBlob GetUnitFilledRect(HbGpuBlobCache cache) => + cache.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.UnitFilledRect, 0, 0), + DesignUpem, + RectVerbs, + UnitFilledRectArgs); + + public static CachedBlob GetUnitFilledCircle(HbGpuBlobCache cache) => + cache.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.UnitCircleFill, 0, 0), + DesignUpem, + CircleVerbs, + UnitFilledCircleArgs); + + public static CachedBlob GetUnitRingStroke(HbGpuBlobCache cache, ushort strokeUnits = 24) + { + var key = new VectorBlobKey(VectorShapeKind.UnitRingStroke, strokeUnits, 0); + if (cache.TryGetStaticPath(key, out CachedBlob cached)) + { + return cached; + } + + Span args = stackalloc float[4]; + args[0] = 0f; + args[1] = 0f; + args[2] = 500f; + args[3] = strokeUnits; + return cache.GetOrEncodeStaticPath(key, DesignUpem, CircleVerbs, args); + } + + public static CachedBlob GetTargetBracketCorner(HbGpuBlobCache cache, ushort thicknessUnits = 120) + { + var key = new VectorBlobKey(VectorShapeKind.TargetBracketCorner, thicknessUnits, 0); + if (cache.TryGetStaticPath(key, out CachedBlob cached)) + { + return cached; + } + + float t = Math.Clamp((float)thicknessUnits, 10f, 450f); + Span args = stackalloc float[12]; + args[0] = 0f; args[1] = 0f; + args[2] = 1000f; args[3] = 0f; + args[4] = 1000f; args[5] = -t; + args[6] = t; args[7] = -t; + args[8] = t; args[9] = -1000f; + args[10] = 0f; args[11] = -1000f; + return cache.GetOrEncodeStaticPath(key, DesignUpem, CornerBracketVerbs, args); + } + + public static CachedBlob GetChevronTriangle(HbGpuBlobCache cache) => + cache.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.ChevronTriangle, 0, 0), + DesignUpem, + ChevronVerbs, + ChevronArgs); + + public static CachedBlob GetDirectionalArrow(HbGpuBlobCache cache) => + cache.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.DirectionalArrow, 0, 0), + DesignUpem, + ChevronVerbs, + ArrowArgs); + + public static CachedBlob GetDiamondBlip(HbGpuBlobCache cache) => + cache.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.DiamondBlip, 0, 0), + DesignUpem, + ChevronVerbs, + DiamondArgs); + + /// + /// Returns a permanently cached static stroked circular arc in design space (radius=500, Y-up). + /// Eliminates per-frame dynamic atlas uploads for fixed/quantized HUD arcs. + /// + public static CachedBlob GetStaticArcStroke( + HbGpuBlobCache cache, + VectorBlobKey key, + float startRad, + float endRad, + float radius = 500f, + float halfThickness = 32f) + { + if (cache.TryGetStaticPath(key, out CachedBlob cached)) + { + return cached; + } + + float sweep = endRad - startRad; + if (MathF.Abs(sweep) < 1e-4f) + { + return default; + } + + Span verbs = stackalloc byte[19]; // max 1 + 8 + 1 + 8 + 1 + Span args = stackalloc float[100]; // max 2 + 8*6 + 2 + 8*6 + BuildArcPath(startRad, endRad, radius, halfThickness, verbs, args, out int vCount, out int aCount); + return cache.GetOrEncodeStaticPath(key, DesignUpem, verbs[..vCount], args[..aCount]); + } + + /// + /// Encodes a stroked circular arc in design space (radius=500, Y-up) using cubic Bezier segments. + /// Useful for thermal heat arcs and directional incoming-hit arcs. + /// Angles are in radians counter-clockwise from +X (Y-up). + /// + public static CachedBlob EncodeArcStrokeDynamic( + HbGpuBlobCache cache, + float startRad, + float endRad, + float radius = 500f, + float halfThickness = 32f) + { + float sweep = endRad - startRad; + if (MathF.Abs(sweep) < 1e-4f) + { + return default; + } + + Span verbs = stackalloc byte[19]; + Span args = stackalloc float[100]; + BuildArcPath(startRad, endRad, radius, halfThickness, verbs, args, out int vCount, out int aCount); + return cache.EncodeDynamicPath(DesignUpem, verbs[..vCount], args[..aCount]); + } + + private static void BuildArcPath( + float startRad, + float endRad, + float radius, + float halfThickness, + Span verbs, + Span args, + out int v, + out int a) + { + float sweep = endRad - startRad; + int segs = Math.Clamp((int)MathF.Ceiling(MathF.Abs(sweep) / (MathF.PI * 0.4f)), 1, 8); + float rOut = radius + halfThickness; + float rIn = MathF.Max(1f, radius - halfThickness); + float dt = sweep / segs; + float k = (4f / 3f) * MathF.Tan(dt * 0.25f); + + v = 0; + a = 0; + + float ca0 = MathF.Cos(startRad); + float sa0 = MathF.Sin(startRad); + verbs[v++] = (byte)HbGpuPathVerb.Move; + args[a++] = rOut * ca0; + args[a++] = rOut * sa0; + + for (int i = 0; i < segs; i++) + { + float t0 = startRad + i * dt; + float t1 = t0 + dt; + float c0 = MathF.Cos(t0), s0 = MathF.Sin(t0); + float c1 = MathF.Cos(t1), s1 = MathF.Sin(t1); + verbs[v++] = (byte)HbGpuPathVerb.CubicTo; + args[a++] = rOut * (c0 - k * s0); + args[a++] = rOut * (s0 + k * c0); + args[a++] = rOut * (c1 + k * s1); + args[a++] = rOut * (s1 - k * c1); + args[a++] = rOut * c1; + args[a++] = rOut * s1; + } + + float ce = MathF.Cos(endRad); + float se = MathF.Sin(endRad); + verbs[v++] = (byte)HbGpuPathVerb.LineTo; + args[a++] = rIn * ce; + args[a++] = rIn * se; + + for (int i = segs - 1; i >= 0; i--) + { + float t1 = startRad + (i + 1) * dt; + float t0 = startRad + i * dt; + float c1 = MathF.Cos(t1), s1 = MathF.Sin(t1); + float c0 = MathF.Cos(t0), s0 = MathF.Sin(t0); + verbs[v++] = (byte)HbGpuPathVerb.CubicTo; + args[a++] = rIn * (c1 + k * s1); + args[a++] = rIn * (s1 - k * c1); + args[a++] = rIn * (c0 - k * s0); + args[a++] = rIn * (s0 + k * c0); + args[a++] = rIn * c0; + args[a++] = rIn * s0; + } + + verbs[v++] = (byte)HbGpuPathVerb.Close; + } +} diff --git a/src/RustToDust.HbGpu/RustToDust.HbGpu.csproj b/src/RustToDust.HbGpu/RustToDust.HbGpu.csproj new file mode 100644 index 0000000..eb31d97 --- /dev/null +++ b/src/RustToDust.HbGpu/RustToDust.HbGpu.csproj @@ -0,0 +1,42 @@ + + + + net8.0 + enable + disable + true + RustToDust.HbGpu + RustToDust.HbGpu + Release + $(MSBuildThisFileDirectory)..\..\native\rtd_hbgpu + $(MSBuildThisFileDirectory)..\..\artifacts\hbgpu-native\$(HbGpuNativeConfiguration) + C:\Program Files\CMake\bin\cmake.exe + cmake + + + + + + + + + + + + + + diff --git a/src/RustToDust.Net/ListenHostArenaSession.cs b/src/RustToDust.Net/ListenHostArenaSession.cs index 07dcb89..f035fb0 100644 --- a/src/RustToDust.Net/ListenHostArenaSession.cs +++ b/src/RustToDust.Net/ListenHostArenaSession.cs @@ -18,7 +18,8 @@ namespace RustToDust.Net int maxHumans = MatchState.ContenderCount, bool startInLobby = false, string serverName = "Rust to Dust", - int minHumansToStart = 1) + int minHumansToStart = 1, + byte squadSize = 1) { _host = new ServerMatchHost( bindAddress, @@ -31,7 +32,8 @@ namespace RustToDust.Net hostContenderId: 0, startInLobby: startInLobby, serverName: serverName, - minHumansToStart: minHumansToStart); + minHumansToStart: minHumansToStart, + squadSize: squadSize); } public ServerMatchHost Host => _host; @@ -44,7 +46,10 @@ namespace RustToDust.Net ? ClientMatchOutcome.Active : _host.Session.State.Phase == MatchPhase.Active ? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat) - : (_host.Session.State.WinnerContenderId == 0 ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat); + : ((_host.Session.State.WinnerContenderId == 0 || + (_host.Session.State.WinnerContenderId.HasValue && _host.Session.State.AreAllies(0, _host.Session.State.WinnerContenderId.Value))) + ? ClientMatchOutcome.Victory + : ClientMatchOutcome.Defeat); public int LocalDetectedByCount => _host.Session.State.ObserverStates.TryGetValue(0, out var obs) ? obs.DetectedByCount : 0; @@ -89,11 +94,15 @@ namespace RustToDust.Net public bool RequestEquipCargo(int cargoIndex, string hardpointId) => _host.TryEquipHostCargo(cargoIndex, hardpointId); + public void RepairArenaScars() => _host.RepairArenaScars(); + public void RequestNewMatch(int seed, ArenaMapKind mapKind) => _host.ResetMatch(seed, mapKind); public bool SetLobbyReady(bool ready) => _host.SetLobbyReady(0, ready); public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) => _host.ConfigureLobby(0, seed, mapKind); + public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind, byte squadSize) => _host.ConfigureLobby(0, seed, mapKind, squadSize); + public bool RequestLobbySquad(byte targetSquadId) => _host.MovePeerToSquad(0, targetSquadId); public bool RequestLobbyStart() => _host.LaunchFromLobby(0); public (Vector3 Pos, Quaternion Rot, Vector3 Vel) GetInterpolatedContenderPose(int contenderId, float alpha) => @@ -107,7 +116,7 @@ namespace RustToDust.Net public ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation) { - var hit = _host.Session.World.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z)); + var hit = _host.Session.CastWorldRayClosest(origin, translation); return new ClientRayHit( hit.Hit, hit.StableId, diff --git a/src/RustToDust.Net/RemoteArenaSession.cs b/src/RustToDust.Net/RemoteArenaSession.cs index 2b08dd3..0fa82b1 100644 --- a/src/RustToDust.Net/RemoteArenaSession.cs +++ b/src/RustToDust.Net/RemoteArenaSession.cs @@ -52,10 +52,13 @@ namespace RustToDust.Net private MatchState _viewState; private Box3DSoaWorld? _predWorld; + private readonly Box3DPhysicsTileSync _predTileSync = new(); private Box3DSoaBodyHandle? _predBody; private WalkerState? _predWalker; private string _predChassisId = string.Empty; + public Box3DPhysicsTileSync PredTileSync => _predTileSync; + private Vector3 _predErrorPos; private Quaternion _predErrorRot = Quaternion.Identity; private bool _pendingChassisSwapSnap; @@ -144,7 +147,10 @@ namespace RustToDust.Net ? ClientMatchOutcome.Active : _viewState.Phase == MatchPhase.Active ? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat) - : (_viewState.WinnerContenderId == _localContenderId ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat); + : ((_viewState.WinnerContenderId == _localContenderId || + (_viewState.WinnerContenderId.HasValue && _viewState.AreAllies(_localContenderId, _viewState.WinnerContenderId.Value))) + ? ClientMatchOutcome.Victory + : ClientMatchOutcome.Defeat); public int LocalDetectedByCount => _localDetectedByCount; @@ -358,14 +364,29 @@ namespace RustToDust.Net return true; } - public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) + public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind) => + RequestLobbyConfig(seed, mapKind, _lobbyState?.SquadSize ?? 0); + + public bool RequestLobbyConfig(int seed, ArenaMapKind mapKind, byte squadSize) { if (!_joined || _viewState.Phase != MatchPhase.Lobby) return false; SendSchemaMessage(new LobbyConfigCmdMsg { ReqSeq = _nextCmdSeq++, Seed = seed, - MapKind = (byte)mapKind + MapKind = (byte)mapKind, + SquadSize = squadSize + }); + return true; + } + + public bool RequestLobbySquad(byte targetSquadId) + { + if (!_joined || _viewState.Phase != MatchPhase.Lobby) return false; + SendSchemaMessage(new LobbySquadCmdMsg + { + ReqSeq = _nextCmdSeq++, + TargetSquadId = targetSquadId }); return true; } @@ -500,7 +521,7 @@ namespace RustToDust.Net var staticHit = _predWorld.CastRayClosest( (origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z)); - if (staticHit.Hit && staticHit.StableId < ArenaSession.ContenderStableIdBase) + if (staticHit.Hit && ArenaSession.IsStaticWorldStableId(staticHit.StableId)) { bestFrac = staticHit.Fraction; best = new ClientRayHit( @@ -723,6 +744,7 @@ namespace RustToDust.Net { var c = _viewState.Contenders[slot.SlotId]; c.IsHuman = slot.IsHuman; + c.SquadId = slot.SquadId; if (!string.IsNullOrWhiteSpace(slot.Callsign)) { c.Name = slot.Callsign; @@ -791,7 +813,8 @@ namespace RustToDust.Net _predErrorRot = Quaternion.Identity; Array.Clear(_lastCombatSpecSeenSeq); - _viewState = new MatchState(dto.Seed, (ArenaMapKind)dto.MapKind, skipInitialDrop: true) + byte initSquadSize = (byte)Math.Clamp((int)dto.SquadSize, 1, 4); + _viewState = new MatchState(dto.Seed, (ArenaMapKind)dto.MapKind, skipInitialDrop: true, squadSize: initSquadSize) { Time = dto.SimTime, Phase = dto.Phase switch @@ -802,7 +825,26 @@ namespace RustToDust.Net }, WinnerContenderId = dto.WinnerContenderId }; + if (dto.ContenderSquadIds is { Length: > 0 } squadIds) + { + int count = Math.Min(squadIds.Length, _viewState.Contenders.Count); + for (int i = 0; i < count; i++) + { + _viewState.Contenders[i].SquadId = squadIds[i]; + } + } _lobbyState = _viewState.Phase == MatchPhase.Lobby ? dto.Lobby : null; + if (_lobbyState is not null) + { + for (int i = 0; i < _lobbyState.Slots.Count; i++) + { + var slot = _lobbyState.Slots[i]; + if (slot.SlotId >= 0 && slot.SlotId < _viewState.Contenders.Count) + { + _viewState.Contenders[slot.SlotId].SquadId = slot.SquadId; + } + } + } _lastKeepaliveUtcMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); _viewState.Spectators.SetReplicatedSafeRadius(dto.SafeRadius); _viewState.OrbitalDrop.ApplyReplicatedWaveState( @@ -815,6 +857,12 @@ namespace RustToDust.Net _timeSinceLastPhysicsPodStep = 0f; _physicsPodSteppingActive = false; + if (dto.PersistentScars is { Length: > 0 }) + { + var snap = ArenaScarLedger.DecompressSnapshot(dto.PersistentScars); + _viewState.ApplyPersistentScars(snap); + } + for (int i = 0; i < dto.TerrainStamps.Count; i++) { ApplyTerrainStamp(dto.TerrainStamps[i]); @@ -856,6 +904,7 @@ namespace RustToDust.Net var c = _viewState.Contenders[cd.Id]; c.Name = cd.Name; c.IsHuman = cd.IsHuman; + c.SquadId = cd.SquadId; if (cd.IsHuman) humans++; c.Lifecycle = (ContenderLifecycle)cd.LifecycleByte; c.RespawnsRemaining = cd.RespawnsRemaining; @@ -908,12 +957,21 @@ namespace RustToDust.Net { _predWorld?.Dispose(); _predWorld = new Box3DSoaWorld(capacity: 256, gravityX: 0f, gravityY: -20f, gravityZ: 0f); - ArenaSession.BuildStaticArena(_predWorld, _viewState); + _predTileSync.Reset(); + ArenaSession.BuildStaticArena(_predWorld, _viewState, _predTileSync, warmAllActors: false); + var local = LocalContender; + if (_viewState.Terrain.IsHeightmapMode) + { + _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; - var local = LocalContender; var q = NormalizeQuat(new Quaternion(local.CurrRotX, local.CurrRotY, local.CurrRotZ, local.CurrRotW)); SpawnLocalPredictionBody(new Vector3(local.X, local.Y, local.Z), q, Vector3.Zero, Vector3.Zero); } @@ -1080,7 +1138,7 @@ namespace RustToDust.Net var pod = pods[i]; if (pod.PodKind == OrbitalPodKind.Contender && pod.ContenderId == _localContenderId) { - if (pod.FlightTime > 25f) + if (pod.FlightTime > 75f) { _viewState.OrbitalDrop.RemoveActivePodAt(i); } @@ -1097,7 +1155,7 @@ namespace RustToDust.Net _viewState.FindClearDropPoint, out _, out _); - if (touched || pod.FlightTime > 25f) + if (touched || pod.FlightTime > 75f) { _viewState.OrbitalDrop.RemoveActivePodAt(i); } @@ -1173,6 +1231,14 @@ namespace RustToDust.Net _predWalker, ArenaSession.FixedDt, injectEngineHeat: false); + if (_viewState.Terrain.IsHeightmapMode) + { + _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); if (local.Grid.Spec.IsWalker && _predWalker is not null) { @@ -1277,6 +1343,14 @@ namespace RustToDust.Net local.VelY = pkt.LocalVel.Y; local.VelZ = pkt.LocalVel.Z; local.TargetHoverAltAgl = pkt.LocalTargetHoverAltAgl; + if (_predWorld is not null && _viewState.Terrain.IsHeightmapMode) + { + _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 && @@ -1455,6 +1529,7 @@ namespace RustToDust.Net c.ThrottleCmd = nc.Throttle; c.SteerCmd = nc.Steer; c.MaxThermalRatio = nc.MaxThermalRatio; + c.Grid.ApplyReplicatedCoreHpRatio(nc.CoreHpRatio, nc.Alive); c.X = nc.Pos.X; c.Y = nc.Pos.Y; c.Z = nc.Pos.Z; c.CurrRotX = nc.Rot.X; c.CurrRotY = nc.Rot.Y; c.CurrRotZ = nc.Rot.Z; c.CurrRotW = nc.Rot.W; c.VelX = nc.Vel.X; c.VelY = nc.Vel.Y; c.VelZ = nc.Vel.Z; @@ -1667,6 +1742,24 @@ 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( ds.DropId, ds.X, ds.Z, @@ -1835,17 +1928,10 @@ namespace RustToDust.Net private void ApplyTerrainStamp(TerrainStampEvent stamp) { - switch ((TerrainStampKind)stamp.Kind) + _viewState.ApplyTerrainStamp(stamp, recordInLedger: true); + if (_predWorld is not null && _viewState.Terrain.IsHeightmapMode) { - case TerrainStampKind.Crater: - _viewState.Terrain.StampCrater(stamp.X, stamp.Z, stamp.Radius, stamp.Depth); - break; - case TerrainStampKind.Scorch: - _viewState.Terrain.StampScorch(stamp.X, stamp.Z, stamp.Radius); - break; - case TerrainStampKind.Track: - _viewState.Terrain.StampTrack(stamp.X, stamp.Z, stamp.Yaw, stamp.Radius, stamp.Length); - break; + _predTileSync.SyncWindow(_predWorld, _viewState.Terrain, LocalContender.X, LocalContender.Z, halfTileRadius: 1); } } diff --git a/src/RustToDust.Net/ServerMatchHost.cs b/src/RustToDust.Net/ServerMatchHost.cs index d3fe744..e7c0bf0 100644 --- a/src/RustToDust.Net/ServerMatchHost.cs +++ b/src/RustToDust.Net/ServerMatchHost.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Net; using System.Net.Sockets; using System.Numerics; @@ -32,6 +33,9 @@ namespace RustToDust.Net public readonly HashSet SentDropIds = new(); public readonly HashSet SentPodIds = new(); 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 @@ -51,6 +55,13 @@ namespace RustToDust.Net private readonly List _stepEvents = new(); 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; + private readonly Dictionary _inMemoryScarsByMap = new(); private readonly int _maxHumans; private readonly double _autoRestartSec; private readonly bool _allowClientReset; @@ -61,6 +72,7 @@ namespace RustToDust.Net private readonly byte[] _udpPeekBuf = new byte[65535]; private ArenaSession _session; + private byte _squadSize; private string _hostCallsign = "Host"; private uint _matchGeneration = 1; private uint _simTick; @@ -71,6 +83,7 @@ namespace RustToDust.Net private uint _nextPeerId = 1; private float _roundCompletedElapsed; private int _lastBroadcastCountdownSec = -1; + private uint _lastScarSaveTick; private bool _disposed; public ServerMatchHost( @@ -85,7 +98,11 @@ namespace RustToDust.Net bool startInLobby = false, string serverName = "Rust to Dust", int minHumansToStart = 1, - bool restartToLobby = false) + bool restartToLobby = false, + byte squadSize = 1, + string? scarFilePath = null, + bool persistScars = false, + bool repairScarsOnStart = false) { _maxHumans = Math.Clamp(maxHumans, 1, MatchState.ContenderCount); _autoRestartSec = autoRestartSec; @@ -94,6 +111,18 @@ namespace RustToDust.Net _serverName = string.IsNullOrWhiteSpace(serverName) ? "Rust to Dust" : serverName.Trim(); _minHumansToStart = Math.Clamp(minHumansToStart, 1, _maxHumans); _restartToLobby = restartToLobby; + _squadSize = (byte)Math.Clamp((int)squadSize, 1, 4); + _persistScars = persistScars; + _configuredScarPath = scarFilePath; + _initialMapKind = mapKind; + for (int tz = 0; tz < 16; tz++) + { + for (int tx = 0; tx < 16; tx++) + { + _tileStampHistory[tx, tz] = new List(4); + _tileTreeChanges[tx, tz] = new HashSet(); + } + } _socket = new Socket(bindAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp) { @@ -114,7 +143,23 @@ namespace RustToDust.Net }); _server.PeerDisconnected += OnTransportPeerDisconnected; - _session = new ArenaSession(seed, mapKind, slot0Human: hostContenderId == 0, startInLobby: startInLobby); + ArenaScarLedgerSnapshot? initialScars = null; + string? initScarPath = _persistScars ? ResolveScarFilePath(_configuredScarPath, _initialMapKind, mapKind) : null; + if (_persistScars && initScarPath is not null) + { + string fp = GetAssetFingerprint(seed, mapKind); + if (repairScarsOnStart) + { + var emptySnap = new ArenaScarLedgerSnapshot { AssetFingerprint = fp }; + ArenaScarLedgerStore.Save(initScarPath, emptySnap); + } + else + { + initialScars = ArenaScarLedgerStore.Load(initScarPath, fp); + } + } + + _session = new ArenaSession(seed, mapKind, slot0Human: hostContenderId == 0, startInLobby: startInLobby, squadSize: _squadSize, initialScars: initialScars); if (hostContenderId.HasValue) { _session.SetHumanSlot(hostContenderId.Value, true, "Host"); @@ -167,19 +212,67 @@ namespace RustToDust.Net public void ResetMatch(int seed, ArenaMapKind mapKind) => ResetMatch(seed, mapKind, startInLobby: false); - public void ResetMatch(int seed, ArenaMapKind mapKind, bool startInLobby) + public void ResetMatch(int seed, ArenaMapKind mapKind, bool startInLobby) => + ResetMatch(seed, mapKind, startInLobby, repairScars: false); + + public void ResetMatch(int seed, ArenaMapKind mapKind, bool startInLobby, bool repairScars) { if (_hostContenderId.HasValue && _hostContenderId.Value >= 0 && _hostContenderId.Value < _session.State.Contenders.Count) { _hostCallsign = _session.State.Contenders[_hostContenderId.Value].Name; } + ArenaMapKind prevMapKind = _session.State.MapKind; + if (repairScars && mapKind == prevMapKind) + { + _session.State.RepairArenaScars(); + _inMemoryScarsByMap.Remove(mapKind); + } + _inMemoryScarsByMap[prevMapKind] = _session.State.ScarLedger.ToSnapshot(); + FlushScarLedgerIfDirty(); + + ArenaScarLedgerSnapshot? preservedScars = null; + if (mapKind == prevMapKind) + { + preservedScars = _session.State.ScarLedger.ToSnapshot(); + } + else if (repairScars) + { + _inMemoryScarsByMap.Remove(mapKind); + if (_persistScars) + { + string targetPath = ResolveScarFilePath(_configuredScarPath, _initialMapKind, mapKind); + if (!string.IsNullOrWhiteSpace(targetPath)) + { + var emptySnap = new ArenaScarLedgerSnapshot { AssetFingerprint = GetAssetFingerprint(seed, mapKind) }; + ArenaScarLedgerStore.Save(targetPath, emptySnap); + } + } + } + else + { + string expectedFp = GetAssetFingerprint(seed, mapKind); + if (_inMemoryScarsByMap.TryGetValue(mapKind, out var memScars) && + string.Equals(memScars.AssetFingerprint, expectedFp, StringComparison.Ordinal)) + { + preservedScars = memScars; + } + else if (_persistScars) + { + string targetPath = ResolveScarFilePath(_configuredScarPath, _initialMapKind, mapKind); + preservedScars = ArenaScarLedgerStore.Load(targetPath, expectedFp); + } + } + _session.Dispose(); - _session = new ArenaSession(seed, mapKind, slot0Human: _hostContenderId == 0, startInLobby: startInLobby); + _session = new ArenaSession(seed, mapKind, slot0Human: _hostContenderId == 0, startInLobby: startInLobby, squadSize: _squadSize, initialScars: preservedScars); _matchGeneration++; _simTick = 0; _roundCompletedElapsed = 0f; _lastBroadcastCountdownSec = -1; _terrainStampHistory.Clear(); + ClearTileStampHistory(); + _treeChangeHistory.Clear(); + ClearTileTreeChanges(); _stepEvents.Clear(); _hostPendingEvents.Clear(); _reconnectTokens.Clear(); @@ -241,7 +334,10 @@ namespace RustToDust.Net return true; } - public bool ConfigureLobby(int requesterContenderId, int seed, ArenaMapKind mapKind) + public bool ConfigureLobby(int requesterContenderId, int seed, ArenaMapKind mapKind) => + ConfigureLobby(requesterContenderId, seed, mapKind, squadSize: null); + + public bool ConfigureLobby(int requesterContenderId, int seed, ArenaMapKind mapKind, byte? squadSize) { if (_session.State.Phase != MatchPhase.Lobby) { @@ -252,10 +348,79 @@ namespace RustToDust.Net return false; } + if (squadSize.HasValue && squadSize.Value >= 1 && squadSize.Value <= 4) + { + _squadSize = squadSize.Value; + } ResetMatch(seed, mapKind, startInLobby: true); return true; } + public bool MovePeerToSquad(int contenderId, byte targetSquadId) + { + if (_session.State.Phase != MatchPhase.Lobby || _session.State.Lobby is not { } lobby) + { + return false; + } + if (contenderId < 0 || contenderId >= lobby.Slots.Length) + { + return false; + } + byte squadSize = (byte)Math.Clamp((int)lobby.SquadSize, 1, 4); + if (squadSize <= 1) + { + return false; + } + + int maxSquads = (MatchState.ContenderCount + squadSize - 1) / squadSize; + if (targetSquadId >= maxSquads) + { + return false; + } + byte targetSq = targetSquadId; + var srcSlot = lobby.Slots[contenderId]; + byte srcSq = srcSlot.SquadId; + if (srcSq == targetSq) + { + return true; + } + + int targetCount = 0; + LobbySlotState? swapAi = null; + for (int i = 0; i < lobby.Slots.Length; i++) + { + var s = lobby.Slots[i]; + if (s.SquadId == targetSq) + { + targetCount++; + if (!s.IsHuman && swapAi is null) + { + swapAi = s; + } + } + } + + if (targetCount < squadSize) + { + srcSlot.SquadId = targetSq; + _session.State.Contenders[contenderId].SquadId = targetSq; + } + else if (swapAi is not null) + { + swapAi.SquadId = srcSq; + _session.State.Contenders[swapAi.SlotId].SquadId = srcSq; + srcSlot.SquadId = targetSq; + _session.State.Contenders[contenderId].SquadId = targetSq; + } + else + { + return false; + } + + BroadcastLobbySnapshot(); + return true; + } + public bool LaunchFromLobby(int requesterContenderId) { if (_session.State.Phase != MatchPhase.Lobby || _session.State.Lobby is not { } lobby) @@ -293,6 +458,7 @@ namespace RustToDust.Net lobby.MinHumansToAutoStart = _minHumansToStart; lobby.SelectedMap = session.State.MapKind; lobby.SelectedSeed = session.State.Seed; + lobby.SquadSize = session.State.SquadSize; lobby.CountdownSeconds = null; lobby.ForceLaunched = false; for (int i = 0; i < session.State.Contenders.Count && i < lobby.Slots.Length; i++) @@ -301,6 +467,7 @@ namespace RustToDust.Net lobby.Slots[i].IsHuman = c.IsHuman; lobby.Slots[i].Callsign = c.Name; lobby.Slots[i].IsReady = false; + lobby.Slots[i].SquadId = c.SquadId; } } @@ -354,6 +521,7 @@ namespace RustToDust.Net ForceLaunched = lobby.ForceLaunched, SelectedMap = (byte)lobby.SelectedMap, SelectedSeed = lobby.SelectedSeed, + SquadSize = lobby.SquadSize, Slots = new List(lobby.Slots.Length) }; for (int i = 0; i < lobby.Slots.Length; i++) @@ -364,7 +532,8 @@ namespace RustToDust.Net SlotId = s.SlotId, Callsign = s.Callsign, IsHuman = s.IsHuman, - IsReady = s.IsReady + IsReady = s.IsReady, + SquadId = s.SquadId }); } return dto; @@ -509,12 +678,25 @@ namespace RustToDust.Net { if (_stepEvents[i] is TerrainStampEvent ts) { + int stampIdx = _terrainStampHistory.Count; _terrainStampHistory.Add(ts); + _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(); BroadcastSnapshots(); + if (_persistScars && (_simTick - _lastScarSaveTick) >= 1800) + { + FlushScarLedgerIfDirty(); + } try { _server.PollResends(); @@ -621,6 +803,16 @@ namespace RustToDust.Net } } break; + case RepairArenaCmdMsg: + if (_peersByEndpoint.TryGetValue(epKey, out var repPeer) && repPeer.Active && ReferenceEquals(repPeer.TransportPeer, transportPeer)) + { + repPeer.LastHeardUtcMs = nowUtcMs; + if (_allowClientReset || (_hostContenderId.HasValue && _hostContenderId.Value == repPeer.AssignedContenderId)) + { + RepairArenaScars(); + } + } + break; case InteractCmdMsg interactCmd: if (_peersByEndpoint.TryGetValue(epKey, out var intPeer) && intPeer.Active && ReferenceEquals(intPeer.TransportPeer, transportPeer)) { @@ -643,7 +835,15 @@ namespace RustToDust.Net if (_peersByEndpoint.TryGetValue(epKey, out var cfgPeer) && cfgPeer.Active && ReferenceEquals(cfgPeer.TransportPeer, transportPeer)) { cfgPeer.LastHeardUtcMs = nowUtcMs; - ConfigureLobby(cfgPeer.AssignedContenderId, cfgCmd.Seed, (ArenaMapKind)cfgCmd.MapKind); + byte? reqSquadSize = cfgCmd.SquadSize >= 1 && cfgCmd.SquadSize <= 4 ? cfgCmd.SquadSize : null; + ConfigureLobby(cfgPeer.AssignedContenderId, cfgCmd.Seed, (ArenaMapKind)cfgCmd.MapKind, reqSquadSize); + } + break; + case LobbySquadCmdMsg sqCmd: + if (_peersByEndpoint.TryGetValue(epKey, out var sqPeer) && sqPeer.Active && ReferenceEquals(sqPeer.TransportPeer, transportPeer)) + { + sqPeer.LastHeardUtcMs = nowUtcMs; + MovePeerToSquad(sqPeer.AssignedContenderId, sqCmd.TargetSquadId); } break; case LobbyStartCmdMsg: @@ -909,6 +1109,29 @@ namespace RustToDust.Net } peer.SentPodIds.Clear(); 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); + } + var terrain = _session.State.Terrain; + for (int tz = 0; tz < terrain.TileGridCount; tz++) + { + for (int tx = 0; tx < terrain.TileGridCount; tx++) + { + peer.SentTileVersions[tx, tz] = terrain.VisualTileVersions[tx, tz]; + } + } var activePods = _session.State.OrbitalDrop.ActivePods; for (int i = 0; i < activePods.Count; i++) { @@ -924,7 +1147,9 @@ namespace RustToDust.Net { if (pod.PodKind == OrbitalPodKind.Contender) { - return pod.ContenderId == obsId || _session.IsEntityInPeerPvs(obsId, true, pod.ContenderId); + return pod.ContenderId == obsId || + _session.State.AreAllies(obsId, pod.ContenderId) || + _session.IsEntityInPeerPvs(obsId, true, pod.ContenderId); } return _session.IsPointInPeerPvs(obsId, pod.X, pod.Y + 2.0f, pod.Z); } @@ -1098,11 +1323,13 @@ namespace RustToDust.Net : new DropPickedUpEvent { DropId = dp.DropId, ContenderId = -1 }); } break; - case TerrainStampEvent stamp: - if (_session.IsPointInPeerPvs(obsId, stamp.X, _session.State.Terrain.SampleHeight(stamp.X, stamp.Z) + 0.5f, stamp.Z)) - { - filtered.Add(stamp); - } + case TerrainStampEvent: + // 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) @@ -1217,6 +1444,8 @@ namespace RustToDust.Net } } + SyncPeerLocalGeometryBubble(peer, obsId, filtered); + if (enteredPvsMask != 0) { var activePods = _session.State.OrbitalDrop.ActivePods; @@ -1614,11 +1843,19 @@ namespace RustToDust.Net private InitialMatchStateDto BuildInitialMatchStateDto(int forContenderId) { + var squadIds = new byte[_session.State.Contenders.Count]; + for (int i = 0; i < squadIds.Length; i++) + { + squadIds[i] = _session.State.Contenders[i].SquadId; + } + var dto = new InitialMatchStateDto { MatchGeneration = _matchGeneration, Seed = _session.State.Seed, MapKind = (byte)_session.State.MapKind, + SquadSize = _session.State.SquadSize, + ContenderSquadIds = squadIds, SimTime = _session.State.Time, SafeRadius = _session.State.Spectators.SafeRadius, Phase = (byte)(_session.State.Phase == MatchPhase.Completed ? 1 : _session.State.Phase == MatchPhase.Lobby ? 2 : 0), @@ -1656,19 +1893,18 @@ namespace RustToDust.Net }); } - for (int i = 0; i < _terrainStampHistory.Count; i++) + var scarSnap = _session.State.ScarLedger.ToSnapshot(); + if (scarSnap.Terrain.Count > 0 || scarSnap.Buildings.Count > 0 || scarSnap.Trees.Count > 0) { - var ts = _terrainStampHistory[i]; - if (_session.IsPointInPeerPvs(forContenderId, ts.X, _session.State.Terrain.SampleHeight(ts.X, ts.Z) + 0.5f, ts.Z)) - { - dto.TerrainStamps.Add(ts); - } + dto.PersistentScars = ArenaScarLedger.CompressSnapshot(scarSnap); } for (int i = 0; i < _session.State.Contenders.Count; i++) { var c = _session.State.Contenders[i]; - if (c.Id != forContenderId && !_session.IsEntityInPeerPvs(forContenderId, true, c.Id)) + if (c.Id != forContenderId && + !_session.State.AreAllies(forContenderId, c.Id) && + !_session.IsEntityInPeerPvs(forContenderId, true, c.Id)) { continue; } @@ -1681,7 +1917,8 @@ namespace RustToDust.Net Kills = c.Kills, Loadout = ArenaSession.BuildContenderLoadoutEvent(c, includeCargo: c.Id == forContenderId), LifecycleByte = (byte)c.Lifecycle, - RespawnsRemaining = (byte)Math.Clamp(c.RespawnsRemaining, 0, 255) + RespawnsRemaining = (byte)Math.Clamp(c.RespawnsRemaining, 0, 255), + SquadId = c.SquadId }); } @@ -1765,10 +2002,209 @@ namespace RustToDust.Net } } + public void RepairArenaScars() + { + _session.RepairArenaScars(); + _inMemoryScarsByMap.Remove(_session.State.MapKind); + _terrainStampHistory.Clear(); + ClearTileStampHistory(); + _treeChangeHistory.Clear(); + ClearTileTreeChanges(); + FlushScarLedgerIfDirty(); + + uint rev = _session.State.ScarLedger.LedgerRevision; + var repairEv = new ArenaRepairEvent { LedgerRevision = rev }; + if (_hostContenderId.HasValue) + { + _hostPendingEvents.Add(repairEv); + } + + foreach (var peer in _peersByEndpoint.Values) + { + if (!peer.Active) continue; + peer.SentTerrainStampIndices.Clear(); + Array.Clear(peer.SentTileVersions); + peer.SentTreeStates.Clear(); + SendSchemaToPeer(peer, new SimEventBatchMsg + { + BatchSeq = _eventBatchSeq++, + SimTick = _simTick, + SimTime = _session.State.Time, + MatchGeneration = _matchGeneration, + Events = new List { repairEv } + }); + } + } + + private void SyncPeerLocalGeometryBubble(ConnectedPeer peer, int obsId, List filtered) + { + if ((_terrainStampHistory.Count == 0 && _treeChangeHistory.Count == 0) || + obsId < 0 || obsId >= _session.State.Contenders.Count) + { + return; + } + var obs = _session.State.Contenders[obsId]; + var terrain = _session.State.Terrain; + terrain.MapWorldToTile(obs.X, obs.Z, out int cx, out int cz); + int grid = terrain.TileGridCount; + int minTx = Math.Max(0, cx - 4); + int maxTx = Math.Min(grid - 1, cx + 4); + int minTz = Math.Max(0, cz - 4); + int maxTz = Math.Min(grid - 1, cz + 4); + const float bubbleRadiusSq = 576f * 576f; + + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + if (_terrainStampHistory.Count > 0) + { + var list = _tileStampHistory[tx, tz]; + if (list.Count == 0) + { + peer.SentTileVersions[tx, tz] = terrain.VisualTileVersions[tx, tz]; + } + else + { + 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 (_treeChangeHistory.Count > 0 && _session.State.SionTrees is { } trees) + { + 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); + } + } + } + } + } + } + + private void ClearTileStampHistory() + { + for (int tz = 0; tz < 16; tz++) + { + for (int tx = 0; tx < 16; tx++) + { + _tileStampHistory[tx, tz].Clear(); + } + } + } + + 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)) + { + return ArenaScarLedgerStore.GetDefaultPath(targetMapKind); + } + + string mapTag = targetMapKind == ArenaMapKind.Sion ? "sion" : "desert"; + if (configuredPath.EndsWith(Path.DirectorySeparatorChar) || + configuredPath.EndsWith(Path.AltDirectorySeparatorChar) || + Directory.Exists(configuredPath)) + { + return Path.Combine(configuredPath, $"{mapTag}_scars_default.cultcache"); + } + + if (targetMapKind == initialMapKind) + { + return configuredPath; + } + + string dir = Path.GetDirectoryName(configuredPath) ?? "."; + string fileName = Path.GetFileName(configuredPath); + string initTag = initialMapKind == ArenaMapKind.Sion ? "sion" : "desert"; + if (fileName.StartsWith(initTag + "_", StringComparison.OrdinalIgnoreCase)) + { + return Path.Combine(dir, mapTag + fileName.Substring(initTag.Length)); + } + + string stem = Path.GetFileNameWithoutExtension(fileName); + string ext = Path.GetExtension(fileName); + return Path.Combine(dir, $"{stem}.{mapTag}{ext}"); + } + + private static string GetAssetFingerprint(int seed, ArenaMapKind mapKind) => + mapKind == ArenaMapKind.Sion ? SionMapLoader.Load().AssetFingerprint : $"desert:{seed}"; + + private void FlushScarLedgerIfDirty() + { + if (!_persistScars) + { + return; + } + string scarPath = ResolveScarFilePath(_configuredScarPath, _initialMapKind, _session.State.MapKind); + if (string.IsNullOrWhiteSpace(scarPath)) + { + return; + } + if (!_session.State.ScarLedger.IsDirty && File.Exists(scarPath)) + { + return; + } + ArenaScarLedgerStore.Save(scarPath, _session.State.ScarLedger.ToSnapshot()); + _session.State.ScarLedger.IsDirty = false; + _lastScarSaveTick = _simTick; + } + public void Dispose() { if (_disposed) return; _disposed = true; + FlushScarLedgerIfDirty(); _server.PeerDisconnected -= OnTransportPeerDisconnected; _server.Dispose(); _socket.Dispose(); diff --git a/src/RustToDust.Server/Program.cs b/src/RustToDust.Server/Program.cs index 2e1339b..5f7ae2b 100644 --- a/src/RustToDust.Server/Program.cs +++ b/src/RustToDust.Server/Program.cs @@ -27,6 +27,10 @@ namespace RustToDust.Server bool startInLobby = TryParseBool(Environment.GetEnvironmentVariable("RTD_LOBBY"), false); int minHumansToStart = TryParseInt(Environment.GetEnvironmentVariable("RTD_MIN_HUMANS"), 1); bool restartToLobby = TryParseBool(Environment.GetEnvironmentVariable("RTD_RESTART_TO_LOBBY"), false); + int squadSize = Math.Clamp(TryParseInt(Environment.GetEnvironmentVariable("RTD_SQUAD_SIZE"), 3), 1, 4); + string? scarFilePath = Environment.GetEnvironmentVariable("RTD_SCAR_FILE"); + bool persistScars = TryParseBool(Environment.GetEnvironmentVariable("RTD_PERSIST_SCARS"), true); + bool repairScars = false; for (int i = 0; i < args.Length; i++) { @@ -58,6 +62,12 @@ namespace RustToDust.Server else if (a == "--min-humans" && i + 1 < args.Length) minHumansToStart = TryParseInt(args[++i], minHumansToStart); else if (a.StartsWith("--min-humans=", StringComparison.Ordinal)) minHumansToStart = TryParseInt(a.Substring("--min-humans=".Length), minHumansToStart); else if (a == "--restart-to-lobby") restartToLobby = true; + else if (a == "--squad-size" && i + 1 < args.Length) squadSize = Math.Clamp(TryParseInt(args[++i], squadSize), 1, 4); + else if (a.StartsWith("--squad-size=", StringComparison.Ordinal)) squadSize = Math.Clamp(TryParseInt(a.Substring("--squad-size=".Length), squadSize), 1, 4); + else if (a == "--scar-file" && i + 1 < args.Length) scarFilePath = args[++i]; + else if (a.StartsWith("--scar-file=", StringComparison.Ordinal)) scarFilePath = a.Substring("--scar-file=".Length); + else if (a == "--no-persist-scars") persistScars = false; + else if (a == "--repair-scars") repairScars = true; } if (!IPAddress.TryParse(bindStr, out var bindIp)) @@ -95,7 +105,11 @@ namespace RustToDust.Server startInLobby: startInLobby, serverName: serverName, minHumansToStart: minHumansToStart, - restartToLobby: restartToLobby); + restartToLobby: restartToLobby, + squadSize: (byte)squadSize, + scarFilePath: scarFilePath, + persistScars: persistScars, + repairScarsOnStart: repairScars); host.LogMessage += msg => Console.WriteLine(msg); static DirectoryHeartbeatSnapshot BuildSnapshot(ServerMatchHost h, string hostAddr) => diff --git a/src/RustToDust.Ymir/ArenaSession.cs b/src/RustToDust.Ymir/ArenaSession.cs index 4a99b01..4c67fc9 100644 --- a/src/RustToDust.Ymir/ArenaSession.cs +++ b/src/RustToDust.Ymir/ArenaSession.cs @@ -11,7 +11,7 @@ namespace RustToDust.Ymir { public const float FixedDt = 1f / 60f; public const int SubStepCount = 4; - public const int WorldBodyCapacity = 384; + public const int WorldBodyCapacity = 1024; internal const ulong GroundStableId = 1; internal const ulong StaticBoxStableIdBase = 10; @@ -20,6 +20,7 @@ namespace RustToDust.Ymir private const ulong SpectatorStableIdBase = 3000; private readonly Box3DSoaWorld _world; + private readonly Box3DPhysicsTileSync _tileSync = new(); private readonly Dictionary _contenderBodies = new(); private readonly Dictionary _spectatorBodies = new(); private readonly Dictionary _contenderWalkers = new(); @@ -31,13 +32,14 @@ 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; - public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool slot0Human = false, bool skipInitialDrop = false, bool startInLobby = false) + public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool slot0Human = false, bool skipInitialDrop = false, bool startInLobby = false, byte squadSize = 1, ArenaScarLedgerSnapshot? initialScars = null) { - State = new MatchState(seed, mapKind, skipInitialDrop, startInLobby); + State = new MatchState(seed, mapKind, skipInitialDrop, startInLobby, squadSize, initialScars); Ordnance = new OrdnanceRuntime(this); _spectatorPvs = new bool[MatchState.ContenderCount, State.Spectators.Spectators.Count]; _forwardedPodEventId = State.PodEvents.Count > 0 ? State.PodEvents[^1].EventId : 0; @@ -73,7 +75,7 @@ namespace RustToDust.Ymir gravityY: -20f, gravityZ: 0f); - BuildStaticArena(_world, State); + BuildStaticArena(_world, State, _tileSync, warmAllActors: true); SpawnContenderBodies(); SpawnSpectatorBodies(); UpdateObserverDetectionMemories(); @@ -91,8 +93,41 @@ namespace RustToDust.Ymir public MatchState State { get; } public OrdnanceRuntime Ordnance { get; } public Box3DSoaWorld World => _world; + public Box3DPhysicsTileSync TileSync => _tileSync; public bool EnableNetworkPvs { get; set; } = true; + public void RepairArenaScars() + { + State.RepairArenaScars(); + if (State.Terrain.IsHeightmapMode) + { + int dirtyResidentCount = _tileSync.CountDirtyResidentTiles(State.Terrain); + if (dirtyResidentCount > 0) + { + int budget = _world.FreeBodySlots >= dirtyResidentCount + 32 + ? dirtyResidentCount + : 4; + _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) => + stableId < ContenderStableIdBase || stableId >= Box3DPhysicsTileSync.HeightfieldTileStableIdBase; + + public static bool IsStaticBuildingOrCoverStableId(ulong stableId) => + (stableId >= StaticMeshStableIdBase && stableId < ContenderStableIdBase) || + (stableId >= Box3DPhysicsTileSync.BuildingTileStableIdBase && stableId < Box3DPhysicsTileSync.TreeTileStableIdBase); + + public Box3DSoaRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation) + { + return _world.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z)); + } + public void SetHumanSlot(int contenderId, bool isHuman, string? callsign = null) { if (contenderId < 0 || contenderId >= State.Contenders.Count) @@ -322,6 +357,10 @@ namespace RustToDust.Ymir _contenderBodies.Remove(contenderId); } _contenderWalkers.Remove(contenderId); + if (State.Terrain.IsHeightmapMode) + { + _tileSync.EnsureTileRegion(_world, State.Terrain, x, z, halfTileRadius: 1); + } if (c.IsGroundedActive) { SpawnContenderBody(c); @@ -519,7 +558,7 @@ namespace RustToDust.Ymir { break; } - if (hit.StableId < ContenderStableIdBase) + if (IsStaticWorldStableId(hit.StableId)) { return false; } @@ -659,6 +698,7 @@ namespace RustToDust.Ymir MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight); State.OrbitalDrop.Step(FixedDt, QueryDropSurface, OnPodTouchedDown); + EnsureActivePhysicsTilesAndFlush(); ApplyPhysicsDrives(); _world.Step(FixedDt, subSteps); PostStepWalkers(); @@ -680,6 +720,7 @@ namespace RustToDust.Ymir MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight); State.OrbitalDrop.Step(FixedDt, QueryDropSurface, OnPodTouchedDown); long t2 = Stopwatch.GetTimestamp(); + EnsureActivePhysicsTilesAndFlush(); ApplyPhysicsDrives(); long t3 = Stopwatch.GetTimestamp(); _world.Step(FixedDt, subSteps); @@ -736,23 +777,18 @@ namespace RustToDust.Ymir return true; } - public static void BuildStaticArena(Box3DSoaWorld world, MatchState state) + public static void BuildStaticArena(Box3DSoaWorld world, MatchState state, Box3DPhysicsTileSync? tileSync = null, bool warmAllActors = true) { if (state.MapKind == ArenaMapKind.Sion && state.SionMap is { } sion) { - var meta = sion.Metadata; - float half = state.Terrain.MapHalfExtent; - world.AddStaticHeightField( - GroundStableId, - (-half, 0f, -half), - sion.Heights, - meta.GridRes, - meta.GridRes, - (meta.CellSizeMeters, 1.0f, meta.CellSizeMeters), - meta.MinY - 2f, - meta.MaxY + 2f, - friction: 0.15f, - restitution: 0.0f); + if (tileSync is not null && warmAllActors && state.Terrain.IsHeightmapMode) + { + Span needed = stackalloc bool[Box3DPhysicsTileSync.MaxTiles]; + 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; for (int i = 0; i < state.ArenaBoundaryBoxes.Count; i++) @@ -835,6 +871,20 @@ namespace RustToDust.Ymir _contenderWalkers.Remove(c.Id); if (c.IsGroundedActive) { + if (State.Terrain.IsHeightmapMode) + { + 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 + { + _tileSync.EnsureTileRegion(_world, State.Terrain, c.X, c.Z, halfTileRadius: 0); + } + } SpawnContenderBody(c); } } @@ -888,8 +938,82 @@ namespace RustToDust.Ymir } } - public DropSurfaceSample QueryDropSurface(float x, float z, float footRadius, float referenceMaxY) => - QueryDropSurface(State, _world, x, z, footRadius, referenceMaxY); + private static void MarkPhysicsOccupancyTiles(MatchState state, Span needed, Span immediate = default) + { + needed.Clear(); + if (!immediate.IsEmpty) + { + immediate.Clear(); + } + var terrain = state.Terrain; + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (!c.IsGroundedActive) + { + continue; + } + if (!immediate.IsEmpty) + { + Box3DPhysicsTileSync.MarkTileFootprint(terrain, immediate, c.X, c.Z, marginMeters: 0f); + } + if (c.IsHuman) + { + Box3DPhysicsTileSync.MarkTileFootprint(terrain, needed, c.X, c.Z, marginMeters: 28f); + } + else + { + Box3DPhysicsTileSync.MarkTileFootprint(terrain, needed, c.X, c.Z, marginMeters: 16f); + } + } + for (int i = 0; i < state.Spectators.Spectators.Count; i++) + { + var s = state.Spectators.Spectators[i]; + if (s.Alive && s.Stance != SpectatorStance.Neutral) + { + if (!immediate.IsEmpty) + { + Box3DPhysicsTileSync.MarkTileFootprint(terrain, immediate, s.X, s.Z, marginMeters: 0f); + } + Box3DPhysicsTileSync.MarkTileFootprint(terrain, needed, s.X, s.Z, marginMeters: 8f); + } + } + for (int i = 0; i < state.OrbitalDrop.ActivePods.Count; i++) + { + var pod = state.OrbitalDrop.ActivePods[i]; + if (pod.Y - terrain.SampleHeight(pod.X, pod.Z) <= 80f) + { + if (!immediate.IsEmpty) + { + Box3DPhysicsTileSync.MarkTileRegion(terrain, immediate, pod.X, pod.Z, halfTileRadius: 0); + } + Box3DPhysicsTileSync.MarkTileRegion(terrain, needed, pod.X, pod.Z, halfTileRadius: 0); + } + } + } + + private void EnsureActivePhysicsTilesAndFlush() + { + if (!State.Terrain.IsHeightmapMode) + { + return; + } + Span needed = stackalloc bool[Box3DPhysicsTileSync.MaxTiles]; + Span immediate = stackalloc bool[Box3DPhysicsTileSync.MaxTiles]; + 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) + { + return QueryDropSurface(State, _world, x, z, footRadius, referenceMaxY); + } public static DropSurfaceSample QueryDropSurface( MatchState state, @@ -1486,7 +1610,8 @@ namespace RustToDust.Ymir Vector3 toGoal = new Vector3(goalX - pos.X, 0f, goalZ - pos.Z); float dist = toGoal.Length(); - // On Sion, StaticHeightField supports settled non-walker Neutral Patrons directly so Box3D can sleep them. + // On Sion, StaticHeightField supports settled non-walker Neutral Patrons directly so Box3D can sleep them, + // provided the underlying heightfield tile is currently resident. if (!s.Grid.Spec.IsWalker && State.MapKind == ArenaMapKind.Sion && s.Stance == SpectatorStance.Neutral && @@ -1496,13 +1621,17 @@ namespace RustToDust.Ymir angVel.LengthSquared() < 0.09f && up.Y > 0.90f) { - view.ForceX[lane] = 0f; - view.ForceY[lane] = 0f; - view.ForceZ[lane] = 0f; - view.TorqueX[lane] = 0f; - view.TorqueY[lane] = 0f; - view.TorqueZ[lane] = 0f; - continue; + State.Terrain.MapWorldToTile(pos.X, pos.Z, out int stx, out int stz); + if (_tileSync.TryGetResidentHandle(stx, stz, State.Terrain.TileGridCount, out _)) + { + view.ForceX[lane] = 0f; + view.ForceY[lane] = 0f; + view.ForceZ[lane] = 0f; + view.TorqueX[lane] = 0f; + view.TorqueY[lane] = 0f; + view.TorqueZ[lane] = 0f; + continue; + } } Vector3 desiredVel = dist > 0.5f ? Vector3.Normalize(toGoal) * MathF.Min(s.MaxSpeed, dist * 1.5f) : Vector3.Zero; @@ -2066,6 +2195,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++) @@ -2094,6 +2235,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); + } + } } } @@ -2114,10 +2265,20 @@ namespace RustToDust.Ymir for (int i = 0; i < State.Contenders.Count; i++) { _contenderPvs[obs.Id, i] = i == obs.Id; + if (memState.ContenderContacts.TryGetValue(State.Contenders[i].Id, out var mem)) + { + mem.VisibleToPlayer = false; + mem.FaintHorizonPing = false; + } } for (int i = 0; i < State.Spectators.Spectators.Count; i++) { _spectatorPvs[obs.Id, i] = false; + if (memState.SpectatorContacts.TryGetValue(State.Spectators.Spectators[i].Id, out var smem)) + { + smem.VisibleToPlayer = false; + smem.FaintHorizonPing = false; + } } continue; } @@ -2136,6 +2297,28 @@ namespace RustToDust.Ymir } var mem = memState.GetOrCreateContenderContact(c.Id); + if (State.AreAllies(obs.Id, c.Id)) + { + bool allyAlive = c.Alive || c.IsInDropPod; + _contenderPvs[obs.Id, i] = allyAlive; + if (allyAlive) + { + mem.VisibleToPlayer = true; + mem.FaintHorizonPing = false; + mem.LastSeenAge = 0f; + mem.LastSeenX = c.X; + mem.LastSeenZ = c.Z; + mem.HasEverBeenSeen = true; + } + else + { + mem.VisibleToPlayer = false; + mem.FaintHorizonPing = false; + mem.LastSeenAge = float.PositiveInfinity; + } + continue; + } + if (!c.Alive) { mem.VisibleToPlayer = false; @@ -2536,7 +2719,7 @@ namespace RustToDust.Ymir for (int j = 0; j < State.Contenders.Count; j++) { var other = State.Contenders[j]; - if (other.Id == shooter.Id || !other.IsGroundedActive || !other.Grid.Spec.IsVtol) + if (other.Id == shooter.Id || State.AreAllies(shooter.Id, other.Id) || !other.IsGroundedActive || !other.Grid.Spec.IsVtol) { continue; } @@ -2798,6 +2981,14 @@ namespace RustToDust.Ymir { continue; } + if (shooterStableId >= ContenderStableIdBase && shooterStableId < SpectatorStableIdBase) + { + int shooterCid = (int)(shooterStableId - ContenderStableIdBase); + if (State.AreAllies(shooterCid, c.Id)) + { + continue; + } + } float dx = c.X - aimX; float dy = c.Y - aimY; float dz = c.Z - aimZ; @@ -2854,6 +3045,10 @@ namespace RustToDust.Ymir if (targetRef.IsContender) { var target = State.Contenders[targetRef.Index]; + if (shooterContender is not null && shooterContender.Id != target.Id && State.AreAllies(shooterContender.Id, target.Id)) + { + return; + } if (!target.IsGroundedActive || !_contenderBodies.TryGetValue(target.Id, out var body)) { return; @@ -3046,11 +3241,13 @@ namespace RustToDust.Ymir State.SpawnModuleDrop(victim.X + (i - 1) * 0.9f, victim.Z + 1.2f, victim.Grid.Mounted[i].Spec); } - State.Terrain.StampCrater(victim.X, victim.Z, radius: 5.2f, depth: 1.3f); - State.Terrain.StampScorch(victim.X, victim.Z, radius: 6.2f); + var craterEv = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = victim.X, Z = victim.Z, Radius = 5.2f, Depth = 1.3f }; + var scorchEv = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = victim.X, Z = victim.Z, Radius = 6.2f }; + State.ApplyTerrainStamp(craterEv, recordInLedger: true); + State.ApplyTerrainStamp(scorchEv, recordInLedger: true); State.OrbitalDrop.OnContenderEliminated(victim); - _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = victim.X, Z = victim.Z, Radius = 5.2f, Depth = 1.3f }); - _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = victim.X, Z = victim.Z, Radius = 6.2f }); + _stepEvents.Add(craterEv); + _stepEvents.Add(scorchEv); _stepEvents.Add(new ContenderEliminatedEvent { VictimId = victim.Id, @@ -3082,10 +3279,12 @@ namespace RustToDust.Ymir State.SpawnModuleDrop(spec.X + (i - 0.5f) * 1.1f, spec.Z, drops[i]); } - State.Terrain.StampCrater(spec.X, spec.Z, radius: 4.5f, depth: 1.1f); - State.Terrain.StampScorch(spec.X, spec.Z, radius: 5.4f); - _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = spec.X, Z = spec.Z, Radius = 4.5f, Depth = 1.1f }); - _stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = spec.X, Z = spec.Z, Radius = 5.4f }); + var specCraterEv = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = spec.X, Z = spec.Z, Radius = 4.5f, Depth = 1.1f }; + var specScorchEv = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = spec.X, Z = spec.Z, Radius = 5.4f }; + State.ApplyTerrainStamp(specCraterEv, recordInLedger: true); + State.ApplyTerrainStamp(specScorchEv, recordInLedger: true); + _stepEvents.Add(specCraterEv); + _stepEvents.Add(specScorchEv); _stepEvents.Add(new SpectatorDestroyedEvent { SpectatorId = spec.Id, @@ -3173,6 +3372,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++) { @@ -3181,6 +3389,10 @@ namespace RustToDust.Ymir { continue; } + if (shooterContender is not null && shooterContender.Id != c.Id && State.AreAllies(shooterContender.Id, c.Id)) + { + continue; + } ulong cStable = ContenderStableIdBase + (ulong)c.Id; if (cStable == ignoreStableId) { @@ -3387,26 +3599,58 @@ namespace RustToDust.Ymir { if (craterRadius > 0f && craterDepth > 0f) { - State.Terrain.StampCrater(x, z, radius: craterRadius, depth: craterDepth); - _stepEvents.Add(new TerrainStampEvent + var ev = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = x, Z = z, Radius = craterRadius, Depth = craterDepth - }); + }; + State.ApplyTerrainStamp(ev, recordInLedger: true); + _stepEvents.Add(ev); } if (scorchRadius > 0f) { - State.Terrain.StampScorch(x, z, radius: scorchRadius); - _stepEvents.Add(new TerrainStampEvent + var ev = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = x, Z = z, Radius = scorchRadius - }); + }; + State.ApplyTerrainStamp(ev, recordInLedger: true); + _stepEvents.Add(ev); + } + } + + 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); } } diff --git a/src/RustToDust.Ymir/Box3DPhysicsTileSync.cs b/src/RustToDust.Ymir/Box3DPhysicsTileSync.cs new file mode 100644 index 0000000..ebef7bd --- /dev/null +++ b/src/RustToDust.Ymir/Box3DPhysicsTileSync.cs @@ -0,0 +1,742 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Runtime.InteropServices; +using RustToDust.Core; +using Ymir.Box3D; + +namespace RustToDust.Ymir +{ + public sealed class Box3DPhysicsTileSync + { + public const ulong HeightfieldTileStableIdBase = 10_000; + public const ulong BuildingTileStableIdBase = 11_000; + public const ulong TreeTileStableIdBase = 12_000; + public const int MaxTiles = 256; + + private readonly Box3DSoaBodyHandle[] _residentHandles = new Box3DSoaBodyHandle[MaxTiles]; + private readonly bool[] _residentFlags = new bool[MaxTiles]; + 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 bool[] _treeTileActivated = 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) + { + if ((uint)tx < (uint)tileGridCount && (uint)tz < (uint)tileGridCount) + { + int idx = tz * tileGridCount + tx; + if (_residentFlags[idx]) + { + handle = _residentHandles[idx]; + return true; + } + } + handle = default; + 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(_treeTileActivated); + Array.Clear(_syncedTreeVersions); + ResidentTreeTileCount = 0; + } + + public bool EnsureTileResident(Box3DSoaWorld world, TerrainField terrain, int tx, int tz) + { + if (!terrain.IsHeightmapMode) + { + return false; + } + + int grid = terrain.TileGridCount; + if ((uint)tx >= (uint)grid || (uint)tz >= (uint)grid) + { + return false; + } + + int idx = tz * grid + tx; + int curVer = terrain.StructuralTileVersions[tx, tz]; + if (_residentFlags[idx] && _syncedStructuralVersions[idx] == curVer) + { + return false; + } + + int samplesPerTile = (terrain.HeightmapRes - 1) / grid; + int side = samplesPerTile + 1; + int sampleCount = side * side; + if (_scratchHeights is null || _scratchHeights.Length < sampleCount) + { + _scratchHeights = new float[sampleCount]; + } + + terrain.ExtractTilePhysicsHeights(tx, tz, _scratchHeights, out float minY, out float maxY); + + if (_residentFlags[idx]) + { + world.RemoveBody(_residentHandles[idx]); + ResidentTileCount--; + _residentFlags[idx] = false; + } + + float originX = -terrain.MapHalfExtent + tx * terrain.MapTileSize; + float originZ = -terrain.MapHalfExtent + tz * terrain.MapTileSize; + ulong stableId = HeightfieldTileStableIdBase + (ulong)idx; + var handle = world.AddStaticHeightField( + stableId, + (originX, 0f, originZ), + _scratchHeights.AsSpan(0, sampleCount), + side, + side, + (terrain.HeightmapCellSize, 1.0f, terrain.HeightmapCellSize), + minY - 2f, + maxY + 2f, + friction: 0.15f, + restitution: 0.0f); + + _residentHandles[idx] = handle; + _residentFlags[idx] = true; + _syncedStructuralVersions[idx] = curVer; + ResidentTileCount++; + return true; + } + + public void EnsureTileRegion(Box3DSoaWorld world, TerrainField terrain, float worldX, float worldZ, int halfTileRadius) + { + if (!terrain.IsHeightmapMode) + { + return; + } + + terrain.MapWorldToTile(worldX, worldZ, out int cx, out int cz); + int grid = terrain.TileGridCount; + 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 = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + EnsureTileResident(world, terrain, tx, tz); + } + } + } + + 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 (_treeTileActivated[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++; + } + + _treeTileActivated[idx] = true; + _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 (_treeTileActivated[idx] && !keep) + { + if (_treeResidentFlags[idx]) + { + world.RemoveBody(_treeHandles[idx]); + _treeHandles[idx] = default; + _treeResidentFlags[idx] = false; + ResidentTreeTileCount--; + } + _treeTileActivated[idx] = false; + _syncedTreeVersions[idx] = 0; + } + } + } + + 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] && !_treeTileActivated[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] && !_treeTileActivated[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 (!_treeTileActivated[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 (_treeTileActivated[idx] && (tx < minTx || tx > maxTx || tz < minTz || tz > maxTz)) + { + if (_treeResidentFlags[idx]) + { + world.RemoveBody(_treeHandles[idx]); + _treeHandles[idx] = default; + _treeResidentFlags[idx] = false; + ResidentTreeTileCount--; + } + _treeTileActivated[idx] = false; + _syncedTreeVersions[idx] = 0; + } + } + } + + 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) + { + return; + } + + terrain.MapWorldToTile(worldX, worldZ, out int cx, out int cz); + int grid = terrain.TileGridCount; + 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 = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + needed[tz * grid + tx] = true; + } + } + } + + public static void MarkTileFootprint(TerrainField terrain, Span needed, float worldX, float worldZ, float marginMeters) + { + if (!terrain.IsHeightmapMode) + { + return; + } + + float half = terrain.MapHalfExtent; + float r = MathF.Max(0f, marginMeters); + terrain.MapWorldToTile(Math.Clamp(worldX - r, -half, half), Math.Clamp(worldZ - r, -half, half), out int minTx, out int minTz); + terrain.MapWorldToTile(Math.Clamp(worldX + r, -half, half), Math.Clamp(worldZ + r, -half, half), out int maxTx, out int maxTz); + int grid = terrain.TileGridCount; + + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + needed[tz * grid + tx] = true; + } + } + } + + public void SyncNeededTiles( + Box3DSoaWorld world, + TerrainField terrain, + ReadOnlySpan needed, + ReadOnlySpan immediate = default, + int maxNewPrefetchPerTick = int.MaxValue) + { + if (!terrain.IsHeightmapMode) + { + return; + } + + int grid = terrain.TileGridCount; + 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 (_residentFlags[idx] && !keep) + { + world.RemoveBody(_residentHandles[idx]); + _residentHandles[idx] = default; + _residentFlags[idx] = false; + _syncedStructuralVersions[idx] = 0; + ResidentTileCount--; + } + } + } + + 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] && !_residentFlags[idx]) + { + EnsureTileResident(world, terrain, 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] && !_residentFlags[idx]) + { + if (EnsureTileResident(world, terrain, tx, tz)) + { + newPrefetch++; + } + } + } + } + } + + public void EnsureTilesAlongRay( + Box3DSoaWorld world, + TerrainField terrain, + float ox, float oz, + float dx, float dz, + float maxDistance) + { + if (!terrain.IsHeightmapMode || maxDistance <= 0f) + { + return; + } + + float half = terrain.MapHalfExtent; + float tileSize = terrain.MapTileSize; + int grid = terrain.TileGridCount; + + 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; + terrain.MapWorldToTile(sx, sz, out int tx, out int tz); + + float ex = ox + dx * tMax; + float ez = oz + dz * tMax; + terrain.MapWorldToTile(ex, ez, out int endTx, out int endTz); + + 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; + + int maxSteps = grid * 2 + 4; + for (int iter = 0; iter < maxSteps; iter++) + { + EnsureTileResident(world, terrain, 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 >= (uint)grid || (uint)tz >= (uint)grid || curT > tMax) + { + break; + } + } + + if ((uint)endTx < (uint)grid && (uint)endTz < (uint)grid) + { + EnsureTileResident(world, terrain, endTx, endTz); + } + } + + public int CountDirtyResidentTiles(TerrainField terrain) + { + if (!terrain.IsHeightmapMode) + { + return 0; + } + + int grid = terrain.TileGridCount; + int count = 0; + for (int tz = 0; tz < grid; tz++) + { + for (int tx = 0; tx < grid; tx++) + { + int idx = tz * grid + tx; + if (_residentFlags[idx] && terrain.StructuralTileVersions[tx, tz] != _syncedStructuralVersions[idx]) + { + count++; + } + } + } + return count; + } + + public int FlushDirtyHeightfields(Box3DSoaWorld world, TerrainField terrain, int maxTilesPerTick = 4) + { + if (!terrain.IsHeightmapMode || maxTilesPerTick <= 0) + { + return 0; + } + + int grid = terrain.TileGridCount; + int rebuilt = 0; + for (int tz = 0; tz < grid; tz++) + { + for (int tx = 0; tx < grid; tx++) + { + int idx = tz * grid + tx; + if (!_residentFlags[idx]) + { + continue; + } + if (terrain.StructuralTileVersions[tx, tz] != _syncedStructuralVersions[idx]) + { + if (world.FreeBodySlots < 8) + { + return rebuilt; + } + if (EnsureTileResident(world, terrain, tx, tz)) + { + rebuilt++; + if (rebuilt >= maxTilesPerTick) + { + return rebuilt; + } + } + } + } + } + return rebuilt; + } + + public void SyncWindow(Box3DSoaWorld world, TerrainField terrain, float centerX, float centerZ, int halfTileRadius = 1) + { + if (!terrain.IsHeightmapMode) + { + return; + } + + terrain.MapWorldToTile(centerX, centerZ, out int cx, out int cz); + int grid = terrain.TileGridCount; + 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 (_residentFlags[idx] && (tx < minTx || tx > maxTx || tz < minTz || tz > maxTz)) + { + world.RemoveBody(_residentHandles[idx]); + _residentHandles[idx] = default; + _residentFlags[idx] = false; + _syncedStructuralVersions[idx] = 0; + ResidentTileCount--; + } + } + } + + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + EnsureTileResident(world, terrain, tx, tz); + } + } + } + + private static bool SlabClip(float o, float d, float minB, float maxB, ref float tMin, ref float tMax) + { + if (MathF.Abs(d) < 1e-9f) + { + return o >= minB && o <= maxB; + } + float invD = 1f / d; + float t1 = (minB - o) * invD; + float t2 = (maxB - o) * invD; + if (t1 > t2) (t1, t2) = (t2, t1); + tMin = MathF.Max(tMin, t1); + tMax = MathF.Min(tMax, t2); + return tMax >= tMin; + } + } +} diff --git a/src/RustToDust.Ymir/LocalArenaSession.cs b/src/RustToDust.Ymir/LocalArenaSession.cs index 38f05c3..c7fd253 100644 --- a/src/RustToDust.Ymir/LocalArenaSession.cs +++ b/src/RustToDust.Ymir/LocalArenaSession.cs @@ -8,10 +8,11 @@ namespace RustToDust.Ymir public sealed class LocalArenaSession : IClientArenaSession { private readonly List _pendingEvents = new(); + private readonly Dictionary _scarsByMap = new(); - public LocalArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, string? callsign = null, bool skipInitialDrop = false) + public LocalArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, string? callsign = null, bool skipInitialDrop = false, byte squadSize = 1) { - Inner = new ArenaSession(seed, mapKind, slot0Human: true, skipInitialDrop: skipInitialDrop) + Inner = new ArenaSession(seed, mapKind, slot0Human: true, skipInitialDrop: skipInitialDrop, squadSize: squadSize) { EnableNetworkPvs = false }; @@ -31,7 +32,10 @@ namespace RustToDust.Ymir ? ClientMatchOutcome.Active : Inner.State.Phase == MatchPhase.Active ? ((LocalContender.Alive || LocalContender.WaitingForRespawn) ? ClientMatchOutcome.Active : ClientMatchOutcome.Defeat) - : (Inner.State.WinnerContenderId == LocalContenderId ? ClientMatchOutcome.Victory : ClientMatchOutcome.Defeat); + : ((Inner.State.WinnerContenderId == LocalContenderId || + (Inner.State.WinnerContenderId.HasValue && Inner.State.AreAllies(LocalContenderId, Inner.State.WinnerContenderId.Value))) + ? ClientMatchOutcome.Victory + : ClientMatchOutcome.Defeat); public int LocalDetectedByCount => Inner.State.ObserverStates.TryGetValue(LocalContenderId, out var obs) ? obs.DetectedByCount : 0; @@ -92,12 +96,21 @@ namespace RustToDust.Ymir return ok; } + public void RepairArenaScars() + { + Inner.RepairArenaScars(); + _scarsByMap.Remove(Inner.State.MapKind); + } + public void RequestNewMatch(int seed, ArenaMapKind mapKind) { string? name = LocalContender.Name; + byte squadSize = Inner.State.SquadSize; + _scarsByMap[Inner.State.MapKind] = Inner.State.ScarLedger.ToSnapshot(); + _scarsByMap.TryGetValue(mapKind, out var initialScars); _pendingEvents.Clear(); Inner.Dispose(); - Inner = new ArenaSession(seed, mapKind, slot0Human: true) + Inner = new ArenaSession(seed, mapKind, slot0Human: true, squadSize: squadSize, initialScars: initialScars) { EnableNetworkPvs = false }; @@ -122,7 +135,7 @@ namespace RustToDust.Ymir public ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation) { - var hit = Inner.World.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z)); + var hit = Inner.CastWorldRayClosest(origin, translation); return new ClientRayHit( hit.Hit, hit.StableId, diff --git a/src/RustToDust.Ymir/OrdnanceRuntime.cs b/src/RustToDust.Ymir/OrdnanceRuntime.cs index b2101bb..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 @@ -301,6 +303,7 @@ namespace RustToDust.Ymir targetPos = Vector3.Zero; float bestDistSq = maxRange * maxRange; bool found = false; + bool shooterIsContender = _sink.TryResolveActor(shooterStableId, out bool sIsC, out int shooterContenderId) && sIsC; for (int i = 0; i < PoolCapacity; i++) { @@ -309,7 +312,7 @@ namespace RustToDust.Ymir continue; } ref readonly var inst = ref _pool[i]; - if (inst.ShooterStableId == shooterStableId || inst.Def.InterceptHp <= 0f) + if (inst.Def.InterceptHp <= 0f || IsFriendlyOrdnance(shooterStableId, shooterIsContender, shooterContenderId, in inst)) { continue; } @@ -434,6 +437,10 @@ namespace RustToDust.Ymir { continue; } + if (!inst.IsSpectatorShooter && inst.ShooterContenderId >= 0 && state.AreAllies(inst.ShooterContenderId, c.Id)) + { + continue; + } Vector3 targetPt = _sink.GetActorAimPosition(true, i); Vector3 delta = targetPt - inst.Pos; @@ -599,7 +606,8 @@ namespace RustToDust.Ymir if (isContender) { var c = _sink.State.Contenders[idx]; - if (c.IsGroundedActive) + bool isAlly = !inst.IsSpectatorShooter && inst.ShooterContenderId >= 0 && _sink.State.AreAllies(inst.ShooterContenderId, c.Id); + if (c.IsGroundedActive && !isAlly) { targetPos = _sink.GetActorAimPosition(true, idx); return true; @@ -634,6 +642,10 @@ namespace RustToDust.Ymir { continue; } + if (!inst.IsSpectatorShooter && inst.ShooterContenderId >= 0 && state.AreAllies(inst.ShooterContenderId, c.Id)) + { + continue; + } Vector3 pt = _sink.GetActorAimPosition(true, i); Vector3 d = pt - inst.Pos; float d2 = d.LengthSquared(); @@ -686,6 +698,10 @@ namespace RustToDust.Ymir { continue; } + if (!inst.IsSpectatorShooter && inst.ShooterContenderId >= 0 && inst.ShooterContenderId != c.Id && state.AreAllies(inst.ShooterContenderId, c.Id)) + { + continue; + } Vector3 pt = _sink.GetActorAimPosition(true, i); float d2 = Vector3.DistanceSquared(inst.Pos, pt); @@ -743,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; @@ -829,12 +846,13 @@ namespace RustToDust.Ymir return !inst.Active; } + bool isTerrainTile = Box3DPhysicsTileSync.IsHeightfieldTileStableId(hitStableId); inst.Pos = boxPoint; HandleProjectileImpact( slotIndex, - HitTargetKind.StaticCover, - (int)hitStableId, - hitStableId, + isTerrainTile ? HitTargetKind.Terrain : HitTargetKind.StaticCover, + isTerrainTile ? -1 : (int)hitStableId, + isTerrainTile ? 0UL : hitStableId, boxPoint, boxNormal, dir); @@ -1176,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, @@ -1263,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; @@ -1399,6 +1422,16 @@ namespace RustToDust.Ymir continue; } + if (Box3DPhysicsTileSync.IsHeightfieldTileStableId(rayHit.StableId)) + { + hitTerrain = true; + terrainHitX = rayHit.Point.X; + terrainHitY = rayHit.Point.Y; + terrainHitZ = rayHit.Point.Z; + hitAny = false; + break; + } + hitAny = true; hitStableId = rayHit.StableId; hitPoint = rayHit.Point; @@ -1475,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, @@ -1569,6 +1606,33 @@ namespace RustToDust.Ymir } } + private bool IsFriendlyOrdnance( + ulong shooterStableId, + bool shooterIsContender, + int shooterContenderId, + in LiveOrdnanceInstance inst) + { + if (inst.ShooterStableId == shooterStableId) + { + return true; + } + if (!shooterIsContender || shooterContenderId < 0) + { + return false; + } + if (!inst.IsSpectatorShooter && inst.ShooterContenderId >= 0) + { + return _sink.State.AreAllies(shooterContenderId, inst.ShooterContenderId); + } + if (_sink.TryResolveActor(inst.ShooterStableId, out bool instIsContender, out int instContenderId) && + instIsContender && + instContenderId >= 0) + { + return _sink.State.AreAllies(shooterContenderId, instContenderId); + } + return false; + } + private bool TryHitInterceptableOrdnance( Vector3 origin, Vector3 dir, @@ -1581,6 +1645,7 @@ namespace RustToDust.Ymir bestSlot = -1; bestDist = maxDist; hitPt = Vector3.Zero; + bool shooterIsContender = _sink.TryResolveActor(shooterStableId, out bool sIsC, out int shooterContenderId) && sIsC; for (int i = 0; i < PoolCapacity; i++) { @@ -1589,7 +1654,7 @@ namespace RustToDust.Ymir continue; } ref readonly var inst = ref _pool[i]; - if (inst.ShooterStableId == shooterStableId || inst.Def.InterceptHp <= 0f) + if (inst.Def.InterceptHp <= 0f || IsFriendlyOrdnance(shooterStableId, shooterIsContender, shooterContenderId, in inst)) { continue; } diff --git a/src/RustToDust.Ymir/WalkerLocomotion.cs b/src/RustToDust.Ymir/WalkerLocomotion.cs index 99abc84..68eca41 100644 --- a/src/RustToDust.Ymir/WalkerLocomotion.cs +++ b/src/RustToDust.Ymir/WalkerLocomotion.cs @@ -585,6 +585,15 @@ namespace RustToDust.Ymir private static bool IsDesertFloorSlab(TerrainField terrain, ulong stableId) => !terrain.IsHeightmapMode && stableId == ArenaSession.GroundStableId; + private static bool IsHeightfieldStableId(ulong stableId) => + stableId == ArenaSession.GroundStableId || + Box3DPhysicsTileSync.IsHeightfieldTileStableId(stableId); + + private static bool IsBuildingOrCoverStableId(ulong stableId) => + (stableId >= ArenaSession.StaticBoxStableIdBase && stableId < ArenaSession.ContenderStableIdBase) || + (stableId >= Box3DPhysicsTileSync.BuildingTileStableIdBase && + stableId < Box3DPhysicsTileSync.TreeTileStableIdBase); + internal static WalkableSurfaceHit SampleGroundAt( TerrainField terrain, Box3DSoaWorld? world, @@ -616,21 +625,23 @@ namespace RustToDust.Ymir ignoreLane: -1, Box3DSoaQueryMask.Static); - if (!hit.Hit || IsDesertFloorSlab(terrain, hit.StableId) || hit.Point.Y < terrY - 0.35f) + if (!hit.Hit || + IsDesertFloorSlab(terrain, hit.StableId) || + Box3DPhysicsTileSync.IsTreeTileStableId(hit.StableId) || + hit.Point.Y < terrY - 0.35f) { return new WalkableSurfaceHit(true, terrY, terrN, false); } Vector3 hitN = new(hit.Normal.X, hit.Normal.Y, hit.Normal.Z); hitN = hitN.LengthSquared() > 1e-6f ? Vector3.Normalize(hitN) : Vector3.UnitY; - bool isBuildingOrCover = hit.StableId >= ArenaSession.StaticBoxStableIdBase && - hit.StableId < ArenaSession.ContenderStableIdBase; + bool isBuildingOrCover = IsBuildingOrCoverStableId(hit.StableId); if (isBuildingOrCover && hit.Point.Y >= terrY - 0.05f) { return new WalkableSurfaceHit(true, hit.Point.Y, hitN, true); } - if (hit.StableId == ArenaSession.GroundStableId) + if (IsHeightfieldStableId(hit.StableId)) { if (terrY < hit.Point.Y - 0.05f) { @@ -924,9 +935,12 @@ namespace RustToDust.Ymir Box3DSoaQueryMask.Static); bool hasStaticStep = false; - if (fwdHit.Hit && !IsDesertFloorSlab(terrain, fwdHit.StableId) && fwdHit.Normal.Y < WalkerState.MaxWalkableNormalY) + if (fwdHit.Hit && + !IsDesertFloorSlab(terrain, fwdHit.StableId) && + !Box3DPhysicsTileSync.IsTreeTileStableId(fwdHit.StableId) && + fwdHit.Normal.Y < WalkerState.MaxWalkableNormalY) { - if (fwdHit.StableId == ArenaSession.GroundStableId) + if (IsHeightfieldStableId(fwdHit.StableId)) { Vector3 terrHitN = WalkerState.SampleTerrainNormal(terrain, fwdHit.Point.X, fwdHit.Point.Z); if (terrHitN.Y < WalkerState.MaxWalkableNormalY) @@ -1025,7 +1039,9 @@ namespace RustToDust.Ymir bool staticValid = false; float staticDownEndY = float.NegativeInfinity; - if (downHit.Hit && !IsDesertFloorSlab(terrain, downHit.StableId)) + if (downHit.Hit && + !IsDesertFloorSlab(terrain, downHit.StableId) && + !Box3DPhysicsTileSync.IsTreeTileStableId(downHit.StableId)) { staticDownEndY = acrossPos.Y - downSpan * downHit.Fraction; var lipTop = SampleGroundAt( @@ -1149,12 +1165,13 @@ namespace RustToDust.Ymir bool hasStatic = downHit.Hit && !IsDesertFloorSlab(terrain, downHit.StableId) && + !Box3DPhysicsTileSync.IsTreeTileStableId(downHit.StableId) && (downHit.Normal.Y >= WalkerState.MaxWalkableNormalY || - (downHit.StableId == ArenaSession.GroundStableId && terrN.Y >= groundMinNy)); + (IsHeightfieldStableId(downHit.StableId) && terrN.Y >= groundMinNy)); float staticCenterY = hasStatic ? castStart.Y - castSpan * downHit.Fraction + 0.005f : float.NegativeInfinity; - if (hasStatic && downHit.StableId == ArenaSession.GroundStableId && terrY < staticCenterY - physHalfH - 0.05f) + if (hasStatic && IsHeightfieldStableId(downHit.StableId) && terrY < staticCenterY - physHalfH - 0.05f) { hasStatic = false; } @@ -1237,9 +1254,10 @@ namespace RustToDust.Ymir float gTerrY = terrain.SampleHeight(pos.X, pos.Z); Vector3 gTerrN = WalkerState.SampleTerrainNormal(terrain, pos.X, pos.Z); - bool staticIsHeightfield = catHit.Hit && catHit.StableId == ArenaSession.GroundStableId && terrain.IsHeightmapMode; + bool staticIsHeightfield = catHit.Hit && IsHeightfieldStableId(catHit.StableId) && terrain.IsHeightmapMode; bool staticGround = catHit.Hit && !IsDesertFloorSlab(terrain, catHit.StableId) && + !Box3DPhysicsTileSync.IsTreeTileStableId(catHit.StableId) && (catHit.Normal.Y >= WalkerState.MaxWalkableNormalY || (staticIsHeightfield && gTerrN.Y >= WalkerState.MaxCliffGuardNormalY)); Vector3 staticNorm = staticGround diff --git a/tests/RustToDust.Tests/CameraJuiceTests.cs b/tests/RustToDust.Tests/CameraJuiceTests.cs index 9b14abb..aea6e9e 100644 --- a/tests/RustToDust.Tests/CameraJuiceTests.cs +++ b/tests/RustToDust.Tests/CameraJuiceTests.cs @@ -142,4 +142,39 @@ public sealed class CameraJuiceTests float expected = 0.14f * (1f - 20f / 90f); Assert.InRange(juice.Trauma, expected - 1e-4f, expected + 1e-4f); } + + [Fact] + public void DropPodFov_WidensTo82DegAndEasesTo58DegOnTouchdown() + { + var juice = new CameraJuiceState(); + const float dt = 1f / 60f; + + // 1. Freefall at max cross-zone glide speed (124 m/s) -> widens to 82..84 deg smoothly + for (int i = 0; i < 120; i++) + { + juice.Update(dt, localSpeedMps: 124f, isVtol: false, isInDropPod: true, podPhase: OrbitalPodPhase.Freefall); + } + float freefallFov = CameraJuiceState.BaseFovDeg + juice.FovOffsetDeg; + Assert.InRange(freefallFov, 80.0f, 85.0f); + + // 2. RetroBurn -> tightens to ~76 deg + for (int i = 0; i < 90; i++) + { + juice.Update(dt, localSpeedMps: 15f, isVtol: false, isInDropPod: true, podPhase: OrbitalPodPhase.RetroBurn); + } + float retroFov = CameraJuiceState.BaseFovDeg + juice.FovOffsetDeg; + Assert.InRange(retroFov, 74.5f, 77.5f); + + // 3. Touchdown ground release -> eases monotonically back toward 58 deg within ~1.5s + float prevFov = retroFov; + for (int i = 0; i < 90; i++) + { + juice.Update(dt, localSpeedMps: 0f, isVtol: false, isInDropPod: false); + float curFov = CameraJuiceState.BaseFovDeg + juice.FovOffsetDeg; + Assert.True(curFov <= prevFov + 1e-4f, $"Expected monotonic FOV release, jumped {prevFov:F3} -> {curFov:F3}"); + Assert.True(prevFov - curFov < 2.0f, $"Expected smooth FOV release without discontinuity: delta={prevFov - curFov:F2}"); + prevFov = curFov; + } + Assert.InRange(prevFov, 57.9f, 59.0f); + } } diff --git a/tests/RustToDust.Tests/CultNetMultiplayerTests.cs b/tests/RustToDust.Tests/CultNetMultiplayerTests.cs index 19dfaa1..adc3746 100644 --- a/tests/RustToDust.Tests/CultNetMultiplayerTests.cs +++ b/tests/RustToDust.Tests/CultNetMultiplayerTests.cs @@ -957,6 +957,171 @@ namespace RustToDust.Tests Assert.True(sawBlastClimb, "Idle local client must sync _predWalker smoothly to server upward blast without stale prediction lock"); } + [Fact] + public void Cut13a_OutOfPvsHistoricalCratersSyncViaPersistentScars_AndLiveCratersEnterWithin576mBubble() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, maxHumans: 12, autoRestartSec: 0); + var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + const float histX = 700f; + const float histZ = 700f; + float baseHistH = host.Session.State.Terrain.SampleHeight(histX, histZ); + + // 1. Historical out-of-PVS crater stamped before Client A joins + ((IOrdnanceTargetSink)host.Session).StampTerrainImpact(histX, histZ, craterRadius: 6f, craterDepth: 2.0f, scorchRadius: 7f); + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + host.StepOnce(nowMs += 16); + float scarredHistH = host.Session.State.Terrain.SampleHeight(histX, histZ); + Assert.True(scarredHistH < baseHistH - 1.2f); + + using var clientA = new RemoteArenaSession(ep, "Scout"); + Assert.True(PumpUntil(host, new[] { clientA }, () => clientA.IsJoined, ref nowMs, 3000)); + + // Out-of-PVS historical crater must be present immediately via PersistentScars + Assert.Equal(scarredHistH, clientA.ViewState.Terrain.SampleHeight(histX, histZ), precision: 3); + Assert.InRange(clientA.PredTileSync.ResidentTileCount, 1, 9); + + // 2. Live crater stamped far outside 576m bubble (-700, 100 vs open-sky ~700, 100 = ~1400m apart) + int slotA = clientA.LocalContenderId; + var sion = host.Session.State.SionMap!; + float liveX = 700f, liveZ = 100f; + for (float x = 640f; x <= 760f; x += 8f) + { + if (!sion.IsInsideAnyBuildingXz(x, liveZ, padding: 10f)) + { + liveX = x; + break; + } + } + float baseLiveH = host.Session.State.Terrain.SampleHeight(liveX, liveZ); + + host.Session.SetContenderPose(slotA, -700f, liveZ, 0f); + host.StepOnce(nowMs += 16); + ((IOrdnanceTargetSink)host.Session).StampTerrainImpact(liveX, liveZ, craterRadius: 6f, craterDepth: 2.0f, scorchRadius: 7f); + for (int t = 0; t < 10; t++) + { + nowMs += 16; + host.StepOnce(nowMs); + clientA.PumpNetwork(); + Thread.Sleep(1); + } + float hostLiveH = host.Session.State.Terrain.SampleHeight(liveX, liveZ); + Assert.True(hostLiveH < baseLiveH - 1.2f); + Assert.Equal(baseLiveH, clientA.ViewState.Terrain.SampleHeight(liveX, liveZ), precision: 3); + + // 3. Client A enters 576m local geometry bubble (liveX - 450m -> dist = 450m <= 576m) + host.Session.SetContenderPose(slotA, liveX - 450f, liveZ, 0f); + Assert.True(PumpUntil( + host, + new[] { clientA }, + () => MathF.Abs(clientA.ViewState.Terrain.SampleHeight(liveX, liveZ) - hostLiveH) < 0.05f, + ref nowMs, + 3000), + "Client must receive live TerrainStampEvent upon entering 576m bubble before reaching _predWorld 3x3 window"); + + // 4. Client A steps into (liveX, liveZ) tile -> _predWorld 3x3 window matches server Box3D crater depth 1:1 + host.Session.SetContenderPose(slotA, liveX - 20f, liveZ, 0f); + for (int t = 0; t < 10; t++) + { + nowMs += 16; + host.StepOnce(nowMs); + clientA.BeginRenderFrame(1.0 / 60.0, 1f); + Thread.Sleep(1); + } + Assert.InRange(clientA.PredTileSync.ResidentTileCount, 1, 9); + float rayStartY = sion.Metadata.MaxY + 25f; + float raySpanY = -(sion.Metadata.MaxY - sion.Metadata.MinY + 60f); + var hostHit = host.Session.CastWorldRayClosest(new Vector3(liveX, rayStartY, liveZ), new Vector3(0f, raySpanY, 0f)); + var predHit = clientA.CastWorldRayClosest(new Vector3(liveX, rayStartY, liveZ), new Vector3(0f, raySpanY, 0f)); + Assert.True(hostHit.Hit && predHit.Hit); + Assert.True(MathF.Abs(hostHit.Point.Y - predHit.Point.Y) < 0.05f, + $"Expected _predWorld crater impact Y ({predHit.Point.Y:F3}m) to match server ({hostHit.Point.Y:F3}m)"); + } + + [Fact] + public void Cut13a_OverlappingCraters_CoalesceIdenticallyAcrossLiveHostJoinerAndPostReset() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, maxHumans: 12, autoRestartSec: 0); + var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + const float cx = -120f; + const float cz = 180f; + + // Stamp 3 overlapping craters within < 0.75m (coalesce radius) + ((IOrdnanceTargetSink)host.Session).StampTerrainImpact(cx, cz, craterRadius: 4.0f, craterDepth: 1.1f, scorchRadius: 4.5f); + ((IOrdnanceTargetSink)host.Session).StampTerrainImpact(cx + 0.30f, cz - 0.20f, craterRadius: 5.8f, craterDepth: 2.2f, scorchRadius: 6.0f); + ((IOrdnanceTargetSink)host.Session).StampTerrainImpact(cx - 0.15f, cz + 0.25f, craterRadius: 3.0f, craterDepth: 0.7f, scorchRadius: 3.5f); + + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + host.StepOnce(nowMs += 16); + + float liveHostH = host.Session.State.Terrain.SampleHeight(cx, cz); + float liveHostEdgeH = host.Session.State.Terrain.SampleHeight(cx + 2.5f, cz - 1.5f); + + using var clientA = new RemoteArenaSession(ep, "Joiner"); + Assert.True(PumpUntil(host, new[] { clientA }, () => clientA.IsJoined, ref nowMs, 3000)); + + float clientJoinH = clientA.ViewState.Terrain.SampleHeight(cx, cz); + float clientJoinEdgeH = clientA.ViewState.Terrain.SampleHeight(cx + 2.5f, cz - 1.5f); + Assert.True(MathF.Abs(liveHostH - clientJoinH) < 0.001f, + $"Expected liveHostH ({liveHostH:F4}) == clientJoinH ({clientJoinH:F4}) within 0.001m"); + Assert.True(MathF.Abs(liveHostEdgeH - clientJoinEdgeH) < 0.001f, + $"Expected liveHostEdgeH ({liveHostEdgeH:F4}) == clientJoinEdgeH ({clientJoinEdgeH:F4}) within 0.001m"); + + host.ResetMatch(43, ArenaMapKind.Sion, startInLobby: false); + float postResetHostH = host.Session.State.Terrain.SampleHeight(cx, cz); + float postResetHostEdgeH = host.Session.State.Terrain.SampleHeight(cx + 2.5f, cz - 1.5f); + Assert.True(MathF.Abs(liveHostH - postResetHostH) < 0.001f, + $"Expected liveHostH ({liveHostH:F4}) == postResetHostH ({postResetHostH:F4}) within 0.001m"); + Assert.True(MathF.Abs(liveHostEdgeH - postResetHostEdgeH) < 0.001f, + $"Expected liveHostEdgeH ({liveHostEdgeH:F4}) == postResetHostEdgeH ({postResetHostEdgeH:F4}) within 0.001m"); + } + + [Fact] + public void RemoteArenaSession_AppliesRemoteContenderCoreHpRatioOnPvsSnapshot() + { + using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Desert, maxHumans: 12, autoRestartSec: 0); + var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + using var client = new RemoteArenaSession(ep, "HpProbe"); + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + Assert.True(PumpUntil(host, new[] { client }, () => client.IsJoined, ref nowMs, 3000)); + int localSlot = client.LocalContenderId; + int rivalSlot = localSlot == 0 ? 1 : 0; + + var serverLocal = host.Session.State.Contenders[localSlot]; + var serverRival = host.Session.State.Contenders[rivalSlot]; + host.Session.SetContenderPose(localSlot, 0f, 0f, 0f); + host.Session.SetContenderPose(rivalSlot, 0f, 40f, MathF.PI); + + float targetHp = serverRival.Grid.MaxCoreHp * 0.42f; + serverRival.Grid.ApplyReplicatedDamage(0, 0, 0f, 20f, targetHp, serverRival.Grid.HitSequence + 1); + float expectedRatio = serverRival.Grid.CoreHp / serverRival.Grid.MaxCoreHp; + + bool synced = PumpUntil(host, new[] { client }, () => + { + if (!client.IsContenderVisible(rivalSlot)) return false; + var c = client.ViewState.Contenders[rivalSlot]; + float r = c.Grid.MaxCoreHp > 0f ? c.Grid.CoreHp / c.Grid.MaxCoreHp : 1f; + return MathF.Abs(r - expectedRatio) < 0.02f; + }, ref nowMs, 2500); + + var clientRival = client.ViewState.Contenders[rivalSlot]; + float actualRatio = clientRival.Grid.MaxCoreHp > 0f ? clientRival.Grid.CoreHp / clientRival.Grid.MaxCoreHp : 1f; + Assert.True(synced, $"Expected remote contender {rivalSlot} CoreHpRatio ~ {expectedRatio:F3}, got {actualRatio:F3}"); + + // Edge case: living rival at 0.30 HP rounds 8-bit CoreHpRatio to 0, yet must remain Alive on remote client + serverRival.Grid.ApplyReplicatedDamage(0, 0, 0f, 20f, 0.30f, serverRival.Grid.HitSequence + 1); + Assert.True(serverRival.Alive); + bool lowHpSynced = PumpUntil(host, new[] { client }, () => + { + var c = client.ViewState.Contenders[rivalSlot]; + return c.Alive && c.Grid.CoreHp > 0f && c.Grid.CoreHp <= 0.5f; + }, ref nowMs, 2500); + Assert.True(lowHpSynced && clientRival.Alive && !clientRival.Grid.IsDestroyed && clientRival.Grid.CoreHp > 0f, + $"Expected living 0.30 HP rival to stay Alive on remote client, got Alive={clientRival.Alive}, CoreHp={clientRival.Grid.CoreHp:F3}"); + } + private static byte[] EncodeRudpLatestDatagram(byte[] frameBytes, uint sequence) => CultNetRudpPacketCodec.Encode(new CultNetRudpPacket { diff --git a/tests/RustToDust.Tests/DetectionLosTests.cs b/tests/RustToDust.Tests/DetectionLosTests.cs index 01ae85f..e403838 100644 --- a/tests/RustToDust.Tests/DetectionLosTests.cs +++ b/tests/RustToDust.Tests/DetectionLosTests.cs @@ -584,5 +584,30 @@ namespace RustToDust.Tests Assert.Equal(0, targetNearest.TargetContenderId); } } + + [Fact] + public void DeadObserver_ClearsSpectatorContactsVisibleToPlayer() + { + using var session = new ArenaSession(seed: 12, slot0Human: true); + var player = session.State.Contenders[0]; + var spec = session.State.Spectators.Spectators.First(s => s.Alive); + + session.SetContenderPose(player.Id, 0f, 0f); + session.SetSpectatorPose(spec.Id, 0f, 35f); + session.State.Spectators.OnSpectatorDamaged(spec, player.Id); + + session.Step(); + var obs0 = session.State.GetOrCreateObserverState(0); + Assert.True(obs0.SpectatorContacts.TryGetValue(spec.Id, out var memBefore) && memBefore.VisibleToPlayer, + "Expected living observer in open LOS to mark provoked spectator VisibleToPlayer=true"); + + // Kill observer and step once; stale SpectatorContacts must clear VisibleToPlayer + player.Grid.ApplyReplicatedDamage(0, 0, 0f, 20f, 0f, player.Grid.HitSequence + 1); + Assert.False(player.Alive); + + session.Step(); + Assert.False(obs0.SpectatorContacts[spec.Id].VisibleToPlayer, + "Expected dead observer to clear SpectatorContacts.VisibleToPlayer"); + } } } diff --git a/tests/RustToDust.Tests/GraphicsSettingsTests.cs b/tests/RustToDust.Tests/GraphicsSettingsTests.cs new file mode 100644 index 0000000..e798424 --- /dev/null +++ b/tests/RustToDust.Tests/GraphicsSettingsTests.cs @@ -0,0 +1,158 @@ +using System; +using System.IO; +using RustToDust.Client; +using Xunit; + +namespace RustToDust.Tests; + +public sealed class GraphicsSettingsTests +{ + [Fact] + public void Defaults_MatchExpectedBaseline() + { + var settings = new GraphicsSettings(); + Assert.Equal(VfxResolutionScale.Half, settings.VfxResolution); + Assert.Equal(VolumetricSamples.Medium, settings.VolumetricSamples); + Assert.Equal(SdfgiQuality.Balanced, settings.SdfgiQuality); + Assert.True(settings.BorderlessFullscreen); + + Assert.Equal(0.50f, GraphicsSettings.GetResolutionScaleFactor(settings.VfxResolution)); + Assert.Equal((10, 15), GraphicsSettings.GetVolumetricStepBudget(settings.VolumetricSamples)); + var sdfgi = GraphicsSettings.GetSdfgiConfig(settings.SdfgiQuality); + Assert.True(sdfgi.Enabled); + Assert.Equal(0.8f, sdfgi.MinCellSize); + Assert.Equal(3, sdfgi.Cascades); + Assert.True(sdfgi.HalfResolution); + Assert.Equal(4, sdfgi.RayCount); + } + + [Fact] + public void MissingOrCorruptJson_FallsBackToSafeDefaults() + { + string tempDir = Path.Combine(Path.GetTempPath(), "rtd-gfx-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempDir); + try + { + string missingPath = Path.Combine(tempDir, "missing.json"); + var missingLoaded = GraphicsSettings.Load(missingPath); + Assert.Equal(VfxResolutionScale.Half, missingLoaded.VfxResolution); + Assert.Equal(VolumetricSamples.Medium, missingLoaded.VolumetricSamples); + Assert.Equal(SdfgiQuality.Balanced, missingLoaded.SdfgiQuality); + Assert.True(missingLoaded.BorderlessFullscreen); + + string corruptPath = Path.Combine(tempDir, "corrupt.json"); + File.WriteAllText(corruptPath, "{ this is not valid json !!!"); + var corruptLoaded = GraphicsSettings.Load(corruptPath); + Assert.Equal(VfxResolutionScale.Half, corruptLoaded.VfxResolution); + Assert.Equal(VolumetricSamples.Medium, corruptLoaded.VolumetricSamples); + Assert.Equal(SdfgiQuality.Balanced, corruptLoaded.SdfgiQuality); + Assert.True(corruptLoaded.BorderlessFullscreen); + + // ResetToDefaults(persist: true) must unconditionally rewrite a corrupt file even when memory equals defaults + corruptLoaded.ResetToDefaults(persist: true); + string repairedJson = File.ReadAllText(corruptPath); + Assert.DoesNotContain("not valid json", repairedJson, StringComparison.Ordinal); + var repaired = new GraphicsSettings(); + Assert.True(repaired.LoadFromJson(repairedJson)); + Assert.Equal(VfxResolutionScale.Half, repaired.VfxResolution); + Assert.Equal(VolumetricSamples.Medium, repaired.VolumetricSamples); + Assert.Equal(SdfgiQuality.Balanced, repaired.SdfgiQuality); + Assert.True(repaired.BorderlessFullscreen); + + var outOfRange = new GraphicsSettings(); + Assert.True(outOfRange.LoadFromJson("""{"vfxResolutionScale":99,"volumetricSamples":42,"sdfgiQuality":77,"borderlessFullscreen":false}""")); + Assert.Equal(VfxResolutionScale.Half, outOfRange.VfxResolution); + Assert.Equal(VolumetricSamples.Medium, outOfRange.VolumetricSamples); + Assert.Equal(SdfgiQuality.Balanced, outOfRange.SdfgiQuality); + Assert.False(outOfRange.BorderlessFullscreen); + } + finally + { + if (Directory.Exists(tempDir)) + { + Directory.Delete(tempDir, recursive: true); + } + } + } + + [Fact] + public void SaveAndReload_RoundtripsAllFieldsAndFiresChanged() + { + string tempDir = Path.Combine(Path.GetTempPath(), "rtd-gfx-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempDir); + try + { + string path = Path.Combine(tempDir, "graphics_settings.json"); + var settings = GraphicsSettings.Load(path); + int changeEvents = 0; + settings.Changed += _ => changeEvents++; + + settings.Apply( + VfxResolutionScale.Full, + VolumetricSamples.Ultra, + SdfgiQuality.High, + borderlessFullscreen: false, + persist: true); + Assert.Equal(1, changeEvents); + Assert.True(File.Exists(path)); + + // No-op apply must not fire duplicate Changed events + settings.Apply( + VfxResolutionScale.Full, + VolumetricSamples.Ultra, + SdfgiQuality.High, + borderlessFullscreen: false, + persist: true); + Assert.Equal(1, changeEvents); + + var reloaded = GraphicsSettings.Load(path); + Assert.Equal(VfxResolutionScale.Full, reloaded.VfxResolution); + Assert.Equal(VolumetricSamples.Ultra, reloaded.VolumetricSamples); + Assert.Equal(SdfgiQuality.High, reloaded.SdfgiQuality); + Assert.False(reloaded.BorderlessFullscreen); + + reloaded.ResetToDefaults(persist: true); + var afterReset = GraphicsSettings.Load(path); + Assert.Equal(VfxResolutionScale.Half, afterReset.VfxResolution); + Assert.Equal(VolumetricSamples.Medium, afterReset.VolumetricSamples); + Assert.Equal(SdfgiQuality.Balanced, afterReset.SdfgiQuality); + Assert.True(afterReset.BorderlessFullscreen); + } + finally + { + if (Directory.Exists(tempDir)) + { + Directory.Delete(tempDir, recursive: true); + } + } + } + + [Fact] + public void PresetMappings_MatchSpecification() + { + Assert.Equal(0.50f, GraphicsSettings.GetResolutionScaleFactor(VfxResolutionScale.Half)); + Assert.Equal(0.75f, GraphicsSettings.GetResolutionScaleFactor(VfxResolutionScale.ThreeQuarter)); + Assert.Equal(1.00f, GraphicsSettings.GetResolutionScaleFactor(VfxResolutionScale.Full)); + + Assert.Equal((8, 12), GraphicsSettings.GetVolumetricStepBudget(VolumetricSamples.Low)); + Assert.Equal((10, 15), GraphicsSettings.GetVolumetricStepBudget(VolumetricSamples.Medium)); + Assert.Equal((16, 24), GraphicsSettings.GetVolumetricStepBudget(VolumetricSamples.High)); + Assert.Equal((24, 36), GraphicsSettings.GetVolumetricStepBudget(VolumetricSamples.Ultra)); + + Assert.False(GraphicsSettings.GetSdfgiConfig(SdfgiQuality.Off).Enabled); + + var balanced = GraphicsSettings.GetSdfgiConfig(SdfgiQuality.Balanced); + Assert.True(balanced.Enabled); + Assert.Equal(0.8f, balanced.MinCellSize); + Assert.Equal(3, balanced.Cascades); + Assert.True(balanced.HalfResolution); + Assert.Equal(4, balanced.RayCount); + + var high = GraphicsSettings.GetSdfgiConfig(SdfgiQuality.High); + Assert.True(high.Enabled); + Assert.Equal(0.4f, high.MinCellSize); + Assert.Equal(4, high.Cascades); + Assert.False(high.HalfResolution); + Assert.Equal(8, high.RayCount); + } +} diff --git a/tests/RustToDust.Tests/HbGpuNativeTests.cs b/tests/RustToDust.Tests/HbGpuNativeTests.cs new file mode 100644 index 0000000..72d2e8a --- /dev/null +++ b/tests/RustToDust.Tests/HbGpuNativeTests.cs @@ -0,0 +1,271 @@ +using System; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using RustToDust.HbGpu; +using Xunit; + +namespace RustToDust.Tests; + +public sealed class HbGpuNativeTests +{ + private static string RepoRoot + { + get + { + string? dir = AppContext.BaseDirectory; + while (dir is not null) + { + if (File.Exists(Path.Combine(dir, "RustToDust.slnx"))) + { + return dir; + } + dir = Directory.GetParent(dir)?.FullName; + } + throw new DirectoryNotFoundException("Could not locate RustToDust.slnx from test output directory."); + } + } + + [Fact] + public void NativeDllExistsAndMeetsSizeBudget() + { + if (OperatingSystem.IsWindows()) + { + string dllPath = Path.Combine(AppContext.BaseDirectory, "rtd_hbgpu.dll"); + Assert.True(File.Exists(dllPath), $"Expected rtd_hbgpu.dll at '{dllPath}'."); + long size = new FileInfo(dllPath).Length; + Assert.InRange(size, 100_000, 2_621_440); // < 2.5 MiB + } + + string ver = HbGpuNative.GetVersionString(); + Assert.Equal("15.2.0", ver); + + string vertShared = HbGpuNative.GetShaderSource(HbGpuShaderStage.Vertex, HbGpuShaderKind.Shared); + string fragShared = HbGpuNative.GetShaderSource(HbGpuShaderStage.Fragment, HbGpuShaderKind.Shared); + string fragDraw = HbGpuNative.GetShaderSource(HbGpuShaderStage.Fragment, HbGpuShaderKind.Draw); + Assert.Contains("hb_gpu_dilate", vertShared); + Assert.Contains("uniform isamplerBuffer hb_gpu_atlas;", fragShared); + Assert.Contains("hb_gpu_draw", fragDraw); + } + + [Fact] + public void KryptonFontAndLicensesAreCompliant() + { + string root = RepoRoot; + string fontPath = Path.Combine(root, "assets", "fonts", "Krypton.ttf"); + string oflPath = Path.Combine(root, "assets", "fonts", "OFL-1.1.txt"); + string hbCopyPath = Path.Combine(root, "assets", "fonts", "HARFBUZZ-COPYING.txt"); + string noticesPath = Path.Combine(root, "THIRD_PARTY_NOTICES.txt"); + + Assert.True(File.Exists(fontPath)); + Assert.True(File.Exists(oflPath)); + Assert.True(File.Exists(hbCopyPath)); + Assert.True(File.Exists(noticesPath)); + + byte[] fontBytes = File.ReadAllBytes(fontPath); + Assert.Equal(1_363_340, fontBytes.Length); + string sha = Convert.ToHexString(SHA256.HashData(fontBytes)).ToLowerInvariant(); + Assert.Equal("6462cae55b336ae6ffb7c8f1932177960510a4207e65803f527b276d42c8a240", sha); + + string oflText = File.ReadAllText(oflPath); + Assert.Contains("Copyright (c) 2023, GitHub", oflText); + Assert.Contains("Krypton", oflText); + } + + [Fact] + public void QuadInstanceStructIs80Bytes() + { + Assert.Equal(80, Unsafe.SizeOf()); + Assert.Equal(80, Marshal.SizeOf()); + } + + [Fact] + public void ShapingAndGlyphEncodingWorkAcrossKryptonAxes() + { + string fontPath = Path.Combine(RepoRoot, "assets", "fonts", "Krypton.ttf"); + using var fonts = new HbGpuFontCache(); + fonts.RegisterFontFromFile(0, fontPath); + + RtdHbFontMetrics metrics = fonts.GetMetrics(0); + Assert.Equal(2000, metrics.Upem); + + var atlas = new HbGpuAtlasAllocator(); + var blobs = new HbGpuBlobCache(atlas); + var writer = new HbGpuCommandWriter(); + + writer.BeginFrame(); + float wReg = writer.DrawTextUtf16("RAPTOR -> 142.8m", 10f, 40f, 24f, 1f, 1f, 1f, 1f, fonts, blobs, 0, wght: 200f); + float wBold = writer.DrawTextUtf16("CHASSIS", 10f, 80f, 24f, 1f, 1f, 1f, 1f, fonts, blobs, 0, wght: 700f); + float wSlnt = writer.DrawTextUtf16("SLANT", 10f, 120f, 24f, 1f, 1f, 1f, 1f, fonts, blobs, 0, wght: 400f, slnt: -9f); + + Assert.True(wReg > 50f); + Assert.True(wBold > 20f); + Assert.True(wSlnt > 20f); + Assert.True(writer.QuadCount >= 18); // spaces omit quads, visible glyphs emit quads + Assert.True(blobs.CachedGlyphCount >= 15); + Assert.True(atlas.PersistentCursor > 0); + Assert.True(atlas.PendingChunkCount > 0); + + // Space glyph encodes cleanly as empty + CachedBlob spaceBlob = blobs.GetOrEncodeGlyph(fonts, 0, 1 /* glyph or verify space */, 200, 1000, 0); + Assert.True(spaceBlob.TexelCount >= 0); + + // Hot steady-state loop allocates zero managed bytes once glyphs/styles are cached + writer.BeginFrame(); + atlas.ClearPending(); + ReadOnlySpan hotText = "RAPTOR -> 142.8m"; + long before = GC.GetAllocatedBytesForCurrentThread(); + for (int i = 0; i < 64; i++) + { + writer.BeginFrame(); + writer.DrawTextUtf16(hotText, 10f, 40f, 24f, 1f, 1f, 1f, 1f, fonts, blobs, 0, wght: 200f); + } + long after = GC.GetAllocatedBytesForCurrentThread(); + Assert.Equal(0, after - before); + } + + [Fact] + public void VectorPathsAndAtlasBudgetResetWork() + { + var atlas = new HbGpuAtlasAllocator(); + var blobs = new HbGpuBlobCache(atlas); + + CachedBlob rect = HbGpuVectorShapes.GetUnitFilledRect(blobs); + CachedBlob circle = HbGpuVectorShapes.GetUnitFilledCircle(blobs); + CachedBlob ring = HbGpuVectorShapes.GetUnitRingStroke(blobs, 24); + CachedBlob bracket = HbGpuVectorShapes.GetTargetBracketCorner(blobs, 120); + CachedBlob arrow = HbGpuVectorShapes.GetDirectionalArrow(blobs); + CachedBlob chevron = HbGpuVectorShapes.GetChevronTriangle(blobs); + CachedBlob diamond = HbGpuVectorShapes.GetDiamondBlip(blobs); + CachedBlob arc = HbGpuVectorShapes.EncodeArcStrokeDynamic(blobs, -2.356f, 0.785f); + + Assert.True(rect.IsValid && rect.TexelCount > 2); + Assert.True(circle.IsValid && circle.TexelCount > 2); + Assert.True(ring.IsValid && ring.TexelCount > 4); + Assert.True(bracket.IsValid && bracket.TexelCount > 2); + Assert.True(arrow.IsValid && arrow.TexelCount > 2); + Assert.True(chevron.IsValid && chevron.TexelCount > 2); + Assert.True(diamond.IsValid && diamond.TexelCount > 2); + Assert.True(arc.IsValid && arc.TexelCount > 4); + Assert.True(arc.AtlasOffset >= HbGpuAtlasAllocator.DynamicBase); + + // Also test tapered line verb directly + Span lineVerb = stackalloc byte[] { (byte)HbGpuPathVerb.Line }; + Span lineArgs = stackalloc float[] { -400f, 0f, 20f, 400f, 0f, 60f, 1f }; + CachedBlob lineBlob = blobs.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.Custom, 1, 0), 1000u, lineVerb, lineArgs); + Assert.True(lineBlob.IsValid); + + // Drain uploads with zero allocations + byte[] staging = new byte[HbGpuBlobCache.ScratchShortsCapacity * sizeof(short)]; + int drainedBytes = 0; + Action cb = (_, len) => drainedBytes += (int)len; + int chunks = atlas.DrainChunks(staging, cb); + Assert.True(chunks >= 9); + Assert.True(drainedBytes > 0); + Assert.Equal(0, atlas.PendingChunkCount); + + // Verify static arc caching (0 pending chunks and 0 B GC allocs on repeat lookup) + var staticArcKey = new VectorBlobKey(VectorShapeKind.ThermalHeatArc, 45, 1); + CachedBlob staticArc = HbGpuVectorShapes.GetStaticArcStroke(blobs, staticArcKey, -2.356f, 0.785f, 500f, 30f); + Assert.True(staticArc.IsValid); + Assert.True(staticArc.AtlasOffset < HbGpuAtlasAllocator.DynamicBase); + atlas.ClearPending(); + + // Warm up cache-hit path once before measuring GC allocations + CachedBlob warmHit = HbGpuVectorShapes.GetStaticArcStroke(blobs, staticArcKey, -2.356f, 0.785f, 500f, 30f); + Assert.Equal(staticArc.AtlasOffset, warmHit.AtlasOffset); + + uint expectedOffset = staticArc.AtlasOffset; + bool allMatched = true; + long arcGcBefore = GC.GetAllocatedBytesForCurrentThread(); + for (int i = 0; i < 64; i++) + { + CachedBlob hit = HbGpuVectorShapes.GetStaticArcStroke(blobs, staticArcKey, -2.356f, 0.785f, 500f, 30f); + if (hit.AtlasOffset != expectedOffset) allMatched = false; + } + long arcGcAfter = GC.GetAllocatedBytesForCurrentThread(); + Assert.True(allMatched); + Assert.Equal(0, arcGcAfter - arcGcBefore); + Assert.Equal(0, atlas.PendingChunkCount); + + // Verify dynamic ring wrap-around + for (int i = 0; i < 600; i++) + { + CachedBlob dyn = HbGpuVectorShapes.EncodeArcStrokeDynamic(blobs, -1.5f, 1.5f); + Assert.True(dyn.AtlasOffset >= HbGpuAtlasAllocator.DynamicBase); + Assert.True(dyn.AtlasOffset + dyn.TexelCount <= HbGpuAtlasAllocator.TotalTexels); + atlas.ClearPending(); + } + } + + [Fact] + public void PersistentAtlasOverflowDoesNotResetMidFrame() + { + var atlas = new HbGpuAtlasAllocator(); + var blobs = new HbGpuBlobCache(atlas); + + // Fill persistent zone right up near PersistentCapacity without crossing it + short[] chunk = new short[4096 * 4]; // 4096 texels + chunk[0] = 1; + while (atlas.PersistentCursor + 4096 <= HbGpuAtlasAllocator.PersistentCapacity) + { + atlas.AllocatePersistent(chunk); + atlas.ClearPending(); + } + + uint epochBefore = atlas.Epoch; + uint cursorBefore = atlas.PersistentCursor; + Assert.True(cursorBefore > HbGpuAtlasAllocator.PersistentResetWatermark); + + // Encode a static vector that exceeds remaining PersistentCapacity: must NOT reset mid-frame! + Span bigVerbs = stackalloc byte[64]; + Span bigArgs = stackalloc float[128]; + int v = 0, a = 0; + bigVerbs[v++] = (byte)HbGpuPathVerb.Move; + bigArgs[a++] = 0f; + bigArgs[a++] = 0f; + for (int i = 1; i <= 30; i++) + { + float ang = i * 0.2f; + bigVerbs[v++] = (byte)HbGpuPathVerb.LineTo; + bigArgs[a++] = MathF.Cos(ang) * 400f; + bigArgs[a++] = MathF.Sin(ang) * 400f; + } + bigVerbs[v++] = (byte)HbGpuPathVerb.Close; + + // First force a large remaining fill so the encoded vector overflows remaining space + uint rem = HbGpuAtlasAllocator.PersistentCapacity - atlas.PersistentCursor; + if (rem > 2) + { + atlas.AllocatePersistent(new short[(rem - 1) * 4]); + atlas.ClearPending(); + } + cursorBefore = atlas.PersistentCursor; + + CachedBlob overflowed = blobs.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.Custom, 999, 1), + 1000u, + bigVerbs[..v], + bigArgs[..a]); + + Assert.False(overflowed.IsValid); + Assert.Equal(epochBefore, atlas.Epoch); + Assert.Equal(cursorBefore, atlas.PersistentCursor); + Assert.True(blobs.IsPersistentOverflowPending); + + // Next BeginFrame resets cleanly and allows encoding + Assert.True(blobs.EnsureBudgetOrReset()); + Assert.Equal(epochBefore + 1, atlas.Epoch); + Assert.Equal(0u, atlas.PersistentCursor); + Assert.False(blobs.IsPersistentOverflowPending); + + CachedBlob recovered = blobs.GetOrEncodeStaticPath( + new VectorBlobKey(VectorShapeKind.Custom, 999, 1), + 1000u, + bigVerbs[..v], + bigArgs[..a]); + Assert.True(recovered.IsValid); + } +} diff --git a/tests/RustToDust.Tests/HybridBWalkerTests.cs b/tests/RustToDust.Tests/HybridBWalkerTests.cs index c9c485f..cbd0d67 100644 --- a/tests/RustToDust.Tests/HybridBWalkerTests.cs +++ b/tests/RustToDust.Tests/HybridBWalkerTests.cs @@ -741,7 +741,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++) { @@ -774,6 +774,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/LobbyAndDirectoryTests.cs b/tests/RustToDust.Tests/LobbyAndDirectoryTests.cs index 7704547..85693eb 100644 --- a/tests/RustToDust.Tests/LobbyAndDirectoryTests.cs +++ b/tests/RustToDust.Tests/LobbyAndDirectoryTests.cs @@ -633,5 +633,204 @@ namespace RustToDust.Tests Assert.NotNull(res.Summary); Assert.Equal(new string('\u2022', 16), res.Summary!.Value.ServerName); } + + [Fact] + public void LobbySquadSwap_ReliableRoundTrip() + { + using var listenHost = new ListenHostArenaSession( + IPAddress.Loopback, + 0, + seed: 42, + mapKind: ArenaMapKind.Desert, + startInLobby: true, + minHumansToStart: 2, + squadSize: 3); + using var remote = new RemoteArenaSession( + new IPEndPoint(IPAddress.Loopback, listenHost.Host.BoundPort), + "WingBuddy"); + + var deadline = DateTime.UtcNow.AddSeconds(3); + while (!remote.IsJoined && DateTime.UtcNow < deadline) + { + PumpListenHostAndClient(listenHost, remote); + } + Assert.True(remote.IsJoined); + int remoteId = remote.LocalContenderId; + + Assert.Equal((byte)3, listenHost.LobbyState?.SquadSize); + Assert.Equal((byte)3, remote.LobbyState?.SquadSize); + Assert.Equal((byte)0, remote.LobbyState!.Slots[remoteId].SquadId); + + // 1. Remote client swaps to Squad 2 -> swaps cleanly with an AI in Squad 2 + Assert.True(remote.RequestLobbySquad(2)); + PumpListenHostAndClient(listenHost, remote, ticks: 15); + Assert.Equal((byte)2, listenHost.LobbyState!.Slots[remoteId].SquadId); + Assert.Equal((byte)2, remote.LobbyState!.Slots[remoteId].SquadId); + + // 2. Host switches SquadMode to Duos (2) -> slots regroup cleanly to 2-player squads + Assert.True(listenHost.RequestLobbyConfig(77, ArenaMapKind.Desert, 2)); + PumpListenHostAndClient(listenHost, remote, ticks: 15); + Assert.Equal((byte)2, listenHost.LobbyState!.SquadSize); + Assert.Equal((byte)2, remote.LobbyState!.SquadSize); + Assert.Equal((byte)0, remote.LobbyState!.Slots[remoteId].SquadId); + + // 3. Remote swaps to Squad 3, then back to Squad 0 (Host's Duo), both ready up & launch! + Assert.True(remote.RequestLobbySquad(3)); + PumpListenHostAndClient(listenHost, remote, ticks: 15); + Assert.Equal((byte)3, remote.LobbyState!.Slots[remoteId].SquadId); + + Assert.True(remote.RequestLobbySquad(0)); + PumpListenHostAndClient(listenHost, remote, ticks: 15); + Assert.Equal((byte)0, remote.LobbyState!.Slots[remoteId].SquadId); + + Assert.True(listenHost.SetLobbyReady(true)); + Assert.True(remote.SetLobbyReady(true)); + for (int tick = 0; tick < 340; tick++) + { + listenHost.SubmitLocalInput(default, isPhysicsTick: true); + remote.PumpNetwork(); + if (listenHost.ViewState.Phase == MatchPhase.Active && + remote.ViewState.Phase == MatchPhase.Active && + remote.ActivePods.Count > 0) + { + break; + } + Thread.Sleep(1); + } + PumpListenHostAndClient(listenHost, remote, ticks: 10); + + Assert.Equal(MatchPhase.Active, listenHost.ViewState.Phase); + Assert.Equal(MatchPhase.Active, remote.ViewState.Phase); + Assert.Equal((byte)2, listenHost.ViewState.SquadSize); + Assert.Equal((byte)2, remote.ViewState.SquadSize); + Assert.Equal(0, listenHost.ViewState.Contenders[remoteId].SquadId); + Assert.Equal(0, remote.ViewState.Contenders[remoteId].SquadId); + Assert.True(listenHost.ViewState.AreAllies(0, remoteId)); + Assert.True(remote.ViewState.AreAllies(0, remoteId)); + } + + [Fact] + public void LobbySquadSwap_MidMatchReconnectAndLateJoin_PreservesAll12SquadIdsOutsidePvs() + { + using var host = new ServerMatchHost( + IPAddress.Loopback, + 0, + seed: 42, + mapKind: ArenaMapKind.Desert, + startInLobby: true, + minHumansToStart: 1, + squadSize: 3); + var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort); + + using var clientA = new RemoteArenaSession(ep, "LeaderSwap"); + long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var deadline = DateTime.UtcNow.AddSeconds(3); + while (!clientA.IsJoined && DateTime.UtcNow < deadline) + { + nowMs += 16; + host.StepOnce(nowMs); + clientA.PumpNetwork(nowMs); + Thread.Sleep(2); + } + Assert.True(clientA.IsJoined); + int slotA = clientA.LocalContenderId; + Assert.Equal(0, slotA); + + // Polish check: out-of-range TargetSquadId >= maxSquads (4 for SquadSize=3) must be rejected, not clamped + Assert.False(host.MovePeerToSquad(slotA, 4)); + Assert.Equal((byte)0, host.Session.State.Contenders[slotA].SquadId); + + // Swap Slot 0 (0 -> 2) and Slot 6 (2 -> 0) in Lobby (SquadSize = 3) + Assert.True(clientA.RequestLobbySquad(2)); + for (int t = 0; t < 20; t++) + { + nowMs += 16; + host.StepOnce(nowMs); + clientA.PumpNetwork(nowMs); + Thread.Sleep(2); + } + Assert.Equal((byte)2, host.Session.State.Contenders[0].SquadId); + Assert.Equal((byte)0, host.Session.State.Contenders[6].SquadId); + + // Launch to MatchPhase.Active + Assert.True(host.SetLobbyReady(slotA, true)); + for (int tick = 0; tick < 340; tick++) + { + nowMs += 16; + host.StepOnce(nowMs); + clientA.PumpNetwork(nowMs); + if (host.Session.State.Phase == MatchPhase.Active && clientA.ViewState.Phase == MatchPhase.Active) + { + break; + } + Thread.Sleep(1); + } + Assert.Equal(MatchPhase.Active, host.Session.State.Phase); + + // Position contenders far apart across Desert so non-allies (including Slot 6) are outside PVS + host.Session.SetContenderPose(0, -320f, -320f, 0f); + for (int i = 1; i < MatchState.ContenderCount; i++) + { + if (host.Session.State.AreAllies(0, i)) + { + host.Session.SetContenderPose(i, -310f + i * 3f, -320f, 0f); + } + else + { + host.Session.SetContenderPose(i, 320f, 320f - i * 8f, MathF.PI); + } + } + nowMs += 16; + host.StepOnce(nowMs); + Assert.False(host.Session.IsEntityInPeerPvs(0, true, 6)); + + // 1. Reconnect clientA mid-match and assert ALL 12 SquadIds and AreAllies match server 12/12 + Guid tokenA = clientA.ReconnectToken; + clientA.DisconnectGracefully("ReconnectSquadTest"); + clientA.Dispose(); + for (int t = 0; t < 20; t++) + { + nowMs += 16; + host.StepOnce(nowMs); + Thread.Sleep(1); + } + + using var clientARejoin = new RemoteArenaSession(ep, "LeaderSwap", tokenA); + deadline = DateTime.UtcNow.AddSeconds(3); + while (!clientARejoin.IsJoined && DateTime.UtcNow < deadline) + { + nowMs += 16; + host.StepOnce(nowMs); + clientARejoin.PumpNetwork(nowMs); + Thread.Sleep(2); + } + Assert.True(clientARejoin.IsJoined); + Assert.Equal(0, clientARejoin.LocalContenderId); + + // 2. Late-join a fresh clientB mid-match while non-allies are outside PVS + using var clientB = new RemoteArenaSession(ep, "LateJoiner"); + deadline = DateTime.UtcNow.AddSeconds(3); + while (!clientB.IsJoined && DateTime.UtcNow < deadline) + { + nowMs += 16; + host.StepOnce(nowMs); + clientARejoin.PumpNetwork(nowMs); + clientB.PumpNetwork(nowMs); + Thread.Sleep(2); + } + Assert.True(clientB.IsJoined); + + var serverState = host.Session.State; + for (int i = 0; i < MatchState.ContenderCount; i++) + { + Assert.Equal(serverState.Contenders[i].SquadId, clientARejoin.ViewState.Contenders[i].SquadId); + Assert.Equal(serverState.Contenders[i].SquadId, clientB.ViewState.Contenders[i].SquadId); + for (int j = 0; j < MatchState.ContenderCount; j++) + { + Assert.Equal(serverState.AreAllies(i, j), clientARejoin.ViewState.AreAllies(i, j)); + Assert.Equal(serverState.AreAllies(i, j), clientB.ViewState.AreAllies(i, j)); + } + } + } } } diff --git a/tests/RustToDust.Tests/OrbitalDropTests.cs b/tests/RustToDust.Tests/OrbitalDropTests.cs index c017051..e61278e 100644 --- a/tests/RustToDust.Tests/OrbitalDropTests.cs +++ b/tests/RustToDust.Tests/OrbitalDropTests.cs @@ -25,16 +25,18 @@ namespace RustToDust.Tests [Fact] public void HoverSlam_FlatDesertAnd30DegSionSlope_TouchdownUnder3MsAndZeroPenetration() { - // 1. Flat Desert trajectory & cross-range steering [120m, 180m] + // 1. Flat Desert trajectory & cross-range steering { using var session = new ArenaSession(seed: 42, ArenaMapKind.Desert, slot0Human: true); var player = session.State.Contenders[0]; float startX = player.X; float startZ = player.Z; - float aimX = startX; - float aimZ = startZ + 100f; + // Steer straight across the arena center so boundary clamp does not reverse heading + float dirLen = MathF.Max(1f, MathF.Sqrt(startX * startX + startZ * startZ)); + float dirX = -startX / dirLen; + float dirZ = -startZ / dirLen; - int maxTicks = 600; + int maxTicks = 1200; float impactSpeed = -1f; float touchTime = -1f; float snapDiffAtTouchdown = float.NaN; @@ -50,8 +52,8 @@ namespace RustToDust.Tests session.SetHumanInput(0, new PlayerInput( Throttle: 1.0f, Steer: 0f, - AimWorldX: player.X, - AimWorldZ: player.Z + 100f, + AimWorldX: player.X + dirX * 100f, + AimWorldZ: player.Z + dirZ * 100f, Fire: false, InteractPickup: false, Brake: false)); @@ -67,12 +69,12 @@ namespace RustToDust.Tests } } - Assert.True(player.IsGroundedActive, "Player pod failed to touch down within 10s on Desert"); - Assert.InRange(impactSpeed, 0.5f, 2.99f); - Assert.InRange(touchTime, 5.5f, 9.5f); + Assert.True(player.IsGroundedActive, "Player pod failed to touch down within 20s on Desert"); + Assert.InRange(impactSpeed, 0.5f, 2.49f); + Assert.InRange(touchTime, 12.5f, 18.0f); float glideDist = MathF.Sqrt((player.X - startX) * (player.X - startX) + (player.Z - startZ) * (player.Z - startZ)); - Assert.InRange(glideDist, 120f, 180f); + Assert.True(glideDist >= 800f, $"Expected cross-arena Desert glide >= 800m, got {glideDist:F1}m"); // Verify PrevY == Y right at touchdown SnapPreviousPose() and continuous post-Step settlement (< 0.06m, zero sky pop) Assert.True(snapDiffAtTouchdown < 1e-4f, @@ -130,7 +132,7 @@ namespace RustToDust.Tests }; float impactSpeed = -1f; - for (int t = 0; t < 600; t++) + for (int t = 0; t < 2000; t++) { pod.LookForwardX = -snx; pod.LookForwardZ = -snz; @@ -146,7 +148,7 @@ namespace RustToDust.Tests } Assert.True(c.IsGroundedActive, $"Pod failed to land on {slopeDeg:F1} deg Sion slope"); - Assert.InRange(impactSpeed, 0.5f, 2.99f); + Assert.InRange(impactSpeed, 0.5f, 2.49f); Assert.True(snapDiffAtTouchdown < 1e-4f); Assert.True(MathF.Abs(c.PrevY - c.Y) < 0.06f); AssertZeroChassisPenetration(session.State, c); @@ -167,7 +169,7 @@ namespace RustToDust.Tests float maxGearTouchTime = 0f; float minContenderTouchTime = float.PositiveInfinity; - for (int t = 0; t < 660; t++) + for (int t = 0; t < 2000; t++) { session.Step(); if (session.State.OrbitalDrop.ActivePods.Count == 0) @@ -192,7 +194,7 @@ namespace RustToDust.Tests var state = new MatchState(seed: 42, map); var gearTouchTimes = new List(); var contenderTouchTimes = new List(); - for (int t = 0; t < 660; t++) + for (int t = 0; t < 2000; t++) { state.Time += ArenaSession.FixedDt; state.OrbitalDrop.Step(ArenaSession.FixedDt, state.DefaultDropSurfaceQuery, (pod, _) => @@ -246,7 +248,7 @@ namespace RustToDust.Tests var pod = session.State.OrbitalDrop.LaunchGearPod(0, tx, tz, null, Catalog.Autocannon, session.QueryDropSurface); bool landed = false; - for (int t = 0; t < 600; t++) + for (int t = 0; t < 1800; t++) { bool touched = OrbitalDropKinematics.StepPod( pod, @@ -267,12 +269,12 @@ namespace RustToDust.Tests Assert.False(touchSample.IsInsideSolidBuilding, $"Target #{i} ({tx:F1},{tz:F1}) landed with IsInsideSolidBuilding=true at ({pod.X:F1},{pod.Z:F1})!"); Assert.False(touchSample.IsBuildingRoof); - Assert.InRange(pod.TouchdownSpeed, 0.5f, 2.99f); + Assert.InRange(pod.TouchdownSpeed, 0.5f, 2.5f); break; } } Assert.True(landed, $"Target #{i} ({tx:F1},{tz:F1}) hover-stalled!"); - Assert.True(pod.FlightTime <= 9.5f, $"Target #{i} took too long: {pod.FlightTime:F2}s"); + Assert.True(pod.FlightTime <= 28.0f, $"Target #{i} took too long: {pod.FlightTime:F2}s"); tested++; } @@ -312,7 +314,7 @@ namespace RustToDust.Tests player, 0, fr.CenterX, fr.CenterZ, 0f, session.QueryDropSurface, isRespawn: false); roofPod.AllowFlatRoofLanding = true; - for (int t = 0; t < 600 && !player.IsGroundedActive; t++) + for (int t = 0; t < 2000 && !player.IsGroundedActive; t++) { session.SetHumanInput(0, new PlayerInput(0f, 0f, player.X, player.Z + 20f, false, false, false)); session.Step(); @@ -390,15 +392,15 @@ namespace RustToDust.Tests var state = session.State; var player = state.Contenders[0]; - // Step until Wave 0 contenders touch down (~7.5s) - for (int t = 0; t < 480 && !state.Contenders.All(c => c.IsGroundedActive); t++) + // Step until Wave 0 contenders touch down (~15s on Desert) + for (int t = 0; t < 1200 && !state.Contenders.All(c => c.IsGroundedActive); t++) { session.Step(); } Assert.All(state.Contenders, c => Assert.True(c.IsGroundedActive)); - // 1. Kill 11 AIs at t = 15s -> must enter WaitingForRespawnWave and match stays Active! - while (state.Time < 15f) + // 1. Kill 11 AIs at t = 20s -> must enter WaitingForRespawnWave and match stays Active! + while (state.Time < 20f) { session.Step(); } @@ -414,8 +416,8 @@ namespace RustToDust.Tests Assert.True(state.Contenders[i].WaitingForRespawn); } - // 2. Step past Wave 1 (t = 75s) + drop time -> all 11 AIs re-drop in stock Jackals with RespawnsRemaining == 0! - while (state.Time < 75.5f) + // 2. Step past Wave 1 (t = 85s) + drop time -> all 11 AIs re-drop in stock Jackals with RespawnsRemaining == 0! + while (state.Time < 85.5f) { session.Step(); } @@ -426,15 +428,15 @@ namespace RustToDust.Tests Assert.Equal(0, state.Contenders[i].RespawnsRemaining); Assert.Equal(Catalog.Jackal.Id, state.Contenders[i].Grid.Spec.Id); } - for (int t = 0; t < 480; t++) + for (int t = 0; t < 1200; t++) { session.Step(); if (state.Contenders.All(c => c.IsGroundedActive)) break; } Assert.All(state.Contenders, c => Assert.True(c.IsGroundedActive)); - // 3. Kill Player before Wave 2 (t = 120s) -> match MUST stay Active (Player.WaitingForRespawn == true) - while (state.Time < 120f) + // 3. Kill Player before Wave 2 (t = 130s) -> match MUST stay Active (Player.WaitingForRespawn == true) + while (state.Time < 130f) { session.Step(); } @@ -444,8 +446,8 @@ namespace RustToDust.Tests Assert.Equal(MatchPhase.Active, state.Phase); Assert.True(player.WaitingForRespawn); - // Step past Wave 2 (t = 155s) -> Player re-drops in stock Jackal (RespawnsRemaining == 0), RespawnCutoffReached == true! - while (state.Time < 155.5f) + // Step past Wave 2 (t = 165s) -> Player re-drops in stock Jackal (RespawnsRemaining == 0), RespawnCutoffReached == true! + while (state.Time < 165.5f) { session.Step(); } @@ -454,8 +456,8 @@ namespace RustToDust.Tests Assert.Equal(ContenderLifecycle.Deploying, player.Lifecycle); Assert.Equal(0, player.RespawnsRemaining); - // 4. Kill an AI at t = 158.1s (after Wave 2 cutoff) -> immediately Eliminated (never WaitingForRespawnWave)! - while (state.Time < 158.1f) + // 4. Kill an AI at t = 168.1s (after Wave 2 cutoff) -> immediately Eliminated (never WaitingForRespawnWave)! + while (state.Time < 168.1f) { session.Step(); } @@ -524,9 +526,9 @@ namespace RustToDust.Tests Assert.True(clientIface.ActivePods.Count >= 12, $"Expected active Wave 0 pods on RemoteArenaSession join, got {clientIface.ActivePods.Count}"); - // Step through full Wave 0 orbital drop (~7.8s = 470 ticks) with steering input + // Step through full Wave 0 orbital drop (~15.1s = 905 ticks) with steering input var simEvents = new List(); - for (int t = 0; t < 480; t++) + for (int t = 0; t < 1100; t++) { nowMs += 16; clientIface.SubmitLocalInput(new PlayerInput( @@ -621,9 +623,9 @@ namespace RustToDust.Tests Assert.True(midGearPod.LastAgl < gearAgl0 - 20f && midGearPod.LastAgl > 0f, $"Gear pod LastAgl failed to update: {gearAgl0:F2} -> {midGearPod.LastAgl:F2}"); - // Step through remainder of Wave 0 + 30 settle ticks so all pods touch down across Sion PVS + // Step through remainder of Wave 0 + 30 settle ticks so all pods touch down across Sion PVS (~27.6s = 1658 ticks) var simEvents = new List(); - for (int t = 0; t < 560; t++) + for (int t = 0; t < 1900; t++) { nowMs += 16; clientIface.SubmitLocalInput(new PlayerInput( @@ -690,7 +692,7 @@ namespace RustToDust.Tests } // 1. Land Wave 0 - for (int i = 0; i < 480 && !clientIface.LocalContender.IsGroundedActive; i++) + for (int i = 0; i < 1100 && !clientIface.LocalContender.IsGroundedActive; i++) { PumpStep(1); } @@ -708,8 +710,8 @@ namespace RustToDust.Tests PumpStep(12); Assert.Equal(ContenderLifecycle.WaitingForRespawnWave, clientIface.LocalContender.Lifecycle); - // 4. Advance past Wave 1 (75.0s) -> server resets local player to Jackal (256/256) and launches Wave 1 pod - host.Session.State.Time = 74.85f; + // 4. Advance past Wave 1 (85.0s) -> server resets local player to Jackal (256/256) and launches Wave 1 pod + host.Session.State.Time = 84.85f; PumpStep(30); Assert.Equal(ContenderLifecycle.Deploying, clientIface.LocalContender.Lifecycle); @@ -1019,7 +1021,7 @@ namespace RustToDust.Tests // 2. Full Sion Wave 0 drop steering human toward sion_1365 + steep Sion terrain checks across all 12 contenders var maxBurnStartAgl = new Dictionary(); - for (int t = 0; t < 700; t++) + for (int t = 0; t < 2200; t++) { var p0 = session.State.Contenders[0]; session.SetHumanInput(0, new PlayerInput( @@ -1044,7 +1046,7 @@ namespace RustToDust.Tests maxBurnStartAgl[pod.PodId] = pod.LastAgl; Assert.True(pod.LastAgl <= 160f, $"Wave 0 pod {pod.PodId} ignited RetroBurn at {pod.LastAgl:F1}m AGL"); } - Assert.True(pod.FlightTime <= 10.5f, $"Wave 0 pod {pod.PodId} exceeded 10.5s flight time: {pod.FlightTime:F2}s"); + Assert.True(pod.FlightTime <= 34.0f, $"Wave 0 pod {pod.PodId} exceeded 34.0s flight time: {pod.FlightTime:F2}s"); } if (session.State.OrbitalDrop.ActivePods.Count == 0 && p0.IsGroundedActive) @@ -1110,8 +1112,8 @@ namespace RustToDust.Tests host.Session.SetContenderPose(localId, -900f, -900f, 0f); PumpStep(5); - // Trigger Wave 1 (75.0s) so rival launches its drop pod out of observer PVS - host.Session.State.Time = 74.9f; + // Trigger Wave 1 (85.0s) so rival launches its drop pod out of observer PVS + host.Session.State.Time = 84.9f; for (int i = 0; i < 20 && host.Session.State.Contenders[rivalId].Lifecycle != ContenderLifecycle.Deploying; i++) { PumpStep(1); @@ -1189,7 +1191,7 @@ namespace RustToDust.Tests foreach (bool allowFlat in new[] { false, true }) { - foreach (float startAgl in new[] { 410f, 80f }) + foreach (float startAgl in new[] { 1620f, 80f }) { foreach (var (label, sx, sz) in startPoints) { @@ -1209,7 +1211,7 @@ namespace RustToDust.Tests X = sx, Y = terrain0 + startAgl, Z = sz, - VelY = startAgl > 200f ? OrbitalPodPreset.Contender.InitialVelY : -28f, + VelY = startAgl > 200f ? OrbitalPodPreset.GetContender(ArenaMapKind.Sion).InitialVelY : -28f, LookForwardX = dirX, LookForwardZ = dirZ, SteerForwardCmd = 1f, @@ -1217,7 +1219,7 @@ namespace RustToDust.Tests }; bool landed = false; - for (int t = 0; t < 720; t++) + for (int t = 0; t < 2200; t++) { float prevX = pod.X; float prevY = pod.Y; @@ -1248,7 +1250,7 @@ namespace RustToDust.Tests (pod.Y - prevY) * (pod.Y - prevY) + (pod.Z - prevZ) * (pod.Z - prevZ)); maxTouchdownStep = MathF.Max(maxTouchdownStep, tdStep3D); - if (tdStep3D > 1.0f || horizStep > 1.0f) + if (tdStep3D > 1.0f || horizStep > 2.25f) { touchdownWarps++; } @@ -1271,8 +1273,332 @@ namespace RustToDust.Tests Assert.Equal(0, wallBreachFrames); Assert.Equal(0, touchdownWarps); - Assert.True(maxHorizStep <= 1.0f, $"Horizontal warp {maxHorizStep:F3}m > 1.0m/tick"); - Assert.True(maxTouchSpeed < 3.0f, $"Touchdown speed {maxTouchSpeed:F2} m/s >= 3.0 m/s"); + Assert.True(maxHorizStep <= 2.25f, $"Horizontal warp {maxHorizStep:F3}m > 2.25m/tick"); + Assert.True(maxTouchSpeed < 2.5f, $"Touchdown speed {maxTouchSpeed:F2} m/s >= 2.5 m/s"); + } + + [Fact] + public void HoverSlam_CrossZoneDrop_SionAndDesert() + { + // Large synthetic flat terrain to measure unobstructed max-burn cross-zone horizontal glide + var largeHeights = new float[17 * 17]; + var largeFlat = TerrainField.LoadHeightmap(sizeMeters: 10000f, gridRes: 17, largeHeights, minY: 0f, maxY: 0f, seed: 1); + DropSurfaceSample FlatQuery(float x, float z, float footR, float refMaxY) => + new(0f, Vector3.UnitY, false, false, false, false); + (float X, float Z) FlatClear(float x, float z, float pad) => (x, z); + + foreach (var (map, minGlideM) in new[] { (ArenaMapKind.Sion, 3000f), (ArenaMapKind.Desert, 1400f) }) + { + var preset = OrbitalPodPreset.GetContender(map); + var pod = new OrbitalPod + { + PodId = 100 + (int)map, + PodKind = OrbitalPodKind.Contender, + Phase = OrbitalPodPhase.Freefall, + X = 0f, + Y = preset.StartAltAgl, + Z = 0f, + VelY = preset.InitialVelY, + LookForwardX = 0f, + LookForwardZ = 1f, + SteerForwardCmd = 1.0f, + Yaw = 0f + }; + + float burnStartAgl = -1f; + bool touched = false; + for (int t = 0; t < 2400; t++) + { + if (OrbitalDropKinematics.StepPod(pod, ArenaSession.FixedDt, largeFlat, FlatQuery, FlatClear, out bool retroStarted, out _)) + { + touched = true; + break; + } + if (retroStarted) + { + burnStartAgl = pod.Y; + } + } + + Assert.True(touched, $"{map} cross-zone pod failed to touch down"); + Assert.True(pod.Z >= minGlideM, $"{map} max-burn horizontal glide {pod.Z:F1}m < {minGlideM:F1}m"); + Assert.True(pod.TouchdownSpeed < 2.5f, $"{map} flat touchdown speed {pod.TouchdownSpeed:F2} >= 2.5 m/s"); + Assert.InRange(burnStartAgl, 8f, 160f); + Assert.Equal(0f, pod.Y, precision: 3); + _output.WriteLine($"{map} flat cross-zone: glide={pod.Z:F1}m, flight={pod.FlightTime:F2}s, retroAgl={burnStartAgl:F2}m, tdVel={pod.TouchdownSpeed:F2} m/s"); + } + + // +-30 deg slope hover-slam verification + float slopeTan = MathF.Tan(30f * MathF.PI / 180f); // ~0.57735 + foreach (float sign in new[] { 1f, -1f }) + { + const int res = 129; + const float size = 8000f; + var slopeHeights = new float[res * res]; + for (int gz = 0; gz < res; gz++) + { + float wz = -size * 0.5f + (gz / (float)(res - 1)) * size; + float h = sign > 0f ? MathF.Max(0f, wz * slopeTan) : MathF.Max(0f, (1000f - wz) * slopeTan); + for (int gx = 0; gx < res; gx++) + { + slopeHeights[gz * res + gx] = h; + } + } + var slopeTerrain = TerrainField.LoadHeightmap(size, res, slopeHeights, 0f, 3000f, 2UL); + DropSurfaceSample SlopeQuery(float x, float z, float footR, float refMaxY) + { + float sy = slopeTerrain.SampleHeight(x, z); + var (nx, ny, nz) = slopeTerrain.SampleNormal(x, z); + return new DropSurfaceSample(sy, Vector3.Normalize(new Vector3(nx, ny, nz)), false, false, false, false); + } + + var sionPreset = OrbitalPodPreset.GetContender(ArenaMapKind.Sion); + float startZ = -400f; + float startSurf = slopeTerrain.SampleHeight(0f, startZ); + var pod = new OrbitalPod + { + PodId = 300 + (sign > 0 ? 1 : 2), + PodKind = OrbitalPodKind.Contender, + Phase = OrbitalPodPhase.Freefall, + X = 0f, + Y = startSurf + sionPreset.StartAltAgl, + Z = startZ, + VelY = sionPreset.InitialVelY, + LookForwardX = 0f, + LookForwardZ = 1f, + SteerForwardCmd = 1.0f, + Yaw = 0f + }; + + float burnStartAgl = -1f; + bool touched = false; + for (int t = 0; t < 3000; t++) + { + if (OrbitalDropKinematics.StepPod(pod, ArenaSession.FixedDt, slopeTerrain, SlopeQuery, FlatClear, out bool retroStarted, out _)) + { + touched = true; + break; + } + if (retroStarted) + { + burnStartAgl = pod.Y - slopeTerrain.SampleHeight(pod.X, pod.Z); + } + } + + Assert.True(touched, $"Slope sign={sign} pod failed to touch down"); + Assert.True(pod.TouchdownSpeed < 2.5f, $"Slope sign={sign} touchdown speed {pod.TouchdownSpeed:F2} >= 2.5 m/s"); + Assert.InRange(burnStartAgl, 5f, 160f); + float endTerrain = slopeTerrain.SampleHeight(pod.X, pod.Z); + Assert.True(MathF.Abs(pod.Y - endTerrain) < 0.001f, $"Slope sign={sign} penetration/hover error {pod.Y - endTerrain:F5}m"); + _output.WriteLine($"Slope sign={sign:+#;-#}: flight={pod.FlightTime:F2}s, retroAgl={burnStartAgl:F2}m, tdVel={pod.TouchdownSpeed:F2} m/s"); + } + } + + [Fact] + public void SquadFormation_TrioDrop_ZeroPodOverlapAndFormationVisible() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, squadSize: 3); + var state = session.State; + Assert.Equal(3, state.SquadSize); + + // Verify 4 squads of 3; inter-squad anchors >= 220m apart, intra-squad pods >= 14m apart at launch + var squadGroups = state.Contenders.GroupBy(c => c.SquadId).ToList(); + Assert.Equal(4, squadGroups.Count); + foreach (var grp in squadGroups) + { + var members = grp.ToList(); + Assert.Equal(3, members.Count); + for (int a = 0; a < members.Count; a++) + { + for (int b = a + 1; b < members.Count; b++) + { + float d = MathF.Sqrt( + (members[a].X - members[b].X) * (members[a].X - members[b].X) + + (members[a].Z - members[b].Z) * (members[a].Z - members[b].Z)); + Assert.True(d >= 14f, $"Same-squad launch separation too small: {d:F2}m"); + } + } + } + + // Different squad leaders >= 200m apart (anchors >= 220m, leaders +8m fwd) + for (int i = 0; i < squadGroups.Count; i++) + { + var li = state.GetSquadLeader(squadGroups[i].Key)!; + for (int j = i + 1; j < squadGroups.Count; j++) + { + var lj = state.GetSquadLeader(squadGroups[j].Key)!; + float d = MathF.Sqrt((li.X - lj.X) * (li.X - lj.X) + (li.Z - lj.Z) * (li.Z - lj.Z)); + Assert.True(d >= 195f, $"Inter-squad separation too small: {d:F1}m"); + } + } + + // Allied persistent PVS + zero false DetectedBy from allies + Assert.True(session.IsEntityInPeerPvs(0, true, 1)); + Assert.True(session.IsEntityInPeerPvs(0, true, 2)); + Assert.Equal(0, state.ObserverStates[0].DetectedByCount); + + // Step Wave 0 drop while player glides gently forward; track formation and touchdown separation + for (int t = 0; t < 2200; t++) + { + var p0 = state.Contenders[0]; + session.SetHumanInput(0, new PlayerInput( + Throttle: 0.45f, + Steer: 0f, + AimWorldX: p0.X + MathF.Sin(p0.Yaw) * 100f, + AimWorldZ: p0.Z + MathF.Cos(p0.Yaw) * 100f, + Fire: false, + InteractPickup: false, + Brake: false)); + session.Step(); + + if (state.Contenders.All(c => c.IsGroundedActive)) + { + break; + } + } + + Assert.All(state.Contenders, c => Assert.True(c.IsGroundedActive)); + + // Wingmen (1, 2) landed >= 12m apart from player (0) and each other, with 0 penetration + for (int a = 0; a < 3; a++) + { + AssertZeroChassisPenetration(state, state.Contenders[a]); + for (int b = a + 1; b < 3; b++) + { + float d = MathF.Sqrt( + (state.Contenders[a].X - state.Contenders[b].X) * (state.Contenders[a].X - state.Contenders[b].X) + + (state.Contenders[a].Z - state.Contenders[b].Z) * (state.Contenders[a].Z - state.Contenders[b].Z)); + Assert.True(d >= 11.5f, $"Squadmates {a} & {b} landed too close: {d:F2}m"); + } + } + + // Verify AI allies do not target allies and friendly fire does 0 damage + var ally1 = state.Contenders[1]; + float allyHpBefore = ally1.Grid.CoreHp; + session.SetContenderPose(0, 0f, 0f, 0f); + session.SetContenderPose(1, 0f, 20f, MathF.PI); + for (int t = 0; t < 30; t++) + { + session.SetHumanInput(0, new PlayerInput(0f, 0f, ally1.X, ally1.Z, Fire: true, InteractPickup: false, Brake: true)); + session.Step(); + Assert.False(ally1.AiTargetContenderId.HasValue && state.AreAllies(1, ally1.AiTargetContenderId.Value), + "AI wingman targeted an allied squadmate!"); + } + Assert.Equal(allyHpBefore, ally1.Grid.CoreHp); + + // Advance past Wave 2 cutoff and eliminate all 9 non-Squad-0 contenders -> Squad 0 wins! + state.Time = 250f; + session.Step(); + Assert.True(state.OrbitalDrop.RespawnCutoffReached); + for (int i = 3; i < state.Contenders.Count; i++) + { + session.ForceEliminateContender(i); + } + MatchRules.UpdateMatchOutcome(state); + Assert.Equal(MatchPhase.Completed, state.Phase); + Assert.Equal(0, state.WinnerContenderId); + } + + [Fact] + public void CorePvs_MaxDatagramCap_StrictlyUnder1152B() + { + var state = new MatchState(seed: 42, ArenaMapKind.Desert, skipInitialDrop: true, squadSize: 3); + var local = state.Contenders[0]; + local.Grid.SwapChassis(Catalog.Bastion); + + var contenders = new List(12); + var walkers = new List(12); + var specs = new List(10); + + for (int i = 0; i < 12; i++) + { + contenders.Add(new NetContenderState + { + SlotId = (byte)i, + Alive = true, + IsHuman = i < 3, + Lifecycle = ContenderLifecycle.Active, + Pos = new Vector3(i * 12f, 3f, -i * 6f), + Rot = Quaternion.Identity, + Vel = Vector3.Zero, + CoreHpRatio = 1f + }); + walkers.Add(new NetWalkerEntry + { + IsContender = true, + EntityId = (byte)i, + Snapshot = new WalkerVisualSnapshot { LegCount = 4 } + }); + } + + byte[] payload = SnapshotCodec.EncodeCorePvs( + 1, 10, 20, 12.5f, 0, 0, 772f, MatchPhase.Active, null, 0, 0xFFF, + local, Vector3.Zero, contenders, walkers, specs); + byte[] wire = SnapshotCodec.WrapLatest(payload, 1, 10); + Assert.True(wire.Length <= SnapshotCodec.MaxLatestDatagramBytes, + $"CorePvs wire frame {wire.Length}B > {SnapshotCodec.MaxLatestDatagramBytes}B"); + } + + [Fact] + public void SquadTrioDrop_AllSeedsAndMaps_AllLandedSquadmatesSeparatedAtLeast12Meters() + { + int[] seeds = { 1, 7, 42, 1337 }; + ArenaMapKind[] maps = { ArenaMapKind.Sion, ArenaMapKind.Desert }; + + foreach (var mapKind in maps) + { + foreach (int seed in seeds) + { + using var session = new ArenaSession(seed: seed, mapKind: mapKind, slot0Human: false, squadSize: 3); + var state = session.State; + + var tdPos = new (float X, float Z, int Tick)[MatchState.ContenderCount]; + var landed = new bool[MatchState.ContenderCount]; + for (int t = 0; t < 2400; t++) + { + session.Step(); + for (int i = 0; i < state.Contenders.Count; i++) + { + var c = state.Contenders[i]; + if (!landed[i] && c.IsGroundedActive) + { + landed[i] = true; + tdPos[i] = (c.X, c.Z, t); + } + } + if (state.Contenders.All(c => c.IsGroundedActive)) + { + break; + } + } + + Assert.All(state.Contenders, c => Assert.True(c.IsGroundedActive, + $"Map={mapKind} Seed={seed} contender {c.Id} failed to land")); + + foreach (var grp in state.Contenders.GroupBy(c => c.SquadId)) + { + var members = grp.ToList(); + for (int a = 0; a < members.Count; a++) + { + for (int b = a + 1; b < members.Count; b++) + { + var ma = members[a]; + var mb = members[b]; + float tdDx = tdPos[ma.Id].X - tdPos[mb.Id].X; + float tdDz = tdPos[ma.Id].Z - tdPos[mb.Id].Z; + float tdDist = MathF.Sqrt(tdDx * tdDx + tdDz * tdDz); + float dx = ma.X - mb.X; + float dz = ma.Z - mb.Z; + float d = MathF.Sqrt(dx * dx + dz * dz); + Assert.True(tdDist >= 12.0f, + $"Map={mapKind} Seed={seed} Squad={grp.Key} pair ({ma.Id}@t{tdPos[ma.Id].Tick},{mb.Id}@t{tdPos[mb.Id].Tick}) touchdown too close: td={tdDist:F2}m (now={d:F2}m)"); + Assert.True(d >= 12.0f, + $"Map={mapKind} Seed={seed} Squad={grp.Key} pair ({ma.Id}@t{tdPos[ma.Id].Tick},{mb.Id}@t{tdPos[mb.Id].Tick}) landed too close: now={d:F2}m (td={tdDist:F2}m)"); + } + } + } + } + } } private static void AssertZeroChassisPenetration(MatchState state, ContenderState c) diff --git a/tests/RustToDust.Tests/OrdnanceAndProceduralWeaponTests.cs b/tests/RustToDust.Tests/OrdnanceAndProceduralWeaponTests.cs index b8d8d81..81bbf59 100644 --- a/tests/RustToDust.Tests/OrdnanceAndProceduralWeaponTests.cs +++ b/tests/RustToDust.Tests/OrdnanceAndProceduralWeaponTests.cs @@ -979,5 +979,133 @@ namespace RustToDust.Tests var ex = Assert.Throws(() => OrdnanceGraphValidator.ValidateAndFlatten(combined)); Assert.Contains("sub-spawn budget", ex.Message, StringComparison.OrdinalIgnoreCase); } + + [Fact] + public void AlliedPdAndHitscan_DoNotInterceptSquadmateOrdnance() + { + using var session = new ArenaSession(seed: 101, slot0Human: true, skipInitialDrop: true, squadSize: 3); + var ally0 = session.State.Contenders[0]; + var ally1 = session.State.Contenders[1]; + var enemy = session.State.Contenders[3]; + Assert.True(session.State.AreAllies(ally0.Id, ally1.Id)); + Assert.False(session.State.AreAllies(ally0.Id, enemy.Id)); + IsolateContenders(session, ally0.Id, ally1.Id, enemy.Id); + + // Place Ally 0 and Ally 1 nearby facing Enemy so Ally 1's PD + RailPlasmaBeam shoot across Ally 0's ordnance + session.SetContenderPose(ally0.Id, 0f, 0f, 0f); + session.SetContenderPose(ally1.Id, 16f, 16f, -0.5f); + session.SetContenderPose(enemy.Id, 0f, 80f, MathF.PI); + + foreach (var c in new[] { ally0, ally1, enemy }) + { + session.State.SpawnChassisDrop(c.X, c.Z, Catalog.Anvil); + Assert.True(session.State.TrySwapNearbyChassis(c.Id)); + c.Grid.Mounted.RemoveAll(m => m.Spec.Kind == HardpointKind.Weapon); + } + session.SetContenderPose(ally0.Id, 0f, 0f, 0f); + session.SetContenderPose(ally1.Id, 16f, 16f, -0.5f); + session.SetContenderPose(enemy.Id, 0f, 80f, MathF.PI); + + var droneSpec = ProceduralWeaponGenerator.CreateDreamLoiteringDrone(); + var swarmSpec = ProceduralWeaponGenerator.CreateDreamWeapon(WeaponArchetypeKind.HomingSwarmPod); + var railSpec = ProceduralWeaponGenerator.CreateDreamWeapon(WeaponArchetypeKind.RailPlasmaBeam); + Assert.True(ally0.Grid.TryMount(droneSpec.Module, "hp.weapon.siege_l")); + Assert.True(ally0.Grid.TryMount(swarmSpec.Module, "hp.weapon.siege_r")); + Assert.True(ally1.Grid.TryMount(Catalog.ImperialAegisPd, "hp.weapon.sponson_l")); + Assert.True(ally1.Grid.TryMount(railSpec.Module, "hp.weapon.siege_l")); + Assert.True(ally1.Grid.TryMount(Catalog.GoldRadiator, "hp.radiator.l")); + Assert.True(ally1.Grid.TryMount(Catalog.GoldRadiator, "hp.radiator.r")); + + session.SetHumanSlot(ally1.Id, true, "Ally1"); + session.SetHumanInput(ally0.Id, new PlayerInput(0f, 0f, enemy.X, enemy.Z, Fire: false, InteractPickup: false, Brake: true, AimWorldY: enemy.Y + 2f)); + session.SetHumanInput(ally1.Id, new PlayerInput(0f, 0f, 0f, 25f, Fire: false, InteractPickup: false, Brake: true, AimWorldY: 12f)); + session.Step(); + + var events = new List(); + session.DrainStepEvents(events); + + int allyOrdnanceSpawned = 0; + int allyOrdnanceIntercepted = 0; + int railShotsWhileAllyOrdnanceAirborne = 0; + + for (int tick = 0; tick < 360; tick++) + { + Vector3? allyAirbornePos = null; + var pool = session.Ordnance.PoolSpan; + for (int i = 0; i < pool.Length; i++) + { + ref readonly var inst = ref pool[i]; + if (!inst.Active || inst.IsSpectatorShooter || inst.ShooterContenderId != ally0.Id) + { + continue; + } + if (inst.Def.InterceptHp > 0f && + inst.Def.Motion is OrdnanceMotion.LoiterOrbit or OrdnanceMotion.HomingMissile) + { + allyAirbornePos = inst.Pos; + break; + } + } + + // Keep Ally 1 cool enough to continuously fire PD + RailPlasmaBeam directly at Ally 0's airborne ordnance + foreach (var mod in ally1.Grid.Mounted) + { + mod.CurrentTemp = mod.Spec.OptimalTemp; + } + + session.SetHumanInput(ally0.Id, new PlayerInput( + 0f, 0f, + enemy.X, enemy.Z, + Fire: tick < 5, + InteractPickup: false, + Brake: true, + AimWorldY: enemy.Y + 2f)); + + if (allyAirbornePos.HasValue) + { + var p = allyAirbornePos.Value; + session.SetHumanInput(ally1.Id, new PlayerInput( + 0f, 0f, + p.X, p.Z, + Fire: true, + InteractPickup: false, + Brake: true, + AimWorldY: p.Y)); + railShotsWhileAllyOrdnanceAirborne++; + } + else + { + session.SetHumanInput(ally1.Id, new PlayerInput( + 0f, 0f, + enemy.X, enemy.Z, + Fire: false, + InteractPickup: false, + Brake: true, + AimWorldY: enemy.Y + 2f)); + } + + session.Step(); + events.Clear(); + session.DrainStepEvents(events); + foreach (var ev in events) + { + if (ev is OrdnanceNodeEvent one && !one.IsSpectatorShooter && one.ShooterId == ally0.Id) + { + if (one.Kind == (byte)OrdnanceEventKind.Spawned) + { + allyOrdnanceSpawned++; + } + else if (one.Kind == (byte)OrdnanceEventKind.Intercepted) + { + allyOrdnanceIntercepted++; + } + } + } + } + + Assert.True(allyOrdnanceSpawned >= 2, $"Expected Ally 0 to spawn drone + swarm ordnance, got {allyOrdnanceSpawned}"); + Assert.True(railShotsWhileAllyOrdnanceAirborne >= 10, $"Expected Ally 1 to aim RailPlasmaBeam + PD at airborne ally ordnance, got {railShotsWhileAllyOrdnanceAirborne}"); + Assert.Equal(0, allyOrdnanceIntercepted); + } } } diff --git a/tests/RustToDust.Tests/PlaytestFixesTests.cs b/tests/RustToDust.Tests/PlaytestFixesTests.cs index 2443389..0637618 100644 --- a/tests/RustToDust.Tests/PlaytestFixesTests.cs +++ b/tests/RustToDust.Tests/PlaytestFixesTests.cs @@ -67,8 +67,9 @@ namespace RustToDust.Tests } } - // 3. Step 4.5s (270 ticks) so Wave 0 gear pods touch down into GroundDrops; all 14 non-Jackal chassis exist - for (int t = 0; t < 270; t++) + // 3. Step Wave 0 gear drop duration so Wave 0 gear pods touch down into GroundDrops; all 14 non-Jackal chassis exist + int gearDropTicks = map == ArenaMapKind.Sion ? 1600 : 900; + for (int t = 0; t < gearDropTicks; t++) { session.Step(); } diff --git a/tests/RustToDust.Tests/RustToDust.Tests.csproj b/tests/RustToDust.Tests/RustToDust.Tests.csproj index e2ea589..e833c3a 100644 --- a/tests/RustToDust.Tests/RustToDust.Tests.csproj +++ b/tests/RustToDust.Tests/RustToDust.Tests.csproj @@ -18,11 +18,13 @@ + + diff --git a/tests/RustToDust.Tests/SionMapTests.cs b/tests/RustToDust.Tests/SionMapTests.cs index 3b4736f..df3bdc5 100644 --- a/tests/RustToDust.Tests/SionMapTests.cs +++ b/tests/RustToDust.Tests/SionMapTests.cs @@ -1,6 +1,10 @@ using System; +using System.Collections.Generic; +using System.IO; +using System.Net; using System.Numerics; using RustToDust.Core; +using RustToDust.Net; using RustToDust.Ymir; using Xunit; using Ymir.Box3D; @@ -16,20 +20,24 @@ namespace RustToDust.Tests var meta = sion.Metadata; Assert.Equal(3072f, meta.SizeMeters); - Assert.Equal(6, meta.TileGrid); - Assert.Equal(512f, meta.TileSizeMeters); - Assert.Equal(1025, meta.GridRes); - Assert.Equal(3.0f, meta.CellSizeMeters); + Assert.Equal(16, meta.TileGrid); + Assert.Equal(192f, meta.TileSizeMeters); + Assert.Equal(6145, meta.GridRes); + Assert.Equal(0.5f, meta.CellSizeMeters); + Assert.Equal("heightmap_05m.u16z", meta.HeightmapFile); + Assert.False(string.IsNullOrWhiteSpace(meta.DemAssetHash)); Assert.Contains("swisstopo", meta.Attribution, StringComparison.OrdinalIgnoreCase); - Assert.Equal(1025 * 1025, sion.Heights.Length); + Assert.Equal(6145 * 6145, sion.BaseDem.Length); Assert.Equal(2319, sion.Buildings.Count); Assert.Equal(36, sion.CollisionMeshes.Count); - var terrain = TerrainField.LoadHeightmap( - meta.SizeMeters, meta.GridRes, sion.Heights, meta.MinY, meta.MaxY); + var terrain = TerrainField.LoadSharedHeightmap( + meta.SizeMeters, meta.GridRes, meta.TileGrid, + sion.BaseDem, sion.BaseDemMinY, sion.BaseDemScale, + meta.MinY, meta.MaxY); - // Verify Basilique de Valere and valley buildings align cleanly with heightmap.f32 (0.00m coordinate drift) + // Verify Basilique de Valere and valley buildings align cleanly with heightmap_05m.u16z (0.00m coordinate drift) bool foundValere = false; int flatAlignChecked = 0; int closeAlignCount = 0; @@ -82,16 +90,19 @@ namespace RustToDust.Tests { var sion = SionMapLoader.Load(); var meta = sion.Metadata; - var terrain = TerrainField.LoadHeightmap( - meta.SizeMeters, meta.GridRes, sion.Heights, meta.MinY, meta.MaxY); + var terrain = TerrainField.LoadSharedHeightmap( + meta.SizeMeters, meta.GridRes, meta.TileGrid, + sion.BaseDem, sion.BaseDemMinY, sion.BaseDemScale, + meta.MinY, meta.MaxY); Assert.True(terrain.IsHeightmapMode); Assert.Equal(3072f, terrain.MapSize); Assert.Equal(1536f, terrain.MapHalfExtent); + Assert.Equal(16, terrain.TileGridCount); // Grid vertex exactness at (-1536, -1536) and (0, 0) - Assert.Equal(sion.Heights[0], terrain.SampleHeight(-1536f, -1536f), precision: 4); - Assert.Equal(sion.Heights[512 * 1025 + 512], terrain.SampleHeight(0f, 0f), precision: 4); + Assert.Equal(sion.SampleBaseDemAtIndex(0), terrain.SampleHeight(-1536f, -1536f), precision: 4); + Assert.Equal(sion.SampleBaseDemAtIndex(3072 * 6145 + 3072), terrain.SampleHeight(0f, 0f), precision: 4); // Plaza spawn area is flat; Valere hill rises > 100m var (_, plazaNy, _) = terrain.SampleNormal(-60f, 360f); @@ -126,7 +137,7 @@ namespace RustToDust.Tests Assert.Empty(state.ArenaCoverBoxes); Assert.Equal(MatchState.SionInitialSafeRadius, state.Spectators.SafeRadius); - // Verify StaticHeightField (1) + StaticMesh (36) exist in Ymir + // Verify lazy tiled StaticHeightField (192m tiles) + StaticMesh (36) exist in Ymir int hfCount = 0; int meshCount = 0; var view = session.World.View; @@ -136,8 +147,10 @@ namespace RustToDust.Tests if (kind == Box3DSoaKind.StaticHeightField) hfCount++; else if (kind == Box3DSoaKind.StaticMesh) meshCount++; } - Assert.Equal(1, hfCount); - Assert.Equal(36, meshCount); + Assert.InRange(hfCount, 1, 45); + Assert.Equal(hfCount, session.TileSync.ResidentTileCount); + 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) @@ -225,5 +238,567 @@ namespace RustToDust.Tests float pDisp = MathF.Sqrt((player.X - pStartX) * (player.X - pStartX) + (player.Z - pStartZ) * (player.Z - pStartZ)); Assert.True(pDisp > 5f, $"Expected player displacement > 5m on Sion after 180 ticks, got {pDisp:F2}m"); } + + [Fact] + public void SionBox3DTile_CraterRebuildsLocalTileOnlyAndLeavesNeighborsIntact() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true); + var terrain = session.State.Terrain; + + // Tile (7, 7) spans [-192, 0) x [-192, 0); neighbor tile (8, 7) spans [0, 192) x [-192, 0). + // Pick an open-sky coordinate strictly inside tile (7, 7) away from any building footprint. + var sion = session.State.SionMap!; + float cx = -96f, cz = -96f; + bool foundSpot = false; + for (float z = -176f; z <= -16f && !foundSpot; z += 8f) + { + for (float x = -176f; x <= -16f; x += 8f) + { + if (!sion.IsInsideAnyBuildingXz(x, z, padding: 10f)) + { + cx = x; + cz = z; + foundSpot = true; + break; + } + } + } + Assert.True(foundSpot, "Expected open-sky spot inside Sion tile (7, 7)"); + + session.TileSync.EnsureTileRegion(session.World, terrain, cx, cz, halfTileRadius: 1); + + Assert.True(session.TileSync.TryGetResidentHandle(7, 7, terrain.TileGridCount, out var handleTargetBefore)); + Assert.True(session.TileSync.TryGetResidentHandle(8, 7, terrain.TileGridCount, out var handleNeighborBefore)); + + float rayStartY = sion.Metadata.MaxY + 25f; + float raySpanY = -(sion.Metadata.MaxY - sion.Metadata.MinY + 60f); + var hitBefore = session.CastWorldRayClosest(new Vector3(cx, rayStartY, cz), new Vector3(0f, raySpanY, 0f)); + Assert.True(hitBefore.Hit); + Assert.Equal(Box3DPhysicsTileSync.HeightfieldTileStableIdBase + (ulong)(7 * 16 + 7), hitBefore.StableId); + + // Stamp crater strictly inside tile (7, 7) + session.State.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = cx, + Z = cz, + Radius = 6f, + Depth = 2.0f + }); + int rebuilt = session.TileSync.FlushDirtyHeightfields(session.World, terrain, maxTilesPerTick: 4); + Assert.Equal(1, rebuilt); + + Assert.True(session.TileSync.TryGetResidentHandle(7, 7, terrain.TileGridCount, out var handleTargetAfter)); + Assert.True(session.TileSync.TryGetResidentHandle(8, 7, terrain.TileGridCount, out var handleNeighborAfter)); + + Assert.NotEqual(handleTargetBefore, handleTargetAfter); + Assert.Equal(handleNeighborBefore, handleNeighborAfter); + + var hitAfter = session.CastWorldRayClosest(new Vector3(cx, rayStartY, cz), new Vector3(0f, raySpanY, 0f)); + Assert.True(hitAfter.Hit); + Assert.True(hitAfter.Point.Y < hitBefore.Point.Y - 1.2f, + $"Expected Box3D raycast impact height to drop in crater (before={hitBefore.Point.Y:F3}, after={hitAfter.Point.Y:F3})"); + } + + [Fact] + public void ArenaScarLedgerStore_PersistsCratersAndRubbleAcrossResetAndRepairsToLayer0() + { + string tempDir = Path.Combine(Path.GetTempPath(), "rtd-cut13a-scar-test-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempDir); + string scarPath = Path.Combine(tempDir, "sion_scars_test.cultcache"); + + try + { + const float craterX = -120f; + const float craterZ = 180f; + const float rubbleX = 140f; + const float rubbleZ = 180f; + float baseCraterH; + float baseRubbleH; + float scarredCraterH; + float scarredRubbleH; + + using (var host1 = new ServerMatchHost( + IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, + autoRestartSec: 0, scarFilePath: scarPath, persistScars: true)) + { + var state1 = host1.Session.State; + baseCraterH = state1.Terrain.SampleHeight(craterX, craterZ); + baseRubbleH = state1.Terrain.SampleHeight(rubbleX, rubbleZ); + + state1.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = craterX, + Z = craterZ, + Radius = 5.5f, + Depth = 1.8f + }); + state1.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Rubble, + X = rubbleX, + Z = rubbleZ, + Radius = 6.0f, + Depth = 1.2f, + Yaw = 0.4f + }); + + scarredCraterH = state1.Terrain.SampleHeight(craterX, craterZ); + scarredRubbleH = state1.Terrain.SampleHeight(rubbleX, rubbleZ); + Assert.True(scarredCraterH < baseCraterH - 1.2f); + Assert.True(scarredRubbleH > baseRubbleH + 0.6f); + + // ResetMatch preserves scars in RAM & flushes to CultCache + host1.ResetMatch(43, ArenaMapKind.Sion, startInLobby: false); + Assert.Equal(scarredCraterH, host1.Session.State.Terrain.SampleHeight(craterX, craterZ), precision: 3); + Assert.Equal(scarredRubbleH, host1.Session.State.Terrain.SampleHeight(rubbleX, rubbleZ), precision: 3); + } + + Assert.True(File.Exists(scarPath), "Expected CultCache scar file on disk after host dispose"); + + using (var host2 = new ServerMatchHost( + IPAddress.Loopback, 0, seed: 44, ArenaMapKind.Sion, + autoRestartSec: 0, scarFilePath: scarPath, persistScars: true)) + { + var state2 = host2.Session.State; + Assert.Equal(scarredCraterH, state2.Terrain.SampleHeight(craterX, craterZ), precision: 3); + Assert.Equal(scarredRubbleH, state2.Terrain.SampleHeight(rubbleX, rubbleZ), precision: 3); + + // RepairArenaScars zeroes back to Layer 0 + host2.RepairArenaScars(); + Assert.Equal(baseCraterH, state2.Terrain.SampleHeight(craterX, craterZ), precision: 3); + Assert.Equal(baseRubbleH, state2.Terrain.SampleHeight(rubbleX, rubbleZ), precision: 3); + Assert.Empty(state2.ScarLedger.Terrain); + } + } + finally + { + if (Directory.Exists(tempDir)) + { + Directory.Delete(tempDir, recursive: true); + } + } + } + + [Fact] + public void ValereSlopeHits_ClassifyAsTerrainNeverStaticCover_ForHitscanAndProjectile() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true); + var terrain = session.State.Terrain; + var sion = session.State.SionMap!; + + // Ensure Valere hill heightfield tiles are resident so Box3D heightfields are active on the slope ray + session.TileSync.EnsureTileRegion(session.World, terrain, 113f, -211f, halfTileRadius: 1); + + // Find an open-sky steep Valere slope point and an unobstructed muzzle above it (zero buildings on ray) + Vector3 muzzle = default; + Vector3 dir = default; + bool foundSlope = false; + for (float sz = -290f; sz <= -175f && !foundSlope; sz += 6f) + { + for (float sx = 40f; sx <= 185f && !foundSlope; sx += 6f) + { + if (sion.IsInsideAnyBuildingXz(sx, sz, padding: 8.0f)) + { + continue; + } + float sh = terrain.SampleHeight(sx, sz); + var (nx, ny, nz) = terrain.SampleNormal(sx, sz); + if (sh < 55f || ny >= 0.88f) + { + continue; + } + Vector3 slopePt = new(sx, sh, sz); + Vector3 nrm = Vector3.Normalize(new Vector3(nx, ny, nz)); + Vector3 candMuzzle = slopePt + nrm * 32f + Vector3.UnitY * 8f; + Vector3 candDir = Vector3.Normalize(slopePt - candMuzzle); + float dist = Vector3.Distance(candMuzzle, slopePt) + 5f; + if (!sion.IntersectsAnyBuildingAabb(candMuzzle.X, candMuzzle.Y, candMuzzle.Z, candDir.X, candDir.Y, candDir.Z, dist) && + terrain.Raycast(candMuzzle.X, candMuzzle.Y, candMuzzle.Z, candDir.X, candDir.Y, candDir.Z, dist, out float tx, out _, out float tz, out _) && + !sion.IsInsideAnyBuildingXz(tx, tz, padding: 2.0f)) + { + muzzle = candMuzzle; + dir = candDir; + foundSlope = true; + } + } + } + Assert.True(foundSlope, "Expected open-sky steep Valere slope ray unobstructed by buildings"); + session.TileSync.EnsureTileRegion(session.World, terrain, muzzle.X, muzzle.Z, halfTileRadius: 1); + + var events = new List(); + session.DrainStepEvents(events); + + // 1. Fire hitscan directly into Valere slope + var hitscanSpec = ProceduralWeaponGenerator.CreateDreamWeapon(WeaponArchetypeKind.RotaryAutocannon); + session.Ordnance.FireWeapon(new OrdnanceFireRequest( + Module: new MountedModule(hitscanSpec.Module, "hp.weapon.main", 0f), + ShooterStableId: ArenaSession.ContenderStableIdBase, + ShooterContender: session.State.Contenders[0], + ShooterLabel: "Tester", + IsSpectatorShooter: false, + ShooterEntityId: 0, + ShooterPos: muzzle, + MuzzlePos: muzzle, + AimDir: dir, + AimDist: 160f, + SpreadRad: 0f, + TargetEntityStableId: 0UL, + RootDef: hitscanSpec.RootNode, + WeaponKey: hitscanSpec.Key)); + + // 2. Fire ballistic projectile into Valere slope + var projSpec = ProceduralWeaponGenerator.CreateDreamWeapon(WeaponArchetypeKind.SabotSlugCannon); + session.Ordnance.FireWeapon(new OrdnanceFireRequest( + Module: new MountedModule(projSpec.Module, "hp.weapon.main", 0f), + ShooterStableId: ArenaSession.ContenderStableIdBase, + ShooterContender: session.State.Contenders[0], + ShooterLabel: "Tester", + IsSpectatorShooter: false, + ShooterEntityId: 0, + ShooterPos: muzzle, + MuzzlePos: muzzle, + AimDir: dir, + AimDist: 160f, + SpreadRad: 0f, + TargetEntityStableId: 0UL, + RootDef: projSpec.RootNode, + WeaponKey: projSpec.Key)); + + var impacts = new List(); + for (int tick = 0; tick < 60; tick++) + { + session.Step(); + events.Clear(); + session.DrainStepEvents(events); + foreach (var ev in events) + { + if (ev is HitImpactEvent hit) + { + impacts.Add(hit); + } + } + if (impacts.Count >= 2) + { + break; + } + } + + Assert.True(impacts.Count >= 2, $"Expected >= 2 slope impacts (hitscan + projectile), got {impacts.Count}"); + Assert.All(impacts, h => Assert.Equal((byte)HitTargetKind.Terrain, h.TargetKind)); + } + + [Fact] + public void RepairArenaScars_ManyScarredTilesRebuildIncrementallyWithoutExhaustingWorldCapacity() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true); + var terrain = session.State.Terrain; + + // Materialize 20 resident tiles in a 5x4 grid and crater all 20 + var spots = new List<(float X, float Z, float BaseH)>(); + for (int tz = 5; tz <= 8; tz++) + { + for (int tx = 5; tx <= 9; tx++) + { + float wx = -terrain.MapHalfExtent + (tx + 0.5f) * terrain.MapTileSize; + float wz = -terrain.MapHalfExtent + (tz + 0.5f) * terrain.MapTileSize; + session.TileSync.EnsureTileResident(session.World, terrain, tx, tz); + float baseH = terrain.SampleHeight(wx, wz); + spots.Add((wx, wz, baseH)); + session.State.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = wx, + Z = wz, + Radius = 5f, + Depth = 1.6f + }); + } + } + + // Flush all 20 cratered tiles into Box3D heightfields without evicting non-actor tiles + int flushedBeforeRepair = session.TileSync.FlushDirtyHeightfields(session.World, terrain, maxTilesPerTick: 20); + Assert.Equal(20, flushedBeforeRepair); + session.World.Step(1f / 60f); + + var sion = session.State.SionMap!; + var sionMeta = sion.Metadata; + (float X, float Z, float BaseH) openSpot = default; + bool foundOpenSpot = false; + foreach (var s in spots) + { + if (!sion.IsInsideAnyBuildingXz(s.X, s.Z, padding: 6f)) + { + openSpot = s; + foundOpenSpot = true; + break; + } + } + Assert.True(foundOpenSpot, "Expected at least one open-sky spot among the 20 cratered tiles"); + + float rayStartY = sionMeta.MaxY + 25f; + float raySpanY = -(sionMeta.MaxY - sionMeta.MinY + 60f); + var hitCratered = session.CastWorldRayClosest(new Vector3(openSpot.X, rayStartY, openSpot.Z), new Vector3(0f, raySpanY, 0f)); + Assert.True(hitCratered.Hit); + Assert.True(hitCratered.Point.Y < openSpot.BaseH - 1.0f, + $"Expected cratered Box3D raycast height ({hitCratered.Point.Y:F3}) well below base ({openSpot.BaseH:F3})"); + + int freeBeforeRepair = session.World.FreeBodySlots; + Assert.True(freeBeforeRepair >= 20 + 32); + session.RepairArenaScars(); + // When FreeBodySlots >= dirtyResidentCount + 32, RepairArenaScars flushes all dirty resident tiles immediately on tick 0 + Assert.True(session.World.View.Count < ArenaSession.WorldBodyCapacity - 256, + $"Expected View.Count ({session.World.View.Count}) well below WorldBodyCapacity ({ArenaSession.WorldBodyCapacity}) after repair"); + Assert.Equal(0, session.TileSync.CountDirtyResidentTiles(terrain)); + + var hitTick0 = session.CastWorldRayClosest(new Vector3(openSpot.X, rayStartY, openSpot.Z), new Vector3(0f, raySpanY, 0f)); + Assert.True(hitTick0.Hit); + Assert.True(MathF.Abs(hitTick0.Point.Y - openSpot.BaseH) < 0.05f, + $"Expected tick-0 Box3D raycast height ({hitTick0.Point.Y:F3}) to match restored base ({openSpot.BaseH:F3})"); + + // Step across ticks so recycled slots remain healthy without exhausting world capacity + for (int t = 0; t < 20; t++) + { + session.Step(); + Assert.True(session.World.View.Count < ArenaSession.WorldBodyCapacity - 256, + $"Expected View.Count ({session.World.View.Count}) well below WorldBodyCapacity ({ArenaSession.WorldBodyCapacity}) at tick {t}"); + } + + foreach (var (wx, wz, baseH) in spots) + { + Assert.Equal(baseH, terrain.SampleHeight(wx, wz), precision: 3); + } + } + + [Fact] + public void ServerMatchHost_SionDesertSion_PreservesSionScarsAndDoesNotClobberExplicitScarFile() + { + string tempDir = Path.Combine(Path.GetTempPath(), "rtd-cut13a-mapswitch-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempDir); + string explicitSionPath = Path.Combine(tempDir, "sion_scars_explicit.cultcache"); + + try + { + const float craterX = -120f; + const float craterZ = 180f; + float sionBaseH; + float sionScarredH; + + using (var host = new ServerMatchHost( + IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, + autoRestartSec: 0, scarFilePath: explicitSionPath, persistScars: true)) + { + sionBaseH = host.Session.State.Terrain.SampleHeight(craterX, craterZ); + host.Session.State.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = craterX, + Z = craterZ, + Radius = 5.5f, + Depth = 1.8f + }); + sionScarredH = host.Session.State.Terrain.SampleHeight(craterX, craterZ); + Assert.True(sionScarredH < sionBaseH - 1.2f); + + // Switch Sion -> Desert: Desert must NOT inherit Sion craters, nor overwrite explicitSionPath + float desertBaseH; + host.ResetMatch(42, ArenaMapKind.Desert, startInLobby: false); + Assert.Empty(host.Session.State.ScarLedger.Terrain); + desertBaseH = host.Session.State.Terrain.SampleHeight(0f, 0f); + host.Session.State.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = 0f, + Z = 0f, + Radius = 4.5f, + Depth = 1.4f + }); + float desertScarredH = host.Session.State.Terrain.SampleHeight(0f, 0f); + Assert.True(desertScarredH < desertBaseH - 0.8f); + + // Switch Desert -> Sion: Sion craters must be restored cleanly! + host.ResetMatch(43, ArenaMapKind.Sion, startInLobby: false); + Assert.Equal(sionScarredH, host.Session.State.Terrain.SampleHeight(craterX, craterZ), precision: 3); + + // Verify explicitSionPath on disk still holds Sion's AssetFingerprint & crater (never clobbered by Desert) + var diskSnap = ArenaScarLedgerStore.Load(explicitSionPath, host.Session.State.SionMap!.AssetFingerprint); + Assert.Single(diskSnap.Terrain); + Assert.Equal(craterX, diskSnap.Terrain[0].X); + Assert.Equal(craterZ, diskSnap.Terrain[0].Z); + } + + // Also verify LocalArenaSession & ListenHostArenaSession carry scars across rounds and Sion -> Desert -> Sion + using (var local = new LocalArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, skipInitialDrop: true)) + { + local.Inner.State.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = craterX, + Z = craterZ, + Radius = 5.5f, + Depth = 1.8f + }); + local.RequestNewMatch(43, ArenaMapKind.Sion); + Assert.Equal(sionScarredH, local.ViewState.Terrain.SampleHeight(craterX, craterZ), precision: 3); + + local.RequestNewMatch(42, ArenaMapKind.Desert); + Assert.Empty(local.ViewState.ScarLedger.Terrain); + + local.RequestNewMatch(44, ArenaMapKind.Sion); + Assert.Equal(sionScarredH, local.ViewState.Terrain.SampleHeight(craterX, craterZ), precision: 3); + + local.RepairArenaScars(); + local.RequestNewMatch(45, ArenaMapKind.Sion); + Assert.Equal(sionBaseH, local.ViewState.Terrain.SampleHeight(craterX, craterZ), precision: 3); + } + + using (var listen = new ListenHostArenaSession(IPAddress.Loopback, 0, seed: 42, mapKind: ArenaMapKind.Sion)) + { + listen.Host.Session.State.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = craterX, + Z = craterZ, + Radius = 5.5f, + Depth = 1.8f + }); + listen.RequestNewMatch(43, ArenaMapKind.Desert); + Assert.Empty(listen.ViewState.ScarLedger.Terrain); + + listen.RequestNewMatch(44, ArenaMapKind.Sion); + Assert.Equal(sionScarredH, listen.ViewState.Terrain.SampleHeight(craterX, craterZ), precision: 3); + } + } + finally + { + if (Directory.Exists(tempDir)) + { + Directory.Delete(tempDir, recursive: true); + } + } + } + + [Fact] + public void FlushDirtyHeightfields_RecycledFreeSlots_DoesNotWedgeAtHighViewCount() + { + using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true); + var terrain = session.State.Terrain; + var sion = session.State.SionMap!; + + float cx = -96f, cz = -96f; + bool foundSpot = false; + for (float z = -176f; z <= -16f && !foundSpot; z += 8f) + { + for (float x = -176f; x <= -16f; x += 8f) + { + if (!sion.IsInsideAnyBuildingXz(x, z, padding: 10f)) + { + cx = x; + cz = z; + foundSpot = true; + break; + } + } + } + Assert.True(foundSpot, "Expected open-sky spot inside Sion tile (7, 7)"); + + session.TileSync.EnsureTileRegion(session.World, terrain, cx, cz, halfTileRadius: 0); + + // Push View.Count >= 1016, then remove those temporary bodies and step to recycle FreeBodySlots > 500 + var tempHandles = new List(); + ulong nextId = 900_000UL; + while (session.World.View.Count < 1016 && session.World.FreeBodySlots > 0) + { + tempHandles.Add(session.World.AddStaticBox(nextId++, (0f, -500f, 0f), (0.5f, 0.5f, 0.5f))); + } + Assert.True(session.World.View.Count >= 1016, $"Expected View.Count >= 1016, got {session.World.View.Count}"); + + foreach (var h in tempHandles) + { + session.World.RemoveBody(h); + } + session.World.Step(1f / 60f); + + Assert.True(session.World.View.Count >= 1016, $"Expected monotonic View.Count >= 1016, got {session.World.View.Count}"); + Assert.True(session.World.FreeBodySlots > 500, $"Expected recycled FreeBodySlots > 500, got {session.World.FreeBodySlots}"); + + session.State.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = cx, + Z = cz, + Radius = 6f, + Depth = 2.5f + }); + int rebuilt = session.TileSync.FlushDirtyHeightfields(session.World, terrain, maxTilesPerTick: 4); + Assert.Equal(1, rebuilt); + + float cpuH = terrain.SampleHeight(cx, cz); + float rayStartY = sion.Metadata.MaxY + 25f; + float raySpanY = -(sion.Metadata.MaxY - sion.Metadata.MinY + 60f); + var hit = session.CastWorldRayClosest(new Vector3(cx, rayStartY, cz), new Vector3(0f, raySpanY, 0f)); + Assert.True(hit.Hit); + Assert.True(MathF.Abs(hit.Point.Y - cpuH) < 0.05f, + $"Expected Box3D raycast height ({hit.Point.Y:F3}) to match CPU height ({cpuH:F3}) within 0.05 m"); + } + + [Fact] + public void ServerMatchHost_ResetMatch_RepairScarsOnCrossMapSwitch_ClearsTargetOnlyAndPreservesSource() + { + string tempDir = Path.Combine(Path.GetTempPath(), "rtd-cut13a-repairswitch-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(tempDir); + string explicitSionPath = Path.Combine(tempDir, "sion_scars_explicit.cultcache"); + string desertPath = ServerMatchHost.ResolveScarFilePath(explicitSionPath, ArenaMapKind.Sion, ArenaMapKind.Desert); + + try + { + using var host = new ServerMatchHost( + IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, + autoRestartSec: 0, scarFilePath: explicitSionPath, persistScars: true); + + string sionFp = host.Session.State.SionMap!.AssetFingerprint; + + // Stamp Sion crater + host.Session.State.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = -120f, + Z = 180f, + Radius = 5.5f, + Depth = 1.8f + }); + + // Switch to Desert and stamp Desert crater + host.ResetMatch(42, ArenaMapKind.Desert, startInLobby: false); + host.Session.State.ApplyTerrainStamp(new TerrainStampEvent + { + Kind = (byte)TerrainStampKind.Crater, + X = 0f, + Z = 0f, + Radius = 4.5f, + Depth = 1.4f + }); + + // Switch back to Sion, then ResetMatch(42, Desert, repairScars: true) FROM Sion + host.ResetMatch(42, ArenaMapKind.Sion, startInLobby: false); + Assert.Single(host.Session.State.ScarLedger.Terrain); + + host.ResetMatch(42, ArenaMapKind.Desert, startInLobby: false, repairScars: true); + + Assert.Empty(host.Session.State.ScarLedger.Terrain); + var sionDisk = ArenaScarLedgerStore.Load(explicitSionPath, sionFp); + var desertDisk = ArenaScarLedgerStore.Load(desertPath, "desert:42"); + Assert.Single(sionDisk.Terrain); + Assert.Empty(desertDisk.Terrain); + } + finally + { + if (Directory.Exists(tempDir)) + { + Directory.Delete(tempDir, recursive: true); + } + } + } } } diff --git a/tests/RustToDust.Tests/SionTreeTests.cs b/tests/RustToDust.Tests/SionTreeTests.cs new file mode 100644 index 0000000..0d5412b --- /dev/null +++ b/tests/RustToDust.Tests/SionTreeTests.cs @@ -0,0 +1,453 @@ +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); + Assert.False(string.IsNullOrWhiteSpace(catalog.AssetHash)); + Assert.Contains($":trees:{catalog.AssetHash}", sion.AssetFingerprint, StringComparison.Ordinal); + + // 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() + { + using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, slot0Human: true); + var sion = session.State.SionMap!; + var trees = session.State.SionTrees!; + + Assert.True(Catalog.Raptor.MassKg < SionTreeDestructionState.HeavyWalkerMinMassKg, + $"Expected Raptor ({Catalog.Raptor.MassKg}kg) < HeavyWalkerMinMassKg"); + Assert.True(Catalog.Bastion.MassKg >= SionTreeDestructionState.HeavyWalkerMinMassKg, + $"Expected Bastion ({Catalog.Bastion.MassKg}kg) >= HeavyWalkerMinMassKg"); + + SionTreePlacement thin = default; + SionTreePlacement thick = default; + bool foundThin = false, foundThick = false; + foreach (var t in sion.Trees.Trees) + { + if (!foundThin && t.TrunkRadiusM >= 0.12f && t.TrunkRadiusM < SionTreeDestructionState.WalkerTrampleMaxTrunkRadiusM && + !sion.IsInsideAnyBuildingXz(t.X, t.Z, 4.0f)) + { + thin = t; + foundThin = true; + } + if (!foundThick && t.TrunkRadiusM >= 0.45f && + !sion.IsInsideAnyBuildingXz(t.X, t.Z, 4.0f)) + { + thick = t; + foundThick = true; + } + if (foundThin && foundThick) break; + } + Assert.True(foundThin && foundThick); + + // Light walker (Raptor < HeavyWalkerMinMassKg) placed overlapping thin tree must NOT trample it + session.SetContenderPose(0, thin.X, thin.Z, 0f); + session.State.SpawnChassisDrop(thin.X, thin.Z, Catalog.Raptor); + Assert.True(session.TrySwapNearbyChassis(0), "Expected swap to Raptor near thin tree"); + session.SetContenderPose(0, thin.X, thin.Z, 0f); + session.Step(); + Assert.Equal(SionTreeState.Intact, trees.GetState(thin.TreeId)); + + // Heavy walker (Bastion >= HeavyWalkerMinMassKg) trampling same thin (< 0.30m) tree snaps it cleanly + session.State.SpawnChassisDrop(thin.X, thin.Z, Catalog.Bastion); + Assert.True(session.TrySwapNearbyChassis(0), "Expected swap to Bastion near thin tree"); + session.SetContenderPose(0, thin.X, thin.Z, 0f); + session.Step(); + Assert.Equal(SionTreeState.Snapped, trees.GetState(thin.TreeId)); + + // Heavy walker overlapping thick (>= 0.30m) tree must NOT trample it + session.SetContenderPose(0, thick.X, thick.Z, 0f); + session.Step(); + Assert.Equal(SionTreeState.Intact, trees.GetState(thick.TreeId)); + } + + [Fact] + public void SionTreeDestruction_FlushDirtyTreeTiles_RestoresColliderImmediatelyAfterAllTileTreesSnappedAndRepaired() + { + using var session = new ArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, slot0Human: true); + var sion = session.State.SionMap!; + var trees = session.State.SionTrees!; + + // Find an active-near tile or any tile containing solid (>= 0.20m) trees clear of buildings + SionTreePlacement targetTree = default; + bool found = false; + for (int i = 0; i < sion.Trees.Count; i++) + { + var t = sion.Trees.Trees[i]; + if (t.TrunkRadiusM >= SionTreeDestructionState.MinColliderTrunkRadiusM && + !sion.IsInsideAnyBuildingXz(t.X, t.Z, 4.5f)) + { + targetTree = t; + found = true; + break; + } + } + Assert.True(found); + + // Place contender 0 in the target tile so SyncNeededTreeTiles keeps it needed across Step(), + // and do NOT manually call EnsureTreeTileResident after repair. + session.SetContenderPose(0, targetTree.X + 8.0f, targetTree.Z + 8.0f, 0f); + session.TileSync.EnsureTreeTileResident(session.World, trees, targetTree.Tx, targetTree.Tz); + ulong expectedStableId = Box3DPhysicsTileSync.TreeTileStableIdBase + (ulong)targetTree.TileIndex; + var rayOrigin = new Vector3(targetTree.X - 4.0f, targetTree.Y + 1.4f, targetTree.Z); + var raySpan = new Vector3(8.0f, 0f, 0f); + Assert.Equal(expectedStableId, session.CastWorldRayClosest(rayOrigin, raySpan).StableId); + + // Snap EVERY solid tree in that tile -> removes the Box3D body completely (ResidentTreeTileCount drops) + foreach (int idx in sion.Trees.GetTileTreeIndices(targetTree.Tx, targetTree.Tz)) + { + var tileTree = sion.Trees.Trees[idx]; + if (tileTree.TrunkRadiusM >= SionTreeDestructionState.MinColliderTrunkRadiusM) + { + trees.ApplyBlast(new Vector3(tileTree.X, tileTree.Y + 0.5f, tileTree.Z), splashRadius: 4f, blastDamage: 300f); + } + } + session.TileSync.FlushDirtyTreeTiles(session.World, trees, maxTilesPerTick: 8); + var afterSnapHit = session.CastWorldRayClosest(rayOrigin, raySpan); + Assert.False(afterSnapHit.Hit && afterSnapHit.StableId == expectedStableId, + "Expected Box3D tree tile body to be removed when all collider trees in tile are snapped"); + + // RepairArenaScars() + Step() (NO manual EnsureTreeTileResident!) must immediately restore Box3D collider + session.RepairArenaScars(); + var immediateHit = session.CastWorldRayClosest(rayOrigin, raySpan); + Assert.True(immediateHit.Hit && immediateHit.StableId == expectedStableId, + $"Expected RepairArenaScars FlushDirtyTreeTiles to restore tree collider {expectedStableId}, got Hit={immediateHit.Hit} StableId={immediateHit.StableId}"); + session.Step(); + var stepHit = session.CastWorldRayClosest(rayOrigin, raySpan); + Assert.True(stepHit.Hit && stepHit.StableId == expectedStableId, + $"Expected tick-0 Step() to keep restored tree collider {expectedStableId}, got Hit={stepHit.Hit} StableId={stepHit.StableId}"); + } + + [Fact] + public void SionTreeDestruction_CumulativeBlastDamage_TwoColdStartRecoillessHitsSnapMediumTrunk() + { + var sion = SionMapLoader.Load(); + var trees = new SionTreeDestructionState(sion.Trees); + + SionTreePlacement med = default; + bool found = false; + foreach (var t in sion.Trees.Trees) + { + if (t.TrunkRadiusM >= 0.32f && t.TrunkRadiusM <= 0.39f) + { + med = t; + found = true; + break; + } + } + Assert.True(found, "Expected a medium ~0.35m trunk tree in Sion catalog"); + + // Cold-start Recoilless shell: WeaponDamage=85 * ~0.65 cold thermal scale = ~55.25 damage (< 65f one-shot core threshold) + float coldRecoillessDmg = Catalog.Recoilless.WeaponDamage * 0.65f; + var hitPoint = new Vector3(med.X + med.TrunkRadiusM, med.Y + 1.0f, med.Z); + + // Hit #1: chars the tree without snapping it immediately + trees.ApplyBlast(hitPoint, splashRadius: 2.5f, blastDamage: coldRecoillessDmg); + Assert.Equal(SionTreeState.Charred, trees.GetState(med.TreeId)); + + // Hit #2: cumulative damage reaches snapThreshold (~98..105) -> cleanly snaps the trunk + trees.ApplyBlast(hitPoint, splashRadius: 2.5f, blastDamage: coldRecoillessDmg); + Assert.Equal(SionTreeState.Snapped, trees.GetState(med.TreeId)); + + // Repair clears accumulated damage so another single cold-start hit only chars again + trees.RepairAll(); + Assert.Equal(SionTreeState.Intact, trees.GetState(med.TreeId)); + trees.ApplyBlast(hitPoint, splashRadius: 2.5f, blastDamage: coldRecoillessDmg); + Assert.Equal(SionTreeState.Charred, trees.GetState(med.TreeId)); + } + + [Fact] + public void SionTreeDestruction_SmallArmsCannotFellOrCharMediumOakOrMonumentalSequoia() + { + var sion = SionMapLoader.Load(); + var trees = new SionTreeDestructionState(sion.Trees); + + SionTreePlacement oak = default; + SionTreePlacement sequoia = default; + bool foundOak = false, foundSequoia = false; + foreach (var t in sion.Trees.Trees) + { + if (!foundOak && t.Species == SionTreeSpecies.QuercusPubescens && t.TrunkRadiusM >= 0.32f) + { + oak = t; + foundOak = true; + } + if (!foundSequoia && t.Species == SionTreeSpecies.Sequoiadendron) + { + sequoia = t; + foundSequoia = true; + } + if (foundOak && foundSequoia) break; + } + Assert.True(foundOak && foundSequoia); + + float mgDmg = Catalog.Mg762.WeaponDamage; // 12f (< 25f) + var oakHit = new Vector3(oak.X + oak.TrunkRadiusM, oak.Y + 1.0f, oak.Z); + var seqHit = new Vector3(sequoia.X + sequoia.TrunkRadiusM, sequoia.Y + 1.0f, sequoia.Z); + + for (int i = 0; i < 30; i++) + { + trees.ApplyBlast(oakHit, splashRadius: 2.5f, blastDamage: mgDmg); + trees.ApplyBlast(seqHit, splashRadius: 2.5f, blastDamage: mgDmg); + } + + Assert.Equal(SionTreeState.Intact, trees.GetState(oak.TreeId)); + Assert.Equal(SionTreeState.Intact, trees.GetState(sequoia.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/tests/RustToDust.Tests/TerrainTests.cs b/tests/RustToDust.Tests/TerrainTests.cs index 4ba9ea8..1e17818 100644 --- a/tests/RustToDust.Tests/TerrainTests.cs +++ b/tests/RustToDust.Tests/TerrainTests.cs @@ -13,7 +13,7 @@ namespace RustToDust.Tests public void Generate_ProducesDeterministicNonFlatReliefWithinBounds() { Assert.Equal(1536f, TerrainField.ArenaSize); - Assert.Equal(8, TerrainField.TileGridCount); + Assert.Equal(8, TerrainField.DesertTileGridCount); Assert.Equal(192f, TerrainField.TileSize); Assert.Equal(-18f, TerrainField.MinWorldHeight); Assert.Equal(52f, TerrainField.MaxWorldHeight); @@ -56,7 +56,6 @@ namespace RustToDust.Tests public void StampCrater_LowersCenterRaisesRimAndDirtyOnlyOverlappingTiles() { var terrain = TerrainField.Generate(42UL, Array.Empty()); - terrain.ClearDirtyMask(); // Tile (3, 3) spans X in [-192, 0), Z in [-192, 0). // Point (-96, -96) with radius 6m is strictly inside tile (3, 3) and nowhere else. @@ -79,15 +78,15 @@ namespace RustToDust.Tests $"Expected crater ejecta rim to rise >0.2m (before {beforeRim:F2}, after {afterRim:F2})"); // Only tile (3, 3) should have incremented from version 1 to 2 - for (int tz = 0; tz < TerrainField.TileGridCount; tz++) + for (int tz = 0; tz < terrain.TileGridCount; tz++) { - for (int tx = 0; tx < TerrainField.TileGridCount; tx++) + for (int tx = 0; tx < terrain.TileGridCount; tx++) { int expected = (tx == 3 && tz == 3) ? 2 : 1; - Assert.Equal(expected, terrain.TileVersions[tx, tz]); + Assert.Equal(expected, terrain.StructuralTileVersions[tx, tz]); + Assert.Equal(expected, terrain.VisualTileVersions[tx, tz]); } } - Assert.Equal(1UL << (3 * TerrainField.TileGridCount + 3), terrain.DirtyTileMask); } [Fact] diff --git a/tests/RustToDust.Tests/VehiclePackageTests.cs b/tests/RustToDust.Tests/VehiclePackageTests.cs index 237611d..5cd85ba 100644 --- a/tests/RustToDust.Tests/VehiclePackageTests.cs +++ b/tests/RustToDust.Tests/VehiclePackageTests.cs @@ -125,7 +125,7 @@ namespace RustToDust.Tests // All 14 non-starter chassis launch in Wave 0 orbital gear pods and touch down into GroundDrops var state = new MatchState(seed: 42); - for (int t = 0; t < 300; t++) + for (int t = 0; t < 900; t++) { state.Time += 1f / 60f; state.OrbitalDrop.Step(1f / 60f); 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/build_release.ps1 b/tools/build_release.ps1 new file mode 100644 index 0000000..ff2c083 --- /dev/null +++ b/tools/build_release.ps1 @@ -0,0 +1,458 @@ +[CmdletBinding()] +param( + [string]$OutDir = "dist", + [string]$Tag = "", + [switch]$Publish, + [string]$ForgeUrl = "https://eureka.gamecult.org/forge", + [string]$Repo = "GameCult/RustToDust", + [string]$Token = "", + [string]$GodotExe = "", + [string]$YmirRoot = "", + [string]$CultLibRoot = "" +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = "Stop" + +try { + [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 +} +catch { + # Ignore on runtimes where SecurityProtocol is managed by OS +} + +$MinReleaseYmirDllBytes = 400000L +$MaxReleaseYmirDllBytes = 2000000L # Release is ~750-900 KB; Debug (with BOX3D_VALIDATE) is > 4 MB +$MinReleaseHbGpuDllBytes = 100000L +$MaxReleaseHbGpuDllBytes = 2621440L # < 2.5 MiB HarfBuzz 15.2.0 hb-gpu DLL budget + +function Resolve-RepoPath { + param([string]$PathValue, [string]$BaseDir) + if ([System.IO.Path]::IsPathRooted($PathValue)) { + return [System.IO.Path]::GetFullPath($PathValue) + } + return [System.IO.Path]::GetFullPath((Join-Path $BaseDir $PathValue)) +} + +function Resolve-DependencyRoot { + param( + [string]$Explicit, + [string]$EnvName, + [string]$SiblingName, + [string]$FallbackPath, + [string]$RepoRoot + ) + if (-not [string]::IsNullOrWhiteSpace($Explicit) -and (Test-Path $Explicit)) { + return (Resolve-Path $Explicit).Path + } + $envVal = [Environment]::GetEnvironmentVariable($EnvName) + if (-not [string]::IsNullOrWhiteSpace($envVal) -and (Test-Path $envVal)) { + return (Resolve-Path $envVal).Path + } + $sibling = Join-Path (Split-Path $RepoRoot -Parent) $SiblingName + if (Test-Path $sibling) { + return (Resolve-Path $sibling).Path + } + if (Test-Path $FallbackPath) { + return (Resolve-Path $FallbackPath).Path + } + throw "Could not locate $SiblingName root. Set -$($SiblingName)Root or `$env:$EnvName." +} + +function Resolve-GodotConsoleExe { + param([string]$Explicit) + if (-not [string]::IsNullOrWhiteSpace($Explicit)) { + if (-not (Test-Path $Explicit)) { + throw "Godot console executable not found at '$Explicit'." + } + return (Resolve-Path $Explicit).Path + } + $candidates = @( + $env:GODOT_CONSOLE_EXE, + "F:\Applications\Godot_v4.7.2-stable_mono_win64\Godot_v4.7.2-stable_mono_win64_console.exe", + "C:\Program Files\Godot\Godot_v4.7.2-stable_mono_win64_console.exe" + ) + foreach ($c in $candidates) { + if (-not [string]::IsNullOrWhiteSpace($c) -and (Test-Path $c)) { + return (Resolve-Path $c).Path + } + } + $cmd = Get-Command "Godot_v4.7.2-stable_mono_win64_console.exe" -ErrorAction SilentlyContinue + if ($cmd) { + return $cmd.Source + } + throw "Could not locate Godot_v4.7.2-stable_mono_win64_console.exe. Pass -GodotExe or set GODOT_CONSOLE_EXE." +} + +function Resolve-ForgejoToken { + param([string]$Explicit, [string]$ForgeBaseUrl) + if (-not [string]::IsNullOrWhiteSpace($Explicit)) { + return $Explicit.Trim() + } + if (-not [string]::IsNullOrWhiteSpace($env:FORGEJO_TOKEN)) { + return $env:FORGEJO_TOKEN.Trim() + } + + $eurekaTokenPath = Join-Path $env:USERPROFILE ".config\forgejo\eureka-pr-token" + if (Test-Path $eurekaTokenPath) { + $tok = (Get-Content $eurekaTokenPath -Raw).Trim() + if (-not [string]::IsNullOrWhiteSpace($tok)) { + return $tok + } + } + + $teaPaths = @( + (Join-Path $env:USERPROFILE ".config\tea\config.yml"), + (Join-Path $env:APPDATA "tea\config.yml") + ) + $forgeHost = ([Uri]$ForgeBaseUrl).Host + foreach ($teaPath in $teaPaths) { + if (Test-Path $teaPath) { + $blockUrl = "" + $blockToken = "" + foreach ($line in (Get-Content $teaPath)) { + if ($line -match "^\s*-\s+") { + if ($blockUrl -match [regex]::Escape($forgeHost) -and -not [string]::IsNullOrWhiteSpace($blockToken)) { + return $blockToken + } + $blockUrl = "" + $blockToken = "" + } + if ($line -match "url:\s*(.+)") { + $blockUrl = $Matches[1].Trim().Trim('"').Trim("'") + } + elseif ($line -match "token:\s*(.+)") { + $blockToken = $Matches[1].Trim().Trim('"').Trim("'") + } + } + if ($blockUrl -match [regex]::Escape($forgeHost) -and -not [string]::IsNullOrWhiteSpace($blockToken)) { + return $blockToken + } + } + } + + $gitCredPath = Join-Path $env:USERPROFILE ".git-credentials" + if (Test-Path $gitCredPath) { + foreach ($line in Get-Content $gitCredPath) { + if ($line -match "^https?://[^:]+:([^@]+)@$([regex]::Escape($forgeHost))") { + return [Uri]::UnescapeDataString($Matches[1]) + } + } + } + + throw "Forgejo token not found. Pass -Token, set `$env:FORGEJO_TOKEN, or store a token in ~/.config/forgejo/eureka-pr-token or ~/.config/tea/config.yml." +} + +function Copy-FilteredTree { + param( + [string]$SourceDir, + [string]$DestDir, + [string[]]$IncludeExtensions + ) + if (-not (Test-Path $SourceDir)) { + throw "Required asset source directory missing: '$SourceDir'" + } + $srcFull = (Resolve-Path $SourceDir).Path.TrimEnd('\', '/') + New-Item -ItemType Directory -Force -Path $DestDir | Out-Null + $files = Get-ChildItem -Path $srcFull -Recurse -File + $count = 0 + foreach ($file in $files) { + if ($IncludeExtensions -notcontains $file.Extension.ToLowerInvariant()) { + continue + } + $rel = $file.FullName.Substring($srcFull.Length + 1) + $target = Join-Path $DestDir $rel + $targetParent = Split-Path $target -Parent + if (-not (Test-Path $targetParent)) { + New-Item -ItemType Directory -Force -Path $targetParent | Out-Null + } + Copy-Item -Path $file.FullName -Destination $target -Force + $count++ + } + return $count +} + +function Invoke-ForgeApiJson { + param( + [string]$Method, + [string]$Url, + [string]$Token, + [object]$Body = $null + ) + $headers = @{ + "Authorization" = "token $Token" + "Accept" = "application/json" + } + $params = @{ + Method = $Method + Uri = $Url + Headers = $headers + ErrorAction = "Stop" + } + if ($null -ne $Body) { + $params["ContentType"] = "application/json" + $params["Body"] = ($Body | ConvertTo-Json -Depth 6) + } + return Invoke-RestMethod @params +} + +$RepoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path +$ClientDir = Join-Path $RepoRoot "client" +$AssetsSrcDir = Join-Path $RepoRoot "assets" + +$fullSha = (& git -C $RepoRoot rev-parse HEAD).Trim() +if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($fullSha)) { + throw "Failed to resolve git HEAD SHA." +} + +if ([string]::IsNullOrWhiteSpace($Tag)) { + $shortSha = (& git -C $RepoRoot rev-parse --short HEAD).Trim() + if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($shortSha)) { + throw "Failed to resolve git short SHA for default tag." + } + $dateStamp = (Get-Date).ToUniversalTime().ToString("yyyyMMdd") + $Tag = "rtd-$dateStamp-$shortSha" +} + +$ResolvedOutDir = Resolve-RepoPath -PathValue $OutDir -BaseDir $RepoRoot +$StageDir = Join-Path $ResolvedOutDir "stage-$Tag" +$ZipName = "RustToDust-win64-$Tag.zip" +$ZipPath = Join-Path $ResolvedOutDir $ZipName +$ShaPath = Join-Path $ResolvedOutDir "SHA256SUMS.txt" + +$YmirRoot = Resolve-DependencyRoot -Explicit $YmirRoot -EnvName "YMIR_ROOT" -SiblingName "Ymir" -FallbackPath "F:\Projects\Ymir" -RepoRoot $RepoRoot +$CultLibRoot = Resolve-DependencyRoot -Explicit $CultLibRoot -EnvName "CULTLIB_ROOT" -SiblingName "CultLib" -FallbackPath "F:\Projects\CultLib" -RepoRoot $RepoRoot +$GodotConsole = Resolve-GodotConsoleExe -Explicit $GodotExe + +$TemplateDir = Join-Path $env:APPDATA "Godot\export_templates\4.7.2.stable.mono" +if (-not (Test-Path $TemplateDir)) { + throw "Godot 4.7.2.stable.mono export templates missing at '$TemplateDir'." +} + +$env:YMIR_ROOT = $YmirRoot +$env:CULTLIB_ROOT = $CultLibRoot +$env:MSBUILDDISABLENODEREUSE = "1" +$env:DOTNET_CLI_DO_NOT_USE_MSBUILD_SERVER = "1" +$env:UseSharedCompilation = "false" + +Write-Host "=== Rust to Dust win64 Release Build ===" +Write-Host "RepoRoot : $RepoRoot" +Write-Host "Tag : $Tag" +Write-Host "YmirRoot : $YmirRoot" +Write-Host "CultLibRoot: $CultLibRoot" +Write-Host "Godot : $GodotConsole" +Write-Host "OutDir : $ResolvedOutDir" + +# Step 1: Build Release ymir_box3d.dll and verify exact Release binary size +Write-Host "`n[1/5] Building Release ymir_box3d.dll..." +$ymirProj = Join-Path $YmirRoot "src\Ymir.Box3D\Ymir.Box3D.csproj" +& dotnet build $ymirProj -c Release -p:YmirNativeConfiguration=Release --disable-build-servers -p:UseSharedCompilation=false -nr:false +if ($LASTEXITCODE -ne 0) { + throw "dotnet build Ymir.Box3D failed with exit code $LASTEXITCODE." +} + +$ymirDllPath = Join-Path $YmirRoot "artifacts\box3d-native\production\Release\bin\Release\ymir_box3d.dll" +if (-not (Test-Path $ymirDllPath)) { + throw "Release ymir_box3d.dll not found at '$ymirDllPath'." +} +$ymirDllLen = (Get-Item $ymirDllPath).Length +if ($ymirDllLen -lt $MinReleaseYmirDllBytes -or $ymirDllLen -gt $MaxReleaseYmirDllBytes) { + throw "ymir_box3d.dll size outside Release range ($MinReleaseYmirDllBytes..$MaxReleaseYmirDllBytes B; Debug is >4 MB): got $ymirDllLen bytes at '$ymirDllPath'." +} +Write-Host "Verified Release ymir_box3d.dll ($ymirDllLen B)." + +Write-Host "`n[1b/5] Building Release rtd_hbgpu.dll..." +$hbGpuProj = Join-Path $RepoRoot "src\RustToDust.HbGpu\RustToDust.HbGpu.csproj" +& dotnet build $hbGpuProj -c Release -p:HbGpuNativeConfiguration=Release --disable-build-servers -p:UseSharedCompilation=false -nr:false +if ($LASTEXITCODE -ne 0) { + throw "dotnet build RustToDust.HbGpu failed with exit code $LASTEXITCODE." +} + +$hbGpuDllPath = Join-Path $RepoRoot "artifacts\hbgpu-native\Release\bin\Release\rtd_hbgpu.dll" +if (-not (Test-Path $hbGpuDllPath)) { + throw "Release rtd_hbgpu.dll not found at '$hbGpuDllPath'." +} +$hbGpuDllLen = (Get-Item $hbGpuDllPath).Length +if ($hbGpuDllLen -lt $MinReleaseHbGpuDllBytes -or $hbGpuDllLen -gt $MaxReleaseHbGpuDllBytes) { + throw "rtd_hbgpu.dll size outside Release range ($MinReleaseHbGpuDllBytes..$MaxReleaseHbGpuDllBytes B): got $hbGpuDllLen bytes at '$hbGpuDllPath'." +} +Write-Host "Verified Release rtd_hbgpu.dll ($hbGpuDllLen B)." + +# Step 2: Export Windows Desktop Release via Godot +Write-Host "`n[2/5] Exporting Windows Desktop Release..." +if (Test-Path $StageDir) { + Remove-Item -Recurse -Force $StageDir +} +New-Item -ItemType Directory -Force -Path $StageDir | Out-Null + +$exportExePath = Join-Path $StageDir "RustToDust.exe" +$clientSlnPath = Join-Path $ClientDir "RustToDust.Client.sln" +$createdTempSln = $false + +try { + if (-not (Test-Path $clientSlnPath)) { + Write-Host "Creating temporary client/RustToDust.Client.sln for Godot export..." + & dotnet new sln -n "RustToDust.Client" -o $ClientDir --format sln | Out-Null + if ($LASTEXITCODE -ne 0) { + throw "dotnet new sln failed with exit code $LASTEXITCODE." + } + $createdTempSln = $true + & dotnet sln $clientSlnPath add (Join-Path $ClientDir "RustToDust.Client.csproj") | Out-Null + if ($LASTEXITCODE -ne 0) { + throw "dotnet sln add failed with exit code $LASTEXITCODE." + } + } + + if (-not (Test-Path (Join-Path $ClientDir ".godot"))) { + Write-Host "Bootstrapping client/.godot import cache (headless)..." + & $GodotConsole --headless --audio-driver Dummy --path $ClientDir --import --quit + if ($LASTEXITCODE -ne 0) { + throw "Godot headless --import failed with exit code $LASTEXITCODE." + } + } + + & $GodotConsole --headless --audio-driver Dummy --path $ClientDir --quit --export-release "Windows Desktop" $exportExePath + if ($LASTEXITCODE -ne 0) { + throw "Godot --export-release failed with exit code $LASTEXITCODE." + } +} +finally { + if ($createdTempSln -and (Test-Path $clientSlnPath)) { + Remove-Item -Force $clientSlnPath -ErrorAction SilentlyContinue + } +} +if (-not (Test-Path $exportExePath)) { + throw "Expected exported executable missing: '$exportExePath'." +} + +$dataDirCandidates = @( + (Join-Path $StageDir "data_RustToDust_windows_x86_64"), + (Join-Path $StageDir "data_RustToDust.Client_windows_x86_64") +) +$stagedDataDir = $dataDirCandidates | Where-Object { Test-Path $_ } | Select-Object -First 1 +if (-not $stagedDataDir) { + throw "Expected Godot Mono data directory missing under '$StageDir'." +} + +# Remove PDBs if any slipped through +Get-ChildItem -Path $StageDir -Recurse -Filter "*.pdb" -File | Remove-Item -Force + +# Step 3: Stage Release ymir_box3d.dll, rtd_hbgpu.dll, licenses & runtime assets/ +Write-Host "`n[3/5] Staging Release native DLLs, licenses, and runtime assets/..." +Copy-Item -Path $ymirDllPath -Destination (Join-Path $StageDir "ymir_box3d.dll") -Force +Copy-Item -Path $ymirDllPath -Destination (Join-Path $stagedDataDir "ymir_box3d.dll") -Force +Copy-Item -Path $hbGpuDllPath -Destination (Join-Path $StageDir "rtd_hbgpu.dll") -Force +Copy-Item -Path $hbGpuDllPath -Destination (Join-Path $stagedDataDir "rtd_hbgpu.dll") -Force + +$fontLicenseSrc = Join-Path $ClientDir "fonts\MONASPACE_LICENSE.txt" +if (-not (Test-Path $fontLicenseSrc)) { + throw "Required font license notice missing: '$fontLicenseSrc'." +} +Copy-Item -Path $fontLicenseSrc -Destination (Join-Path $StageDir "MONASPACE_LICENSE.txt") -Force + +$thirdPartySrc = Join-Path $RepoRoot "THIRD_PARTY_NOTICES.txt" +if (-not (Test-Path $thirdPartySrc)) { + throw "Required third-party notices missing: '$thirdPartySrc'." +} +Copy-Item -Path $thirdPartySrc -Destination (Join-Path $StageDir "THIRD_PARTY_NOTICES.txt") -Force + +$stagedAssetsDir = Join-Path $StageDir "assets" +$vCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "vehicles") -DestDir (Join-Path $stagedAssetsDir "vehicles") -IncludeExtensions @(".glb", ".cc", ".json") +$gCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "gear") -DestDir (Join-Path $stagedAssetsDir "gear") -IncludeExtensions @(".glb") +$dCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "decals") -DestDir (Join-Path $stagedAssetsDir "decals") -IncludeExtensions @(".png") +$aCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "audio") -DestDir (Join-Path $stagedAssetsDir "audio") -IncludeExtensions @(".wav", ".md") +$fCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "fonts") -DestDir (Join-Path $stagedAssetsDir "fonts") -IncludeExtensions @(".ttf", ".txt", ".md") +$mCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "maps\sion") -DestDir (Join-Path $stagedAssetsDir "maps\sion") -IncludeExtensions @(".json", ".u16z", ".png", ".bin", ".glb") +foreach ($reqFontFile in @("Krypton.ttf", "OFL-1.1.txt", "HARFBUZZ-COPYING.txt")) { + $reqPath = Join-Path (Join-Path $stagedAssetsDir "fonts") $reqFontFile + if (-not (Test-Path $reqPath)) { + throw "Required staged font/license file missing: '$reqPath'." + } +} +Write-Host "Staged runtime assets: vehicles=$vCount gear=$gCount decals=$dCount audio=$aCount fonts=$fCount sion=$mCount" + +# Step 4: Create ZIP and SHA256SUMS.txt +Write-Host "`n[4/5] Packaging $ZipName..." +New-Item -ItemType Directory -Force -Path $ResolvedOutDir | Out-Null +if (Test-Path $ZipPath) { + Remove-Item -Force $ZipPath +} +Add-Type -AssemblyName System.IO.Compression.FileSystem +[System.IO.Compression.ZipFile]::CreateFromDirectory($StageDir, $ZipPath, [System.IO.Compression.CompressionLevel]::Optimal, $false) + +$zipInfo = Get-Item $ZipPath +$zipHash = (Get-FileHash -Path $ZipPath -Algorithm SHA256).Hash.ToLowerInvariant() +"$zipHash $ZipName" | Set-Content -Path $ShaPath -Encoding ASCII +Write-Host "Created $ZipPath ($($zipInfo.Length) B, sha256=$zipHash)" + +# Remove intermediate stage directory so dist/ holds clean release outputs +Remove-Item -Recurse -Force $StageDir + +# Step 5: Optional Forgejo Release publish +if ($Publish) { + Write-Host "`n[5/5] Publishing release '$Tag' to $ForgeUrl ($Repo)..." + $resolvedToken = Resolve-ForgejoToken -Explicit $Token -ForgeBaseUrl $ForgeUrl + $apiBase = "$($ForgeUrl.TrimEnd('/'))/api/v1/repos/$Repo" + + $release = $null + try { + $release = Invoke-ForgeApiJson -Method "GET" -Url "$apiBase/releases/tags/$Tag" -Token $resolvedToken + Write-Host "Found existing release id=$($release.id) for tag '$Tag'." + } + catch { + $statusCode = $null + $ex = $_.Exception + if ($ex -is [System.Net.WebException] -and $ex.Response) { + $statusCode = [int]$ex.Response.StatusCode + } + elseif ($ex.PSObject.Properties['Response'] -and $ex.Response -and $ex.Response.PSObject.Properties['StatusCode']) { + $statusCode = [int]$ex.Response.StatusCode + } + if ($statusCode -ne 404) { + throw + } + } + + $releaseNotes = "Standalone Windows x64 build ($Tag). Unzip and run RustToDust.exe." + if ($null -eq $release) { + $release = Invoke-ForgeApiJson -Method "POST" -Url "$apiBase/releases" -Token $resolvedToken -Body @{ + tag_name = $Tag + target_commitish = $fullSha + name = $Tag + body = $releaseNotes + draft = $false + prerelease = $false + } + Write-Host "Created release id=$($release.id) for tag '$Tag' ($fullSha)." + } + else { + $release = Invoke-ForgeApiJson -Method "PATCH" -Url "$apiBase/releases/$($release.id)" -Token $resolvedToken -Body @{ + name = $Tag + body = $releaseNotes + draft = $false + prerelease = $false + } + } + + foreach ($assetPath in @($ZipPath, $ShaPath)) { + $assetName = [System.IO.Path]::GetFileName($assetPath) + if ($release.assets) { + foreach ($existing in $release.assets) { + if ($existing.name -eq $assetName) { + Write-Host "Removing existing release asset '$assetName' (id=$($existing.id))..." + Invoke-ForgeApiJson -Method "DELETE" -Url "$apiBase/releases/$($release.id)/assets/$($existing.id)" -Token $resolvedToken | Out-Null + } + } + } + Write-Host "Uploading '$assetName'..." + $uploadUrl = "$apiBase/releases/$($release.id)/assets?name=$([Uri]::EscapeDataString($assetName))" + & curl.exe -fsS -X POST -H "Authorization: token $resolvedToken" -F "attachment=@$assetPath" $uploadUrl | Out-Null + if ($LASTEXITCODE -ne 0) { + throw "curl.exe failed uploading '$assetName' (exit $LASTEXITCODE)." + } + } + Write-Host "Published: $($ForgeUrl.TrimEnd('/'))/$Repo/releases/tag/$Tag" +} +else { + Write-Host "`n[5/5] Skipping Forgejo publish (-Publish not set)." +} 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.py b/tools/maps/sion/bake_sion.py index ab735fa..18a2658 100644 --- a/tools/maps/sion/bake_sion.py +++ b/tools/maps/sion/bake_sion.py @@ -27,6 +27,7 @@ import struct import urllib.parse import urllib.request import zipfile +import zlib from collections import Counter, defaultdict from pathlib import Path @@ -54,12 +55,15 @@ import tifffile # --------------------------------------------------------------------------- ARENA_SIZE_M = 3072.0 HALF_EXTENT_M = 1536.0 -GRID_RES = 1025 -CELL_SIZE_M = ARENA_SIZE_M / (GRID_RES - 1) # 3.0m exact -TILE_GRID = 6 -TILE_SIZE_M = ARENA_SIZE_M / TILE_GRID # 512.0m exact +GRID_RES = 6145 +CELL_SIZE_M = ARENA_SIZE_M / (GRID_RES - 1) # 0.5m exact +TILE_GRID = 16 +TILE_SIZE_M = ARENA_SIZE_M / TILE_GRID # 192.0m exact +BUILDING_TILE_GRID = 6 +BUILDING_TILE_SIZE_M = ARENA_SIZE_M / BUILDING_TILE_GRID # 512.0m legacy until Cut 13b -SURFACE_TEX_RES = 2048 +SURFACE_TEX_RES = 4096 +SURFACE_MASK_RES = 2048 # Centered around Valere & Tourbillon twin citadels to frame: # - Valere & Tourbillon fortress hills @@ -77,8 +81,8 @@ WMS_BASE_URL = "https://wms.geo.admin.ch/" SKIRT_DEPTH_M = 4.0 MAX_LOD1_TRIS = 275_000 MAX_TILES_GLB_BYTES = 28_000_000 -MAX_SURFACE_PNG_BYTES = 3_000_000 -MAX_TOTAL_ASSETS_BYTES = 40_000_000 +MAX_SURFACE_PNG_BYTES = 14_000_000 +MAX_TOTAL_ASSETS_BYTES = 85_000_000 # --------------------------------------------------------------------------- @@ -266,7 +270,7 @@ def acquire_swisstopo_data( if (ek, nk) not in needed_tiles: continue for asset_name, asset in item.get("assets", {}).items(): - if "_2_2056_5728.tif" in asset_name: + if "_0.5_2056_5728.tif" in asset_name: prev = best_alti.get((ek, nk)) if prev is None or yr > prev[0]: best_alti[(ek, nk)] = (yr, item["id"], asset_name, asset["href"]) @@ -320,7 +324,7 @@ def acquire_swisstopo_data( def sample_mosaic_grid( mosaic: np.ndarray, e_origin: float, n_top: float, center_e: float, center_n: float, res: int ) -> np.ndarray: - pixel_m = 2.0 + pixel_m = 0.5 step_m = ARENA_SIZE_M / (res - 1) xs = -HALF_EXTENT_M + np.arange(res, dtype=np.float64) * step_m zs = -HALF_EXTENT_M + np.arange(res, dtype=np.float64) * step_m @@ -337,7 +341,7 @@ def build_heightmap( ) -> tuple[np.ndarray, np.ndarray, float, float, float]: ekms = sorted({k[0] for k in tif_paths}) nkms = sorted({k[1] for k in tif_paths}, reverse=True) # north-to-south rows - tile_px = 500 + tile_px = 2000 mosaic = np.zeros((len(nkms) * tile_px, len(ekms) * tile_px), dtype=np.float32) for ni, nk in enumerate(nkms): @@ -351,8 +355,8 @@ def build_heightmap( n_top = (nkms[0] + 1) * 1000.0 # Grid coordinates in RustToDust: - # row iz (0..1024): Z = -1536 + iz * 3.0 (North -> South), N = center_n - Z - # col ix (0..1024): X = -1536 + ix * 3.0 (West -> East), E = center_e + X + # row iz (0..6144): Z = -1536 + iz * 0.5 (North -> South), N = center_n - Z + # col ix (0..6144): X = -1536 + ix * 0.5 (West -> East), E = center_e + X hm_asl = sample_mosaic_grid(mosaic, e_origin, n_top, center_e, center_n, GRID_RES) surf_dem_asl = sample_mosaic_grid(mosaic, e_origin, n_top, center_e, center_n, SURFACE_TEX_RES) @@ -362,6 +366,37 @@ def build_heightmap( return hm_rel, surf_dem_asl, base_elev, float(hm_rel.min()), float(hm_rel.max()) +def export_heightmap_u16z(hm: np.ndarray, out_path: Path) -> tuple[float, float, str]: + """ + Export 0.5m quantized heightmap as heightmap_05m.u16z: + Header (24 bytes LE): + magic="RDHM", uint32 version=2, uint32 gridRes=6145, + float32 minY, float32 scale, uint32 rawByteCount + Payload: + zlib-compressed row-wise zig-zag int16 spatial prediction residuals of uint16[gridRes*gridRes]. + """ + min_y = float(np.float32(hm.min())) + max_y = float(np.float32(hm.max())) + scale = float(np.float32(max(1e-6, (max_y - min_y) / 65535.0))) + q = np.clip(np.round((hm.astype(np.float64) - min_y) / scale), 0, 65535).astype(np.uint16) + + pred = np.empty_like(q) + pred[0, 0] = 0 + pred[1:, 0] = q[:-1, 0] + pred[:, 1:] = q[:, :-1] + + diff = (q.astype(np.int32) - pred.astype(np.int32)).astype(np.int16) + d32 = diff.astype(np.int32) + zz = (((d32 << 1) ^ (d32 >> 15)) & 0xFFFF).astype(np.uint16) + raw_bytes = np.ascontiguousarray(zz, dtype=" dict[str, np.ndarray]: @@ -386,9 +421,18 @@ def acquire_wms_masks( print(f" [WMS fetch] {layer} -> {dest.name}") req = urllib.request.Request(url, headers={"User-Agent": "RustToDust-SionBaker/1.0"}) tmp = dest.with_suffix(".png.part") - with urllib.request.urlopen(req, timeout=45) as resp: - tmp.write_bytes(resp.read()) - tmp.replace(dest) + try: + with urllib.request.urlopen(req, timeout=45) as resp: + tmp.write_bytes(resp.read()) + tmp.replace(dest) + except Exception: + if res > 2048: + fallback = acquire_wms_masks(cache_dir, e0, n0, e1, n1, 2048) + return { + k: zoom(v, (res / v.shape[0], res / v.shape[1], 1), order=1) + for k, v in fallback.items() + } + raise out[key] = imagecodecs.png_decode(dest.read_bytes()) return out @@ -452,13 +496,10 @@ def build_terrain_surface_texture( fp_res_tris: list[np.ndarray], fp_ind_tris: list[np.ndarray], fp_fort_tris: list[np.ndarray], -) -> bytes: +) -> tuple[bytes, bytes]: """ - Synthesize 2048x2048 RGB surface albedo PNG (< 3 MB) combining: - - Grey alpine limestone cliffs (steep Valere / Tourbillon / hillside slopes) - - Valley meadows, terraced vineyards & alpine forest slopes - - Old Town stone plazas, industrial yards, rail ballast & road/bridge network - - Rhone river & canal glacial teal-blue water tint + Synthesize 4096x4096 RGB surface albedo PNG and 2048x2048 RGBA8 surface class mask PNG + (R=rock_cliff, G=grass_vineyard, B=asphalt_gravel, A=water_channel). """ res = dem_asl.shape[0] px_m = ARENA_SIZE_M / (res - 1) # 1.5m/px @@ -572,6 +613,7 @@ def build_terrain_surface_texture( water_col = np.array([0.13, 0.27, 0.34], dtype=np.float32) + (fbm[..., None] - 0.5) * 0.03 rgb = rgb * (1.0 - water_soft[..., None] * 0.96) + water_col * (water_soft[..., None] * 0.96) + road_total = np.zeros((res, res), dtype=np.float32) # 6. Roads, highway A9 & bridges (drawn after water so bridges span the Rhone!) if wms_masks and "roads" in wms_masks: r_rgba = wms_masks["roads"] @@ -586,11 +628,28 @@ def build_terrain_surface_texture( highway_col = np.array([0.25, 0.25, 0.26], dtype=np.float32) rgb = rgb * (1.0 - minor_soft[..., None] * 0.72) + street_col * (minor_soft[..., None] * 0.72) rgb = rgb * (1.0 - major_soft[..., None] * 0.88) + highway_col * (major_soft[..., None] * 0.88) + road_total = np.clip(np.maximum(minor_soft, major_soft), 0.0, 1.0) # Darken slightly under exact building footprints for subtle ambient grounding bldg_under = (mask_res | mask_ind | mask_fort) & (normal_y > 0.75) rgb[bldg_under] *= 0.88 + # Build 2048x2048 RGBA8 surface class mask: + # R = rock_cliff, G = grass_vineyard, B = asphalt_gravel, A = water_channel + water_ch = gaussian_filter(water_mask.astype(np.float32), sigma=1.0) if np.any(water_mask) else np.zeros((res, res), dtype=np.float32) + rail_ch = gaussian_filter(binary_dilation(wms_masks["rail"][..., 3] > 50, iterations=4).astype(np.float32), sigma=1.2) if (wms_masks and "rail" in wms_masks) else np.zeros((res, res), dtype=np.float32) + asphalt_gravel = np.clip(np.maximum(road_total, np.maximum(rail_ch, np.maximum(res_soft, np.maximum(ind_soft, fort_soft)))), 0.0, 1.0) + rock_cliff = np.clip(cliff_t, 0.0, 1.0) + grass_vineyard = np.clip((1.0 - rock_cliff) * (1.0 - water_ch) * (1.0 - asphalt_gravel * 0.85), 0.0, 1.0) + mask_full = np.stack([rock_cliff, grass_vineyard, asphalt_gravel, np.clip(water_ch, 0.0, 1.0)], axis=-1) + step = max(1, res // SURFACE_MASK_RES) + if step > 1: + mask_ds = mask_full.reshape(SURFACE_MASK_RES, step, SURFACE_MASK_RES, step, 4).mean(axis=(1, 3)) + else: + mask_ds = mask_full + mask_u8 = np.clip(np.round(mask_ds * 255.0), 0, 255).astype(np.uint8) + mask_png_bytes = imagecodecs.png_encode(mask_u8, level=9) + rgb_u8 = np.clip(np.round(rgb * 255.0), 0, 255).astype(np.uint8) png_bytes = imagecodecs.png_encode(rgb_u8, level=9) if len(png_bytes) >= MAX_SURFACE_PNG_BYTES: @@ -600,7 +659,7 @@ def build_terrain_surface_texture( if len(png_bytes) >= MAX_SURFACE_PNG_BYTES: rgb_u8 = (rgb_u8 & 0xFC) png_bytes = imagecodecs.png_encode(rgb_u8, level=9) - return png_bytes + return png_bytes, mask_png_bytes def sample_heightmap(hm: np.ndarray, x: np.ndarray | float, z: np.ndarray | float) -> np.ndarray | float: @@ -1715,6 +1774,7 @@ def main() -> None: parser.add_argument("--cache-dir", default=os.path.join(os.environ.get("TEMP", "/tmp"), "sion-cache")) parser.add_argument("--center-e", type=float, default=DEFAULT_CENTER_E) parser.add_argument("--center-n", type=float, default=DEFAULT_CENTER_N) + parser.add_argument("--terrain-only", action="store_true", help="Re-bake 0.5m DEM, surface, mask & metadata.json while preserving existing tiles/ & buildings_manifest.json") args = parser.parse_args() repo_root = Path(args.repo_root).resolve() @@ -1725,21 +1785,23 @@ def main() -> None: cache_dir = Path(args.cache_dir) cache_dir.mkdir(parents=True, exist_ok=True) - # Cut obsolete single-monolith GLBs & any stale tile files before baking - for obsolete in ("sion_lod2.glb", "sion_lod1.glb"): + # Cut obsolete single-monolith GLBs & legacy float32 heightmap + for obsolete in ("sion_lod2.glb", "sion_lod1.glb", "heightmap.f32"): obs_path = out_dir / obsolete if obs_path.exists(): obs_path.unlink() - print(f"[Sion Baker] Removed obsolete monolith {obs_path.name}") - for stale in tiles_dir.iterdir(): - if stale.is_file(): - stale.unlink() + print(f"[Sion Baker] Removed obsolete {obs_path.name}") + if not args.terrain_only: + for stale in tiles_dir.iterdir(): + if stale.is_file(): + stale.unlink() cE, cN = args.center_e, args.center_n e0, n0, e1, n1 = cE - HALF_EXTENT_M, cN - HALF_EXTENT_M, cE + HALF_EXTENT_M, cN + HALF_EXTENT_M print( - f"[Sion Baker] Arena {ARENA_SIZE_M:.0f}m x {ARENA_SIZE_M:.0f}m ({TILE_GRID}x{TILE_GRID} tiles of {TILE_SIZE_M:.0f}m) " + f"[Sion Baker] Arena {ARENA_SIZE_M:.0f}m x {ARENA_SIZE_M:.0f}m (terrain {TILE_GRID}x{TILE_GRID} @ {TILE_SIZE_M:.0f}m, " + f"bldg {BUILDING_TILE_GRID}x{BUILDING_TILE_GRID} @ {BUILDING_TILE_SIZE_M:.0f}m) " f"EPSG:2056 center=({cE:.1f}, {cN:.1f}) bbox=[{e0:.1f}..{e1:.1f}, {n0:.1f}..{n1:.1f}]" ) tif_paths, gdb_paths, stac_ids = acquire_swisstopo_data(cache_dir, e0, n0, e1, n1) @@ -1750,15 +1812,105 @@ def main() -> None: except Exception as exc: print(f" [WMS warning] Falling back to DEM-only river/road synthesis ({exc})") - print(f"[Sion Baker] Stitching & resampling swissALTI3D to {GRID_RES}x{GRID_RES} float32...") + print(f"[Sion Baker] Stitching & resampling swissALTI3D 0.5m to {GRID_RES}x{GRID_RES}...") hm, surf_dem_asl, base_elev, min_y, max_y = build_heightmap(tif_paths, cE, cN) - hm_path = out_dir / "heightmap.f32" - hm.astype("= MAX_TOTAL_ASSETS_BYTES: + raise RuntimeError(f"Total asset budget exceeded: {total_assets_bytes} bytes >= {MAX_TOTAL_ASSETS_BYTES}") + return + # Read semantic layers across intersecting GDB tiles print("[Sion Baker] Reading swissBUILDINGS3D 3.0 layers (Building_solid, Wall, Roof, Floor)...") reader = OgrReader() @@ -1877,8 +2029,8 @@ def main() -> None: bmax = all_rtd_pts.max(axis=0) box_center = (bmin + bmax) * 0.5 - tx = max(0, min(TILE_GRID - 1, int(math.floor((float(box_center[0]) + HALF_EXTENT_M) / TILE_SIZE_M)))) - tz = max(0, min(TILE_GRID - 1, int(math.floor((float(box_center[2]) + HALF_EXTENT_M) / TILE_SIZE_M)))) + tx = max(0, min(BUILDING_TILE_GRID - 1, int(math.floor((float(box_center[0]) + HALF_EXTENT_M) / BUILDING_TILE_SIZE_M)))) + tz = max(0, min(BUILDING_TILE_GRID - 1, int(math.floor((float(box_center[2]) + HALF_EXTENT_M) / BUILDING_TILE_SIZE_M)))) tkey = (tx, tz) tile_bldg_counts[tkey] += 1 @@ -1942,16 +2094,19 @@ def main() -> None: } ) - # Bake 2048x2048 terrain_surface.png albedo - print(f"[Sion Baker] Synthesizing {SURFACE_TEX_RES}x{SURFACE_TEX_RES} terrain_surface.png...") - surf_png = build_terrain_surface_texture( + # Bake 4096x4096 terrain_surface.png albedo + 2048x2048 terrain_surface_mask.png + print(f"[Sion Baker] Synthesizing {SURFACE_TEX_RES}x{SURFACE_TEX_RES} terrain_surface.png + {SURFACE_MASK_RES}x{SURFACE_MASK_RES} terrain_surface_mask.png...") + surf_png, mask_png = build_terrain_surface_texture( surf_dem_asl, base_elev, wms_masks, fp_res_tris, fp_ind_tris, fp_fort_tris ) surf_path = out_dir / "terrain_surface.png" surf_path.write_bytes(surf_png) + mask_path = out_dir / "terrain_surface_mask.png" + mask_path.write_bytes(mask_png) print(f" terrain_surface.png: {len(surf_png):,} bytes ({len(surf_png)/1e6:.2f} MB)") + print(f" terrain_surface_mask.png: {len(mask_png):,} bytes ({len(mask_png)/1e6:.2f} MB)") if len(surf_png) >= MAX_SURFACE_PNG_BYTES: - raise RuntimeError(f"terrain_surface.png exceeded 3 MB budget: {len(surf_png)} bytes") + raise RuntimeError(f"terrain_surface.png exceeded budget: {len(surf_png)} bytes") # Export per-tile LOD2 GLBs & RCOL v1 collision bins non_empty_tiles = sorted(tile_bldg_counts.keys()) @@ -1971,8 +2126,8 @@ def main() -> None: total_lod2_bytes += l2_bytes total_col_tris += c_tris total_col_bytes += c_bytes - tile_cx = -HALF_EXTENT_M + (tx + 0.5) * TILE_SIZE_M - tile_cz = -HALF_EXTENT_M + (tz + 0.5) * TILE_SIZE_M + tile_cx = -HALF_EXTENT_M + (tx + 0.5) * BUILDING_TILE_SIZE_M + tile_cz = -HALF_EXTENT_M + (tz + 0.5) * BUILDING_TILE_SIZE_M tile_stats[tkey] = { "tx": tx, "tz": tz, @@ -2035,8 +2190,8 @@ def main() -> None: "coordinateSystem": "rusttodust_arena_gltf", "attribution": "Federal Office of Topography swisstopo", "sizeMeters": ARENA_SIZE_M, - "tileGrid": TILE_GRID, - "tileSizeMeters": TILE_SIZE_M, + "tileGrid": BUILDING_TILE_GRID, + "tileSizeMeters": BUILDING_TILE_SIZE_M, "count": len(manifest_entries), "classes": dict(class_counts.most_common()), "buildings": manifest_entries, @@ -2048,10 +2203,11 @@ def main() -> None: "name": "Sion, Valais, Switzerland", "attribution": "Federal Office of Topography swisstopo", "sources": [ - "ch.swisstopo.swissalti3d (2m DTM, Open Government Data)", + "ch.swisstopo.swissalti3d (0.5m DTM, Open Government Data)", "ch.swisstopo.swissbuildings3d_3_0 (LOD2 3D Buildings, Open Government Data)", ], "stacItems": stac_ids, + "demAssetHash": dem_hash, "crs": "EPSG:2056", "originE": e0, "originN": n0, @@ -2064,12 +2220,20 @@ def main() -> None: "sizeMeters": ARENA_SIZE_M, "tileGrid": TILE_GRID, "tileSizeMeters": TILE_SIZE_M, + "buildingTileGrid": BUILDING_TILE_GRID, + "buildingTileSizeMeters": BUILDING_TILE_SIZE_M, "gridRes": GRID_RES, "cellSizeMeters": CELL_SIZE_M, - "heightmapFormat": "float32_le_row_major", + "heightmapFile": "heightmap_05m.u16z", + "heightmapFormat": "rdhm_v2_u16_zigzag_zlib", + "heightmapMinY": hm_min_y, + "heightmapScale": hm_scale, "surfaceTexture": "terrain_surface.png", "surfaceTextureSize": SURFACE_TEX_RES, "surfaceTextureFormat": "png_rgb_north_to_south_west_to_east", + "surfaceMaskTexture": "terrain_surface_mask.png", + "surfaceMaskTextureSize": SURFACE_MASK_RES, + "surfaceMaskFormat": "png_rgba_rock_grass_asphalt_water", "collisionFormat": { "magic": "RCOL", "version": 1, @@ -2096,7 +2260,7 @@ def main() -> None: print( f"[Sion Baker] Summary: {len(manifest_entries)} buildings across {len(non_empty_tiles)} tiles | " f"LOD1+LOD2 GLBs = {combined_glb_bytes/1e6:.2f} MB (< 28 MB limit) | " - f"Total assets/maps/sion = {total_assets_bytes/1e6:.2f} MB (< 40 MB limit)" + f"Total assets/maps/sion = {total_assets_bytes/1e6:.2f} MB (< 85 MB limit)" ) if combined_glb_bytes >= MAX_TILES_GLB_BYTES: raise RuntimeError(f"Combined tile GLB budget exceeded: {combined_glb_bytes} bytes >= {MAX_TILES_GLB_BYTES}") 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), + }