{"TotalCount":8,"Files":[{"Ident":"redsnail.grasstool","Path":"Code/GrassDefinition.cs","FileName":"GrassDefinition.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":427870,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing Sandbox;\nusing Sandbox.Rendering;\n\nnamespace RedSnail.GrassTool;\n\n/// \u003Csummary\u003E\n/// How a grass instance is turned into geometry. Both styles share the entire generation pipeline -\n/// the painted density map, the slope limit, the distance thinning and the GPU culling - and differ\n/// only in what the vertex shader builds out of each instance.\n/// \u003C/summary\u003E\npublic enum GrassStyle\n{\n\t/// \u003Csummary\u003E\n\t/// Procedural blades, bent and tapered on the GPU. Nothing to author, almost no overdraw, and\n\t/// cheap enough for millions of them - but a blade is all it can ever look like.\n\t/// \u003C/summary\u003E\n\tBlades,\n\n\t/// \u003Csummary\u003E\n\t/// Textured cards crossed through each other, cut out of a sprite sheet. Far more convincing\n\t/// for anything that is not a lawn, at the cost of real overdraw - which is why cards want a\n\t/// much shorter \u003Csee cref=\u0022GrassDefinition.MaxDistance\u0022/\u003E than blades do.\n\t/// \u003C/summary\u003E\n\tSprites,\n}\n\n/// \u003Csummary\u003E\n/// Look and behaviour of one grass layer. Shared by every \u003Csee cref=\u0022GrassRenderer\u0022/\u003E that\n/// references it, so a whole world can be retuned from a single asset.\n/// \u003C/summary\u003E\n[AssetType(Name = \u0022Grass Definition\u0022, Extension = \u0022grassdef\u0022, Category = \u0022Grass\u0022)]\npublic sealed class GrassDefinition : GameResource\n{\n\t/// \u003Csummary\u003E\n\t/// Which geometry each instance becomes. Everything below applies to both styles except the\n\t/// Sprite group, which is cards only, and Root/Tip Color, which blades only - a card takes its\n\t/// colour from the sheet.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Blade\u0022)]\n\tpublic GrassStyle Style { get; set; } = GrassStyle.Blades;\n\n\t[Property, Group(\u0022Density\u0022), Range(1, 32)]\n\tpublic int BladesPerCell { get; set; } = 8;\n\n\t/// \u003Csummary\u003EBlades stop generating past this distance from the camera.\u003C/summary\u003E\n\t[Property, Group(\u0022Density\u0022), Range(500, 60000)]\n\tpublic float MaxDistance { get; set; } = 12000.0f;\n\n\t/// \u003Csummary\u003EDistance at which blade count starts thinning out toward \u003Csee cref=\u0022MaxDistance\u0022/\u003E.\u003C/summary\u003E\n\t[Property, Group(\u0022Density\u0022), Range(0, 60000)]\n\tpublic float FadeStart { get; set; } = 4000.0f;\n\n\t/// \u003Csummary\u003EMinimum ground normal Z. Steeper cells generate nothing, so cliffs stay bare.\u003C/summary\u003E\n\t[Property, Group(\u0022Density\u0022), Range(0, 1)]\n\tpublic float SlopeLimit { get; set; } = 0.5f;\n\n\t/// \u003Csummary\u003E\n\t/// How tall, before the distance thinning scales the last one of a cell down. For a sprite\n\t/// card this is the height of the card itself - ground cards have no height, so they ignore\n\t/// this and take both of their axes from \u003Csee cref=\u0022Width\u0022/\u003E.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Blade\u0022)]\n\tpublic RangedFloat Height { get; set; } = new(16.0f, 30.0f);\n\n\t/// \u003Csummary\u003E\n\t/// How wide. The default is blade-sized: a sprite card wants this close to \u003Csee cref=\u0022Height\u0022/\u003E\n\t/// because the sprites are square, and left at a blade\u0027s width a card renders as a sliver.\n\t/// Both come from the same random roll, so a large piece of grass is large in both directions.\n\t/// A ground card is square, and this is the side of that square.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Blade\u0022)]\n\tpublic RangedFloat Width { get; set; } = new(1.5f, 2.5f);\n\n\t/// \u003Csummary\u003EHow far the blade tip leans forward at rest, as a fraction of its height.\u003C/summary\u003E\n\t[Property, Group(\u0022Blade\u0022), Range(0, 1)]\n\tpublic float Curve { get; set; } = 0.25f;\n\n\t/// \u003Csummary\u003EBlends the blade\u0027s up axis from world up (0) toward the ground normal (1).\u003C/summary\u003E\n\t[Property, Group(\u0022Blade\u0022), Range(0, 1)]\n\tpublic float AlignToGround { get; set; } = 0.35f;\n\n\t[Property, Group(\u0022Color\u0022), ShowIf(nameof(Style), GrassStyle.Blades)]\n\tpublic Color RootColor { get; set; } = new(0.11f, 0.20f, 0.06f);\n\n\t[Property, Group(\u0022Color\u0022), ShowIf(nameof(Style), GrassStyle.Blades)]\n\tpublic Color TipColor { get; set; } = new(0.42f, 0.58f, 0.18f);\n\n\t/// \u003Csummary\u003EPer-blade brightness jitter, so a field doesn\u0027t read as one flat sheet.\u003C/summary\u003E\n\t[Property, Group(\u0022Color\u0022), Range(0, 1)]\n\tpublic float ColorVariation { get; set; } = 0.25f;\n\n\t/// \u003Csummary\u003EDarkening at the blade root, faking the occlusion of a dense canopy.\u003C/summary\u003E\n\t[Property, Group(\u0022Color\u0022), Range(0, 1)]\n\tpublic float RootOcclusion { get; set; } = 0.4f;\n\n\t/// \u003Csummary\u003E\n\t/// Light bleeding through the blade from a source behind it. This is most of what sells a\n\t/// field backlit by a low sun. Fades out toward the root, where the canopy is dense.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Color\u0022), Range(0, 2)]\n\tpublic float Transmission { get; set; } = 0.5f;\n\n\t/// \u003Csummary\u003E\n\t/// Softens the lighting terminator. A blade is thin rather than solid, so a hard cutoff at\n\t/// grazing light turns a field into a mass of black edges.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Color\u0022), Range(0, 1)]\n\tpublic float Wrap { get; set; } = 0.5f;\n\n\t/// \u003Csummary\u003E\n\t/// Pushes the lighting normal toward world up. Grass lit by its true geometric normal reads\n\t/// as a mass of hard black edges; biasing up keeps a field looking like a soft surface.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Color\u0022), Range(0, 1)]\n\tpublic float NormalUpBias { get; set; } = 0.6f;\n\n\t[Property, Group(\u0022Wind\u0022)]\n\tpublic Vector2 WindDirection { get; set; } = new(1.0f, 0.35f);\n\n\t[Property, Group(\u0022Wind\u0022), Range(0, 4)]\n\tpublic float WindStrength { get; set; } = 0.35f;\n\n\t[Property, Group(\u0022Wind\u0022), Range(0, 10)]\n\tpublic float WindSpeed { get; set; } = 1.6f;\n\n\t/// \u003Csummary\u003ESpatial frequency of the travelling wind wave. Smaller values give broader gusts.\u003C/summary\u003E\n\t[Property, Group(\u0022Wind\u0022)]\n\tpublic float WindWaveScale { get; set; } = 0.0016f;\n\n\t/// \u003Csummary\u003E\n\t/// Material the cards are drawn with: one using the \u003Cc\u003Egrass_sprite\u003C/c\u003E shader, with the sprite\n\t/// sheet in its Color slot and a greyscale image of the cutout in its Alpha slot. Both are read\n\t/// as a grid of \u003Csee cref=\u0022SpriteColumns\u0022/\u003E x \u003Csee cref=\u0022SpriteRows\u0022/\u003E cells.\n\t///\n\t/// The cutout has to be its own image. Pointing the Alpha slot at an RGBA sheet reads its\n\t/// luminance rather than its alpha channel, which gives every card a solid rectangle with the\n\t/// plant cut out of it.\n\t///\n\t/// The sheet travels in a material rather than being handed to the shader directly because\n\t/// that is what the engine\u0027s texture streaming watches. A texture passed straight as a render\n\t/// attribute is invisible to it, and gets its mips evicted out from under the draw.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Sprite\u0022), ShowIf(nameof(Style), GrassStyle.Sprites)]\n\tpublic Material SpriteMaterial { get; set; }\n\n\t[Property, Group(\u0022Sprite\u0022), Range(1, 16), ShowIf(nameof(Style), GrassStyle.Sprites)]\n\tpublic int SpriteColumns { get; set; } = 4;\n\n\t[Property, Group(\u0022Sprite\u0022), Range(1, 16), ShowIf(nameof(Style), GrassStyle.Sprites)]\n\tpublic int SpriteRows { get; set; } = 4;\n\n\t/// \u003Csummary\u003E\n\t/// How many cells of the sheet to use, counted in reading order from the top left. Only applies\n\t/// when \u003Csee cref=\u0022Sprites\u0022/\u003E is empty - list cells there to pick them out individually.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Sprite\u0022), Range(1, 64), ShowIf(nameof(Style), GrassStyle.Sprites)]\n\tpublic int SpriteCount { get; set; } = 4;\n\n\t/// \u003Csummary\u003E\n\t/// Exactly which cells of the sheet this definition draws, as grid indices counting left to\n\t/// right then top to bottom from zero. Cards pick one of them at random.\n\t///\n\t/// This is what lets one sheet serve several definitions - 3, 4, 5 for the dry tufts and 7, 8,\n\t/// 10 for the green ones - instead of cutting a separate sheet per definition. Leave it empty to\n\t/// take the first \u003Csee cref=\u0022SpriteCount\u0022/\u003E cells instead, and indices the grid does not have\n\t/// are dropped rather than drawing a blank cell.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Sprite\u0022), ShowIf(nameof(Style), GrassStyle.Sprites)]\n\tpublic List\u003Cint\u003E Sprites { get; set; } = [];\n\n\t/// \u003Csummary\u003E\n\t/// Quads each card is built from, spread evenly over a half turn. Two is the classic cross and\n\t/// is almost always the right answer; three covers more viewing angles for half as much again\n\t/// in overdraw.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Sprite\u0022), Range(1, 3), ShowIf(nameof(Style), GrassStyle.Sprites)]\n\tpublic int Planes { get; set; } = 2;\n\n\t/// \u003Csummary\u003E\n\t/// Alpha below which a pixel of the sheet is thrown away. Cards are cut out rather than\n\t/// blended, which is what lets thousands of them draw in any order - the trade is that this\n\t/// threshold is a hard edge. Lower it if distant grass thins out, which is mipmapping eroding\n\t/// the alpha channel.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Sprite\u0022), Range(0, 1), ShowIf(nameof(Style), GrassStyle.Sprites)]\n\tpublic float AlphaCutoff { get; set; } = 0.35f;\n\n\t/// \u003Csummary\u003E\n\t/// How much of the far end of \u003Csee cref=\u0022MaxDistance\u0022/\u003E cards fade in over, dithered per pixel.\n\t/// This is also what hides grass streaming in, since a card entering range does so at the far\n\t/// edge where it is fully faded out. Worth a good fraction of the render distance.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Sprite\u0022), Range(0, 4000), ShowIf(nameof(Style), GrassStyle.Sprites)]\n\tpublic float CardFade { get; set; } = 800.0f;\n\n\t/// \u003Csummary\u003EMultiplies the sheet, for matching one set of sprites to a drier or greener scene.\u003C/summary\u003E\n\t[Property, Group(\u0022Sprite\u0022), ShowIf(nameof(Style), GrassStyle.Sprites)]\n\tpublic Color CardTint { get; set; } = Color.White;\n\n\t/// \u003Csummary\u003E\n\t/// Fills \u003Cparamref name=\u0022_Into\u0022/\u003E with the sheet cells a card may draw, resolving\n\t/// \u003Csee cref=\u0022Sprites\u0022/\u003E against the grid and falling back to the first \u003Csee cref=\u0022SpriteCount\u0022/\u003E\n\t/// cells when nothing usable is listed. Never comes back empty, so the generation pass always\n\t/// has something to pick from.\n\t/// \u003C/summary\u003E\n\tpublic void GetSpriteCells(List\u003Cint\u003E _Into)\n\t{\n\t\t_Into.Clear();\n\n\t\tvar cells = Math.Max(SpriteColumns, 1) * Math.Max(SpriteRows, 1);\n\n\t\tif (Sprites is not null)\n\t\t{\n\t\t\tforeach (var cell in Sprites)\n\t\t\t{\n\t\t\t\tif (cell \u003E= 0 \u0026\u0026 cell \u003C cells)\n\t\t\t\t\t_Into.Add(cell);\n\t\t\t}\n\t\t}\n\n\t\tif (_Into.Count \u003E 0)\n\t\t\treturn;\n\n\t\t// Nothing listed, or none of it resolved against the grid.\n\t\tvar count = Math.Clamp(SpriteCount, 1, cells);\n\n\t\tfor (var i = 0; i \u003C count; i\u002B\u002B)\n\t\t\t_Into.Add(i);\n\t}\n\n\t/// \u003Csummary\u003EQuads per card, clamped to what the shader\u0027s half-turn spread supports.\u003C/summary\u003E\n\tpublic int PlaneCount =\u003E Math.Clamp(Planes, 1, 3);\n\n\tpublic void ApplyTo(CommandList.AttributeAccess attributes)\n\t{\n\t\tattributes.Set(\u0022GrassBladesPerCell\u0022, BladesPerCell);\n\t\tattributes.Set(\u0022GrassMaxDistance\u0022, MaxDistance);\n\t\tattributes.Set(\u0022GrassFadeStart\u0022, MathX.Clamp(FadeStart, 0.0f, MaxDistance - 1.0f));\n\t\tattributes.Set(\u0022GrassSlopeLimit\u0022, SlopeLimit);\n\n\t\tattributes.Set(\u0022GrassBladeHeight\u0022, new Vector2(Height.Min, Height.Max));\n\t\tattributes.Set(\u0022GrassBladeWidth\u0022, new Vector2(Width.Min, Width.Max));\n\t\tattributes.Set(\u0022GrassBladeCurve\u0022, Curve);\n\t\tattributes.Set(\u0022GrassAlignToGround\u0022, AlignToGround);\n\n\t\tattributes.Set(\u0022GrassRootColor\u0022, (Vector3)RootColor);\n\t\tattributes.Set(\u0022GrassTipColor\u0022, (Vector3)TipColor);\n\t\tattributes.Set(\u0022GrassColorVariation\u0022, ColorVariation);\n\t\tattributes.Set(\u0022GrassRootOcclusion\u0022, RootOcclusion);\n\t\tattributes.Set(\u0022GrassTransmission\u0022, Transmission);\n\t\tattributes.Set(\u0022GrassWrap\u0022, Wrap);\n\t\tattributes.Set(\u0022GrassNormalUpBias\u0022, NormalUpBias);\n\n\t\tattributes.Set(\u0022GrassWindDirection\u0022, WindDirection.Normal);\n\t\tattributes.Set(\u0022GrassWindStrength\u0022, WindStrength);\n\t\tattributes.Set(\u0022GrassWindSpeed\u0022, WindSpeed);\n\t\tattributes.Set(\u0022GrassWindWaveScale\u0022, WindWaveScale);\n\n\t\tif (Style != GrassStyle.Sprites)\n\t\t\treturn;\n\n\t\tattributes.Set(\u0022GrassCardPlanes\u0022, PlaneCount);\n\t\tattributes.Set(\u0022GrassSpriteColumns\u0022, SpriteColumns);\n\t\tattributes.Set(\u0022GrassSpriteRows\u0022, SpriteRows);\n\t\tattributes.Set(\u0022GrassCardFadeRange\u0022, CardFade);\n\t\tattributes.Set(\u0022GrassAlphaCutoff\u0022, AlphaCutoff);\n\t\tattributes.Set(\u0022GrassCardTint\u0022, (Vector3)CardTint);\n\t}\n\n\tprotected override Bitmap CreateAssetTypeIcon(int _Width, int _Height)\n\t{\n\t\treturn CreateSimpleAssetTypeIcon(\u0022grass\u0022, _Width, _Height, \u0022#070f0a\u0022, \u0022#7cfba9\u0022);\n\t}\n}\n"},{"Ident":"redsnail.grasstool","Path":"GrassDefinition.cs","FileName":"GrassDefinition.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":427870,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing Sandbox;\nusing Sandbox.Rendering;\n\nnamespace RedSnail.GrassTool;\n\n/// \u003Csummary\u003E\n/// How a grass instance is turned into geometry. Both styles share the entire generation pipeline -\n/// the painted density map, the slope limit, the distance thinning and the GPU culling - and differ\n/// only in what the vertex shader builds out of each instance.\n/// \u003C/summary\u003E\npublic enum GrassStyle\n{\n\t/// \u003Csummary\u003E\n\t/// Procedural blades, bent and tapered on the GPU. Nothing to author, almost no overdraw, and\n\t/// cheap enough for millions of them - but a blade is all it can ever look like.\n\t/// \u003C/summary\u003E\n\tBlades,\n\n\t/// \u003Csummary\u003E\n\t/// Textured cards crossed through each other, cut out of a sprite sheet. Far more convincing\n\t/// for anything that is not a lawn, at the cost of real overdraw - which is why cards want a\n\t/// much shorter \u003Csee cref=\u0022GrassDefinition.MaxDistance\u0022/\u003E than blades do.\n\t/// \u003C/summary\u003E\n\tSprites,\n}\n\n/// \u003Csummary\u003E\n/// Look and behaviour of one grass layer. Shared by every \u003Csee cref=\u0022GrassRenderer\u0022/\u003E that\n/// references it, so a whole world can be retuned from a single asset.\n/// \u003C/summary\u003E\n[AssetType(Name = \u0022Grass Definition\u0022, Extension = \u0022grassdef\u0022, Category = \u0022Grass\u0022)]\npublic sealed class GrassDefinition : GameResource\n{\n\t/// \u003Csummary\u003E\n\t/// Which geometry each instance becomes. Everything below applies to both styles except the\n\t/// Sprite group, which is cards only, and Root/Tip Color, which blades only - a card takes its\n\t/// colour from the sheet.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Blade\u0022)]\n\tpublic GrassStyle Style { get; set; } = GrassStyle.Blades;\n\n\t[Property, Group(\u0022Density\u0022), Range(1, 32)]\n\tpublic int BladesPerCell { get; set; } = 8;\n\n\t/// \u003Csummary\u003EBlades stop generating past this distance from the camera.\u003C/summary\u003E\n\t[Property, Group(\u0022Density\u0022), Range(500, 60000)]\n\tpublic float MaxDistance { get; set; } = 12000.0f;\n\n\t/// \u003Csummary\u003EDistance at which blade count starts thinning out toward \u003Csee cref=\u0022MaxDistance\u0022/\u003E.\u003C/summary\u003E\n\t[Property, Group(\u0022Density\u0022), Range(0, 60000)]\n\tpublic float FadeStart { get; set; } = 4000.0f;\n\n\t/// \u003Csummary\u003EMinimum ground normal Z. Steeper cells generate nothing, so cliffs stay bare.\u003C/summary\u003E\n\t[Property, Group(\u0022Density\u0022), Range(0, 1)]\n\tpublic float SlopeLimit { get; set; } = 0.5f;\n\n\t/// \u003Csummary\u003E\n\t/// How tall, before the distance thinning scales the last one of a cell down. For a sprite\n\t/// card this is the height of the card itself - ground cards have no height, so they ignore\n\t/// this and take both of their axes from \u003Csee cref=\u0022Width\u0022/\u003E.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Blade\u0022)]\n\tpublic RangedFloat Height { get; set; } = new(16.0f, 30.0f);\n\n\t/// \u003Csummary\u003E\n\t/// How wide. The default is blade-sized: a sprite card wants this close to \u003Csee cref=\u0022Height\u0022/\u003E\n\t/// because the sprites are square, and left at a blade\u0027s width a card renders as a sliver.\n\t/// Both come from the same random roll, so a large piece of grass is large in both directions.\n\t/// A ground card is square, and this is the side of that square.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Blade\u0022)]\n\tpublic RangedFloat Width { get; set; } = new(1.5f, 2.5f);\n\n\t/// \u003Csummary\u003EHow far the blade tip leans forward at rest, as a fraction of its height.\u003C/summary\u003E\n\t[Property, Group(\u0022Blade\u0022), Range(0, 1)]\n\tpublic float Curve { get; set; } = 0.25f;\n\n\t/// \u003Csummary\u003EBlends the blade\u0027s up axis from world up (0) toward the ground normal (1).\u003C/summary\u003E\n\t[Property, Group(\u0022Blade\u0022), Range(0, 1)]\n\tpublic float AlignToGround { get; set; } = 0.35f;\n\n\t[Property, Group(\u0022Color\u0022), ShowIf(nameof(Style), GrassStyle.Blades)]\n\tpublic Color RootColor { get; set; } = new(0.11f, 0.20f, 0.06f);\n\n\t[Property, Group(\u0022Color\u0022), ShowIf(nameof(Style), GrassStyle.Blades)]\n\tpublic Color TipColor { get; set; } = new(0.42f, 0.58f, 0.18f);\n\n\t/// \u003Csummary\u003EPer-blade brightness jitter, so a field doesn\u0027t read as one flat sheet.\u003C/summary\u003E\n\t[Property, Group(\u0022Color\u0022), Range(0, 1)]\n\tpublic float ColorVariation { get; set; } = 0.25f;\n\n\t/// \u003Csummary\u003EDarkening at the blade root, faking the occlusion of a dense canopy.\u003C/summary\u003E\n\t[Property, Group(\u0022Color\u0022), Range(0, 1)]\n\tpublic float RootOcclusion { get; set; } = 0.4f;\n\n\t/// \u003Csummary\u003E\n\t/// Light bleeding through the blade from a source behind it. This is most of what sells a\n\t/// field backlit by a low sun. Fades out toward the root, where the canopy is dense.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Color\u0022), Range(0, 2)]\n\tpublic float Transmission { get; set; } = 0.5f;\n\n\t/// \u003Csummary\u003E\n\t/// Softens the lighting terminator. A blade is thin rather than solid, so a hard cutoff at\n\t/// grazing light turns a field into a mass of black edges.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Color\u0022), Range(0, 1)]\n\tpublic float Wrap { get; set; } = 0.5f;\n\n\t/// \u003Csummary\u003E\n\t/// Pushes the lighting normal toward world up. Grass lit by its true geometric normal reads\n\t/// as a mass of hard black edges; biasing up keeps a field looking like a soft surface.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Color\u0022), Range(0, 1)]\n\tpublic float NormalUpBias { get; set; } = 0.6f;\n\n\t[Property, Group(\u0022Wind\u0022)]\n\tpublic Vector2 WindDirection { get; set; } = new(1.0f, 0.35f);\n\n\t[Property, Group(\u0022Wind\u0022), Range(0, 4)]\n\tpublic float WindStrength { get; set; } = 0.35f;\n\n\t[Property, Group(\u0022Wind\u0022), Range(0, 10)]\n\tpublic float WindSpeed { get; set; } = 1.6f;\n\n\t/// \u003Csummary\u003ESpatial frequency of the travelling wind wave. Smaller values give broader gusts.\u003C/summary\u003E\n\t[Property, Group(\u0022Wind\u0022)]\n\tpublic float WindWaveScale { get; set; } = 0.0016f;\n\n\t/// \u003Csummary\u003E\n\t/// Material the cards are drawn with: one using the \u003Cc\u003Egrass_sprite\u003C/c\u003E shader, with the sprite\n\t/// sheet in its Color slot and a greyscale image of the cutout in its Alpha slot. Both are read\n\t/// as a grid of \u003Csee cref=\u0022SpriteColumns\u0022/\u003E x \u003Csee cref=\u0022SpriteRows\u0022/\u003E cells.\n\t///\n\t/// The cutout has to be its own image. Pointing the Alpha slot at an RGBA sheet reads its\n\t/// luminance rather than its alpha channel, which gives every card a solid rectangle with the\n\t/// plant cut out of it.\n\t///\n\t/// The sheet travels in a material rather than being handed to the shader directly because\n\t/// that is what the engine\u0027s texture streaming watches. A texture passed straight as a render\n\t/// attribute is invisible to it, and gets its mips evicted out from under the draw.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Sprite\u0022), ShowIf(nameof(Style), GrassStyle.Sprites)]\n\tpublic Material SpriteMaterial { get; set; }\n\n\t[Property, Group(\u0022Sprite\u0022), Range(1, 16), ShowIf(nameof(Style), GrassStyle.Sprites)]\n\tpublic int SpriteColumns { get; set; } = 4;\n\n\t[Property, Group(\u0022Sprite\u0022), Range(1, 16), ShowIf(nameof(Style), GrassStyle.Sprites)]\n\tpublic int SpriteRows { get; set; } = 4;\n\n\t/// \u003Csummary\u003E\n\t/// How many cells of the sheet to use, counted in reading order from the top left. Only applies\n\t/// when \u003Csee cref=\u0022Sprites\u0022/\u003E is empty - list cells there to pick them out individually.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Sprite\u0022), Range(1, 64), ShowIf(nameof(Style), GrassStyle.Sprites)]\n\tpublic int SpriteCount { get; set; } = 4;\n\n\t/// \u003Csummary\u003E\n\t/// Exactly which cells of the sheet this definition draws, as grid indices counting left to\n\t/// right then top to bottom from zero. Cards pick one of them at random.\n\t///\n\t/// This is what lets one sheet serve several definitions - 3, 4, 5 for the dry tufts and 7, 8,\n\t/// 10 for the green ones - instead of cutting a separate sheet per definition. Leave it empty to\n\t/// take the first \u003Csee cref=\u0022SpriteCount\u0022/\u003E cells instead, and indices the grid does not have\n\t/// are dropped rather than drawing a blank cell.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Sprite\u0022), ShowIf(nameof(Style), GrassStyle.Sprites)]\n\tpublic List\u003Cint\u003E Sprites { get; set; } = [];\n\n\t/// \u003Csummary\u003E\n\t/// Quads each card is built from, spread evenly over a half turn. Two is the classic cross and\n\t/// is almost always the right answer; three covers more viewing angles for half as much again\n\t/// in overdraw.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Sprite\u0022), Range(1, 3), ShowIf(nameof(Style), GrassStyle.Sprites)]\n\tpublic int Planes { get; set; } = 2;\n\n\t/// \u003Csummary\u003E\n\t/// Alpha below which a pixel of the sheet is thrown away. Cards are cut out rather than\n\t/// blended, which is what lets thousands of them draw in any order - the trade is that this\n\t/// threshold is a hard edge. Lower it if distant grass thins out, which is mipmapping eroding\n\t/// the alpha channel.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Sprite\u0022), Range(0, 1), ShowIf(nameof(Style), GrassStyle.Sprites)]\n\tpublic float AlphaCutoff { get; set; } = 0.35f;\n\n\t/// \u003Csummary\u003E\n\t/// How much of the far end of \u003Csee cref=\u0022MaxDistance\u0022/\u003E cards fade in over, dithered per pixel.\n\t/// This is also what hides grass streaming in, since a card entering range does so at the far\n\t/// edge where it is fully faded out. Worth a good fraction of the render distance.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Sprite\u0022), Range(0, 4000), ShowIf(nameof(Style), GrassStyle.Sprites)]\n\tpublic float CardFade { get; set; } = 800.0f;\n\n\t/// \u003Csummary\u003EMultiplies the sheet, for matching one set of sprites to a drier or greener scene.\u003C/summary\u003E\n\t[Property, Group(\u0022Sprite\u0022), ShowIf(nameof(Style), GrassStyle.Sprites)]\n\tpublic Color CardTint { get; set; } = Color.White;\n\n\t/// \u003Csummary\u003E\n\t/// Fills \u003Cparamref name=\u0022_Into\u0022/\u003E with the sheet cells a card may draw, resolving\n\t/// \u003Csee cref=\u0022Sprites\u0022/\u003E against the grid and falling back to the first \u003Csee cref=\u0022SpriteCount\u0022/\u003E\n\t/// cells when nothing usable is listed. Never comes back empty, so the generation pass always\n\t/// has something to pick from.\n\t/// \u003C/summary\u003E\n\tpublic void GetSpriteCells(List\u003Cint\u003E _Into)\n\t{\n\t\t_Into.Clear();\n\n\t\tvar cells = Math.Max(SpriteColumns, 1) * Math.Max(SpriteRows, 1);\n\n\t\tif (Sprites is not null)\n\t\t{\n\t\t\tforeach (var cell in Sprites)\n\t\t\t{\n\t\t\t\tif (cell \u003E= 0 \u0026\u0026 cell \u003C cells)\n\t\t\t\t\t_Into.Add(cell);\n\t\t\t}\n\t\t}\n\n\t\tif (_Into.Count \u003E 0)\n\t\t\treturn;\n\n\t\t// Nothing listed, or none of it resolved against the grid.\n\t\tvar count = Math.Clamp(SpriteCount, 1, cells);\n\n\t\tfor (var i = 0; i \u003C count; i\u002B\u002B)\n\t\t\t_Into.Add(i);\n\t}\n\n\t/// \u003Csummary\u003EQuads per card, clamped to what the shader\u0027s half-turn spread supports.\u003C/summary\u003E\n\tpublic int PlaneCount =\u003E Math.Clamp(Planes, 1, 3);\n\n\tpublic void ApplyTo(CommandList.AttributeAccess attributes)\n\t{\n\t\tattributes.Set(\u0022GrassBladesPerCell\u0022, BladesPerCell);\n\t\tattributes.Set(\u0022GrassMaxDistance\u0022, MaxDistance);\n\t\tattributes.Set(\u0022GrassFadeStart\u0022, MathX.Clamp(FadeStart, 0.0f, MaxDistance - 1.0f));\n\t\tattributes.Set(\u0022GrassSlopeLimit\u0022, SlopeLimit);\n\n\t\tattributes.Set(\u0022GrassBladeHeight\u0022, new Vector2(Height.Min, Height.Max));\n\t\tattributes.Set(\u0022GrassBladeWidth\u0022, new Vector2(Width.Min, Width.Max));\n\t\tattributes.Set(\u0022GrassBladeCurve\u0022, Curve);\n\t\tattributes.Set(\u0022GrassAlignToGround\u0022, AlignToGround);\n\n\t\tattributes.Set(\u0022GrassRootColor\u0022, (Vector3)RootColor);\n\t\tattributes.Set(\u0022GrassTipColor\u0022, (Vector3)TipColor);\n\t\tattributes.Set(\u0022GrassColorVariation\u0022, ColorVariation);\n\t\tattributes.Set(\u0022GrassRootOcclusion\u0022, RootOcclusion);\n\t\tattributes.Set(\u0022GrassTransmission\u0022, Transmission);\n\t\tattributes.Set(\u0022GrassWrap\u0022, Wrap);\n\t\tattributes.Set(\u0022GrassNormalUpBias\u0022, NormalUpBias);\n\n\t\tattributes.Set(\u0022GrassWindDirection\u0022, WindDirection.Normal);\n\t\tattributes.Set(\u0022GrassWindStrength\u0022, WindStrength);\n\t\tattributes.Set(\u0022GrassWindSpeed\u0022, WindSpeed);\n\t\tattributes.Set(\u0022GrassWindWaveScale\u0022, WindWaveScale);\n\n\t\tif (Style != GrassStyle.Sprites)\n\t\t\treturn;\n\n\t\tattributes.Set(\u0022GrassCardPlanes\u0022, PlaneCount);\n\t\tattributes.Set(\u0022GrassSpriteColumns\u0022, SpriteColumns);\n\t\tattributes.Set(\u0022GrassSpriteRows\u0022, SpriteRows);\n\t\tattributes.Set(\u0022GrassCardFadeRange\u0022, CardFade);\n\t\tattributes.Set(\u0022GrassAlphaCutoff\u0022, AlphaCutoff);\n\t\tattributes.Set(\u0022GrassCardTint\u0022, (Vector3)CardTint);\n\t}\n\n\tprotected override Bitmap CreateAssetTypeIcon(int _Width, int _Height)\n\t{\n\t\treturn CreateSimpleAssetTypeIcon(\u0022grass\u0022, _Width, _Height, \u0022#070f0a\u0022, \u0022#7cfba9\u0022);\n\t}\n}\n"},{"Ident":"redsnail.grasstool","Path":"GrassStorage.cs","FileName":"GrassStorage.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":427870,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.InteropServices;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.GrassTool;\r\n\r\n/// \u003Csummary\u003E\r\n/// Sparse painted grass coverage, stored as a chunked grid of density samples rather than\r\n/// individual blade transforms. Blades are generated procedurally on the GPU from this data,\r\n/// so a square kilometre of dense grass costs a few megabytes instead of hundreds.\r\n/// \u003C/summary\u003E\r\npublic sealed class GrassStorage : BlobData\r\n{\r\n\t// 2: cells are stored sparsely per chunk. See Serialize.\r\n\tpublic override int Version =\u003E 2;\r\n\r\n\t/// \u003Csummary\u003ECells along one edge of a chunk.\u003C/summary\u003E\r\n\tpublic const int ChunkResolution = 64;\r\n\r\n\t/// \u003Csummary\u003EWorld-space size of a single density cell, in source units.\u003C/summary\u003E\r\n\tpublic const float CellSize = 32.0f;\r\n\r\n\t/// \u003Csummary\u003EWorld-space size of a chunk edge, in source units.\u003C/summary\u003E\r\n\tpublic const float ChunkSize = ChunkResolution * CellSize;\r\n\r\n\tpublic const int CellsPerChunk = ChunkResolution * ChunkResolution;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// One density sample. Height and normal are baked when painting so grass sits on any\r\n\t/// geometry, not just terrain. Matches the HLSL \u003Cc\u003EGrassCell\u003C/c\u003E struct exactly.\r\n\t/// \u003C/summary\u003E\r\n\t[StructLayout(LayoutKind.Sequential)]\r\n\tpublic struct Cell\r\n\t{\r\n\t\tpublic float Height;\r\n\r\n\t\t/// \u003Csummary\u003Edensity (0-7) | normal.x (8-15) | normal.y (16-23) | unused (24-31)\u003C/summary\u003E\r\n\t\tpublic uint Packed;\r\n\r\n\t\tpublic readonly float Density =\u003E (Packed \u0026 0xFF) / 255.0f;\r\n\r\n\t\tpublic readonly Vector3 Normal\r\n\t\t{\r\n\t\t\tget\r\n\t\t\t{\r\n\t\t\t\tvar x = ((Packed \u003E\u003E 8) \u0026 0xFF) / 127.5f - 1.0f;\r\n\t\t\t\tvar y = ((Packed \u003E\u003E 16) \u0026 0xFF) / 127.5f - 1.0f;\r\n\t\t\t\tvar z = MathF.Sqrt(Math.Clamp(1.0f - x * x - y * y, 0.0f, 1.0f));\r\n\t\t\t\treturn new Vector3(x, y, z);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static uint Pack(float density, Vector3 normal)\r\n\t\t{\r\n\t\t\tvar d = (uint)Math.Clamp(density * 255.0f \u002B 0.5f, 0.0f, 255.0f);\r\n\t\t\tvar nx = (uint)Math.Clamp((normal.x \u002B 1.0f) * 127.5f \u002B 0.5f, 0.0f, 255.0f);\r\n\t\t\tvar ny = (uint)Math.Clamp((normal.y \u002B 1.0f) * 127.5f \u002B 0.5f, 0.0f, 255.0f);\r\n\t\t\treturn d | (nx \u003C\u003C 8) | (ny \u003C\u003C 16);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic readonly record struct ChunkCoord(int X, int Y);\r\n\r\n\tprivate readonly Dictionary\u003CChunkCoord, Cell[]\u003E _chunks = [];\r\n\r\n\t/// \u003Csummary\u003EBumped on every mutation so the renderer knows to re-upload its GPU buffers.\u003C/summary\u003E\r\n\tpublic int Revision { get; private set; }\r\n\r\n\tpublic int ChunkCount =\u003E _chunks.Count;\r\n\r\n\tpublic IReadOnlyDictionary\u003CChunkCoord, Cell[]\u003E Chunks =\u003E _chunks;\r\n\r\n\tpublic static ChunkCoord WorldToChunk(Vector3 world) =\u003E new(\r\n\t\t(int)MathF.Floor(world.x / ChunkSize),\r\n\t\t(int)MathF.Floor(world.y / ChunkSize));\r\n\r\n\tpublic static Vector2 ChunkOrigin(ChunkCoord coord) =\u003E new(coord.X * ChunkSize, coord.Y * ChunkSize);\r\n\r\n\t/// \u003Csummary\u003EGlobal cell index on an axis. Negative world positions floor correctly.\u003C/summary\u003E\r\n\tprivate static int WorldToCell(float world) =\u003E (int)MathF.Floor(world / CellSize);\r\n\r\n\tprivate static int FloorDiv(int a, int b) =\u003E a \u003E= 0 ? a / b : ~(~a / b);\r\n\r\n\tprivate static int Mod(int a, int b)\r\n\t{\r\n\t\tvar r = a % b;\r\n\t\treturn r \u003C 0 ? r \u002B b : r;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Writes a density sample at a world position, baking the surface height and normal alongside it.\r\n\t/// Density of zero frees the sample.\r\n\t/// \u003C/summary\u003E\r\n\tpublic void SetCell(float worldX, float worldY, float density, float height, Vector3 normal)\r\n\t{\r\n\t\tvar cellX = WorldToCell(worldX);\r\n\t\tvar cellY = WorldToCell(worldY);\r\n\t\tvar coord = new ChunkCoord(FloorDiv(cellX, ChunkResolution), FloorDiv(cellY, ChunkResolution));\r\n\r\n\t\tif (!_chunks.TryGetValue(coord, out var cells))\r\n\t\t{\r\n\t\t\tif (density \u003C= 0.0f) return;\r\n\r\n\t\t\tcells = new Cell[CellsPerChunk];\r\n\t\t\t_chunks[coord] = cells;\r\n\t\t}\r\n\r\n\t\tvar index = Mod(cellY, ChunkResolution) * ChunkResolution \u002B Mod(cellX, ChunkResolution);\r\n\t\tcells[index] = new Cell { Height = height, Packed = Cell.Pack(density, normal) };\r\n\t\tRevision\u002B\u002B;\r\n\t}\r\n\r\n\tpublic Cell GetCell(float worldX, float worldY)\r\n\t{\r\n\t\tvar cellX = WorldToCell(worldX);\r\n\t\tvar cellY = WorldToCell(worldY);\r\n\t\tvar coord = new ChunkCoord(FloorDiv(cellX, ChunkResolution), FloorDiv(cellY, ChunkResolution));\r\n\r\n\t\tif (!_chunks.TryGetValue(coord, out var cells))\r\n\t\t\treturn default;\r\n\r\n\t\treturn cells[Mod(cellY, ChunkResolution) * ChunkResolution \u002B Mod(cellX, ChunkResolution)];\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Reduces density in a radius, removing samples that reach zero.\r\n\t/// \u003C/summary\u003E\r\n\tpublic void Erase(Vector3 center, float radius, float strength)\r\n\t{\r\n\t\tvar radiusSq = radius * radius;\r\n\t\tvar minCellX = WorldToCell(center.x - radius);\r\n\t\tvar maxCellX = WorldToCell(center.x \u002B radius);\r\n\t\tvar minCellY = WorldToCell(center.y - radius);\r\n\t\tvar maxCellY = WorldToCell(center.y \u002B radius);\r\n\r\n\t\tfor (var cy = minCellY; cy \u003C= maxCellY; cy\u002B\u002B)\r\n\t\t{\r\n\t\t\tfor (var cx = minCellX; cx \u003C= maxCellX; cx\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tvar coord = new ChunkCoord(FloorDiv(cx, ChunkResolution), FloorDiv(cy, ChunkResolution));\r\n\t\t\t\tif (!_chunks.TryGetValue(coord, out var cells))\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tvar wx = (cx \u002B 0.5f) * CellSize;\r\n\t\t\t\tvar wy = (cy \u002B 0.5f) * CellSize;\r\n\t\t\t\tvar dx = wx - center.x;\r\n\t\t\t\tvar dy = wy - center.y;\r\n\t\t\t\tif (dx * dx \u002B dy * dy \u003E radiusSq)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tvar index = Mod(cy, ChunkResolution) * ChunkResolution \u002B Mod(cx, ChunkResolution);\r\n\t\t\t\tref var cell = ref cells[index];\r\n\t\t\t\tif ((cell.Packed \u0026 0xFF) == 0)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tvar density = Math.Max(cell.Density - strength, 0.0f);\r\n\t\t\t\tcell.Packed = density \u003C= 0.0f ? 0u : Cell.Pack(density, cell.Normal);\r\n\t\t\t\tRevision\u002B\u002B;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tPruneEmptyChunks();\r\n\t}\r\n\r\n\tpublic void ClearAll()\r\n\t{\r\n\t\tif (_chunks.Count == 0) return;\r\n\r\n\t\t_chunks.Clear();\r\n\t\tRevision\u002B\u002B;\r\n\t}\r\n\r\n\tprivate void PruneEmptyChunks()\r\n\t{\r\n\t\tList\u003CChunkCoord\u003E empty = null;\r\n\r\n\t\tforeach (var (coord, cells) in _chunks)\r\n\t\t{\r\n\t\t\tvar used = false;\r\n\t\t\tfor (var i = 0; i \u003C cells.Length; i\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tif ((cells[i].Packed \u0026 0xFF) != 0) { used = true; break; }\r\n\t\t\t}\r\n\r\n\t\t\tif (!used)\r\n\t\t\t{\r\n\t\t\t\tempty ??= [];\r\n\t\t\t\tempty.Add(coord);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (empty is null) return;\r\n\r\n\t\tforeach (var coord in empty)\r\n\t\t\t_chunks.Remove(coord);\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Writes only the painted cells. A chunk is 4096 cells at 8 bytes each, so storing them densely\r\n\t/// cost 32KB per chunk however little of it was painted - a thin brush stroke across a landscape\r\n\t/// touches a lot of chunks and paid full price for every one.\r\n\t///\r\n\t/// Each painted cell costs 2 bytes more than it did dense (its index), so a chunk past about 80%\r\n\t/// coverage is cheaper stored densely. Both layouts are written and each chunk says which it used.\r\n\t/// \u003C/summary\u003E\r\n\tpublic override void Serialize(ref Writer writer)\r\n\t{\r\n\t\twriter.Stream.Write(_chunks.Count);\r\n\r\n\t\tforeach (var (coord, cells) in _chunks)\r\n\t\t{\r\n\t\t\twriter.Stream.Write(coord.X);\r\n\t\t\twriter.Stream.Write(coord.Y);\r\n\r\n\t\t\tvar painted = 0;\r\n\t\t\tfor (var i = 0; i \u003C CellsPerChunk; i\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tif ((cells[i].Packed \u0026 0xFF) != 0) painted\u002B\u002B;\r\n\t\t\t}\r\n\r\n\t\t\tvar sparse = painted * 10 \u003C CellsPerChunk * 8;\r\n\t\t\twriter.Stream.Write(sparse);\r\n\r\n\t\t\tif (!sparse)\r\n\t\t\t{\r\n\t\t\t\tfor (var i = 0; i \u003C CellsPerChunk; i\u002B\u002B)\r\n\t\t\t\t{\r\n\t\t\t\t\twriter.Stream.Write(cells[i].Height);\r\n\t\t\t\t\twriter.Stream.Write(cells[i].Packed);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\twriter.Stream.Write(painted);\r\n\r\n\t\t\tfor (var i = 0; i \u003C CellsPerChunk; i\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tif ((cells[i].Packed \u0026 0xFF) == 0)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\twriter.Stream.Write((ushort)i);\r\n\t\t\t\twriter.Stream.Write(cells[i].Height);\r\n\t\t\t\twriter.Stream.Write(cells[i].Packed);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tpublic override void Deserialize(ref Reader reader)\r\n\t{\r\n\t\t_chunks.Clear();\r\n\r\n\t\tvar chunkCount = reader.Stream.Read\u003Cint\u003E();\r\n\r\n\t\tfor (var c = 0; c \u003C chunkCount; c\u002B\u002B)\r\n\t\t{\r\n\t\t\tvar coord = new ChunkCoord(reader.Stream.Read\u003Cint\u003E(), reader.Stream.Read\u003Cint\u003E());\r\n\t\t\tvar cells = new Cell[CellsPerChunk];\r\n\r\n\t\t\tif (reader.Stream.Read\u003Cbool\u003E())\r\n\t\t\t{\r\n\t\t\t\tvar painted = reader.Stream.Read\u003Cint\u003E();\r\n\r\n\t\t\t\tfor (var p = 0; p \u003C painted; p\u002B\u002B)\r\n\t\t\t\t{\r\n\t\t\t\t\tvar index = reader.Stream.Read\u003Cushort\u003E();\r\n\t\t\t\t\tvar height = reader.Stream.Read\u003Cfloat\u003E();\r\n\t\t\t\t\tvar packed = reader.Stream.Read\u003Cuint\u003E();\r\n\r\n\t\t\t\t\tif (index \u003C CellsPerChunk)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcells[index].Height = height;\r\n\t\t\t\t\t\tcells[index].Packed = packed;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tfor (var i = 0; i \u003C CellsPerChunk; i\u002B\u002B)\r\n\t\t\t\t{\r\n\t\t\t\t\tcells[i].Height = reader.Stream.Read\u003Cfloat\u003E();\r\n\t\t\t\t\tcells[i].Packed = reader.Stream.Read\u003Cuint\u003E();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t_chunks[coord] = cells;\r\n\t\t}\r\n\r\n\t\tRevision\u002B\u002B;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Version 1 wrote every cell of every chunk with no sparse/dense flag. Read it in that layout so\r\n\t/// scenes painted before the change still load.\r\n\t/// \u003C/summary\u003E\r\n\tpublic override void Upgrade(ref Reader reader, int fromVersion)\r\n\t{\r\n\t\tif (fromVersion != 1)\r\n\t\t{\r\n\t\t\tDeserialize(ref reader);\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t_chunks.Clear();\r\n\r\n\t\tvar chunkCount = reader.Stream.Read\u003Cint\u003E();\r\n\r\n\t\tfor (var c = 0; c \u003C chunkCount; c\u002B\u002B)\r\n\t\t{\r\n\t\t\tvar coord = new ChunkCoord(reader.Stream.Read\u003Cint\u003E(), reader.Stream.Read\u003Cint\u003E());\r\n\t\t\tvar cells = new Cell[CellsPerChunk];\r\n\r\n\t\t\tfor (var i = 0; i \u003C CellsPerChunk; i\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tcells[i].Height = reader.Stream.Read\u003Cfloat\u003E();\r\n\t\t\t\tcells[i].Packed = reader.Stream.Read\u003Cuint\u003E();\r\n\t\t\t}\r\n\r\n\t\t\t_chunks[coord] = cells;\r\n\t\t}\r\n\r\n\t\tRevision\u002B\u002B;\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.grasstool","Path":"Code/GrassRenderer.cs","FileName":"GrassRenderer.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":427870,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing Sandbox;\nusing Sandbox.Rendering;\nusing RenderStage = Sandbox.Rendering.Stage;\n\nnamespace RedSnail.GrassTool;\n\n/// \u003Csummary\u003E\n/// One kind of grass on a renderer: what it looks like, and where it has been painted. Layers are\n/// painted independently and overlap freely, so ground cover can sit under tall grass rather than\n/// competing with it for the same cells.\n/// \u003C/summary\u003E\npublic sealed class GrassLayer\n{\n\t/// \u003Csummary\u003EWhat the brush calls this layer. Only ever shown in the editor.\u003C/summary\u003E\n\t[Property]\n\tpublic string Name { get; set; } = \u0022Grass\u0022;\n\n\t[Property]\n\tpublic GrassDefinition Definition { get; set; }\n\n\t/// \u003Csummary\u003EStops the layer drawing without throwing away what has been painted into it.\u003C/summary\u003E\n\t[Property]\n\tpublic bool Enabled { get; set; } = true;\n\n\t/// \u003Csummary\u003E\n\t/// Decorrelates this layer\u0027s placement from the others. Every random choice a cell makes -\n\t/// where its grass sits, which way it faces, how big it is, which sprite it takes - comes from\n\t/// hashing the cell\u0027s position, so two layers painted over the same ground with the same seed\n\t/// put their grass in exactly the same spots.\n\t///\n\t/// A new layer picks a random one, which is almost always what you want. Set two layers to the\n\t/// same seed deliberately and they will line up, which is occasionally useful - flowers that\n\t/// always sit in the same tufts as the grass, say.\n\t/// \u003C/summary\u003E\n\t[Property]\n\tpublic int Seed { get; set; } = 0;\n\n\t/// \u003Csummary\u003EPainted coverage. Serialized as a binary blob, not JSON.\u003C/summary\u003E\n\t[Property, Hide]\n\tpublic GrassStorage Storage { get; set; } = new();\n\n\t[Hide] public string DisplayName =\u003E string.IsNullOrWhiteSpace(Name) ? \u0022Unnamed\u0022 : Name;\n}\n\n/// \u003Csummary\u003E\n/// Renders painted grass. Each frame a compute pass expands the density map into instances for\n/// whatever is near the camera, then one indirect draw renders them. No blade ever exists on the\n/// CPU, and nothing is stored per-blade in the scene.\n///\n/// A renderer holds any number of \u003Csee cref=\u0022GrassLayer\u0022/\u003Es - tall grass, ground cover, whatever -\n/// each with its own definition, material and painted coverage. They share one instance buffer and\n/// run one after another, so adding a layer costs a dispatch and a draw rather than a second\n/// allocation of the whole budget.\n/// \u003C/summary\u003E\n[Icon(\u0022grass\u0022), Group(\u0022Grass\u0022), Title(\u0022Grass Renderer\u0022)]\npublic sealed class GrassRenderer : Component, Component.ExecuteInEditor, Component.DontExecuteOnServer\n{\n\t/// \u003Csummary\u003E\n\t/// Lets a game steer the grass from its own code, without changing this library: implement it on\n\t/// any component in the same scene as the renderer.\n\t/// \u003C/summary\u003E\n\tpublic interface IEvents : ISceneEvent\u003CIEvents\u003E\n\t{\n\t\t/// \u003Csummary\u003E\n\t\t/// Asked every frame for each layer about to draw. Scale \u003Cparamref name=\u0022size\u0022/\u003E to shrink the\n\t\t/// layer\u0027s grass - height and width together, blades and cards alike - or to grow it. It\n\t\t/// starts at 1, which draws the grass as painted; at 0 the layer is skipped outright, with no\n\t\t/// generation pass and no draw, so grass that is meant to be gone costs nothing. With several\n\t\t/// listeners, each one gets the value the previous one left, so multiplying keeps them all.\n\t\t///\n\t\t/// Snow is the case it was made for: shrink the grass as the snow deepens, and at full depth\n\t\t/// it is buried and stops drawing at all.\n\t\t/// \u003C/summary\u003E\n\t\tvoid OnGrassSize(GrassRenderer renderer, GrassLayer layer, ref float size) { }\n\t}\n\n\t[StructLayout(LayoutKind.Sequential)]\n\tprivate struct GpuChunk\n\t{\n\t\tpublic Vector2 Origin;\n\t\tpublic int CellOffset;\n\t\tpublic int Pad;\n\t}\n\n\t[StructLayout(LayoutKind.Sequential)]\n\tprivate struct GpuBlade\n\t{\n\t\tpublic Vector3 Position;\n\t\tpublic float Yaw;\n\t\tpublic Vector3 Normal;\n\t\tpublic float Height;\n\t\tpublic float Width;\n\t\tpublic float Tint;\n\t\tpublic float Phase;\n\n\t\t// Which sprite of the sheet a card draws. Unused by blades, and it occupies what was\n\t\t// padding, so the struct stays at 48 bytes either way.\n\t\tpublic float Variant;\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// The GPU side of one layer. Chunks and cells are its own painted data; the args buffer is its\n\t/// own because the vertex count per instance follows the layer\u0027s style. Everything else - the\n\t/// instance buffer, the frustum, the camera - is shared across layers.\n\t/// \u003C/summary\u003E\n\tprivate sealed class LayerState\n\t{\n\t\tpublic GrassLayer Source;\n\n\t\tpublic GpuBuffer\u003CGpuChunk\u003E ChunkBuffer;\n\t\tpublic GpuBuffer\u003CGrassStorage.Cell\u003E CellBuffer;\n\t\tpublic GpuBuffer\u003Cint\u003E VisibleChunkBuffer;\n\t\tpublic GpuBuffer\u003CGpuBuffer.IndirectDrawArguments\u003E ArgsBuffer;\n\n\t\t// Which cells of the sheet this layer draws from. Uploaded as a table the generation pass\n\t\t// indexes, so picking a sprite is one lookup whatever the selection looks like.\n\t\tpublic GpuBuffer\u003Cint\u003E SpriteBuffer;\n\t\tpublic readonly List\u003Cint\u003E UploadedSprites = [];\n\n\t\tpublic readonly List\u003CVector2\u003E ChunkOrigins = [];\n\t\tpublic int[] VisibleScratch = [];\n\n\t\tpublic int ChunkCount;\n\t\tpublic int UploadedVersion = -1;\n\t\tpublic int UploadedVertexCount = -1;\n\t\tpublic bool WarnedAboutMaterial;\n\n\t\tpublic void Release()\n\t\t{\n\t\t\tChunkBuffer?.Dispose();\n\t\t\tChunkBuffer = null;\n\n\t\t\tCellBuffer?.Dispose();\n\t\t\tCellBuffer = null;\n\n\t\t\tVisibleChunkBuffer?.Dispose();\n\t\t\tVisibleChunkBuffer = null;\n\n\t\t\tArgsBuffer?.Dispose();\n\t\t\tArgsBuffer = null;\n\n\t\t\tSpriteBuffer?.Dispose();\n\t\t\tSpriteBuffer = null;\n\t\t\tUploadedSprites.Clear();\n\n\t\t\tChunkOrigins.Clear();\n\t\t\tChunkCount = 0;\n\t\t\tUploadedVersion = -1;\n\t\t\tUploadedVertexCount = -1;\n\t\t}\n\t}\n\n\t// Must match GRASS_BLADE_* and GRASS_CARD_* in grass_shared.fxc.\n\tprivate const int BladeStripVerts = 7;\n\tprivate const int BladeVertexCount = (BladeStripVerts - 2) * 3;\n\tprivate const int CardPlaneVertexCount = 6;\n\n\t// Byte offset of InstanceCount within IndirectDrawArguments. The struct is sequential\n\t// { uint VertexCount; uint InstanceCount; uint FirstVertex; uint FirstInstance; }, so this is\n\t// fixed at 4. Marshal.OffsetOf would express it directly but is outside the sandbox whitelist.\n\tprivate const int ArgsInstanceCountOffset = 4;\n\n\t/// \u003Csummary\u003E\n\t/// The kinds of grass this renderer draws. The brush paints whichever one is picked in the Grass\n\t/// tool\u0027s sidebar, so each layer keeps its own coverage and they can overlap.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Layers\u0022)]\n\tpublic List\u003CGrassLayer\u003E Layers { get; set; } = [new GrassLayer()];\n\n\t/// \u003Csummary\u003E\n\t/// How many instances the buffer has room for, at 48 bytes each - so a million is ~48 MB. Every\n\t/// layer draws out of this one buffer, so it has to fit the largest single layer, not their sum.\n\t///\n\t/// This is capacity, not a budget: how much grass there is, is decided by the render distance\n\t/// and the density, and this only needs to be big enough to hold the result. Set it too low and\n\t/// the generation overruns it, at which point which grass gets a slot is settled by whichever\n\t/// GPU thread reaches the counter first - an order that changes every frame, so patches flicker\n\t/// in and out - which is the symptom to recognise if grass ever starts churning at distance.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022General\u0022), Range(50000, 8000000), Alias(\u0022MaxBlades\u0022)]\n\tpublic int MaxGrassObjects { get; set; } = 1000000;\n\n\t/// \u003Csummary\u003E\n\t/// How far outside the camera frustum grass is still generated, in world units. Culling is\n\t/// done against the frustum as it was when the frame started, so turning the camera brings in\n\t/// grass that was never generated. Raise this if it visibly streams in at the screen edges,\n\t/// which is most obvious at low or capped framerates.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022General\u0022), Range(0, 4000)]\n\tpublic float CullPadding { get; set; } = 1000.0f;\n\n\t/// \u003Csummary\u003E\n\t/// Where a renderer kept its definition before it had layers. Still deserialized so that scenes\n\t/// built before the change migrate into the first layer instead of coming back empty.\n\t/// \u003C/summary\u003E\n\t[Property, Hide]\n\tpublic GrassDefinition Definition { get; set; }\n\n\t/// \u003Csummary\u003EPainted coverage from before layers. Migrated into the first layer on load.\u003C/summary\u003E\n\t[Property, Hide]\n\tpublic GrassStorage Storage { get; set; }\n\n\tprivate ComputeShader _generateShader;\n\tprivate Material _bladeMaterial;\n\tprivate CommandList _commandList;\n\n\tprivate GpuBuffer\u003CVector4\u003E _frustumPlaneBuffer;\n\tprivate GpuBuffer\u003CGpuBlade\u003E _bladeBuffer;\n\n\tprivate readonly List\u003CLayerState\u003E _layerStates = [];\n\tprivate readonly List\u003Cint\u003E _spriteScratch = [];\n\tprivate readonly Vector4[] _planeScratch = new Vector4[6];\n\n\tprivate CameraComponent _lastCamera;\n\tprivate int _uploadedCapacity = -1;\n\n\t// The size question put to IEvents listeners, kept in fields so asking it every frame doesn\u0027t\n\t// allocate a fresh closure each time.\n\tprivate Action\u003CIEvents\u003E _askSize;\n\tprivate GrassLayer _sizeLayer;\n\tprivate float _size;\n\n\tprotected override void OnAwake()\n\t{\n\t\tvar existing = Scene.Get\u003CGrassRenderer\u003E();\n\n\t\tif (!existing.IsValid() || existing == this)\n\t\t\treturn;\n\n\t\tLog.Warning($\u0022Only one {nameof(GrassRenderer)} can exist in a scene: the one added to \\\u0022{GameObject.Name}\\\u0022 has been removed. Use the one on \\\u0022{existing.GameObject.Name}\\\u0022. Add a layer to it instead of a second renderer.\u0022);\n\n\t\tDestroy();\n\t}\n\n\tprotected override void OnEnabled()\n\t{\n\t\tLayers ??= [];\n\t\tMigrateSingleLayer();\n\n\t\t_generateShader = new ComputeShader(\u0022grass_generate_cs\u0022);\n\t\t_commandList = new CommandList(\u0022Grass Rendering\u0022);\n\n\t\t// Force a full re-upload: the buffers were released on disable, so a matching version\n\t\t// number here would otherwise leave the compute pass reading freed resources.\n\t\t_uploadedCapacity = -1;\n\n\t\tforeach (var state in _layerStates)\n\t\t\tstate.UploadedVersion = -1;\n\t}\n\n\tprotected override void OnDisabled()\n\t{\n\t\t_lastCamera?.RemoveCommandList(_commandList);\n\t\t_lastCamera = null;\n\n\t\t_commandList?.Reset();\n\t\t_commandList = null;\n\n\t\tReleaseBuffers();\n\n\t\t_generateShader = null;\n\t\t_bladeMaterial = null;\n\n\t\t_uploadedCapacity = -1;\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Moves a pre-layers renderer\u0027s definition and coverage into the first layer. Runs once: the\n\t/// old storage is dropped afterwards, so a second pass has nothing left to find.\n\t/// \u003C/summary\u003E\n\tprivate void MigrateSingleLayer()\n\t{\n\t\tif (Storage is null || Storage.ChunkCount == 0)\n\t\t{\n\t\t\tDefinition = null;\n\t\t\tStorage = null;\n\t\t\treturn;\n\t\t}\n\n\t\tif (Layers.Count == 0)\n\t\t\tLayers.Add(new GrassLayer());\n\n\t\tvar first = Layers[0];\n\n\t\t// Only claim a layer that has nothing of its own to lose.\n\t\tif (first.Storage is null || first.Storage.ChunkCount == 0)\n\t\t{\n\t\t\tfirst.Storage = Storage;\n\t\t\tfirst.Definition ??= Definition;\n\t\t}\n\n\t\tDefinition = null;\n\t\tStorage = null;\n\t}\n\n\tprotected override void OnUpdate()\n\t{\n\t\tvar renderCamera = GetRenderCamera();\n\n\t\t// Re-attach when the camera changes, and also when the one we attached to stopped being\n\t\t// valid. Leaving play mode destroys the play camera without the reference here changing,\n\t\t// so comparing references alone would leave us bound to a dead camera forever.\n\t\tif (renderCamera != _lastCamera || !_lastCamera.IsValid())\n\t\t{\n\t\t\tif (_lastCamera.IsValid())\n\t\t\t\t_lastCamera.RemoveCommandList(_commandList);\n\n\t\t\t_lastCamera = null;\n\n\t\t\tif (renderCamera.IsValid())\n\t\t\t{\n\t\t\t\trenderCamera.AddCommandList(_commandList, RenderStage.AfterOpaque);\n\t\t\t\t_lastCamera = renderCamera;\n\t\t\t}\n\t\t}\n\n\t\t// Nothing to draw through until a camera exists. State is cleared above, so we pick one\n\t\t// up as soon as one appears.\n\t\tif (!_lastCamera.IsValid())\n\t\t\treturn;\n\n\t\t// Culling follows whichever camera the viewport actually looks through, which is not\n\t\t// necessarily the one replaying the list.\n\t\tvar cullCamera = GetCullCamera();\n\n\t\tif (!cullCamera.IsValid())\n\t\t\treturn;\n\n\t\tRefreshBuffers();\n\t\tRecordCommandList(cullCamera);\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// The camera whose command list actually replays. A scene camera does so in the editor\n\t/// viewport as well as in game, so it wins when one exists; with an empty scene the editor\n\t/// camera is the only thing left that will replay ours.\n\t/// \u003C/summary\u003E\n\tprivate CameraComponent GetRenderCamera()\n\t{\n\t\tif (Scene.Camera.IsValid())\n\t\t\treturn Scene.Camera;\n\n\t\tif (Scene.IsEditor)\n\t\t\treturn Application.Editor?.Camera;\n\n\t\treturn null;\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// The camera the grass is generated for. While editing this is the viewport camera, or\n\t/// nothing outside the game camera\u0027s frustum would ever be generated.\n\t/// \u003C/summary\u003E\n\tprivate CameraComponent GetCullCamera()\n\t{\n\t\tif (Scene.IsEditor)\n\t\t{\n\t\t\tvar editorCamera = Application.Editor?.Camera;\n\n\t\t\tif (editorCamera.IsValid())\n\t\t\t\treturn editorCamera;\n\t\t}\n\n\t\treturn Scene.Camera;\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Brings the per-layer GPU state in line with the layer list, then re-packs any layer whose\n\t/// painted data changed. Layers that did not change cost nothing here.\n\t/// \u003C/summary\u003E\n\tprivate void RefreshBuffers()\n\t{\n\t\tLayers ??= [];\n\n\t\t// Layers can be added, removed or reordered in the inspector at any time.\n\t\twhile (_layerStates.Count \u003E Layers.Count)\n\t\t{\n\t\t\t_layerStates[^1].Release();\n\t\t\t_layerStates.RemoveAt(_layerStates.Count - 1);\n\t\t}\n\n\t\twhile (_layerStates.Count \u003C Layers.Count)\n\t\t\t_layerStates.Add(new LayerState());\n\n\t\tvar capacityChanged = _uploadedCapacity != MaxGrassObjects;\n\n\t\tif (capacityChanged || _bladeBuffer is null)\n\t\t{\n\t\t\t_bladeBuffer?.Dispose();\n\t\t\t_bladeBuffer = new GpuBuffer\u003CGpuBlade\u003E(MaxGrassObjects, GpuBuffer.UsageFlags.Structured | GpuBuffer.UsageFlags.Append);\n\t\t\t_uploadedCapacity = MaxGrassObjects;\n\t\t}\n\n\t\t_frustumPlaneBuffer ??= new GpuBuffer\u003CVector4\u003E(6, GpuBuffer.UsageFlags.Structured);\n\n\t\tfor (var i = 0; i \u003C Layers.Count; i\u002B\u002B)\n\t\t\tRefreshLayer(Layers[i], _layerStates[i]);\n\t}\n\n\tprivate void RefreshLayer(GrassLayer layer, LayerState state)\n\t{\n\t\tvar storage = layer?.Storage;\n\n\t\t// A layer the inspector swapped out from under us keeps none of its old upload.\n\t\tif (!ReferenceEquals(state.Source, layer))\n\t\t{\n\t\t\tstate.Release();\n\t\t\tstate.Source = layer;\n\t\t}\n\n\t\tif (storage is null || storage.ChunkCount == 0)\n\t\t{\n\t\t\tif (state.ChunkCount != 0)\n\t\t\t\tstate.Release();\n\n\t\t\tstate.UploadedVersion = storage?.Revision ?? -1;\n\t\t\treturn;\n\t\t}\n\n\t\tif (state.UploadedVersion == storage.Revision \u0026\u0026 state.ChunkBuffer is not null)\n\t\t\treturn;\n\n\t\tstate.Release();\n\t\tstate.Source = layer;\n\n\t\tstate.ChunkCount = storage.ChunkCount;\n\t\tstate.UploadedVersion = storage.Revision;\n\n\t\tvar chunks = new GpuChunk[state.ChunkCount];\n\t\tvar cells = new GrassStorage.Cell[state.ChunkCount * GrassStorage.CellsPerChunk];\n\n\t\tvar index = 0;\n\t\tforeach (var (coord, cellData) in storage.Chunks)\n\t\t{\n\t\t\tvar origin = GrassStorage.ChunkOrigin(coord);\n\t\t\tvar offset = index * GrassStorage.CellsPerChunk;\n\n\t\t\tchunks[index] = new GpuChunk { Origin = origin, CellOffset = offset };\n\t\t\tArray.Copy(cellData, 0, cells, offset, GrassStorage.CellsPerChunk);\n\t\t\tstate.ChunkOrigins.Add(origin);\n\n\t\t\tindex\u002B\u002B;\n\t\t}\n\n\t\tstate.ChunkBuffer = new GpuBuffer\u003CGpuChunk\u003E(state.ChunkCount, GpuBuffer.UsageFlags.Structured);\n\t\tstate.ChunkBuffer.SetData(chunks);\n\n\t\tstate.CellBuffer = new GpuBuffer\u003CGrassStorage.Cell\u003E(cells.Length, GpuBuffer.UsageFlags.Structured);\n\t\tstate.CellBuffer.SetData(cells);\n\n\t\tstate.VisibleChunkBuffer = new GpuBuffer\u003Cint\u003E(state.ChunkCount, GpuBuffer.UsageFlags.Structured);\n\t\tstate.VisibleScratch = new int[state.ChunkCount];\n\n\t\tstate.ArgsBuffer = new GpuBuffer\u003CGpuBuffer.IndirectDrawArguments\u003E(1, GpuBuffer.UsageFlags.IndirectDrawArguments);\n\n\t\t// The vertex count is written when the draw is recorded, which happens later this same\n\t\t// frame - it depends on the style, and that can change without the painted data changing.\n\t\tstate.UploadedVertexCount = -1;\n\t}\n\n\tprivate void RecordCommandList(CameraComponent camera)\n\t{\n\t\t_commandList.Reset();\n\n\t\tif (_bladeBuffer is null || Layers.Count == 0)\n\t\t\treturn;\n\n\t\tvar cameraPosition = camera.WorldPosition;\n\n\t\tUploadFrustumPlanes(camera);\n\n\t\t// Shared by every layer: one camera, one frustum, one instance buffer.\n\t\t_commandList.Attributes.Set(\u0022GrassFrustumPlanes\u0022, _frustumPlaneBuffer);\n\t\t_commandList.Attributes.Set(\u0022GrassBlades\u0022, _bladeBuffer);\n\t\t_commandList.Attributes.Set(\u0022GrassCameraPos\u0022, cameraPosition);\n\t\t_commandList.Attributes.Set(\u0022GrassTime\u0022, RealTime.Now);\n\n\t\tfor (var i = 0; i \u003C Layers.Count; i\u002B\u002B)\n\t\t\tRecordLayer(Layers[i], _layerStates[i], cameraPosition);\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Generates and draws one layer. Layers share the instance buffer, so the barriers around each\n\t/// one also order it against the layer before: the transition back to UnorderedAccess cannot\n\t/// start until the previous layer\u0027s draw has finished reading. That serializes the layers on the\n\t/// GPU, which is the price of not allocating the whole budget once per layer.\n\t/// \u003C/summary\u003E\n\tprivate void RecordLayer(GrassLayer layer, LayerState state, Vector3 cameraPosition)\n\t{\n\t\tif (layer is null || !layer.Enabled || state.ChunkCount == 0)\n\t\t\treturn;\n\n\t\tvar size = AskSize(layer);\n\t\tif (size \u003C= 0.0f)\n\t\t\treturn;\n\n\t\tvar definition = layer.Definition;\n\n\t\tvar visibleCount = CollectVisibleChunks(state, cameraPosition, definition?.MaxDistance ?? 12000.0f);\n\t\tif (visibleCount == 0)\n\t\t\treturn;\n\n\t\tvar (material, vertexCount) = GetDrawSetup(definition);\n\n\t\tif (material is null)\n\t\t{\n\t\t\tif (!state.WarnedAboutMaterial)\n\t\t\t{\n\t\t\t\tstate.WarnedAboutMaterial = true;\n\t\t\t\tLog.Warning($\u0022{nameof(GrassRenderer)}: layer \u0027{layer.DisplayName}\u0027 is set to Sprites but names \u0022 \u002B\n\t\t\t\t\t\u0022no Sprite Material, so there is nothing to draw it with. Assign a material using the \u0022 \u002B\n\t\t\t\t\t\u0022grass_sprite shader, with the sprite sheet in its Color slot and a greyscale image of \u0022 \u002B\n\t\t\t\t\t\u0022the cutout in its Alpha slot.\u0022);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tstate.WarnedAboutMaterial = false;\n\n\t\tUpdateSpriteTable(state, definition);\n\n\t\t// The vertex count only changes when the style or the plane count does, so it is written\n\t\t// then rather than every frame: an unconditional SetData here would be a CPU write racing\n\t\t// the CopyStructureCount below, which fills in the instance count of the same struct.\n\t\tif (vertexCount != state.UploadedVertexCount)\n\t\t{\n\t\t\tstate.ArgsBuffer.SetData(new[] { new GpuBuffer.IndirectDrawArguments { VertexCount = (uint)vertexCount } });\n\t\t\tstate.UploadedVertexCount = vertexCount;\n\t\t}\n\n\t\t_commandList.Attributes.Set(\u0022GrassChunks\u0022, state.ChunkBuffer);\n\t\t_commandList.Attributes.Set(\u0022GrassCells\u0022, state.CellBuffer);\n\t\t_commandList.Attributes.Set(\u0022GrassVisibleChunks\u0022, state.VisibleChunkBuffer);\n\t\t_commandList.Attributes.Set(\u0022GrassVisibleChunkCount\u0022, visibleCount);\n\t\t_commandList.Attributes.Set(\u0022GrassSeed\u0022, layer.Seed);\n\t\t_commandList.Attributes.Set(\u0022GrassSpriteVariants\u0022, state.SpriteBuffer);\n\t\t_commandList.Attributes.Set(\u0022GrassSpriteCount\u0022, state.UploadedSprites.Count);\n\t\t_commandList.Attributes.Set(\u0022GrassSizeScale\u0022, size);\n\n\t\tdefinition?.ApplyTo(_commandList.Attributes);\n\n\t\t_commandList.ResourceBarrierTransition(_bladeBuffer, ResourceState.UnorderedAccess);\n\t\t_commandList.SetCounterValue(_bladeBuffer, 0);\n\n\t\t_commandList.DispatchCompute(_generateShader, visibleCount * GrassStorage.CellsPerChunk, 1, 1);\n\n\t\t// The appends must all land before the counter is read into the draw arguments.\n\t\t_commandList.UavBarrier(_bladeBuffer);\n\n\t\t_commandList.ResourceBarrierTransition(state.ArgsBuffer, ResourceState.CopyDestination);\n\t\t_commandList.CopyStructureCount(_bladeBuffer, state.ArgsBuffer, ArgsInstanceCountOffset);\n\n\t\t_commandList.ResourceBarrierTransition(_bladeBuffer, ResourceState.GenericRead);\n\t\t_commandList.ResourceBarrierTransition(state.ArgsBuffer, ResourceState.IndirectArgument);\n\n\t\t_commandList.DrawInstancedIndirect(material, state.ArgsBuffer);\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// How big the game wants this layer\u0027s grass right now, from \u003Csee cref=\u0022IEvents.OnGrassSize\u0022/\u003E:\n\t/// 1 when nothing listens, never below 0. Asked of this renderer\u0027s own scene, since in the editor\n\t/// the active scene can be another one.\n\t/// \u003C/summary\u003E\n\tprivate float AskSize(GrassLayer layer)\n\t{\n\t\t_sizeLayer = layer;\n\t\t_size = 1.0f;\n\n\t\tScene.RunEvent(_askSize ??= listener =\u003E listener.OnGrassSize(this, _sizeLayer, ref _size));\n\n\t\t_sizeLayer = null;\n\n\t\treturn MathF.Max(_size, 0.0f);\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Keeps the layer\u0027s table of sheet cells in step with its definition. Rebuilt only when the\n\t/// selection actually changes, which is almost never - the comparison is a handful of ints.\n\t/// \u003C/summary\u003E\n\tprivate void UpdateSpriteTable(LayerState state, GrassDefinition definition)\n\t{\n\t\t_spriteScratch.Clear();\n\n\t\tif (definition is not null \u0026\u0026 definition.Style == GrassStyle.Sprites)\n\t\t{\n\t\t\tdefinition.GetSpriteCells(_spriteScratch);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Blades carry a variant they never read, but the table is indexed either way.\n\t\t\t_spriteScratch.Add(0);\n\t\t}\n\n\t\tif (state.SpriteBuffer is not null \u0026\u0026 Matches(state.UploadedSprites, _spriteScratch))\n\t\t\treturn;\n\n\t\tstate.SpriteBuffer?.Dispose();\n\t\tstate.SpriteBuffer = new GpuBuffer\u003Cint\u003E(_spriteScratch.Count, GpuBuffer.UsageFlags.Structured);\n\t\tstate.SpriteBuffer.SetData(_spriteScratch);\n\n\t\tstate.UploadedSprites.Clear();\n\t\tstate.UploadedSprites.AddRange(_spriteScratch);\n\n\t\tstatic bool Matches(List\u003Cint\u003E _Uploaded, List\u003Cint\u003E _Wanted)\n\t\t{\n\t\t\tif (_Uploaded.Count != _Wanted.Count)\n\t\t\t\treturn false;\n\n\t\t\tfor (var i = 0; i \u003C _Uploaded.Count; i\u002B\u002B)\n\t\t\t{\n\t\t\t\tif (_Uploaded[i] != _Wanted[i])\n\t\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// The material and per-instance vertex count a definition draws with. Both shaders read the\n\t/// same instance buffer filled by the same generation pass; they differ only in what the vertex\n\t/// stage builds out of each instance.\n\t/// \u003C/summary\u003E\n\tprivate (Material Material, int VertexCount) GetDrawSetup(GrassDefinition definition)\n\t{\n\t\t// Sprite cards draw with the material the definition names, because that is what carries\n\t\t// the sheet. Null until one is assigned, and the caller skips the draw.\n\t\tif (definition is not null \u0026\u0026 definition.Style == GrassStyle.Sprites)\n\t\t\treturn (definition.SpriteMaterial, definition.PlaneCount * CardPlaneVertexCount);\n\n\t\t_bladeMaterial ??= Material.FromShader(\u0022grass\u0022);\n\t\treturn (_bladeMaterial, BladeVertexCount);\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Narrows a layer\u0027s dispatch to chunks near the camera. Per-instance frustum culling happens\n\t/// on the GPU; this only has to be conservative.\n\t/// \u003C/summary\u003E\n\tprivate static int CollectVisibleChunks(LayerState state, Vector3 cameraPosition, float maxDistance)\n\t{\n\t\t// A chunk\u0027s near corner can be in range while its centre isn\u0027t, hence the circumradius.\n\t\tvar cullRadius = maxDistance \u002B GrassStorage.ChunkSize * 0.7072f;\n\t\tvar cullRadiusSq = cullRadius * cullRadius;\n\n\t\tvar halfChunk = GrassStorage.ChunkSize * 0.5f;\n\t\tvar count = 0;\n\n\t\tfor (var i = 0; i \u003C state.ChunkOrigins.Count; i\u002B\u002B)\n\t\t{\n\t\t\tvar origin = state.ChunkOrigins[i];\n\t\t\tvar dx = origin.x \u002B halfChunk - cameraPosition.x;\n\t\t\tvar dy = origin.y \u002B halfChunk - cameraPosition.y;\n\n\t\t\tif (dx * dx \u002B dy * dy \u003E cullRadiusSq)\n\t\t\t\tcontinue;\n\n\t\t\tstate.VisibleScratch[count\u002B\u002B] = i;\n\t\t}\n\n\t\tif (count \u003E 0)\n\t\t\tstate.VisibleChunkBuffer.SetData(state.VisibleScratch.AsSpan(0, count));\n\n\t\treturn count;\n\t}\n\n\tprivate void UploadFrustumPlanes(CameraComponent camera)\n\t{\n\t\tvar frustum = camera.GetFrustum();\n\n\t\t// These planes are sampled once on the CPU but the grass they cull is not drawn until the\n\t\t// frame presents, by which point the camera has kept turning. Pushing every plane outward\n\t\t// gives the generation something to work with at the screen edges - without it, grass\n\t\t// rotating into view was culled before it was ever needed, which reads as it streaming in\n\t\t// from the sides. The slack that buys scales with the frame time, so a capped or struggling\n\t\t// framerate is exactly when it matters most.\n\t\tvar padding = MathF.Max(CullPadding, 0.0f);\n\n\t\t// Plane.GetDistance is dot( point, Normal ) - Distance, so w is negated to let the shader\n\t\t// use a plain dot( xyz, p ) \u002B w. Adding the padding there slides the plane outward.\n\t\t_planeScratch[0] = ToVector4(frustum.LeftPlane, padding);\n\t\t_planeScratch[1] = ToVector4(frustum.RightPlane, padding);\n\t\t_planeScratch[2] = ToVector4(frustum.TopPlane, padding);\n\t\t_planeScratch[3] = ToVector4(frustum.BottomPlane, padding);\n\t\t_planeScratch[4] = ToVector4(frustum.NearPlane, padding);\n\n\t\t// The far plane is left tight - MaxDistance already governs the far edge, and padding it\n\t\t// would only generate grass that fades out before it is ever visible.\n\t\t_planeScratch[5] = ToVector4(frustum.FarPlane, 0.0f);\n\n\t\t_frustumPlaneBuffer.SetData(_planeScratch);\n\n\t\tstatic Vector4 ToVector4(Plane plane, float padding) =\u003E\n\t\t\tnew(plane.Normal.x, plane.Normal.y, plane.Normal.z, -plane.Distance \u002B padding);\n\t}\n\n\tprivate void ReleaseBuffers()\n\t{\n\t\tforeach (var state in _layerStates)\n\t\t\tstate.Release();\n\n\t\t_layerStates.Clear();\n\n\t\t_frustumPlaneBuffer?.Dispose();\n\t\t_frustumPlaneBuffer = null;\n\n\t\t_bladeBuffer?.Dispose();\n\t\t_bladeBuffer = null;\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Called by the editor tool after painting, so the next frame re-uploads the density map.\n\t/// \u003C/summary\u003E\n\tpublic void MarkDirty()\n\t{\n\t\tforeach (var state in _layerStates)\n\t\t\tstate.UploadedVersion = -1;\n\t}\n\n\tprotected override void DrawGizmos()\n\t{\n\t\tif (!Gizmo.IsSelected || Layers is null)\n\t\t\treturn;\n\n\t\tGizmo.Draw.Color = Color.Green.WithAlpha(0.35f);\n\n\t\tforeach (var layer in Layers)\n\t\t{\n\t\t\tvar storage = layer?.Storage;\n\t\t\tif (storage is null || storage.ChunkCount == 0)\n\t\t\t\tcontinue;\n\n\t\t\tforeach (var (coord, _) in storage.Chunks)\n\t\t\t{\n\t\t\t\tvar origin = GrassStorage.ChunkOrigin(coord);\n\t\t\t\tvar mins = new Vector3(origin.x, origin.y, 0);\n\t\t\t\tvar maxs = new Vector3(origin.x \u002B GrassStorage.ChunkSize, origin.y \u002B GrassStorage.ChunkSize, 0);\n\n\t\t\t\tGizmo.Draw.LineBBox(new BBox(WorldTransform.PointToLocal(mins), WorldTransform.PointToLocal(maxs)));\n\t\t\t}\n\t\t}\n\t}\n}\n"},{"Ident":"redsnail.grasstool","Path":"Code/GrassStorage.cs","FileName":"GrassStorage.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":427870,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Runtime.InteropServices;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.GrassTool;\r\n\r\n/// \u003Csummary\u003E\r\n/// Sparse painted grass coverage, stored as a chunked grid of density samples rather than\r\n/// individual blade transforms. Blades are generated procedurally on the GPU from this data,\r\n/// so a square kilometre of dense grass costs a few megabytes instead of hundreds.\r\n/// \u003C/summary\u003E\r\npublic sealed class GrassStorage : BlobData\r\n{\r\n\t// 2: cells are stored sparsely per chunk. See Serialize.\r\n\tpublic override int Version =\u003E 2;\r\n\r\n\t/// \u003Csummary\u003ECells along one edge of a chunk.\u003C/summary\u003E\r\n\tpublic const int ChunkResolution = 64;\r\n\r\n\t/// \u003Csummary\u003EWorld-space size of a single density cell, in source units.\u003C/summary\u003E\r\n\tpublic const float CellSize = 32.0f;\r\n\r\n\t/// \u003Csummary\u003EWorld-space size of a chunk edge, in source units.\u003C/summary\u003E\r\n\tpublic const float ChunkSize = ChunkResolution * CellSize;\r\n\r\n\tpublic const int CellsPerChunk = ChunkResolution * ChunkResolution;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// One density sample. Height and normal are baked when painting so grass sits on any\r\n\t/// geometry, not just terrain. Matches the HLSL \u003Cc\u003EGrassCell\u003C/c\u003E struct exactly.\r\n\t/// \u003C/summary\u003E\r\n\t[StructLayout(LayoutKind.Sequential)]\r\n\tpublic struct Cell\r\n\t{\r\n\t\tpublic float Height;\r\n\r\n\t\t/// \u003Csummary\u003Edensity (0-7) | normal.x (8-15) | normal.y (16-23) | unused (24-31)\u003C/summary\u003E\r\n\t\tpublic uint Packed;\r\n\r\n\t\tpublic readonly float Density =\u003E (Packed \u0026 0xFF) / 255.0f;\r\n\r\n\t\tpublic readonly Vector3 Normal\r\n\t\t{\r\n\t\t\tget\r\n\t\t\t{\r\n\t\t\t\tvar x = ((Packed \u003E\u003E 8) \u0026 0xFF) / 127.5f - 1.0f;\r\n\t\t\t\tvar y = ((Packed \u003E\u003E 16) \u0026 0xFF) / 127.5f - 1.0f;\r\n\t\t\t\tvar z = MathF.Sqrt(Math.Clamp(1.0f - x * x - y * y, 0.0f, 1.0f));\r\n\t\t\t\treturn new Vector3(x, y, z);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static uint Pack(float density, Vector3 normal)\r\n\t\t{\r\n\t\t\tvar d = (uint)Math.Clamp(density * 255.0f \u002B 0.5f, 0.0f, 255.0f);\r\n\t\t\tvar nx = (uint)Math.Clamp((normal.x \u002B 1.0f) * 127.5f \u002B 0.5f, 0.0f, 255.0f);\r\n\t\t\tvar ny = (uint)Math.Clamp((normal.y \u002B 1.0f) * 127.5f \u002B 0.5f, 0.0f, 255.0f);\r\n\t\t\treturn d | (nx \u003C\u003C 8) | (ny \u003C\u003C 16);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic readonly record struct ChunkCoord(int X, int Y);\r\n\r\n\tprivate readonly Dictionary\u003CChunkCoord, Cell[]\u003E _chunks = [];\r\n\r\n\t/// \u003Csummary\u003EBumped on every mutation so the renderer knows to re-upload its GPU buffers.\u003C/summary\u003E\r\n\tpublic int Revision { get; private set; }\r\n\r\n\tpublic int ChunkCount =\u003E _chunks.Count;\r\n\r\n\tpublic IReadOnlyDictionary\u003CChunkCoord, Cell[]\u003E Chunks =\u003E _chunks;\r\n\r\n\tpublic static ChunkCoord WorldToChunk(Vector3 world) =\u003E new(\r\n\t\t(int)MathF.Floor(world.x / ChunkSize),\r\n\t\t(int)MathF.Floor(world.y / ChunkSize));\r\n\r\n\tpublic static Vector2 ChunkOrigin(ChunkCoord coord) =\u003E new(coord.X * ChunkSize, coord.Y * ChunkSize);\r\n\r\n\t/// \u003Csummary\u003EGlobal cell index on an axis. Negative world positions floor correctly.\u003C/summary\u003E\r\n\tprivate static int WorldToCell(float world) =\u003E (int)MathF.Floor(world / CellSize);\r\n\r\n\tprivate static int FloorDiv(int a, int b) =\u003E a \u003E= 0 ? a / b : ~(~a / b);\r\n\r\n\tprivate static int Mod(int a, int b)\r\n\t{\r\n\t\tvar r = a % b;\r\n\t\treturn r \u003C 0 ? r \u002B b : r;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Writes a density sample at a world position, baking the surface height and normal alongside it.\r\n\t/// Density of zero frees the sample.\r\n\t/// \u003C/summary\u003E\r\n\tpublic void SetCell(float worldX, float worldY, float density, float height, Vector3 normal)\r\n\t{\r\n\t\tvar cellX = WorldToCell(worldX);\r\n\t\tvar cellY = WorldToCell(worldY);\r\n\t\tvar coord = new ChunkCoord(FloorDiv(cellX, ChunkResolution), FloorDiv(cellY, ChunkResolution));\r\n\r\n\t\tif (!_chunks.TryGetValue(coord, out var cells))\r\n\t\t{\r\n\t\t\tif (density \u003C= 0.0f) return;\r\n\r\n\t\t\tcells = new Cell[CellsPerChunk];\r\n\t\t\t_chunks[coord] = cells;\r\n\t\t}\r\n\r\n\t\tvar index = Mod(cellY, ChunkResolution) * ChunkResolution \u002B Mod(cellX, ChunkResolution);\r\n\t\tcells[index] = new Cell { Height = height, Packed = Cell.Pack(density, normal) };\r\n\t\tRevision\u002B\u002B;\r\n\t}\r\n\r\n\tpublic Cell GetCell(float worldX, float worldY)\r\n\t{\r\n\t\tvar cellX = WorldToCell(worldX);\r\n\t\tvar cellY = WorldToCell(worldY);\r\n\t\tvar coord = new ChunkCoord(FloorDiv(cellX, ChunkResolution), FloorDiv(cellY, ChunkResolution));\r\n\r\n\t\tif (!_chunks.TryGetValue(coord, out var cells))\r\n\t\t\treturn default;\r\n\r\n\t\treturn cells[Mod(cellY, ChunkResolution) * ChunkResolution \u002B Mod(cellX, ChunkResolution)];\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Reduces density in a radius, removing samples that reach zero.\r\n\t/// \u003C/summary\u003E\r\n\tpublic void Erase(Vector3 center, float radius, float strength)\r\n\t{\r\n\t\tvar radiusSq = radius * radius;\r\n\t\tvar minCellX = WorldToCell(center.x - radius);\r\n\t\tvar maxCellX = WorldToCell(center.x \u002B radius);\r\n\t\tvar minCellY = WorldToCell(center.y - radius);\r\n\t\tvar maxCellY = WorldToCell(center.y \u002B radius);\r\n\r\n\t\tfor (var cy = minCellY; cy \u003C= maxCellY; cy\u002B\u002B)\r\n\t\t{\r\n\t\t\tfor (var cx = minCellX; cx \u003C= maxCellX; cx\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tvar coord = new ChunkCoord(FloorDiv(cx, ChunkResolution), FloorDiv(cy, ChunkResolution));\r\n\t\t\t\tif (!_chunks.TryGetValue(coord, out var cells))\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tvar wx = (cx \u002B 0.5f) * CellSize;\r\n\t\t\t\tvar wy = (cy \u002B 0.5f) * CellSize;\r\n\t\t\t\tvar dx = wx - center.x;\r\n\t\t\t\tvar dy = wy - center.y;\r\n\t\t\t\tif (dx * dx \u002B dy * dy \u003E radiusSq)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tvar index = Mod(cy, ChunkResolution) * ChunkResolution \u002B Mod(cx, ChunkResolution);\r\n\t\t\t\tref var cell = ref cells[index];\r\n\t\t\t\tif ((cell.Packed \u0026 0xFF) == 0)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tvar density = Math.Max(cell.Density - strength, 0.0f);\r\n\t\t\t\tcell.Packed = density \u003C= 0.0f ? 0u : Cell.Pack(density, cell.Normal);\r\n\t\t\t\tRevision\u002B\u002B;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tPruneEmptyChunks();\r\n\t}\r\n\r\n\tpublic void ClearAll()\r\n\t{\r\n\t\tif (_chunks.Count == 0) return;\r\n\r\n\t\t_chunks.Clear();\r\n\t\tRevision\u002B\u002B;\r\n\t}\r\n\r\n\tprivate void PruneEmptyChunks()\r\n\t{\r\n\t\tList\u003CChunkCoord\u003E empty = null;\r\n\r\n\t\tforeach (var (coord, cells) in _chunks)\r\n\t\t{\r\n\t\t\tvar used = false;\r\n\t\t\tfor (var i = 0; i \u003C cells.Length; i\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tif ((cells[i].Packed \u0026 0xFF) != 0) { used = true; break; }\r\n\t\t\t}\r\n\r\n\t\t\tif (!used)\r\n\t\t\t{\r\n\t\t\t\tempty ??= [];\r\n\t\t\t\tempty.Add(coord);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (empty is null) return;\r\n\r\n\t\tforeach (var coord in empty)\r\n\t\t\t_chunks.Remove(coord);\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Writes only the painted cells. A chunk is 4096 cells at 8 bytes each, so storing them densely\r\n\t/// cost 32KB per chunk however little of it was painted - a thin brush stroke across a landscape\r\n\t/// touches a lot of chunks and paid full price for every one.\r\n\t///\r\n\t/// Each painted cell costs 2 bytes more than it did dense (its index), so a chunk past about 80%\r\n\t/// coverage is cheaper stored densely. Both layouts are written and each chunk says which it used.\r\n\t/// \u003C/summary\u003E\r\n\tpublic override void Serialize(ref Writer writer)\r\n\t{\r\n\t\twriter.Stream.Write(_chunks.Count);\r\n\r\n\t\tforeach (var (coord, cells) in _chunks)\r\n\t\t{\r\n\t\t\twriter.Stream.Write(coord.X);\r\n\t\t\twriter.Stream.Write(coord.Y);\r\n\r\n\t\t\tvar painted = 0;\r\n\t\t\tfor (var i = 0; i \u003C CellsPerChunk; i\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tif ((cells[i].Packed \u0026 0xFF) != 0) painted\u002B\u002B;\r\n\t\t\t}\r\n\r\n\t\t\tvar sparse = painted * 10 \u003C CellsPerChunk * 8;\r\n\t\t\twriter.Stream.Write(sparse);\r\n\r\n\t\t\tif (!sparse)\r\n\t\t\t{\r\n\t\t\t\tfor (var i = 0; i \u003C CellsPerChunk; i\u002B\u002B)\r\n\t\t\t\t{\r\n\t\t\t\t\twriter.Stream.Write(cells[i].Height);\r\n\t\t\t\t\twriter.Stream.Write(cells[i].Packed);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\twriter.Stream.Write(painted);\r\n\r\n\t\t\tfor (var i = 0; i \u003C CellsPerChunk; i\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tif ((cells[i].Packed \u0026 0xFF) == 0)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\twriter.Stream.Write((ushort)i);\r\n\t\t\t\twriter.Stream.Write(cells[i].Height);\r\n\t\t\t\twriter.Stream.Write(cells[i].Packed);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tpublic override void Deserialize(ref Reader reader)\r\n\t{\r\n\t\t_chunks.Clear();\r\n\r\n\t\tvar chunkCount = reader.Stream.Read\u003Cint\u003E();\r\n\r\n\t\tfor (var c = 0; c \u003C chunkCount; c\u002B\u002B)\r\n\t\t{\r\n\t\t\tvar coord = new ChunkCoord(reader.Stream.Read\u003Cint\u003E(), reader.Stream.Read\u003Cint\u003E());\r\n\t\t\tvar cells = new Cell[CellsPerChunk];\r\n\r\n\t\t\tif (reader.Stream.Read\u003Cbool\u003E())\r\n\t\t\t{\r\n\t\t\t\tvar painted = reader.Stream.Read\u003Cint\u003E();\r\n\r\n\t\t\t\tfor (var p = 0; p \u003C painted; p\u002B\u002B)\r\n\t\t\t\t{\r\n\t\t\t\t\tvar index = reader.Stream.Read\u003Cushort\u003E();\r\n\t\t\t\t\tvar height = reader.Stream.Read\u003Cfloat\u003E();\r\n\t\t\t\t\tvar packed = reader.Stream.Read\u003Cuint\u003E();\r\n\r\n\t\t\t\t\tif (index \u003C CellsPerChunk)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcells[index].Height = height;\r\n\t\t\t\t\t\tcells[index].Packed = packed;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tfor (var i = 0; i \u003C CellsPerChunk; i\u002B\u002B)\r\n\t\t\t\t{\r\n\t\t\t\t\tcells[i].Height = reader.Stream.Read\u003Cfloat\u003E();\r\n\t\t\t\t\tcells[i].Packed = reader.Stream.Read\u003Cuint\u003E();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t_chunks[coord] = cells;\r\n\t\t}\r\n\r\n\t\tRevision\u002B\u002B;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Version 1 wrote every cell of every chunk with no sparse/dense flag. Read it in that layout so\r\n\t/// scenes painted before the change still load.\r\n\t/// \u003C/summary\u003E\r\n\tpublic override void Upgrade(ref Reader reader, int fromVersion)\r\n\t{\r\n\t\tif (fromVersion != 1)\r\n\t\t{\r\n\t\t\tDeserialize(ref reader);\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t_chunks.Clear();\r\n\r\n\t\tvar chunkCount = reader.Stream.Read\u003Cint\u003E();\r\n\r\n\t\tfor (var c = 0; c \u003C chunkCount; c\u002B\u002B)\r\n\t\t{\r\n\t\t\tvar coord = new ChunkCoord(reader.Stream.Read\u003Cint\u003E(), reader.Stream.Read\u003Cint\u003E());\r\n\t\t\tvar cells = new Cell[CellsPerChunk];\r\n\r\n\t\t\tfor (var i = 0; i \u003C CellsPerChunk; i\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tcells[i].Height = reader.Stream.Read\u003Cfloat\u003E();\r\n\t\t\t\tcells[i].Packed = reader.Stream.Read\u003Cuint\u003E();\r\n\t\t\t}\r\n\r\n\t\t\t_chunks[coord] = cells;\r\n\t\t}\r\n\r\n\t\tRevision\u002B\u002B;\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.grasstool","Path":"GrassRenderer.cs","FileName":"GrassRenderer.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":427870,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing Sandbox;\nusing Sandbox.Rendering;\nusing RenderStage = Sandbox.Rendering.Stage;\n\nnamespace RedSnail.GrassTool;\n\n/// \u003Csummary\u003E\n/// One kind of grass on a renderer: what it looks like, and where it has been painted. Layers are\n/// painted independently and overlap freely, so ground cover can sit under tall grass rather than\n/// competing with it for the same cells.\n/// \u003C/summary\u003E\npublic sealed class GrassLayer\n{\n\t/// \u003Csummary\u003EWhat the brush calls this layer. Only ever shown in the editor.\u003C/summary\u003E\n\t[Property]\n\tpublic string Name { get; set; } = \u0022Grass\u0022;\n\n\t[Property]\n\tpublic GrassDefinition Definition { get; set; }\n\n\t/// \u003Csummary\u003EStops the layer drawing without throwing away what has been painted into it.\u003C/summary\u003E\n\t[Property]\n\tpublic bool Enabled { get; set; } = true;\n\n\t/// \u003Csummary\u003E\n\t/// Decorrelates this layer\u0027s placement from the others. Every random choice a cell makes -\n\t/// where its grass sits, which way it faces, how big it is, which sprite it takes - comes from\n\t/// hashing the cell\u0027s position, so two layers painted over the same ground with the same seed\n\t/// put their grass in exactly the same spots.\n\t///\n\t/// A new layer picks a random one, which is almost always what you want. Set two layers to the\n\t/// same seed deliberately and they will line up, which is occasionally useful - flowers that\n\t/// always sit in the same tufts as the grass, say.\n\t/// \u003C/summary\u003E\n\t[Property]\n\tpublic int Seed { get; set; } = 0;\n\n\t/// \u003Csummary\u003EPainted coverage. Serialized as a binary blob, not JSON.\u003C/summary\u003E\n\t[Property, Hide]\n\tpublic GrassStorage Storage { get; set; } = new();\n\n\t[Hide] public string DisplayName =\u003E string.IsNullOrWhiteSpace(Name) ? \u0022Unnamed\u0022 : Name;\n}\n\n/// \u003Csummary\u003E\n/// Renders painted grass. Each frame a compute pass expands the density map into instances for\n/// whatever is near the camera, then one indirect draw renders them. No blade ever exists on the\n/// CPU, and nothing is stored per-blade in the scene.\n///\n/// A renderer holds any number of \u003Csee cref=\u0022GrassLayer\u0022/\u003Es - tall grass, ground cover, whatever -\n/// each with its own definition, material and painted coverage. They share one instance buffer and\n/// run one after another, so adding a layer costs a dispatch and a draw rather than a second\n/// allocation of the whole budget.\n/// \u003C/summary\u003E\n[Icon(\u0022grass\u0022), Group(\u0022Grass\u0022), Title(\u0022Grass Renderer\u0022)]\npublic sealed class GrassRenderer : Component, Component.ExecuteInEditor, Component.DontExecuteOnServer\n{\n\t/// \u003Csummary\u003E\n\t/// Lets a game steer the grass from its own code, without changing this library: implement it on\n\t/// any component in the same scene as the renderer.\n\t/// \u003C/summary\u003E\n\tpublic interface IEvents : ISceneEvent\u003CIEvents\u003E\n\t{\n\t\t/// \u003Csummary\u003E\n\t\t/// Asked every frame for each layer about to draw. Scale \u003Cparamref name=\u0022size\u0022/\u003E to shrink the\n\t\t/// layer\u0027s grass - height and width together, blades and cards alike - or to grow it. It\n\t\t/// starts at 1, which draws the grass as painted; at 0 the layer is skipped outright, with no\n\t\t/// generation pass and no draw, so grass that is meant to be gone costs nothing. With several\n\t\t/// listeners, each one gets the value the previous one left, so multiplying keeps them all.\n\t\t///\n\t\t/// Snow is the case it was made for: shrink the grass as the snow deepens, and at full depth\n\t\t/// it is buried and stops drawing at all.\n\t\t/// \u003C/summary\u003E\n\t\tvoid OnGrassSize(GrassRenderer renderer, GrassLayer layer, ref float size) { }\n\t}\n\n\t[StructLayout(LayoutKind.Sequential)]\n\tprivate struct GpuChunk\n\t{\n\t\tpublic Vector2 Origin;\n\t\tpublic int CellOffset;\n\t\tpublic int Pad;\n\t}\n\n\t[StructLayout(LayoutKind.Sequential)]\n\tprivate struct GpuBlade\n\t{\n\t\tpublic Vector3 Position;\n\t\tpublic float Yaw;\n\t\tpublic Vector3 Normal;\n\t\tpublic float Height;\n\t\tpublic float Width;\n\t\tpublic float Tint;\n\t\tpublic float Phase;\n\n\t\t// Which sprite of the sheet a card draws. Unused by blades, and it occupies what was\n\t\t// padding, so the struct stays at 48 bytes either way.\n\t\tpublic float Variant;\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// The GPU side of one layer. Chunks and cells are its own painted data; the args buffer is its\n\t/// own because the vertex count per instance follows the layer\u0027s style. Everything else - the\n\t/// instance buffer, the frustum, the camera - is shared across layers.\n\t/// \u003C/summary\u003E\n\tprivate sealed class LayerState\n\t{\n\t\tpublic GrassLayer Source;\n\n\t\tpublic GpuBuffer\u003CGpuChunk\u003E ChunkBuffer;\n\t\tpublic GpuBuffer\u003CGrassStorage.Cell\u003E CellBuffer;\n\t\tpublic GpuBuffer\u003Cint\u003E VisibleChunkBuffer;\n\t\tpublic GpuBuffer\u003CGpuBuffer.IndirectDrawArguments\u003E ArgsBuffer;\n\n\t\t// Which cells of the sheet this layer draws from. Uploaded as a table the generation pass\n\t\t// indexes, so picking a sprite is one lookup whatever the selection looks like.\n\t\tpublic GpuBuffer\u003Cint\u003E SpriteBuffer;\n\t\tpublic readonly List\u003Cint\u003E UploadedSprites = [];\n\n\t\tpublic readonly List\u003CVector2\u003E ChunkOrigins = [];\n\t\tpublic int[] VisibleScratch = [];\n\n\t\tpublic int ChunkCount;\n\t\tpublic int UploadedVersion = -1;\n\t\tpublic int UploadedVertexCount = -1;\n\t\tpublic bool WarnedAboutMaterial;\n\n\t\tpublic void Release()\n\t\t{\n\t\t\tChunkBuffer?.Dispose();\n\t\t\tChunkBuffer = null;\n\n\t\t\tCellBuffer?.Dispose();\n\t\t\tCellBuffer = null;\n\n\t\t\tVisibleChunkBuffer?.Dispose();\n\t\t\tVisibleChunkBuffer = null;\n\n\t\t\tArgsBuffer?.Dispose();\n\t\t\tArgsBuffer = null;\n\n\t\t\tSpriteBuffer?.Dispose();\n\t\t\tSpriteBuffer = null;\n\t\t\tUploadedSprites.Clear();\n\n\t\t\tChunkOrigins.Clear();\n\t\t\tChunkCount = 0;\n\t\t\tUploadedVersion = -1;\n\t\t\tUploadedVertexCount = -1;\n\t\t}\n\t}\n\n\t// Must match GRASS_BLADE_* and GRASS_CARD_* in grass_shared.fxc.\n\tprivate const int BladeStripVerts = 7;\n\tprivate const int BladeVertexCount = (BladeStripVerts - 2) * 3;\n\tprivate const int CardPlaneVertexCount = 6;\n\n\t// Byte offset of InstanceCount within IndirectDrawArguments. The struct is sequential\n\t// { uint VertexCount; uint InstanceCount; uint FirstVertex; uint FirstInstance; }, so this is\n\t// fixed at 4. Marshal.OffsetOf would express it directly but is outside the sandbox whitelist.\n\tprivate const int ArgsInstanceCountOffset = 4;\n\n\t/// \u003Csummary\u003E\n\t/// The kinds of grass this renderer draws. The brush paints whichever one is picked in the Grass\n\t/// tool\u0027s sidebar, so each layer keeps its own coverage and they can overlap.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Layers\u0022)]\n\tpublic List\u003CGrassLayer\u003E Layers { get; set; } = [new GrassLayer()];\n\n\t/// \u003Csummary\u003E\n\t/// How many instances the buffer has room for, at 48 bytes each - so a million is ~48 MB. Every\n\t/// layer draws out of this one buffer, so it has to fit the largest single layer, not their sum.\n\t///\n\t/// This is capacity, not a budget: how much grass there is, is decided by the render distance\n\t/// and the density, and this only needs to be big enough to hold the result. Set it too low and\n\t/// the generation overruns it, at which point which grass gets a slot is settled by whichever\n\t/// GPU thread reaches the counter first - an order that changes every frame, so patches flicker\n\t/// in and out - which is the symptom to recognise if grass ever starts churning at distance.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022General\u0022), Range(50000, 8000000), Alias(\u0022MaxBlades\u0022)]\n\tpublic int MaxGrassObjects { get; set; } = 1000000;\n\n\t/// \u003Csummary\u003E\n\t/// How far outside the camera frustum grass is still generated, in world units. Culling is\n\t/// done against the frustum as it was when the frame started, so turning the camera brings in\n\t/// grass that was never generated. Raise this if it visibly streams in at the screen edges,\n\t/// which is most obvious at low or capped framerates.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022General\u0022), Range(0, 4000)]\n\tpublic float CullPadding { get; set; } = 1000.0f;\n\n\t/// \u003Csummary\u003E\n\t/// Where a renderer kept its definition before it had layers. Still deserialized so that scenes\n\t/// built before the change migrate into the first layer instead of coming back empty.\n\t/// \u003C/summary\u003E\n\t[Property, Hide]\n\tpublic GrassDefinition Definition { get; set; }\n\n\t/// \u003Csummary\u003EPainted coverage from before layers. Migrated into the first layer on load.\u003C/summary\u003E\n\t[Property, Hide]\n\tpublic GrassStorage Storage { get; set; }\n\n\tprivate ComputeShader _generateShader;\n\tprivate Material _bladeMaterial;\n\tprivate CommandList _commandList;\n\n\tprivate GpuBuffer\u003CVector4\u003E _frustumPlaneBuffer;\n\tprivate GpuBuffer\u003CGpuBlade\u003E _bladeBuffer;\n\n\tprivate readonly List\u003CLayerState\u003E _layerStates = [];\n\tprivate readonly List\u003Cint\u003E _spriteScratch = [];\n\tprivate readonly Vector4[] _planeScratch = new Vector4[6];\n\n\tprivate CameraComponent _lastCamera;\n\tprivate int _uploadedCapacity = -1;\n\n\t// The size question put to IEvents listeners, kept in fields so asking it every frame doesn\u0027t\n\t// allocate a fresh closure each time.\n\tprivate Action\u003CIEvents\u003E _askSize;\n\tprivate GrassLayer _sizeLayer;\n\tprivate float _size;\n\n\tprotected override void OnAwake()\n\t{\n\t\tvar existing = Scene.Get\u003CGrassRenderer\u003E();\n\n\t\tif (!existing.IsValid() || existing == this)\n\t\t\treturn;\n\n\t\tLog.Warning($\u0022Only one {nameof(GrassRenderer)} can exist in a scene: the one added to \\\u0022{GameObject.Name}\\\u0022 has been removed. Use the one on \\\u0022{existing.GameObject.Name}\\\u0022. Add a layer to it instead of a second renderer.\u0022);\n\n\t\tDestroy();\n\t}\n\n\tprotected override void OnEnabled()\n\t{\n\t\tLayers ??= [];\n\t\tMigrateSingleLayer();\n\n\t\t_generateShader = new ComputeShader(\u0022grass_generate_cs\u0022);\n\t\t_commandList = new CommandList(\u0022Grass Rendering\u0022);\n\n\t\t// Force a full re-upload: the buffers were released on disable, so a matching version\n\t\t// number here would otherwise leave the compute pass reading freed resources.\n\t\t_uploadedCapacity = -1;\n\n\t\tforeach (var state in _layerStates)\n\t\t\tstate.UploadedVersion = -1;\n\t}\n\n\tprotected override void OnDisabled()\n\t{\n\t\t_lastCamera?.RemoveCommandList(_commandList);\n\t\t_lastCamera = null;\n\n\t\t_commandList?.Reset();\n\t\t_commandList = null;\n\n\t\tReleaseBuffers();\n\n\t\t_generateShader = null;\n\t\t_bladeMaterial = null;\n\n\t\t_uploadedCapacity = -1;\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Moves a pre-layers renderer\u0027s definition and coverage into the first layer. Runs once: the\n\t/// old storage is dropped afterwards, so a second pass has nothing left to find.\n\t/// \u003C/summary\u003E\n\tprivate void MigrateSingleLayer()\n\t{\n\t\tif (Storage is null || Storage.ChunkCount == 0)\n\t\t{\n\t\t\tDefinition = null;\n\t\t\tStorage = null;\n\t\t\treturn;\n\t\t}\n\n\t\tif (Layers.Count == 0)\n\t\t\tLayers.Add(new GrassLayer());\n\n\t\tvar first = Layers[0];\n\n\t\t// Only claim a layer that has nothing of its own to lose.\n\t\tif (first.Storage is null || first.Storage.ChunkCount == 0)\n\t\t{\n\t\t\tfirst.Storage = Storage;\n\t\t\tfirst.Definition ??= Definition;\n\t\t}\n\n\t\tDefinition = null;\n\t\tStorage = null;\n\t}\n\n\tprotected override void OnUpdate()\n\t{\n\t\tvar renderCamera = GetRenderCamera();\n\n\t\t// Re-attach when the camera changes, and also when the one we attached to stopped being\n\t\t// valid. Leaving play mode destroys the play camera without the reference here changing,\n\t\t// so comparing references alone would leave us bound to a dead camera forever.\n\t\tif (renderCamera != _lastCamera || !_lastCamera.IsValid())\n\t\t{\n\t\t\tif (_lastCamera.IsValid())\n\t\t\t\t_lastCamera.RemoveCommandList(_commandList);\n\n\t\t\t_lastCamera = null;\n\n\t\t\tif (renderCamera.IsValid())\n\t\t\t{\n\t\t\t\trenderCamera.AddCommandList(_commandList, RenderStage.AfterOpaque);\n\t\t\t\t_lastCamera = renderCamera;\n\t\t\t}\n\t\t}\n\n\t\t// Nothing to draw through until a camera exists. State is cleared above, so we pick one\n\t\t// up as soon as one appears.\n\t\tif (!_lastCamera.IsValid())\n\t\t\treturn;\n\n\t\t// Culling follows whichever camera the viewport actually looks through, which is not\n\t\t// necessarily the one replaying the list.\n\t\tvar cullCamera = GetCullCamera();\n\n\t\tif (!cullCamera.IsValid())\n\t\t\treturn;\n\n\t\tRefreshBuffers();\n\t\tRecordCommandList(cullCamera);\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// The camera whose command list actually replays. A scene camera does so in the editor\n\t/// viewport as well as in game, so it wins when one exists; with an empty scene the editor\n\t/// camera is the only thing left that will replay ours.\n\t/// \u003C/summary\u003E\n\tprivate CameraComponent GetRenderCamera()\n\t{\n\t\tif (Scene.Camera.IsValid())\n\t\t\treturn Scene.Camera;\n\n\t\tif (Scene.IsEditor)\n\t\t\treturn Application.Editor?.Camera;\n\n\t\treturn null;\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// The camera the grass is generated for. While editing this is the viewport camera, or\n\t/// nothing outside the game camera\u0027s frustum would ever be generated.\n\t/// \u003C/summary\u003E\n\tprivate CameraComponent GetCullCamera()\n\t{\n\t\tif (Scene.IsEditor)\n\t\t{\n\t\t\tvar editorCamera = Application.Editor?.Camera;\n\n\t\t\tif (editorCamera.IsValid())\n\t\t\t\treturn editorCamera;\n\t\t}\n\n\t\treturn Scene.Camera;\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Brings the per-layer GPU state in line with the layer list, then re-packs any layer whose\n\t/// painted data changed. Layers that did not change cost nothing here.\n\t/// \u003C/summary\u003E\n\tprivate void RefreshBuffers()\n\t{\n\t\tLayers ??= [];\n\n\t\t// Layers can be added, removed or reordered in the inspector at any time.\n\t\twhile (_layerStates.Count \u003E Layers.Count)\n\t\t{\n\t\t\t_layerStates[^1].Release();\n\t\t\t_layerStates.RemoveAt(_layerStates.Count - 1);\n\t\t}\n\n\t\twhile (_layerStates.Count \u003C Layers.Count)\n\t\t\t_layerStates.Add(new LayerState());\n\n\t\tvar capacityChanged = _uploadedCapacity != MaxGrassObjects;\n\n\t\tif (capacityChanged || _bladeBuffer is null)\n\t\t{\n\t\t\t_bladeBuffer?.Dispose();\n\t\t\t_bladeBuffer = new GpuBuffer\u003CGpuBlade\u003E(MaxGrassObjects, GpuBuffer.UsageFlags.Structured | GpuBuffer.UsageFlags.Append);\n\t\t\t_uploadedCapacity = MaxGrassObjects;\n\t\t}\n\n\t\t_frustumPlaneBuffer ??= new GpuBuffer\u003CVector4\u003E(6, GpuBuffer.UsageFlags.Structured);\n\n\t\tfor (var i = 0; i \u003C Layers.Count; i\u002B\u002B)\n\t\t\tRefreshLayer(Layers[i], _layerStates[i]);\n\t}\n\n\tprivate void RefreshLayer(GrassLayer layer, LayerState state)\n\t{\n\t\tvar storage = layer?.Storage;\n\n\t\t// A layer the inspector swapped out from under us keeps none of its old upload.\n\t\tif (!ReferenceEquals(state.Source, layer))\n\t\t{\n\t\t\tstate.Release();\n\t\t\tstate.Source = layer;\n\t\t}\n\n\t\tif (storage is null || storage.ChunkCount == 0)\n\t\t{\n\t\t\tif (state.ChunkCount != 0)\n\t\t\t\tstate.Release();\n\n\t\t\tstate.UploadedVersion = storage?.Revision ?? -1;\n\t\t\treturn;\n\t\t}\n\n\t\tif (state.UploadedVersion == storage.Revision \u0026\u0026 state.ChunkBuffer is not null)\n\t\t\treturn;\n\n\t\tstate.Release();\n\t\tstate.Source = layer;\n\n\t\tstate.ChunkCount = storage.ChunkCount;\n\t\tstate.UploadedVersion = storage.Revision;\n\n\t\tvar chunks = new GpuChunk[state.ChunkCount];\n\t\tvar cells = new GrassStorage.Cell[state.ChunkCount * GrassStorage.CellsPerChunk];\n\n\t\tvar index = 0;\n\t\tforeach (var (coord, cellData) in storage.Chunks)\n\t\t{\n\t\t\tvar origin = GrassStorage.ChunkOrigin(coord);\n\t\t\tvar offset = index * GrassStorage.CellsPerChunk;\n\n\t\t\tchunks[index] = new GpuChunk { Origin = origin, CellOffset = offset };\n\t\t\tArray.Copy(cellData, 0, cells, offset, GrassStorage.CellsPerChunk);\n\t\t\tstate.ChunkOrigins.Add(origin);\n\n\t\t\tindex\u002B\u002B;\n\t\t}\n\n\t\tstate.ChunkBuffer = new GpuBuffer\u003CGpuChunk\u003E(state.ChunkCount, GpuBuffer.UsageFlags.Structured);\n\t\tstate.ChunkBuffer.SetData(chunks);\n\n\t\tstate.CellBuffer = new GpuBuffer\u003CGrassStorage.Cell\u003E(cells.Length, GpuBuffer.UsageFlags.Structured);\n\t\tstate.CellBuffer.SetData(cells);\n\n\t\tstate.VisibleChunkBuffer = new GpuBuffer\u003Cint\u003E(state.ChunkCount, GpuBuffer.UsageFlags.Structured);\n\t\tstate.VisibleScratch = new int[state.ChunkCount];\n\n\t\tstate.ArgsBuffer = new GpuBuffer\u003CGpuBuffer.IndirectDrawArguments\u003E(1, GpuBuffer.UsageFlags.IndirectDrawArguments);\n\n\t\t// The vertex count is written when the draw is recorded, which happens later this same\n\t\t// frame - it depends on the style, and that can change without the painted data changing.\n\t\tstate.UploadedVertexCount = -1;\n\t}\n\n\tprivate void RecordCommandList(CameraComponent camera)\n\t{\n\t\t_commandList.Reset();\n\n\t\tif (_bladeBuffer is null || Layers.Count == 0)\n\t\t\treturn;\n\n\t\tvar cameraPosition = camera.WorldPosition;\n\n\t\tUploadFrustumPlanes(camera);\n\n\t\t// Shared by every layer: one camera, one frustum, one instance buffer.\n\t\t_commandList.Attributes.Set(\u0022GrassFrustumPlanes\u0022, _frustumPlaneBuffer);\n\t\t_commandList.Attributes.Set(\u0022GrassBlades\u0022, _bladeBuffer);\n\t\t_commandList.Attributes.Set(\u0022GrassCameraPos\u0022, cameraPosition);\n\t\t_commandList.Attributes.Set(\u0022GrassTime\u0022, RealTime.Now);\n\n\t\tfor (var i = 0; i \u003C Layers.Count; i\u002B\u002B)\n\t\t\tRecordLayer(Layers[i], _layerStates[i], cameraPosition);\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Generates and draws one layer. Layers share the instance buffer, so the barriers around each\n\t/// one also order it against the layer before: the transition back to UnorderedAccess cannot\n\t/// start until the previous layer\u0027s draw has finished reading. That serializes the layers on the\n\t/// GPU, which is the price of not allocating the whole budget once per layer.\n\t/// \u003C/summary\u003E\n\tprivate void RecordLayer(GrassLayer layer, LayerState state, Vector3 cameraPosition)\n\t{\n\t\tif (layer is null || !layer.Enabled || state.ChunkCount == 0)\n\t\t\treturn;\n\n\t\tvar size = AskSize(layer);\n\t\tif (size \u003C= 0.0f)\n\t\t\treturn;\n\n\t\tvar definition = layer.Definition;\n\n\t\tvar visibleCount = CollectVisibleChunks(state, cameraPosition, definition?.MaxDistance ?? 12000.0f);\n\t\tif (visibleCount == 0)\n\t\t\treturn;\n\n\t\tvar (material, vertexCount) = GetDrawSetup(definition);\n\n\t\tif (material is null)\n\t\t{\n\t\t\tif (!state.WarnedAboutMaterial)\n\t\t\t{\n\t\t\t\tstate.WarnedAboutMaterial = true;\n\t\t\t\tLog.Warning($\u0022{nameof(GrassRenderer)}: layer \u0027{layer.DisplayName}\u0027 is set to Sprites but names \u0022 \u002B\n\t\t\t\t\t\u0022no Sprite Material, so there is nothing to draw it with. Assign a material using the \u0022 \u002B\n\t\t\t\t\t\u0022grass_sprite shader, with the sprite sheet in its Color slot and a greyscale image of \u0022 \u002B\n\t\t\t\t\t\u0022the cutout in its Alpha slot.\u0022);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tstate.WarnedAboutMaterial = false;\n\n\t\tUpdateSpriteTable(state, definition);\n\n\t\t// The vertex count only changes when the style or the plane count does, so it is written\n\t\t// then rather than every frame: an unconditional SetData here would be a CPU write racing\n\t\t// the CopyStructureCount below, which fills in the instance count of the same struct.\n\t\tif (vertexCount != state.UploadedVertexCount)\n\t\t{\n\t\t\tstate.ArgsBuffer.SetData(new[] { new GpuBuffer.IndirectDrawArguments { VertexCount = (uint)vertexCount } });\n\t\t\tstate.UploadedVertexCount = vertexCount;\n\t\t}\n\n\t\t_commandList.Attributes.Set(\u0022GrassChunks\u0022, state.ChunkBuffer);\n\t\t_commandList.Attributes.Set(\u0022GrassCells\u0022, state.CellBuffer);\n\t\t_commandList.Attributes.Set(\u0022GrassVisibleChunks\u0022, state.VisibleChunkBuffer);\n\t\t_commandList.Attributes.Set(\u0022GrassVisibleChunkCount\u0022, visibleCount);\n\t\t_commandList.Attributes.Set(\u0022GrassSeed\u0022, layer.Seed);\n\t\t_commandList.Attributes.Set(\u0022GrassSpriteVariants\u0022, state.SpriteBuffer);\n\t\t_commandList.Attributes.Set(\u0022GrassSpriteCount\u0022, state.UploadedSprites.Count);\n\t\t_commandList.Attributes.Set(\u0022GrassSizeScale\u0022, size);\n\n\t\tdefinition?.ApplyTo(_commandList.Attributes);\n\n\t\t_commandList.ResourceBarrierTransition(_bladeBuffer, ResourceState.UnorderedAccess);\n\t\t_commandList.SetCounterValue(_bladeBuffer, 0);\n\n\t\t_commandList.DispatchCompute(_generateShader, visibleCount * GrassStorage.CellsPerChunk, 1, 1);\n\n\t\t// The appends must all land before the counter is read into the draw arguments.\n\t\t_commandList.UavBarrier(_bladeBuffer);\n\n\t\t_commandList.ResourceBarrierTransition(state.ArgsBuffer, ResourceState.CopyDestination);\n\t\t_commandList.CopyStructureCount(_bladeBuffer, state.ArgsBuffer, ArgsInstanceCountOffset);\n\n\t\t_commandList.ResourceBarrierTransition(_bladeBuffer, ResourceState.GenericRead);\n\t\t_commandList.ResourceBarrierTransition(state.ArgsBuffer, ResourceState.IndirectArgument);\n\n\t\t_commandList.DrawInstancedIndirect(material, state.ArgsBuffer);\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// How big the game wants this layer\u0027s grass right now, from \u003Csee cref=\u0022IEvents.OnGrassSize\u0022/\u003E:\n\t/// 1 when nothing listens, never below 0. Asked of this renderer\u0027s own scene, since in the editor\n\t/// the active scene can be another one.\n\t/// \u003C/summary\u003E\n\tprivate float AskSize(GrassLayer layer)\n\t{\n\t\t_sizeLayer = layer;\n\t\t_size = 1.0f;\n\n\t\tScene.RunEvent(_askSize ??= listener =\u003E listener.OnGrassSize(this, _sizeLayer, ref _size));\n\n\t\t_sizeLayer = null;\n\n\t\treturn MathF.Max(_size, 0.0f);\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Keeps the layer\u0027s table of sheet cells in step with its definition. Rebuilt only when the\n\t/// selection actually changes, which is almost never - the comparison is a handful of ints.\n\t/// \u003C/summary\u003E\n\tprivate void UpdateSpriteTable(LayerState state, GrassDefinition definition)\n\t{\n\t\t_spriteScratch.Clear();\n\n\t\tif (definition is not null \u0026\u0026 definition.Style == GrassStyle.Sprites)\n\t\t{\n\t\t\tdefinition.GetSpriteCells(_spriteScratch);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Blades carry a variant they never read, but the table is indexed either way.\n\t\t\t_spriteScratch.Add(0);\n\t\t}\n\n\t\tif (state.SpriteBuffer is not null \u0026\u0026 Matches(state.UploadedSprites, _spriteScratch))\n\t\t\treturn;\n\n\t\tstate.SpriteBuffer?.Dispose();\n\t\tstate.SpriteBuffer = new GpuBuffer\u003Cint\u003E(_spriteScratch.Count, GpuBuffer.UsageFlags.Structured);\n\t\tstate.SpriteBuffer.SetData(_spriteScratch);\n\n\t\tstate.UploadedSprites.Clear();\n\t\tstate.UploadedSprites.AddRange(_spriteScratch);\n\n\t\tstatic bool Matches(List\u003Cint\u003E _Uploaded, List\u003Cint\u003E _Wanted)\n\t\t{\n\t\t\tif (_Uploaded.Count != _Wanted.Count)\n\t\t\t\treturn false;\n\n\t\t\tfor (var i = 0; i \u003C _Uploaded.Count; i\u002B\u002B)\n\t\t\t{\n\t\t\t\tif (_Uploaded[i] != _Wanted[i])\n\t\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// The material and per-instance vertex count a definition draws with. Both shaders read the\n\t/// same instance buffer filled by the same generation pass; they differ only in what the vertex\n\t/// stage builds out of each instance.\n\t/// \u003C/summary\u003E\n\tprivate (Material Material, int VertexCount) GetDrawSetup(GrassDefinition definition)\n\t{\n\t\t// Sprite cards draw with the material the definition names, because that is what carries\n\t\t// the sheet. Null until one is assigned, and the caller skips the draw.\n\t\tif (definition is not null \u0026\u0026 definition.Style == GrassStyle.Sprites)\n\t\t\treturn (definition.SpriteMaterial, definition.PlaneCount * CardPlaneVertexCount);\n\n\t\t_bladeMaterial ??= Material.FromShader(\u0022grass\u0022);\n\t\treturn (_bladeMaterial, BladeVertexCount);\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Narrows a layer\u0027s dispatch to chunks near the camera. Per-instance frustum culling happens\n\t/// on the GPU; this only has to be conservative.\n\t/// \u003C/summary\u003E\n\tprivate static int CollectVisibleChunks(LayerState state, Vector3 cameraPosition, float maxDistance)\n\t{\n\t\t// A chunk\u0027s near corner can be in range while its centre isn\u0027t, hence the circumradius.\n\t\tvar cullRadius = maxDistance \u002B GrassStorage.ChunkSize * 0.7072f;\n\t\tvar cullRadiusSq = cullRadius * cullRadius;\n\n\t\tvar halfChunk = GrassStorage.ChunkSize * 0.5f;\n\t\tvar count = 0;\n\n\t\tfor (var i = 0; i \u003C state.ChunkOrigins.Count; i\u002B\u002B)\n\t\t{\n\t\t\tvar origin = state.ChunkOrigins[i];\n\t\t\tvar dx = origin.x \u002B halfChunk - cameraPosition.x;\n\t\t\tvar dy = origin.y \u002B halfChunk - cameraPosition.y;\n\n\t\t\tif (dx * dx \u002B dy * dy \u003E cullRadiusSq)\n\t\t\t\tcontinue;\n\n\t\t\tstate.VisibleScratch[count\u002B\u002B] = i;\n\t\t}\n\n\t\tif (count \u003E 0)\n\t\t\tstate.VisibleChunkBuffer.SetData(state.VisibleScratch.AsSpan(0, count));\n\n\t\treturn count;\n\t}\n\n\tprivate void UploadFrustumPlanes(CameraComponent camera)\n\t{\n\t\tvar frustum = camera.GetFrustum();\n\n\t\t// These planes are sampled once on the CPU but the grass they cull is not drawn until the\n\t\t// frame presents, by which point the camera has kept turning. Pushing every plane outward\n\t\t// gives the generation something to work with at the screen edges - without it, grass\n\t\t// rotating into view was culled before it was ever needed, which reads as it streaming in\n\t\t// from the sides. The slack that buys scales with the frame time, so a capped or struggling\n\t\t// framerate is exactly when it matters most.\n\t\tvar padding = MathF.Max(CullPadding, 0.0f);\n\n\t\t// Plane.GetDistance is dot( point, Normal ) - Distance, so w is negated to let the shader\n\t\t// use a plain dot( xyz, p ) \u002B w. Adding the padding there slides the plane outward.\n\t\t_planeScratch[0] = ToVector4(frustum.LeftPlane, padding);\n\t\t_planeScratch[1] = ToVector4(frustum.RightPlane, padding);\n\t\t_planeScratch[2] = ToVector4(frustum.TopPlane, padding);\n\t\t_planeScratch[3] = ToVector4(frustum.BottomPlane, padding);\n\t\t_planeScratch[4] = ToVector4(frustum.NearPlane, padding);\n\n\t\t// The far plane is left tight - MaxDistance already governs the far edge, and padding it\n\t\t// would only generate grass that fades out before it is ever visible.\n\t\t_planeScratch[5] = ToVector4(frustum.FarPlane, 0.0f);\n\n\t\t_frustumPlaneBuffer.SetData(_planeScratch);\n\n\t\tstatic Vector4 ToVector4(Plane plane, float padding) =\u003E\n\t\t\tnew(plane.Normal.x, plane.Normal.y, plane.Normal.z, -plane.Distance \u002B padding);\n\t}\n\n\tprivate void ReleaseBuffers()\n\t{\n\t\tforeach (var state in _layerStates)\n\t\t\tstate.Release();\n\n\t\t_layerStates.Clear();\n\n\t\t_frustumPlaneBuffer?.Dispose();\n\t\t_frustumPlaneBuffer = null;\n\n\t\t_bladeBuffer?.Dispose();\n\t\t_bladeBuffer = null;\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Called by the editor tool after painting, so the next frame re-uploads the density map.\n\t/// \u003C/summary\u003E\n\tpublic void MarkDirty()\n\t{\n\t\tforeach (var state in _layerStates)\n\t\t\tstate.UploadedVersion = -1;\n\t}\n\n\tprotected override void DrawGizmos()\n\t{\n\t\tif (!Gizmo.IsSelected || Layers is null)\n\t\t\treturn;\n\n\t\tGizmo.Draw.Color = Color.Green.WithAlpha(0.35f);\n\n\t\tforeach (var layer in Layers)\n\t\t{\n\t\t\tvar storage = layer?.Storage;\n\t\t\tif (storage is null || storage.ChunkCount == 0)\n\t\t\t\tcontinue;\n\n\t\t\tforeach (var (coord, _) in storage.Chunks)\n\t\t\t{\n\t\t\t\tvar origin = GrassStorage.ChunkOrigin(coord);\n\t\t\t\tvar mins = new Vector3(origin.x, origin.y, 0);\n\t\t\t\tvar maxs = new Vector3(origin.x \u002B GrassStorage.ChunkSize, origin.y \u002B GrassStorage.ChunkSize, 0);\n\n\t\t\t\tGizmo.Draw.LineBBox(new BBox(WorldTransform.PointToLocal(mins), WorldTransform.PointToLocal(maxs)));\n\t\t\t}\n\t\t}\n\t}\n}\n"},{"Ident":"redsnail.grasstool","Path":".obj/__compiler_extra.cs","FileName":"__compiler_extra.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":427870,"IsPrivate":false,"Code":"global using static Sandbox.Internal.GlobalGameNamespace;\r\nglobal using Microsoft.AspNetCore.Components;\r\nglobal using Microsoft.AspNetCore.Components.Rendering;\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022AddonTitle\u0022, \u0022Grass Tool\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022AddonIdent\u0022, \u0022grasstool\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022OrgIdent\u0022, \u0022redsnail\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022Ident\u0022, \u0022redsnail.grasstool\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022EngineVersion\u0022, \u002230\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022EngineMinorVersion\u0022, \u00221\u0022 )]\r\n\r\n[assembly: System.Runtime.Versioning.TargetFramework( \u0022.NETCoreApp,Version=v9.0\u0022, FrameworkDisplayName = \u0022.NET 9.0\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022CompileTime\u0022, \u00222026-10-22T02:56:28.0820255Z\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyVersion(\u00220.0.146.0\u0022)]\r\n[assembly: global::System.Reflection.AssemblyFileVersion(\u00220.0.146.0\u0022)]"},{"Ident":"redsnail.grasstool","Path":"Editor/GrassTool.cs","FileName":"GrassTool.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":427870,"IsPrivate":false,"Code":"using System;\nusing System.Linq;\nusing Editor;\nusing Editor.TerrainEditor;\nusing Sandbox;\n\nnamespace RedSnail.GrassTool.Editor;\n\n/// \u003Csummary\u003E\n/// Paints grass coverage onto any surface. The brush writes density into the target\n/// \u003Csee cref=\u0022GrassRenderer\u0022/\u003E\u0027s density map, baking the surface height and normal under each\n/// cell so blades sit on whatever geometry is there. Hold Ctrl to erase.\n/// \u003C/summary\u003E\n[EditorTool(\u0022grass\u0022)]\n[Title(\u0022Grass\u0022)]\n[Icon(\u0022grass\u0022)]\npublic sealed class GrassPaintTool : EditorTool\n{\n\tpublic BrushSettings BrushSettings { get; private set; } = new();\n\n\tprivate GrassRenderer _target;\n\tprivate int _layerIndex;\n\tprivate ComboBox _layerCombo;\n\tprivate int _layerComboHash;\n\tprivate bool _erasing;\n\tprivate bool _dragging;\n\tprivate bool _painted;\n\tprivate Vector3 _lastPaintPosition;\n\n\t// Repainting the same spot every frame just burns traces, so the brush has to travel a\n\t// fraction of its own radius before it deposits again.\n\tprivate float PaintStepDistance =\u003E BrushSettings.Size * 0.25f;\n\n\tpublic GrassPaintTool()\n\t{\n\t\tRebuildSidebarOnSelectionChange = false;\n\t}\n\n\tpublic override Widget CreateToolSidebar()\n\t{\n\t\tvar sidebar = new ToolSidebarWidget();\n\t\tsidebar.AddTitle(\u0022Grass Brush\u0022, \u0022brush\u0022);\n\t\tsidebar.MinimumWidth = 300;\n\n\t\t{\n\t\t\tvar group = sidebar.AddGroup(\u0022Layer\u0022);\n\t\t\t_layerCombo = new ComboBox();\n\t\t\t_layerComboHash = 0;\n\t\t\tgroup.Add(_layerCombo);\n\t\t\tRebuildLayerCombo();\n\t\t}\n\n\t\t{\n\t\t\tvar group = sidebar.AddGroup(\u0022Brush\u0022);\n\t\t\tvar so = BrushSettings.GetSerialized();\n\t\t\tgroup.Add(ControlSheet.CreateRow(so.GetProperty(nameof(BrushSettings.Size))));\n\t\t\tgroup.Add(ControlSheet.CreateRow(so.GetProperty(nameof(BrushSettings.Opacity))));\n\t\t}\n\n\t\t{\n\t\t\tvar group = sidebar.AddGroup(\u0022Actions\u0022);\n\n\t\t\tvar clear = new Button(\u0022Clear Layer\u0022, \u0022delete_sweep\u0022);\n\t\t\tclear.ToolTip = \u0022Remove every painted cell from the selected layer\u0022;\n\t\t\tclear.Clicked \u002B= () =\u003E\n\t\t\t{\n\t\t\t\tvar layer = ResolveLayer();\n\t\t\t\tif (layer?.Storage is null)\n\t\t\t\t\treturn;\n\n\t\t\t\t// Wiping the density map throws away every stroke and there is no undo for it,\n\t\t\t\t// so this one gets a confirmation.\n\t\t\t\tDialog.AskConfirm(\n\t\t\t\t\t() =\u003E\n\t\t\t\t\t{\n\t\t\t\t\t\tlayer.Storage.ClearAll();\n\t\t\t\t\t\t_target?.MarkDirty();\n\t\t\t\t\t},\n\t\t\t\t\t$\u0022Are you sure you want to delete all grass painted into \u0027{layer.DisplayName}\u0027? \u0022 \u002B\n\t\t\t\t\t\t\u0022This action cannot be undone.\u0022,\n\t\t\t\t\t\u0022Delete Layer\u0027s Grass\u0022,\n\t\t\t\t\t\u0022Delete\u0022,\n\t\t\t\t\t\u0022Cancel\u0022);\n\t\t\t};\n\t\t\tgroup.Add(clear);\n\t\t}\n\n\t\t// Soaks up the leftover height. Without it the column spreads the groups out to fill the\n\t\t// panel instead of stacking them at the top.\n\t\tsidebar.Layout.AddStretchCell();\n\n\t\treturn sidebar;\n\t}\n\n\tpublic override void OnUpdate()\n\t{\n\t\tRebuildLayerCombo();\n\n\t\t_erasing = Gizmo.IsCtrlPressed;\n\n\t\tDrawBrushPreview();\n\n\t\tGizmo.Hitbox.BBox(BBox.FromPositionAndSize(Vector3.Zero, 999999));\n\n\t\tif (Gizmo.IsLeftMouseDown)\n\t\t{\n\t\t\tif (!_dragging)\n\t\t\t{\n\t\t\t\t_dragging = true;\n\t\t\t\t_lastPaintPosition = Vector3.Zero;\n\t\t\t}\n\n\t\t\tOnPaintUpdate();\n\t\t}\n\t\telse if (_dragging)\n\t\t{\n\t\t\t_dragging = false;\n\t\t\t_lastPaintPosition = Vector3.Zero;\n\n\t\t\tif (_painted)\n\t\t\t{\n\t\t\t\tResolveTarget()?.MarkDirty();\n\t\t\t\t_painted = false;\n\t\t\t}\n\t\t}\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Uses the selected renderer if there is one, otherwise the only one in the scene. Creating\n\t/// it implicitly would leave stray components around every time someone opens the tool.\n\t/// \u003C/summary\u003E\n\tprivate GrassRenderer ResolveTarget()\n\t{\n\t\tvar selected = Selection\n\t\t\t.OfType\u003CGameObject\u003E()\n\t\t\t.Select(go =\u003E go.Components.Get\u003CGrassRenderer\u003E(FindMode.EnabledInSelfAndDescendants))\n\t\t\t.FirstOrDefault(r =\u003E r.IsValid());\n\n\t\tif (selected.IsValid())\n\t\t{\n\t\t\t_target = selected;\n\t\t\treturn _target;\n\t\t}\n\n\t\tif (_target.IsValid())\n\t\t\treturn _target;\n\n\t\t_target = Scene.GetAllComponents\u003CGrassRenderer\u003E().FirstOrDefault();\n\t\treturn _target;\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// The layer the brush writes into. Layers each keep their own coverage, so this is what decides\n\t/// whether a stroke lands on the tall grass or the ground cover.\n\t/// \u003C/summary\u003E\n\tprivate GrassLayer ResolveLayer()\n\t{\n\t\tvar target = ResolveTarget();\n\t\tif (!target.IsValid() || target.Layers is null || target.Layers.Count == 0)\n\t\t\treturn null;\n\n\t\t_layerIndex = Math.Clamp(_layerIndex, 0, target.Layers.Count - 1);\n\t\treturn target.Layers[_layerIndex];\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Refills the layer dropdown when the renderer or its layers change. Rebuilt from a hash rather\n\t/// than every frame, since replacing the items would fight the user opening the list.\n\t/// \u003C/summary\u003E\n\tprivate void RebuildLayerCombo()\n\t{\n\t\tif (_layerCombo is null)\n\t\t\treturn;\n\n\t\tvar target = ResolveTarget();\n\t\tvar layers = target.IsValid() ? target.Layers : null;\n\n\t\tvar hash = new HashCode();\n\t\thash.Add(target);\n\n\t\tif (layers is not null)\n\t\t{\n\t\t\tfor (var i = 0; i \u003C layers.Count; i\u002B\u002B)\n\t\t\t\thash.Add(layers[i]?.DisplayName);\n\t\t}\n\n\t\tvar combined = hash.ToHashCode();\n\t\tif (combined == _layerComboHash)\n\t\t\treturn;\n\n\t\t_layerComboHash = combined;\n\t\t_layerCombo.Clear();\n\n\t\tif (layers is null || layers.Count == 0)\n\t\t{\n\t\t\t_layerCombo.AddItem(\u0022No layers\u0022, onSelected: () =\u003E _layerIndex = 0, selected: true);\n\t\t\t_layerCombo.ToolTip = \u0022Add a layer to the Grass Renderer to paint into\u0022;\n\t\t\treturn;\n\t\t}\n\n\t\t_layerIndex = Math.Clamp(_layerIndex, 0, layers.Count - 1);\n\t\t_layerCombo.ToolTip = \u0022Which layer the brush paints into\u0022;\n\n\t\tfor (var i = 0; i \u003C layers.Count; i\u002B\u002B)\n\t\t{\n\t\t\tvar index = i;\n\t\t\t_layerCombo.AddItem(layers[i]?.DisplayName ?? \u0022Unnamed\u0022, onSelected: () =\u003E _layerIndex = index, selected: i == _layerIndex);\n\t\t}\n\t}\n\n\tprivate void OnPaintUpdate()\n\t{\n\t\tvar layer = ResolveLayer();\n\t\tif (layer?.Storage is null)\n\t\t\treturn;\n\n\t\tvar cursor = TraceCursor();\n\t\tif (!cursor.Hit)\n\t\t\treturn;\n\n\t\tif (_lastPaintPosition != Vector3.Zero \u0026\u0026\n\t\t\t Vector3.DistanceBetween(cursor.HitPosition, _lastPaintPosition) \u003C PaintStepDistance)\n\t\t\treturn;\n\n\t\t_lastPaintPosition = cursor.HitPosition;\n\n\t\tvar radius = (float)BrushSettings.Size;\n\t\tvar strength = BrushSettings.Opacity;\n\n\t\tif (_erasing)\n\t\t{\n\t\t\tlayer.Storage.Erase(cursor.HitPosition, radius, strength);\n\t\t\t_painted = true;\n\t\t\treturn;\n\t\t}\n\n\t\tPaintCells(layer.Storage, cursor.HitPosition, radius, strength);\n\t\t_painted = true;\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Walks every density cell the brush touches and traces straight down onto the world to bake\n\t/// the surface height and normal. Blades then follow whatever they were painted onto.\n\t/// \u003C/summary\u003E\n\tprivate void PaintCells(GrassStorage storage, Vector3 center, float radius, float strength)\n\t{\n\t\tvar radiusSq = radius * radius;\n\n\t\tvar minX = (int)MathF.Floor((center.x - radius) / GrassStorage.CellSize);\n\t\tvar maxX = (int)MathF.Floor((center.x \u002B radius) / GrassStorage.CellSize);\n\t\tvar minY = (int)MathF.Floor((center.y - radius) / GrassStorage.CellSize);\n\t\tvar maxY = (int)MathF.Floor((center.y \u002B radius) / GrassStorage.CellSize);\n\n\t\t// Enough headroom to find the surface from above without punching through overhangs the\n\t\t// brush was never aimed at.\n\t\tvar traceHeight = radius \u002B 512.0f;\n\n\t\tfor (var cy = minY; cy \u003C= maxY; cy\u002B\u002B)\n\t\t{\n\t\t\tfor (var cx = minX; cx \u003C= maxX; cx\u002B\u002B)\n\t\t\t{\n\t\t\t\tvar wx = (cx \u002B 0.5f) * GrassStorage.CellSize;\n\t\t\t\tvar wy = (cy \u002B 0.5f) * GrassStorage.CellSize;\n\n\t\t\t\tvar dx = wx - center.x;\n\t\t\t\tvar dy = wy - center.y;\n\t\t\t\tvar distSq = dx * dx \u002B dy * dy;\n\t\t\t\tif (distSq \u003E radiusSq)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tvar from = new Vector3(wx, wy, center.z \u002B traceHeight);\n\t\t\t\tvar to = new Vector3(wx, wy, center.z - traceHeight);\n\n\t\t\t\tvar tr = Scene.Trace.Ray(from, to)\n\t\t\t\t\t.UseRenderMeshes(true)\n\t\t\t\t\t.WithTag(\u0022solid\u0022)\n\t\t\t\t\t.Run();\n\n\t\t\t\tif (!tr.Hit)\n\t\t\t\t\tcontinue;\n\n\t\t\t\t// Soft edge, so overlapping strokes build up smoothly instead of leaving a disc.\n\t\t\t\tvar falloff = 1.0f - MathF.Sqrt(distSq) / radius;\n\t\t\t\tvar added = strength * MathF.Pow(falloff, 0.5f);\n\n\t\t\t\tvar existing = storage.GetCell(wx, wy).Density;\n\t\t\t\tvar density = Math.Clamp(existing \u002B added, 0.0f, 1.0f);\n\n\t\t\t\tstorage.SetCell(wx, wy, density, tr.HitPosition.z, tr.Normal);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate SceneTraceResult TraceCursor() =\u003E\n\t\tScene.Trace.Ray(Gizmo.CurrentRay, 100000)\n\t\t\t.UseRenderMeshes(true)\n\t\t\t.WithTag(\u0022solid\u0022)\n\t\t\t.Run();\n\n\tprivate void DrawBrushPreview()\n\t{\n\t\tvar tr = TraceCursor();\n\t\tif (!tr.Hit)\n\t\t\treturn;\n\n\t\tusing (Gizmo.Scope(\u0022GrassBrush\u0022))\n\t\t{\n\t\t\tGizmo.Draw.Color = _erasing\n\t\t\t\t? Color.FromBytes(250, 150, 150)\n\t\t\t\t: Color.FromBytes(150, 250, 160);\n\n\t\t\tGizmo.Draw.LineCircle(tr.HitPosition \u002B tr.Normal * 1.0f, tr.Normal, BrushSettings.Size);\n\t\t\tGizmo.Draw.LineCircle(tr.HitPosition \u002B tr.Normal * 1.0f, tr.Normal, BrushSettings.Size * 0.5f);\n\t\t}\n\t}\n}\n"}]}