From c3471011b8dd387e8bbe726b2440871af5fa7302 Mon Sep 17 00:00:00 2001
From: Earu <20880060+Earu@users.noreply.github.com>
Date: Thu, 12 Nov 2026 15:58:10 +0400
Subject: [PATCH 1/8] first draft of particles RE/impl based on source sdk 2013
and ghidra decomps
---
Directory.Packages.props | 1 +
Game.Client/Game.Client.csproj | 1 +
Game.Client/HLClient.cs | 40 ++-
Game.Server/Game.Server.csproj | 1 +
Game.Server/GameInterface.cs | 7 +-
Game.Server/World.cs | 2 +-
Game.Shared/Game.Shared.csproj | 1 +
Game.Shared/GarrysMod/GarrysMod.cs | 2 +-
Game.Shared/GarrysMod/LuaGlobalFunctions.cs | 4 +-
Game.Shared/ParticleParse.cs | 97 +++++-
Source.NET.slnx | 6 +
Source.Particles/DmxElementUnpack.cs | 151 ++++++++
Source.Particles/IParticleSystemQuery.cs | 54 +++
Source.Particles/ParticleCollection.cs | 6 +
Source.Particles/ParticleConstants.cs | 97 ++++++
Source.Particles/ParticleOperator.cs | 119 +++++++
Source.Particles/ParticleSystemDefinition.cs | 342 +++++++++++++++++++
Source.Particles/ParticleSystemDictionary.cs | 93 +++++
Source.Particles/ParticleSystemMgr.cs | 202 +++++++++++
Source.Particles/Source.Particles.csproj | 14 +
20 files changed, 1228 insertions(+), 12 deletions(-)
create mode 100644 Source.Particles/DmxElementUnpack.cs
create mode 100644 Source.Particles/IParticleSystemQuery.cs
create mode 100644 Source.Particles/ParticleCollection.cs
create mode 100644 Source.Particles/ParticleConstants.cs
create mode 100644 Source.Particles/ParticleOperator.cs
create mode 100644 Source.Particles/ParticleSystemDefinition.cs
create mode 100644 Source.Particles/ParticleSystemDictionary.cs
create mode 100644 Source.Particles/ParticleSystemMgr.cs
create mode 100644 Source.Particles/Source.Particles.csproj
diff --git a/Directory.Packages.props b/Directory.Packages.props
index cee916b1..a08b1f07 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -14,6 +14,7 @@
+
diff --git a/Game.Client/Game.Client.csproj b/Game.Client/Game.Client.csproj
index c618aea0..556018d4 100644
--- a/Game.Client/Game.Client.csproj
+++ b/Game.Client/Game.Client.csproj
@@ -6,6 +6,7 @@
+
diff --git a/Game.Client/HLClient.cs b/Game.Client/HLClient.cs
index 089660cc..9d57f041 100644
--- a/Game.Client/HLClient.cs
+++ b/Game.Client/HLClient.cs
@@ -79,6 +79,8 @@ public void LevelInitPreEntity(ReadOnlySpan mapname) {
vieweffects.LevelInit();
+ ParseParticleEffectsMap(mapname, true);
+
modemanager.LevelInit(mapname);
ResetToneMapping(1.0f);
IGameSystem.LevelInitPreEntityAllSystems(mapname);
@@ -137,6 +139,10 @@ public bool Init() {
get.IntroScreen()!.Update("Initializing Convars", true);
get.IntroScreen()!.Update("Initializing Objects", true);
get.IntroScreen()!.Update("Initializing Particles", true);
+#endif
+ g_pParticleSystemMgr.Init(null, filesystem);
+ ParseParticleEffects(true, false);
+#if GMOD_DLL
get.IntroScreen()!.Update("Initializing VGUI", true);
get.IntroScreen()!.Update("Adding Game Systems", true);
#endif
@@ -204,6 +210,7 @@ public bool Init() {
public void Shutdown() {
ClientVoiceMgr_Shutdown();
+ g_pParticleSystemMgr.UncacheAllParticleSystems();
#if GMOD_DLL
Game.Client.GarrysMod.GarrysMod.Lua.Kill();
get.MenuSystem()?.Shutdown();
@@ -237,6 +244,31 @@ public bool CanShowSpeakerLabels() {
public static bool g_bLevelInitialized;
public static INetworkStringTable? g_pStringTableClientSideChoreoScenes;
public static INetworkStringTable? g_pStringTableMaterials;
+ public static INetworkStringTable? g_pStringTableParticleEffectNames;
+
+ public static void PrecacheParticleSystem(ReadOnlySpan particleSystemName) {
+ g_pStringTableParticleEffectNames!.AddString(false, particleSystemName);
+ g_pParticleSystemMgr.PrecacheParticleSystem(particleSystemName.ToString());
+ }
+
+ public static int GetParticleSystemIndex(ReadOnlySpan particleSystemName) {
+ if (!particleSystemName.IsEmpty) {
+ int index = g_pStringTableParticleEffectNames!.FindStringIndex(particleSystemName);
+ if (index != INetworkStringTable.INVALID_STRING_INDEX)
+ return index;
+ DevWarning($"Client: Missing precache for particle system \"{particleSystemName}\"!\n");
+ }
+ return 0;
+ }
+
+ public static ReadOnlySpan GetParticleSystemNameFromIndex(int index) {
+ if (index < g_pStringTableParticleEffectNames!.GetMaxStrings())
+ return g_pStringTableParticleEffectNames.GetString(index);
+ return "error";
+ }
+
+ static void OnParticleSystemStringTableChanged(object? context, INetworkStringTable stringTable, int stringNumber, ReadOnlySpan newString, ReadOnlySpan newData)
+ => g_pParticleSystemMgr.PrecacheParticleSystem(newString.ToString());
public static int GetMaterialIndex(ReadOnlySpan materialName) {
if (!materialName.IsEmpty) {
@@ -303,7 +335,11 @@ public void InstallStringTableCallback(ReadOnlySpan tableName) {
case "Scenes":
g_pStringTableClientSideChoreoScenes = networkstringtable.FindTable(tableName);
break;
- case "ParticleEffectNames": Warning("FIXME: ParticleEffectNames string table not being processed yet\n"); break;
+ case "ParticleEffectNames":
+ g_pStringTableParticleEffectNames = networkstringtable.FindTable(tableName);
+ networkstringtable.SetAllowClientSideAddString(g_pStringTableParticleEffectNames!, true);
+ g_pStringTableParticleEffectNames!.SetStringChangedCallback(null, OnParticleSystemStringTableChanged);
+ break;
#if GMOD_DLL
case Protocol.NETWORKSTRING_TABLENAME:
Game.Client.GarrysMod.NetworkString.Install();
@@ -550,6 +586,8 @@ public void LevelShutdown() {
gHUD.LevelShutdown();
+ g_pParticleSystemMgr.UncacheAllParticleSystems();
+
#if GMOD_DLL
Game.Client.GarrysMod.GarrysMod.Lua.Kill();
#endif
diff --git a/Game.Server/Game.Server.csproj b/Game.Server/Game.Server.csproj
index 42019900..216c2794 100644
--- a/Game.Server/Game.Server.csproj
+++ b/Game.Server/Game.Server.csproj
@@ -7,6 +7,7 @@
+
pMapName, ReadOnlyMemory pMapEnti
// UpdateChapterRestrictions(pMapName);
+ ParseParticleEffects(false, false);
+
//Tony; parse custom manifest if exists!
- // ParseParticleEffectsMap(pMapName, false);
+ ParseParticleEffectsMap(pMapName, false);
// IGameSystem::LevelInitPreEntityAllSystems() is called when the world is precached
// That happens either in LoadGameState() or in MapEntity_ParseAllEntities()
diff --git a/Game.Server/World.cs b/Game.Server/World.cs
index 23fc9027..7324e793 100644
--- a/Game.Server/World.cs
+++ b/Game.Server/World.cs
@@ -77,7 +77,7 @@ public override void Precache() {
// InitBodyQue();
SENTENCEG_Init();
- // PrecacheStandardParticleSystems();
+ PrecacheStandardParticleSystems();
BaseCombatWeapon.W_Precache();
GameServerClientMethods.ClientPrecache();
diff --git a/Game.Shared/Game.Shared.csproj b/Game.Shared/Game.Shared.csproj
index 527eb547..607e3bb1 100644
--- a/Game.Shared/Game.Shared.csproj
+++ b/Game.Shared/Game.Shared.csproj
@@ -21,6 +21,7 @@
+
diff --git a/Game.Shared/GarrysMod/GarrysMod.cs b/Game.Shared/GarrysMod/GarrysMod.cs
index 8d64a9c7..7f369f7a 100644
--- a/Game.Shared/GarrysMod/GarrysMod.cs
+++ b/Game.Shared/GarrysMod/GarrysMod.cs
@@ -184,7 +184,7 @@ public void LevelInit(ReadOnlySpan mapName) {
AddCustomFonts();
if (gpGlobals.MaxClients > 1) {
- // todo: ParseParticleEffects(true, false);
+ ParseParticleEffects(true, false);
}
string status = (gpGlobals.MaxClients < 2 ? "Singleplayer - " : "Multiplayer - ") + mapName.ToString();
diff --git a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs
index 405ed4c5..706fdd3f 100644
--- a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs
+++ b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs
@@ -173,8 +173,8 @@ static int PrecacheParticleSystem(ILuaInterface lua) {
string name = lua.CheckString(1);
#if GAME_DLL
GameInterface.PrecacheParticleSystem(name);
-#else
- // PrecacheParticleSystem(name); // TODO!
+#elif CLIENT_DLL
+ HLClient.PrecacheParticleSystem(name);
#endif
return 0;
}
diff --git a/Game.Shared/ParticleParse.cs b/Game.Shared/ParticleParse.cs
index a604c738..fb1f202d 100644
--- a/Game.Shared/ParticleParse.cs
+++ b/Game.Shared/ParticleParse.cs
@@ -1,10 +1,10 @@
-using Source.Common;
-using System;
-using System.Collections.Generic;
-using System.Linq;
+global using static Game.Shared.ParticleParse;
+
+using Source.Common;
+using Source.Common.Formats.Keyvalues;
+using Source.Particles;
+
using System.Numerics;
-using System.Text;
-using System.Threading.Tasks;
namespace Game.Shared;
@@ -36,3 +36,88 @@ public struct ParticleEffectsControlPoint
[NetworkVar("m_vecOffset")]
public Vector3 Offset;
}
+
+public static class ParticleParse
+{
+ public const string PARTICLES_MANIFEST_FILE = "particles/particles_manifest.txt";
+
+ public static readonly ParticleSystemMgr g_pParticleSystemMgr = new();
+
+ public static void GetParticleManifest(List list) {
+ KeyValues manifest = new(PARTICLES_MANIFEST_FILE);
+ if (manifest.LoadFromFile(filesystem, PARTICLES_MANIFEST_FILE, "GAME")) {
+ for (KeyValues? sub = manifest.GetFirstSubKey(); sub != null; sub = sub.GetNextKey()) {
+ if (sub.Name.Equals("file", StringComparison.OrdinalIgnoreCase)) {
+ list.Add(sub.GetString().ToString());
+ continue;
+ }
+
+ Warning($"CParticleMgr::Init: Manifest '{PARTICLES_MANIFEST_FILE}' with bogus file type '{sub.Name}', expecting 'file'\n");
+ }
+ }
+ else
+ Warning($"PARTICLE SYSTEM: Unable to load manifest file '{PARTICLES_MANIFEST_FILE}'\n");
+ }
+
+ public static void ParseParticleEffects(bool loadSheets, bool precache) {
+ g_pParticleSystemMgr.ShouldLoadSheets(loadSheets);
+
+ List files = [];
+ GetParticleManifest(files);
+
+ foreach (string file in files)
+ g_pParticleSystemMgr.ReadParticleConfigFile(file, precache, false);
+
+ g_pParticleSystemMgr.DecommitTempMemory();
+ }
+
+ public static void ParseParticleEffectsMap(ReadOnlySpan mapName, bool loadSheets) {
+ List files = [];
+ string mapManifestFilename = mapName.IsEmpty ? "" : $"maps/{mapName}_particles.txt";
+
+ KeyValues manifest = new(mapManifestFilename);
+ if (!manifest.LoadFromFile(filesystem, mapManifestFilename, "GAME"))
+ return;
+
+ DevMsg($"Successfully loaded particle effects manifest '{mapManifestFilename}' for map '{mapName}'\n");
+ for (KeyValues? sub = manifest.GetFirstSubKey(); sub != null; sub = sub.GetNextKey()) {
+ if (sub.Name.Equals("file", StringComparison.OrdinalIgnoreCase)) {
+ string file = sub.GetString().ToString();
+ int lastSlash = file.LastIndexOfAny(['/', '\\']);
+ ReadOnlySpan path = lastSlash >= 0 ? file.AsSpan(0, lastSlash) : [];
+ if (path.StartsWith("!"))
+ path = path[1..];
+
+ if (path.Equals("particles", StringComparison.OrdinalIgnoreCase)) {
+ files.Add(file);
+ continue;
+ }
+
+ Warning($"CParticleMgr::LevelInit: Manifest '{mapManifestFilename}' contains a particle file '{file}' that's not under the particles directory. Custom particles must be placed in the particles directory.\n");
+ }
+ else
+ Warning($"CParticleMgr::LevelInit: Manifest '{mapManifestFilename}' with bogus file type '{sub.Name}', expecting 'file'\n");
+ }
+
+ if (files.Count == 0)
+ return;
+
+ g_pParticleSystemMgr.ShouldLoadSheets(loadSheets);
+
+ foreach (string file in files)
+ g_pParticleSystemMgr.ReadParticleConfigFile(file, true, true);
+
+ g_pParticleSystemMgr.DecommitTempMemory();
+ }
+
+#if GAME_DLL
+ public static void PrecacheStandardParticleSystems() {
+ for (int i = 0; i < g_pParticleSystemMgr.GetParticleSystemCount(); i++) {
+ string particleSystemName = g_pParticleSystemMgr.GetParticleSystemNameFromIndex(i);
+ ParticleSystemDefinition? particleSystem = g_pParticleSystemMgr.FindParticleSystem(particleSystemName);
+ if (particleSystem != null && particleSystem.ShouldAlwaysPrecache())
+ Game.Server.GameInterface.PrecacheParticleSystem(particleSystemName);
+ }
+ }
+#endif
+}
diff --git a/Source.NET.slnx b/Source.NET.slnx
index a3f97c6c..e6d0f5d6 100644
--- a/Source.NET.slnx
+++ b/Source.NET.slnx
@@ -119,6 +119,9 @@
+
+
+
@@ -175,4 +178,7 @@
+
+
+
diff --git a/Source.Particles/DmxElementUnpack.cs b/Source.Particles/DmxElementUnpack.cs
new file mode 100644
index 00000000..5b0880f8
--- /dev/null
+++ b/Source.Particles/DmxElementUnpack.cs
@@ -0,0 +1,151 @@
+using Datamodel;
+
+using System.Globalization;
+using System.Numerics;
+
+using DmColor = Datamodel.Color;
+using DmQAngle = Datamodel.QAngle;
+using SourceColor = Source.Color;
+using SourceQAngle = Source.Common.Mathematics.QAngle;
+
+namespace Source.Particles;
+
+public enum DmAttributeType
+{
+ Unknown = 0,
+ Element,
+ Int,
+ Float,
+ Bool,
+ String,
+ Void,
+ ObjectId,
+ Color,
+ Vector2,
+ Vector3,
+ Vector4,
+ QAngle,
+ Quaternion,
+ VMatrix
+}
+
+public readonly record struct DmxElementUnpackField(string AttributeName, string? DefaultString, DmAttributeType AttributeType, int Size);
+
+public interface IDmxElementUnpackStructure
+{
+ IEnumerable Fields { get; }
+ void UnpackIntoStructure(Element element, object target);
+}
+
+public static class DmxElementUnpack
+{
+ public static DmAttributeType GetAttributeType(object? value) => value switch {
+ null => DmAttributeType.Element,
+ Element => DmAttributeType.Element,
+ int => DmAttributeType.Int,
+ float => DmAttributeType.Float,
+ bool => DmAttributeType.Bool,
+ string => DmAttributeType.String,
+ byte[] => DmAttributeType.Void,
+ DmColor => DmAttributeType.Color,
+ Vector2 => DmAttributeType.Vector2,
+ Vector3 => DmAttributeType.Vector3,
+ Vector4 => DmAttributeType.Vector4,
+ DmQAngle => DmAttributeType.QAngle,
+ Quaternion => DmAttributeType.Quaternion,
+ Matrix4x4 => DmAttributeType.VMatrix,
+ _ => DmAttributeType.Unknown
+ };
+
+ public static object? ParseValue(DmAttributeType type, string text) {
+ string[] tokens = text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
+ int I(int i) => i < tokens.Length ? ScanInt(tokens[i]) : 0;
+ float F(int i) => i < tokens.Length ? ScanFloat(tokens[i]) : 0;
+ return type switch {
+ DmAttributeType.Int => I(0),
+ DmAttributeType.Float => F(0),
+ DmAttributeType.Bool => I(0) != 0,
+ DmAttributeType.String => text,
+ DmAttributeType.Color => new DmColor((byte)I(0), (byte)I(1), (byte)I(2), (byte)I(3)),
+ DmAttributeType.Vector2 => new Vector2(F(0), F(1)),
+ DmAttributeType.Vector3 => new Vector3(F(0), F(1), F(2)),
+ DmAttributeType.Vector4 => new Vector4(F(0), F(1), F(2), F(3)),
+ DmAttributeType.QAngle => new DmQAngle(F(0), F(1), F(2)),
+ DmAttributeType.Quaternion => new Quaternion(F(0), F(1), F(2), F(3)),
+ _ => null
+ };
+ }
+
+ static int ScanInt(string token) {
+ int end = 0;
+ if (end < token.Length && (token[end] == '-' || token[end] == '+'))
+ end++;
+ while (end < token.Length && char.IsAsciiDigit(token[end]))
+ end++;
+ return int.TryParse(token.AsSpan(0, end), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out int value) ? value : 0;
+ }
+
+ static float ScanFloat(string token) => float.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out float value) ? value : 0;
+}
+
+public sealed class DmxElementUnpackStructure : IDmxElementUnpackStructure where T : class
+{
+ readonly List<(DmxElementUnpackField Field, Action Setter)> fields = [];
+
+ public IEnumerable Fields => fields.Select(f => f.Field);
+
+ DmxElementUnpackStructure Add(string name, string? defaultString, DmAttributeType type, int size, Action setter) {
+ fields.Add((new DmxElementUnpackField(name, defaultString, type, size), setter));
+ return this;
+ }
+
+ public DmxElementUnpackStructure Int(string name, string? defaultString, Action set)
+ => Add(name, defaultString, DmAttributeType.Int, sizeof(int), (t, v) => set(t, (int)v));
+ public DmxElementUnpackStructure Float(string name, string? defaultString, Action set)
+ => Add(name, defaultString, DmAttributeType.Float, sizeof(float), (t, v) => set(t, (float)v));
+ public DmxElementUnpackStructure Bool(string name, string? defaultString, Action set)
+ => Add(name, defaultString, DmAttributeType.Bool, sizeof(bool), (t, v) => set(t, (bool)v));
+ public DmxElementUnpackStructure String(string name, string? defaultString, int size, Action set)
+ => Add(name, defaultString, DmAttributeType.String, size, (t, v) => {
+ string s = (string)v;
+ set(t, s.Length >= size ? s[..(size - 1)] : s);
+ });
+ public DmxElementUnpackStructure Color(string name, string? defaultString, Action set)
+ => Add(name, defaultString, DmAttributeType.Color, 4, (t, v) => {
+ DmColor c = (DmColor)v;
+ set(t, new SourceColor(c.R, c.G, c.B, c.A));
+ });
+ public DmxElementUnpackStructure Vector2(string name, string? defaultString, Action set)
+ => Add(name, defaultString, DmAttributeType.Vector2, 8, (t, v) => set(t, (Vector2)v));
+ public DmxElementUnpackStructure Vector3(string name, string? defaultString, Action set)
+ => Add(name, defaultString, DmAttributeType.Vector3, 12, (t, v) => set(t, (Vector3)v));
+ public DmxElementUnpackStructure Vector4(string name, string? defaultString, Action set)
+ => Add(name, defaultString, DmAttributeType.Vector4, 16, (t, v) => set(t, (Vector4)v));
+ public DmxElementUnpackStructure QAngle(string name, string? defaultString, Action set)
+ => Add(name, defaultString, DmAttributeType.QAngle, 12, (t, v) => {
+ DmQAngle a = (DmQAngle)v;
+ set(t, new SourceQAngle(a.Pitch, a.Yaw, a.Roll));
+ });
+
+ public void UnpackIntoStructure(Element element, object target) => UnpackIntoStructure(element, (T)target);
+
+ public void UnpackIntoStructure(Element element, T target) {
+ foreach ((DmxElementUnpackField field, Action setter) in fields) {
+ if (field.AttributeType == DmAttributeType.Void)
+ continue;
+
+ if (!element.TryGetValue(field.AttributeName, out object? value)) {
+ if (field.DefaultString == null)
+ continue;
+ value = DmxElementUnpack.ParseValue(field.AttributeType, field.DefaultString);
+ }
+
+ if (DmxElementUnpack.GetAttributeType(value) != field.AttributeType) {
+ Warning($"CDmxElement::UnpackIntoStructure: Mismatched attribute type in attribute \"{field.AttributeName}\"!\n");
+ continue;
+ }
+
+ setter(target, value!);
+ }
+ }
+}
diff --git a/Source.Particles/IParticleSystemQuery.cs b/Source.Particles/IParticleSystemQuery.cs
new file mode 100644
index 00000000..0c3a50ef
--- /dev/null
+++ b/Source.Particles/IParticleSystemQuery.cs
@@ -0,0 +1,54 @@
+using Source.Common;
+using Source.Common.Formats.BSP;
+using Source.Common.Mathematics;
+
+using System.Numerics;
+
+namespace Source.Particles;
+
+public struct ModelHitBoxInfo
+{
+ public Vector3 BoxMins;
+ public Vector3 BoxMaxes;
+ public Matrix3x4 Transform;
+}
+
+public interface IParticleSystemQuery
+{
+ void GetLightingAtPoint(in Vector3 origin, out Color tint);
+ void TraceLine(in Vector3 absStart, in Vector3 absEnd, Mask mask, IHandleEntity? ignore, int collisionGroup, ref GameTrace trace);
+
+ bool MovePointInsideControllingObject(ParticleCollection particles, object? obj, ref Vector3 pnt) => true;
+ bool IsPointInControllingObjectHitBox(ParticleCollection particles, int controlPointNumber, Vector3 pos, bool bboxOnly = false) => true;
+ int GetCollisionGroupFromName(ReadOnlySpan collisionGroupName) => 0;
+
+ void GetRandomPointsOnControllingObjectHitBox(ParticleCollection particles, int controlPointNumber, int numPtsOut, float bboxScale, int numTrysToGetAPointInsideTheModel,
+ Span pntsOut, Vector3 directionBias, Span hitBoxRelativeCoordOut = default, Span hitBoxIndexOut = default);
+
+ int GetControllingObjectHitBoxInfo(ParticleCollection particles, int controlPointNumber, Span hitBoxOutputBuffer) => 0;
+
+ Vector3 GetLocalPlayerPos() => Vector3.Zero;
+ void GetLocalPlayerEyeVectors(out Vector3 forward, out Vector3 right, out Vector3 up) {
+ forward = Vector3.Zero;
+ right = Vector3.Zero;
+ up = Vector3.Zero;
+ }
+
+ float GetPixelVisibility(ref int queryHandle, in Vector3 origin, float scale);
+
+ void SetUpLightingEnvironment(in Vector3 pos) { }
+}
+
+public sealed class DefaultParticleSystemQuery : IParticleSystemQuery
+{
+ public void GetLightingAtPoint(in Vector3 origin, out Color tint) => tint = new Color(255, 255, 255, 255);
+
+ public void TraceLine(in Vector3 absStart, in Vector3 absEnd, Mask mask, IHandleEntity? ignore, int collisionGroup, ref GameTrace trace) => trace.Fraction = 1.0f;
+
+ public void GetRandomPointsOnControllingObjectHitBox(ParticleCollection particles, int controlPointNumber, int numPtsOut, float bboxScale, int numTrysToGetAPointInsideTheModel,
+ Span pntsOut, Vector3 directionBias, Span hitBoxRelativeCoordOut = default, Span hitBoxIndexOut = default) {
+ pntsOut[..numPtsOut].Clear();
+ }
+
+ public float GetPixelVisibility(ref int queryHandle, in Vector3 origin, float scale) => 0;
+}
diff --git a/Source.Particles/ParticleCollection.cs b/Source.Particles/ParticleCollection.cs
new file mode 100644
index 00000000..7623e30a
--- /dev/null
+++ b/Source.Particles/ParticleCollection.cs
@@ -0,0 +1,6 @@
+namespace Source.Particles;
+
+public class ParticleCollection
+{
+ public ParticleSystemDefinition? Def;
+}
diff --git a/Source.Particles/ParticleConstants.cs b/Source.Particles/ParticleConstants.cs
new file mode 100644
index 00000000..2108a7ac
--- /dev/null
+++ b/Source.Particles/ParticleConstants.cs
@@ -0,0 +1,97 @@
+namespace Source.Particles;
+
+public enum ParticleFunctionType
+{
+ Renderer = 0,
+ Operator,
+ Initializer,
+ Emitter,
+ Children,
+ ForceGenerator,
+ Constraint,
+ Count
+}
+
+public enum ParticleOperatorId
+{
+ Generic = -2,
+ Singleton = -1,
+ PiPosition,
+ PiRadius,
+ PiAlpha,
+ PiTintRGB,
+ PiRotation,
+ PiYaw,
+ Count
+}
+
+public static class ParticleConstants
+{
+ public const int MAX_RANDOM_FLOATS = 4096;
+ public const int RANDOM_FLOAT_MASK = MAX_RANDOM_FLOATS - 1;
+
+ public const int MAX_PARTICLE_ATTRIBUTES = 32;
+
+ public const int PARTICLE_ATTRIBUTE_XYZ = 0;
+ public const int PARTICLE_ATTRIBUTE_LIFE_DURATION = 1;
+ public const int PARTICLE_ATTRIBUTE_PREV_XYZ = 2;
+ public const int PARTICLE_ATTRIBUTE_RADIUS = 3;
+ public const int PARTICLE_ATTRIBUTE_ROTATION = 4;
+ public const int PARTICLE_ATTRIBUTE_ROTATION_SPEED = 5;
+ public const int PARTICLE_ATTRIBUTE_TINT_RGB = 6;
+ public const int PARTICLE_ATTRIBUTE_ALPHA = 7;
+ public const int PARTICLE_ATTRIBUTE_CREATION_TIME = 8;
+ public const int PARTICLE_ATTRIBUTE_SEQUENCE_NUMBER = 9;
+ public const int PARTICLE_ATTRIBUTE_TRAIL_LENGTH = 10;
+ public const int PARTICLE_ATTRIBUTE_PARTICLE_ID = 11;
+ public const int PARTICLE_ATTRIBUTE_YAW = 12;
+ public const int PARTICLE_ATTRIBUTE_SEQUENCE_NUMBER1 = 13;
+ public const int PARTICLE_ATTRIBUTE_HITBOX_INDEX = 14;
+ public const int PARTICLE_ATTRIBUTE_HITBOX_RELATIVE_XYZ = 15;
+ public const int PARTICLE_ATTRIBUTE_ALPHA2 = 16;
+ public const int PARTICLE_ATTRIBUTE_TRACE_P0 = 17;
+ public const int PARTICLE_ATTRIBUTE_TRACE_P1 = 18;
+ public const int PARTICLE_ATTRIBUTE_TRACE_HIT_T = 19;
+ public const int PARTICLE_ATTRIBUTE_TRACE_HIT_NORMAL = 20;
+ public const int PARTICLE_ATTRIBUTE_CONTROL_POINT_INDEX = 21;
+
+ public const int PARTICLE_ATTRIBUTE_XYZ_MASK = 1 << PARTICLE_ATTRIBUTE_XYZ;
+ public const int PARTICLE_ATTRIBUTE_LIFE_DURATION_MASK = 1 << PARTICLE_ATTRIBUTE_LIFE_DURATION;
+ public const int PARTICLE_ATTRIBUTE_PREV_XYZ_MASK = 1 << PARTICLE_ATTRIBUTE_PREV_XYZ;
+ public const int PARTICLE_ATTRIBUTE_RADIUS_MASK = 1 << PARTICLE_ATTRIBUTE_RADIUS;
+ public const int PARTICLE_ATTRIBUTE_ROTATION_MASK = 1 << PARTICLE_ATTRIBUTE_ROTATION;
+ public const int PARTICLE_ATTRIBUTE_ROTATION_SPEED_MASK = 1 << PARTICLE_ATTRIBUTE_ROTATION_SPEED;
+ public const int PARTICLE_ATTRIBUTE_TINT_RGB_MASK = 1 << PARTICLE_ATTRIBUTE_TINT_RGB;
+ public const int PARTICLE_ATTRIBUTE_ALPHA_MASK = 1 << PARTICLE_ATTRIBUTE_ALPHA;
+ public const int PARTICLE_ATTRIBUTE_CREATION_TIME_MASK = 1 << PARTICLE_ATTRIBUTE_CREATION_TIME;
+ public const int PARTICLE_ATTRIBUTE_SEQUENCE_NUMBER_MASK = 1 << PARTICLE_ATTRIBUTE_SEQUENCE_NUMBER;
+ public const int PARTICLE_ATTRIBUTE_TRAIL_LENGTH_MASK = 1 << PARTICLE_ATTRIBUTE_TRAIL_LENGTH;
+ public const int PARTICLE_ATTRIBUTE_PARTICLE_ID_MASK = 1 << PARTICLE_ATTRIBUTE_PARTICLE_ID;
+ public const int PARTICLE_ATTRIBUTE_YAW_MASK = 1 << PARTICLE_ATTRIBUTE_YAW;
+ public const int PARTICLE_ATTRIBUTE_SEQUENCE_NUMBER1_MASK = 1 << PARTICLE_ATTRIBUTE_SEQUENCE_NUMBER1;
+ public const int PARTICLE_ATTRIBUTE_HITBOX_INDEX_MASK = 1 << PARTICLE_ATTRIBUTE_HITBOX_INDEX;
+ public const int PARTICLE_ATTRIBUTE_HITBOX_RELATIVE_XYZ_MASK = 1 << PARTICLE_ATTRIBUTE_HITBOX_RELATIVE_XYZ;
+ public const int PARTICLE_ATTRIBUTE_ALPHA2_MASK = 1 << PARTICLE_ATTRIBUTE_ALPHA2;
+ public const int PARTICLE_ATTRIBUTE_TRACE_P0_MASK = 1 << PARTICLE_ATTRIBUTE_TRACE_P0;
+ public const int PARTICLE_ATTRIBUTE_TRACE_P1_MASK = 1 << PARTICLE_ATTRIBUTE_TRACE_P1;
+ public const int PARTICLE_ATTRIBUTE_TRACE_HIT_T_MASK = 1 << PARTICLE_ATTRIBUTE_TRACE_HIT_T;
+ public const int PARTICLE_ATTRIBUTE_TRACE_HIT_NORMAL_MASK = 1 << PARTICLE_ATTRIBUTE_TRACE_HIT_NORMAL;
+ public const int PARTICLE_ATTRIBUTE_CONTROL_POINT_INDEX_MASK = 1 << PARTICLE_ATTRIBUTE_CONTROL_POINT_INDEX;
+
+ public const int MAX_PARTICLE_CONTROL_POINTS = 64;
+
+ public const int ATTRIBUTES_WHICH_ARE_VEC3S_MASK = PARTICLE_ATTRIBUTE_TRACE_P0_MASK | PARTICLE_ATTRIBUTE_TRACE_P1_MASK |
+ PARTICLE_ATTRIBUTE_TRACE_HIT_NORMAL | PARTICLE_ATTRIBUTE_XYZ_MASK |
+ PARTICLE_ATTRIBUTE_PREV_XYZ_MASK | PARTICLE_ATTRIBUTE_TINT_RGB_MASK |
+ PARTICLE_ATTRIBUTE_HITBOX_RELATIVE_XYZ_MASK;
+ public const int ATTRIBUTES_WHICH_ARE_0_TO_1 = PARTICLE_ATTRIBUTE_ALPHA_MASK | PARTICLE_ATTRIBUTE_ALPHA2_MASK;
+ public const int ATTRIBUTES_WHICH_ARE_ANGLES = PARTICLE_ATTRIBUTE_ROTATION_MASK | PARTICLE_ATTRIBUTE_YAW_MASK;
+ public const int ATTRIBUTES_WHICH_ARE_INTS = PARTICLE_ATTRIBUTE_PARTICLE_ID_MASK | PARTICLE_ATTRIBUTE_HITBOX_INDEX_MASK | PARTICLE_ATTRIBUTE_CONTROL_POINT_INDEX_MASK;
+
+ public const int MAX_PARTICLES_IN_A_SYSTEM = 5000;
+
+ public const int PCFLAGS_FIRST_FRAME = 0x1;
+ public const int PCFLAGS_PREV_CONTROL_POINTS_INITIALIZED = 0x2;
+
+ public const int INVALID_PARTICLE_SYSTEM_HANDLE = 0xFFFF;
+}
diff --git a/Source.Particles/ParticleOperator.cs b/Source.Particles/ParticleOperator.cs
new file mode 100644
index 00000000..ac233407
--- /dev/null
+++ b/Source.Particles/ParticleOperator.cs
@@ -0,0 +1,119 @@
+using Datamodel;
+
+namespace Source.Particles;
+
+public interface IParticleOperatorDefinition
+{
+ string? GetName();
+ ParticleOperatorInstance? CreateInstance(Guid id);
+ IDmxElementUnpackStructure? GetUnpackStructure();
+ ParticleOperatorId GetId();
+ bool IsObsolete();
+}
+
+public sealed class ParticleOperatorDefinition(string factoryName, ParticleOperatorId id, bool isObsolete, IDmxElementUnpackStructure? unpackParams) : IParticleOperatorDefinition
+ where T : ParticleOperatorInstance, new()
+{
+ public string GetName() => factoryName;
+ public ParticleOperatorId GetId() => id;
+ public IDmxElementUnpackStructure? GetUnpackStructure() => unpackParams;
+ public bool IsObsolete() => isObsolete;
+
+ public ParticleOperatorInstance? CreateInstance(Guid instanceId) {
+ T op = new();
+ op.SetDefinition(this, instanceId);
+ return op;
+ }
+}
+
+public struct ParticleVisibilityInputs
+{
+ public float CameraBias;
+ public float InputMin;
+ public float InputMax;
+ public float AlphaScaleMin;
+ public float AlphaScaleMax;
+ public float RadiusScaleMin;
+ public float RadiusScaleMax;
+ public float ProxyRadius;
+ public float BBoxScale;
+ public bool UseBBox;
+ public int CPin;
+}
+
+public abstract class ParticleOperatorInstance
+{
+ public float OpStartFadeInTime;
+ public float OpEndFadeInTime;
+ public float OpStartFadeOutTime;
+ public float OpEndFadeOutTime;
+ public float OpFadeOscillatePeriod;
+
+ IParticleOperatorDefinition? Def;
+ Guid Id;
+
+ internal void SetDefinition(IParticleOperatorDefinition def, Guid id) {
+ Def = def;
+ Id = id;
+ }
+
+ public IParticleOperatorDefinition? GetDefinition() => Def;
+ public Guid GetId() => Id;
+
+ public virtual void InitParams(ParticleSystemDefinition def, Element element) { }
+ public virtual int GetRequiredContextBytes() => 0;
+
+ public abstract uint GetWrittenAttributes();
+ public abstract uint GetReadAttributes();
+ public virtual ulong GetReadControlPointMask() => 0;
+ public virtual uint GetReadInitialAttributes() => 0;
+
+ public virtual bool IsBatchable() => true;
+ public virtual bool IsFinalConstraint() => false;
+ public virtual bool InitMultipleOverride() => false;
+ public virtual bool IsScrubSafe() => false;
+ public virtual bool ShouldRunBeforeEmitters() => false;
+ public virtual bool RequiresOrderInvariance() => false;
+}
+
+public abstract class ParticleRenderOperatorInstance : ParticleOperatorInstance
+{
+ public ParticleVisibilityInputs VisibilityInputs;
+}
+
+public static class ParticleOperatorUnpack
+{
+ public static DmxElementUnpackStructure Begin() where T : ParticleOperatorInstance
+ => new DmxElementUnpackStructure()
+ .Float("operator start fadein", "0", (o, v) => o.OpStartFadeInTime = v)
+ .Float("operator end fadein", "0", (o, v) => o.OpEndFadeInTime = v)
+ .Float("operator start fadeout", "0", (o, v) => o.OpStartFadeOutTime = v)
+ .Float("operator end fadeout", "0", (o, v) => o.OpEndFadeOutTime = v)
+ .Float("operator fade oscillate", "0", (o, v) => o.OpFadeOscillatePeriod = v);
+
+ public static DmxElementUnpackStructure BeginRender() where T : ParticleRenderOperatorInstance
+ => Begin()
+ .Int("Visibility Proxy Input Control Point Number", "-1", (o, v) => o.VisibilityInputs.CPin = v)
+ .Float("Visibility Proxy Radius", "1.0", (o, v) => o.VisibilityInputs.ProxyRadius = v)
+ .Float("Visibility input minimum", "0", (o, v) => o.VisibilityInputs.InputMin = v)
+ .Float("Visibility input maximum", "1", (o, v) => o.VisibilityInputs.InputMax = v)
+ .Float("Visibility Alpha Scale minimum", "0", (o, v) => o.VisibilityInputs.AlphaScaleMin = v)
+ .Float("Visibility Alpha Scale maximum", "1", (o, v) => o.VisibilityInputs.AlphaScaleMax = v)
+ .Float("Visibility Radius Scale minimum", "1", (o, v) => o.VisibilityInputs.RadiusScaleMin = v)
+ .Float("Visibility Radius Scale maximum", "1", (o, v) => o.VisibilityInputs.RadiusScaleMax = v)
+ .Float("Visibility Camera Depth Bias", "0", (o, v) => o.VisibilityInputs.CameraBias = v);
+}
+
+public sealed class ChildOperatorDefinition : IParticleOperatorDefinition
+{
+ public static readonly ChildOperatorDefinition Instance = new();
+
+ public static readonly DmxElementUnpackStructure ChildrenInfoUnpack = new DmxElementUnpackStructure()
+ .Float("delay", "0.0", (c, v) => c.Delay = v);
+
+ public string? GetName() => null;
+ public ParticleOperatorInstance? CreateInstance(Guid id) => null;
+ public IDmxElementUnpackStructure? GetUnpackStructure() => ChildrenInfoUnpack;
+ public ParticleOperatorId GetId() => ParticleOperatorId.Generic;
+ public bool IsObsolete() => false;
+}
diff --git a/Source.Particles/ParticleSystemDefinition.cs b/Source.Particles/ParticleSystemDefinition.cs
new file mode 100644
index 00000000..5d1e25a8
--- /dev/null
+++ b/Source.Particles/ParticleSystemDefinition.cs
@@ -0,0 +1,342 @@
+using Datamodel;
+
+using Source.Common.MaterialSystem;
+
+using System.Numerics;
+
+using static Source.MaterialDefines;
+using static Source.Particles.ParticleConstants;
+
+namespace Source.Particles;
+
+public class ParticleChildrenInfo
+{
+ public Guid Id;
+ public string? Name;
+ public bool UseNameBasedLookup;
+ public float Delay;
+}
+
+public sealed class ParticleSystemDefinition(ParticleSystemMgr mgr)
+{
+ public const string DmeParticleSystemDefinition = "DmeParticleSystemDefinition";
+
+ static readonly string[] RemapOperatorNameTable = [
+ "alpha_fade", "Alpha Fade and Decay",
+ "alpha_fade_in_random", "Alpha Fade In Random",
+ "alpha_fade_out_random", "Alpha Fade Out Random",
+ "basic_movement", "Movement Basic",
+ "color_fade", "Color Fade",
+ "controlpoint_light", "Color Light From Control Point",
+ "Dampen Movement Relative to Control Point", "Movement Dampen Relative to Control Point",
+ "Distance Between Control Points Scale", "Remap Distance Between Two Control Points to Scalar",
+ "Distance to Control Points Scale", "Remap Distance to Control Point to Scalar",
+ "lifespan_decay", "Lifespan Decay",
+ "lock to bone", "Movement Lock to Bone",
+ "postion_lock_to_controlpoint", "Movement Lock to Control Point",
+ "maintain position along path", "Movement Maintain Position Along Path",
+ "lock to saved position along path", "Movement Lock to Saved Position Along Path",
+ "Match Particle Velocities", "Movement Match Particle Velocities",
+ "Max Velocity", "Movement Max Velocity",
+ "noise", "Noise Scalar",
+ "vector noise", "Noise Vector",
+ "oscillate_scalar", "Oscillate Scalar",
+ "oscillate_vector", "Oscillate Vector",
+ "Orient Rotation to 2D Direction", "Rotation Orient to 2D Direction",
+ "radius_scale", "Radius Scale",
+ "Random Cull", "Cull Random",
+ "remap_scalar", "Remap Scalar",
+ "rotation_movement", "Rotation Basic",
+ "rotation_spin", "Rotation Spin Roll",
+ "rotation_spin yaw", "Rotation Spin Yaw",
+ "alpha_random", "Alpha Random",
+ "color_random", "Color Random",
+ "create from parent particles", "Position From Parent Particles",
+ "Create In Hierarchy", "Position In CP Hierarchy",
+ "random position along path", "Position Along Path Random",
+ "random position on model", "Position on Model Random",
+ "sequential position along path", "Position Along Path Sequential",
+ "position_offset_random", "Position Modify Offset Random",
+ "position_warp_random", "Position Modify Warp Random",
+ "position_within_box", "Position Within Box Random",
+ "position_within_sphere", "Position Within Sphere Random",
+ "Inherit Velocity", "Velocity Inherit from Control Point",
+ "Initial Repulsion Velocity", "Velocity Repulse from World",
+ "Initial Velocity Noise", "Velocity Noise",
+ "Initial Scalar Noise", "Remap Noise to Scalar",
+ "Lifespan from distance to world", "Lifetime from Time to Impact",
+ "Pre-Age Noise", "Lifetime Pre-Age Noise",
+ "lifetime_random", "Lifetime Random",
+ "radius_random", "Radius Random",
+ "random yaw", "Rotation Yaw Random",
+ "Randomly Flip Yaw", "Rotation Yaw Flip Random",
+ "rotation_random", "Rotation Random",
+ "rotation_speed_random", "Rotation Speed Random",
+ "sequence_random", "Sequence Random",
+ "second_sequence_random", "Sequence Two Random",
+ "trail_length_random", "Trail Length Random",
+ "velocity_random", "Velocity Random",
+ ];
+
+ static readonly DmxElementUnpackStructure UnpackStructure = new DmxElementUnpackStructure()
+ .Int("max_particles", "1000", (d, v) => d.MaxParticles = v)
+ .Int("initial_particles", "0", (d, v) => d.InitialParticles = v)
+ .String("material", "vgui/white", MAX_PATH, (d, v) => d.MaterialName = v)
+ .Vector3("bounding_box_min", "-10 -10 -10", (d, v) => d.BoundingBoxMin = v)
+ .Vector3("bounding_box_max", "10 10 10", (d, v) => d.BoundingBoxMax = v)
+ .Float("cull_radius", "0", (d, v) => d.CullRadius = v)
+ .Float("cull_cost", "1", (d, v) => d.CullFillCost = v)
+ .Int("cull_control_point", "0", (d, v) => d.CullControlPoint = v)
+ .String("cull_replacement_definition", "", 128, (d, v) => d.CullReplacementName = v)
+ .Float("radius", "5", (d, v) => d.ConstantRadius = v)
+ .Color("color", "255 255 255 255", (d, v) => d.ConstantColor = v)
+ .Float("rotation", "0", (d, v) => d.ConstantRotation = v)
+ .Float("rotation_speed", "0", (d, v) => d.ConstantRotationSpeed = v)
+ .Int("sequence_number", "0", (d, v) => d.ConstantSequenceNumber = v)
+ .Int("sequence_number 1", "0", (d, v) => d.ConstantSequenceNumber1 = v)
+ .Int("group id", "0", (d, v) => d.GroupID = v)
+ .Float("maximum time step", "0.1", (d, v) => d.MaximumTimeStep = v)
+ .Float("maximum sim tick rate", "0.0", (d, v) => d.MaximumSimTime = v)
+ .Float("minimum sim tick rate", "0.0", (d, v) => d.MinimumSimTime = v)
+ .Int("minimum rendered frames", "0", (d, v) => d.MinimumFrames = v)
+ .Int("control point to disable rendering if it is the camera", "-1", (d, v) => d.SkipRenderControlPoint = v)
+ .Float("maximum draw distance", "100000.0", (d, v) => d.MaxDrawDistance = v)
+ .Float("time to sleep when not drawn", "8", (d, v) => d.NoDrawTimeToGoToSleep = v)
+ .Bool("Sort particles", "1", (d, v) => d.ShouldSort = v)
+ .Bool("batch particle systems", "0", (d, v) => d.ShouldBatch = v)
+ .Bool("view model effect", "0", (d, v) => d.ViewModelEffect = v);
+
+ public static IDmxElementUnpackStructure GetUnpackStructure() => UnpackStructure;
+
+ readonly ParticleSystemMgr Mgr = mgr;
+
+ public int InitialParticles;
+ public int PerParticleUpdatedAttributeMask;
+ public int PerParticleInitializedAttributeMask;
+ public int InitialAttributeReadMask;
+ public int AttributeReadMask;
+ public ulong ControlPointReadMask;
+ public Vector3 BoundingBoxMin;
+ public Vector3 BoundingBoxMax;
+ public string MaterialName = "";
+ public readonly MaterialReference Material = new();
+ public ParticleCollection? FirstCollection;
+ public string CullReplacementName = "";
+ public float CullRadius;
+ public float CullFillCost = 1.0f;
+ public int CullControlPoint;
+ public int RetireCheckFrame;
+
+ public Color ConstantColor = new(0, 0, 0, 0);
+ public float ConstantRadius;
+ public float ConstantRotation;
+ public float ConstantRotationSpeed;
+ public int ConstantSequenceNumber;
+ public int ConstantSequenceNumber1;
+ public int GroupID;
+ public float MaximumTimeStep;
+ public float MaximumSimTime;
+ public float MinimumSimTime;
+ public int MinimumFrames;
+ public bool ViewModelEffect;
+
+ public int ContextDataSize;
+ public Guid Id;
+
+ public float MaxDrawDistance;
+ public float NoDrawTimeToGoToSleep;
+ public int MaxParticles;
+ public int SkipRenderControlPoint;
+ public string Name = "";
+
+ public readonly List Operators = [];
+ public readonly List Renderers = [];
+ public readonly List Initializers = [];
+ public readonly List Emitters = [];
+ public readonly List ForceGenerators = [];
+ public readonly List Constraints = [];
+ public readonly List Children = [];
+
+ public readonly List OperatorsCtxOffsets = [];
+ public readonly List RenderersCtxOffsets = [];
+ public readonly List InitializersCtxOffsets = [];
+ public readonly List EmittersCtxOffsets = [];
+ public readonly List ForceGeneratorsCtxOffsets = [];
+ public readonly List ConstraintsCtxOffsets = [];
+
+ public float TotalSimTime;
+ public float UncomittedTotalSimTime;
+ public float MaxMeasuredSimTime;
+ public int MaximumActiveParticles;
+ public bool ShouldSort = true;
+ public bool ShouldBatch;
+ public bool IsPrecached;
+ public bool AlwaysPrecache;
+
+ public string GetName() => Name;
+ public Guid GetId() => Id;
+ public IMaterial? GetMaterial() => Material.Get();
+ public bool ShouldAlwaysPrecache() => AlwaysPrecache;
+ public bool IsViewModelEffect() => ViewModelEffect;
+ public float GetCullRadius() => CullRadius;
+ public float GetCullFillCost() => CullFillCost;
+ public int GetCullControlPoint() => CullControlPoint;
+ public string GetCullReplacementDefinition() => CullReplacementName;
+ public bool HasRetirementBeenChecked(int frame) => RetireCheckFrame == frame;
+ public void MarkRetirementCheck(int frame) => RetireCheckFrame = frame;
+ public void MarkReadsControlPoint(int point) => ControlPointReadMask |= 1UL << point;
+ public bool ReadsControlPoint(int point) => (ControlPointReadMask & (1UL << point)) != 0;
+
+ public void Read(Element element) {
+ Name = element.Name;
+ Id = element.ID;
+ UnpackStructure.UnpackIntoStructure(element, this);
+
+ if (InitialParticles < 0)
+ InitialParticles = 0;
+
+ MaxParticles = Math.Min(Math.Max(MaxParticles, 1) * ParticleSystemMgr.g_nParticle_Multiplier, MAX_PARTICLES_IN_A_SYSTEM);
+
+ if (CullRadius > 0)
+ ControlPointReadMask |= 1UL << (CullControlPoint & 0x3F);
+
+ ParseOperators("renderers", ParticleFunctionType.Renderer, element, Renderers);
+ ParseOperators("operators", ParticleFunctionType.Operator, element, Operators);
+ ParseOperators("initializers", ParticleFunctionType.Initializer, element, Initializers);
+ ParseOperators("emitters", ParticleFunctionType.Emitter, element, Emitters);
+ ParseChildren(element);
+ ParseOperators("forces", ParticleFunctionType.ForceGenerator, element, ForceGenerators);
+ ParseOperators("constraints", ParticleFunctionType.Constraint, element, Constraints);
+ SetupContextData();
+ }
+
+ static string RemapOperatorName(string name) {
+ for (int i = 0; i < RemapOperatorNameTable.Length; i += 2) {
+ if (string.Equals(name, RemapOperatorNameTable[i], StringComparison.OrdinalIgnoreCase))
+ return RemapOperatorNameTable[i + 1];
+ }
+ return name;
+ }
+
+ void ParseOperators(string opKey, ParticleFunctionType functionType, Element element, List outList) {
+ if (!element.TryGetValue(opKey, out object? attribute) || attribute is not ElementArray ops)
+ return;
+
+ List flist = Mgr.GetAvailableParticleOperatorList(functionType);
+ foreach (Element? op in ops) {
+ if (op == null)
+ continue;
+
+ string functionName = op.TryGetValue("functionName", out object? fn) && fn is string s ? s : "";
+ functionName = RemapOperatorName(functionName);
+
+ IParticleOperatorDefinition? opDef = null;
+ foreach (IParticleOperatorDefinition candidate in flist) {
+ if (string.Equals(functionName, candidate.GetName(), StringComparison.OrdinalIgnoreCase)) {
+ opDef = candidate;
+ break;
+ }
+ }
+
+ if (opDef == null) {
+ if (flist.Count != 0)
+ Warning($"Didn't find particle function {functionName}\n");
+ continue;
+ }
+
+ ParticleOperatorInstance op2 = opDef.CreateInstance(op.ID)!;
+ opDef.GetUnpackStructure()?.UnpackIntoStructure(op, op2);
+ op2.InitParams(this, element);
+
+ AttributeReadMask |= (int)op2.GetReadAttributes();
+ ControlPointReadMask |= op2.GetReadControlPointMask();
+
+ switch (functionType) {
+ case ParticleFunctionType.Renderer:
+ case ParticleFunctionType.Operator:
+ PerParticleUpdatedAttributeMask |= (int)op2.GetWrittenAttributes();
+ InitialAttributeReadMask |= (int)op2.GetReadInitialAttributes();
+ break;
+ case ParticleFunctionType.Initializer:
+ case ParticleFunctionType.Emitter:
+ PerParticleInitializedAttributeMask |= (int)op2.GetWrittenAttributes();
+ break;
+ }
+
+ if (((op2.GetReadAttributes() | op2.GetReadInitialAttributes()) & PARTICLE_ATTRIBUTE_PARTICLE_ID_MASK) != 0) {
+ PerParticleInitializedAttributeMask |= PARTICLE_ATTRIBUTE_PARTICLE_ID_MASK;
+ InitialAttributeReadMask |= PARTICLE_ATTRIBUTE_PARTICLE_ID_MASK;
+ }
+
+ outList.Add(op2);
+ }
+ }
+
+ void ParseChildren(Element element) {
+ if (!element.TryGetValue("children", out object? attribute) || attribute is not ElementArray children)
+ return;
+
+ foreach (Element? childRef in children) {
+ if (childRef == null)
+ continue;
+ if (!childRef.TryGetValue("child", out object? childValue) || childValue is not Element particleSystem)
+ continue;
+ if (!string.Equals(particleSystem.ClassName, DmeParticleSystemDefinition, StringComparison.OrdinalIgnoreCase))
+ continue;
+
+ ParticleChildrenInfo info = new();
+ Children.Add(info);
+ ChildOperatorDefinition.ChildrenInfoUnpack.UnpackIntoStructure(childRef, info);
+ info.UseNameBasedLookup = !(particleSystem.TryGetValue("preventNameBasedLookup", out object? prevent) && prevent is true);
+ if (info.UseNameBasedLookup)
+ info.Name = particleSystem.Name;
+ else
+ info.Id = particleSystem.ID;
+
+ Mgr.Dictionary!.AddParticleSystem(particleSystem);
+ }
+ }
+
+ void SetupContextData() {
+ ContextDataSize = 0;
+ ReadOnlySpan> olists = [Operators, Renderers, Initializers, Emitters, ForceGenerators, Constraints];
+ ReadOnlySpan> offsetLists = [OperatorsCtxOffsets, RenderersCtxOffsets, InitializersCtxOffsets, EmittersCtxOffsets, ForceGeneratorsCtxOffsets, ConstraintsCtxOffsets];
+ for (int i = 0; i < olists.Length; i++) {
+ foreach (ParticleOperatorInstance op in olists[i]) {
+ offsetLists[i].Add(ContextDataSize);
+ ContextDataSize = (ContextDataSize + op.GetRequiredContextBytes() + 15) & ~15;
+ }
+ }
+ }
+
+ ParticleSystemDefinition? FindChild(ParticleChildrenInfo child)
+ => child.UseNameBasedLookup ? Mgr.Dictionary!.FindParticleSystem(child.Name) : Mgr.Dictionary!.FindParticleSystem(child.Id);
+
+ public void Precache() {
+ if (IsPrecached)
+ return;
+
+ IsPrecached = true;
+ Material.Init(MaterialName, TEXTURE_GROUP_OTHER, true);
+
+ foreach (ParticleChildrenInfo child in Children) {
+ ParticleSystemDefinition? childDef = FindChild(child);
+ if (childDef != null && !childDef.IsPrecached)
+ childDef.Precache();
+ }
+ }
+
+ public void Uncache() {
+ if (!IsPrecached)
+ return;
+
+ IsPrecached = false;
+ Material.Shutdown();
+
+ foreach (ParticleChildrenInfo child in Children) {
+ ParticleSystemDefinition? childDef = FindChild(child);
+ if (childDef != null && childDef.IsPrecached)
+ childDef.Uncache();
+ }
+ }
+}
diff --git a/Source.Particles/ParticleSystemDictionary.cs b/Source.Particles/ParticleSystemDictionary.cs
new file mode 100644
index 00000000..98ff50cc
--- /dev/null
+++ b/Source.Particles/ParticleSystemDictionary.cs
@@ -0,0 +1,93 @@
+using Datamodel;
+
+using static Source.Particles.ParticleConstants;
+
+namespace Source.Particles;
+
+public sealed class ParticleSystemDictionary(ParticleSystemMgr mgr)
+{
+ readonly Dictionary NameSymbols = new(StringComparer.OrdinalIgnoreCase);
+ readonly List SymbolNames = [];
+ readonly List ParticleNameMap = [];
+ readonly List ParticleIdMap = [];
+
+ public int NameCount() => SymbolNames.Count;
+ public int Count() => ParticleIdMap.Count;
+ public ParticleSystemDefinition GetParticleSystem(int index) => ParticleIdMap[index];
+
+ public IEnumerable AllDefinitions() {
+ foreach (ParticleSystemDefinition def in ParticleIdMap)
+ yield return def;
+ foreach (ParticleSystemDefinition? def in ParticleNameMap)
+ if (def != null)
+ yield return def;
+ }
+
+ int FindSymbol(string? name) => name != null && NameSymbols.TryGetValue(name, out int symbol) ? symbol : INVALID_PARTICLE_SYSTEM_HANDLE;
+
+ int AddSymbol(string name) {
+ if (NameSymbols.TryGetValue(name, out int symbol))
+ return symbol;
+ symbol = SymbolNames.Count;
+ NameSymbols[name] = symbol;
+ SymbolNames.Add(name);
+ return symbol;
+ }
+
+ public int FindParticleSystemHandle(string? name) => FindSymbol(name);
+
+ public string? GetSymbolName(int handle) => handle >= 0 && handle < SymbolNames.Count ? SymbolNames[handle] : null;
+
+ public ParticleSystemDefinition? FindParticleSystem(int handle)
+ => handle != INVALID_PARTICLE_SYSTEM_HANDLE && handle >= 0 && handle < ParticleNameMap.Count ? ParticleNameMap[handle] : null;
+
+ public ParticleSystemDefinition? FindParticleSystem(string? name) => FindParticleSystem(FindSymbol(name));
+
+ public ParticleSystemDefinition? FindParticleSystem(Guid id) {
+ foreach (ParticleSystemDefinition def in ParticleIdMap)
+ if (def.GetId() == id)
+ return def;
+ return null;
+ }
+
+ static bool PreventNameBasedLookup(Element element)
+ => element.TryGetValue("preventNameBasedLookup", out object? value) && value is true;
+
+ void SetNameMap(int symbol, ParticleSystemDefinition? def) {
+ while (ParticleNameMap.Count <= symbol)
+ ParticleNameMap.Add(null);
+ ParticleNameMap[symbol] = def;
+ }
+
+ void DestroyExistingElement(Element element) {
+ if (PreventNameBasedLookup(element)) {
+ int index = ParticleIdMap.FindIndex(d => d.GetId() == element.ID);
+ if (index < 0)
+ return;
+ ParticleIdMap[index] = ParticleIdMap[^1];
+ ParticleIdMap.RemoveAt(ParticleIdMap.Count - 1);
+ return;
+ }
+
+ int symbol = FindSymbol(element.Name);
+ if (symbol == INVALID_PARTICLE_SYSTEM_HANDLE)
+ return;
+ SetNameMap(symbol, null);
+ }
+
+ public ParticleSystemDefinition? AddParticleSystem(Element particleSystem) {
+ if (!string.Equals(particleSystem.ClassName, ParticleSystemDefinition.DmeParticleSystemDefinition, StringComparison.OrdinalIgnoreCase))
+ return null;
+
+ DestroyExistingElement(particleSystem);
+
+ ParticleSystemDefinition def = new(mgr);
+ if (PreventNameBasedLookup(particleSystem))
+ ParticleIdMap.Add(def);
+ else
+ SetNameMap(AddSymbol(particleSystem.Name), def);
+
+ def.Read(particleSystem);
+ return def;
+ }
+}
diff --git a/Source.Particles/ParticleSystemMgr.cs b/Source.Particles/ParticleSystemMgr.cs
new file mode 100644
index 00000000..6b06c784
--- /dev/null
+++ b/Source.Particles/ParticleSystemMgr.cs
@@ -0,0 +1,202 @@
+using Datamodel;
+
+using Source.Common.Filesystem;
+using Source.Common.Formats.Keyvalues;
+using Source.Common.MaterialSystem;
+
+using DM = Datamodel.Datamodel;
+
+using static Source.Particles.ParticleConstants;
+
+namespace Source.Particles;
+
+public sealed class ParticleSystemMgr
+{
+ public static int g_nParticle_Multiplier = 1;
+
+ readonly List[] ParticleOperators = new List[(int)ParticleFunctionType.Count];
+
+ public ParticleSystemDictionary? Dictionary { get; private set; }
+
+ IParticleSystemQuery Query_ = new DefaultParticleSystemQuery();
+ IFileSystem? FileSystem;
+ IMaterial? ShadowDepthMaterial;
+ float LastSimulationTime;
+ bool DidInit;
+ bool UsingDefaultQuery = true;
+ bool ShouldLoadSheets_ = true;
+
+ public ParticleSystemMgr() {
+ for (int i = 0; i < ParticleOperators.Length; i++)
+ ParticleOperators[i] = [];
+ }
+
+ public IParticleSystemQuery Query() => Query_;
+
+ public bool Init(IParticleSystemQuery? query, IFileSystem fileSystem) {
+ FileSystem = fileSystem;
+
+ if (UsingDefaultQuery && query != null) {
+ Query_ = query;
+ UsingDefaultQuery = false;
+ }
+
+ if (DidInit)
+ return true;
+
+ Dictionary = new ParticleSystemDictionary(this);
+ ParticleOperators[(int)ParticleFunctionType.Children].Add(ChildOperatorDefinition.Instance);
+
+ ShadowDepthMaterial = null;
+ if (Singleton().GetDXSupportLevel() >= 90) {
+ KeyValues vmtKeyValues = new("DepthWrite");
+ vmtKeyValues.SetInt("$no_fullbright", 1);
+ vmtKeyValues.SetInt("$model", 0);
+ vmtKeyValues.SetInt("$alphatest", 0);
+ ShadowDepthMaterial = Singleton().CreateMaterial("__particlesDepthWrite", vmtKeyValues);
+ }
+
+ DidInit = true;
+ return true;
+ }
+
+ public void AddParticleOperator(ParticleFunctionType opType, IParticleOperatorDefinition opFactory)
+ => ParticleOperators[(int)opType].Add(opFactory);
+
+ public List GetAvailableParticleOperatorList(ParticleFunctionType whichList) => ParticleOperators[(int)whichList];
+
+ public IDmxElementUnpackStructure GetParticleSystemDefinitionUnpackStructure() => ParticleSystemDefinition.GetUnpackStructure();
+
+ public void ShouldLoadSheets(bool loadSheets) => ShouldLoadSheets_ = loadSheets;
+ public bool GetShouldLoadSheets() => ShouldLoadSheets_;
+
+ public void DecommitTempMemory() { }
+
+ public void SetLastSimulationTime(float time) => LastSimulationTime = time;
+ public float GetLastSimulationTime() => LastSimulationTime;
+
+ public bool ReadParticleConfigFile(string fileName, bool precache, bool decommitTempMemory = true) {
+ if (fileName.StartsWith('!')) {
+ fileName = fileName[1..];
+ precache = true;
+ }
+
+ IMaterialSystemHardwareConfig hardwareConfig = Singleton();
+ string? fallbackFormat = null;
+ if (hardwareConfig.GetDXSupportLevel() < 90)
+ fallbackFormat = "{0}_dx80.{1}";
+ else if (hardwareConfig.GetDXSupportLevel() == 90 && hardwareConfig.PreferReducedFillrate())
+ fallbackFormat = "{0}_dx90_slow.{1}";
+
+ if (fallbackFormat != null) {
+ int dot = fileName.LastIndexOfAny(['.', '/', '\\']);
+ bool hasExtension = dot >= 0 && fileName[dot] == '.';
+ string stripped = hasExtension ? fileName[..dot] : fileName;
+ string extension = hasExtension ? fileName[(dot + 1)..] : "pcf";
+ string fallback = string.Format(fallbackFormat, stripped, extension);
+ if (FileSystem!.FileExists(fallback))
+ fileName = fallback;
+ }
+
+ using IFileHandle? handle = FileSystem!.Open(fileName, FileOpenOptions.Read | FileOpenOptions.Binary, "GAME");
+ if (handle == null || !handle.IsOK()) {
+ Warning($"Particles: Missing '{fileName}'\n");
+ return false;
+ }
+
+ using MemoryStream buffer = new();
+ handle.Stream.CopyTo(buffer);
+ buffer.Position = 0;
+ return ReadParticleDefinitions(buffer, fileName, precache, decommitTempMemory);
+ }
+
+ public bool ReadParticleConfigFile(Stream buf, bool precache, bool decommitTempMemory = true, string? fileName = null)
+ => ReadParticleDefinitions(buf, fileName, precache, decommitTempMemory);
+
+ bool ReadParticleDefinitions(Stream buf, string? fileName, bool precache, bool decommitTempMemory) {
+ DM dm;
+ try {
+ dm = DM.Load(buf, Datamodel.Codecs.DeferredMode.Disabled);
+ }
+ catch (Exception) {
+ Warning($"Unable to read particle definition {fileName}! UtlBuffer is probably the wrong type!\n");
+ return false;
+ }
+
+ using (dm) {
+ Element? root = dm.Root;
+ if (root == null) {
+ Warning($"Unable to read particle definition {fileName}! UtlBuffer is probably the wrong type!\n");
+ return false;
+ }
+
+ if (string.Equals(root.ClassName, ParticleSystemDefinition.DmeParticleSystemDefinition, StringComparison.OrdinalIgnoreCase)) {
+ AddParticleSystem(root, precache);
+ return true;
+ }
+
+ if (!root.TryGetValue("particleSystemDefinitions", out object? attribute) || attribute is not ElementArray definitions)
+ return false;
+
+ foreach (Element? definition in definitions)
+ if (definition != null)
+ AddParticleSystem(definition, precache);
+ return true;
+ }
+ }
+
+ void AddParticleSystem(Element element, bool precache) {
+ ParticleSystemDefinition? def = Dictionary!.AddParticleSystem(element);
+ if (def != null && precache) {
+ def.AlwaysPrecache = true;
+ if (!def.IsPrecached)
+ def.Precache();
+ }
+ }
+
+ public bool IsParticleSystemDefined(string? name) {
+ if (string.IsNullOrEmpty(name))
+ return false;
+ return Dictionary!.FindParticleSystem(name) != null;
+ }
+
+ public bool IsParticleSystemDefined(Guid id) => id != Guid.Empty && Dictionary!.FindParticleSystem(id) != null;
+
+ public int GetParticleSystemIndex(string? name) => name == null ? INVALID_PARTICLE_SYSTEM_HANDLE : Dictionary!.FindParticleSystemHandle(name);
+
+ public string GetParticleSystemNameFromIndex(int index) {
+ if (index == INVALID_PARTICLE_SYSTEM_HANDLE || index >= Dictionary!.NameCount())
+ return "Unknown";
+ ParticleSystemDefinition? def = Dictionary.FindParticleSystem(index);
+ return def == null ? "Unknown" : def.Name;
+ }
+
+ public int GetParticleSystemCount() => Dictionary!.NameCount();
+
+ public ParticleSystemDefinition? FindParticleSystem(string? name) => Dictionary!.FindParticleSystem(name);
+ public ParticleSystemDefinition? FindParticleSystem(Guid id) => Dictionary!.FindParticleSystem(id);
+
+ public void PrecacheParticleSystem(string? name) {
+ if (string.IsNullOrEmpty(name))
+ return;
+
+ ParticleSystemDefinition? def = Dictionary!.FindParticleSystem(name);
+ if (def == null) {
+ Warning($"Attemped to precache unknown particle system \"{name}\"!\n");
+ return;
+ }
+
+ if (!def.IsPrecached)
+ def.Precache();
+ }
+
+ public void UncacheAllParticleSystems() {
+ if (Dictionary == null)
+ return;
+
+ foreach (ParticleSystemDefinition def in Dictionary.AllDefinitions().ToArray())
+ def.Uncache();
+ }
+
+ public void RecreateDictionary() => Dictionary = new ParticleSystemDictionary(this);
+}
diff --git a/Source.Particles/Source.Particles.csproj b/Source.Particles/Source.Particles.csproj
new file mode 100644
index 00000000..fa070bcd
--- /dev/null
+++ b/Source.Particles/Source.Particles.csproj
@@ -0,0 +1,14 @@
+
+
+ true
+
+
+
+
+
+
+
+
+
+
+
From 8dae88b503146fb1983676560ca5f5bf966db4f3 Mon Sep 17 00:00:00 2001
From: Earu <20880060+Earu@users.noreply.github.com>
Date: Thu, 12 Nov 2026 17:07:07 +0400
Subject: [PATCH 2/8] link particles folder
---
Game.Assets/Assets.cs | 1 +
1 file changed, 1 insertion(+)
diff --git a/Game.Assets/Assets.cs b/Game.Assets/Assets.cs
index 4db9a793..b8607de5 100644
--- a/Game.Assets/Assets.cs
+++ b/Game.Assets/Assets.cs
@@ -33,6 +33,7 @@ public static List GetRequiredAssets() {
new("platform", "platform", IsDirectory: true),
new("sdn/maps", "garrysmod/maps", IsDirectory: true),
new("sdn/materials", "garrysmod/materials", IsDirectory: true),
+ new("sdn/particles", "garrysmod/particles", IsDirectory: true),
new("sdn/resource", "garrysmod/resource", IsDirectory: true),
new("sdn/scenes", "garrysmod/scenes", IsDirectory: true),
#if GMOD_DLL
From 4d6c0d0b3aba4decace450866f98810831ad7d8b Mon Sep 17 00:00:00 2001
From: Earu <20880060+Earu@users.noreply.github.com>
Date: Thu, 12 Nov 2026 17:23:30 +0400
Subject: [PATCH 3/8] particle collection framework: storage, simulate loop,
kill lists, emission control and collection creation
---
Source.Particles/IParticleSystemQuery.cs | 25 +-
Source.Particles/ParticleCollection.cs | 1444 ++++++++++++++++++
Source.Particles/ParticleOperator.cs | 36 +
Source.Particles/ParticleSystemDefinition.cs | 2 +-
Source.Particles/ParticleSystemMgr.cs | 59 +
Source.Particles/Source.Particles.csproj | 3 +
6 files changed, 1567 insertions(+), 2 deletions(-)
diff --git a/Source.Particles/IParticleSystemQuery.cs b/Source.Particles/IParticleSystemQuery.cs
index 0c3a50ef..99f251bc 100644
--- a/Source.Particles/IParticleSystemQuery.cs
+++ b/Source.Particles/IParticleSystemQuery.cs
@@ -13,6 +13,20 @@ public struct ModelHitBoxInfo
public Matrix3x4 Transform;
}
+public sealed class ModelHitBoxesInfo
+{
+ public const int MAX_HITBOXES = 128;
+
+ public float LastUpdateTime = -1;
+ public float PrevLastUpdateTime;
+ public int NumHitBoxes;
+ public int NumPrevHitBoxes;
+ public ModelHitBoxInfo[]? HitBoxes;
+ public ModelHitBoxInfo[]? PrevBoxes;
+
+ public bool CurAndPrevValid() => NumHitBoxes != 0 && NumPrevHitBoxes == NumHitBoxes;
+}
+
public interface IParticleSystemQuery
{
void GetLightingAtPoint(in Vector3 origin, out Color tint);
@@ -23,7 +37,16 @@ public interface IParticleSystemQuery
int GetCollisionGroupFromName(ReadOnlySpan collisionGroupName) => 0;
void GetRandomPointsOnControllingObjectHitBox(ParticleCollection particles, int controlPointNumber, int numPtsOut, float bboxScale, int numTrysToGetAPointInsideTheModel,
- Span pntsOut, Vector3 directionBias, Span hitBoxRelativeCoordOut = default, Span hitBoxIndexOut = default);
+ Span pntsOut, Vector3 directionBias, Span hitBoxRelativeCoordOut = default, Span hitBoxIndexOut = default) {
+ Vector3 position = particles.ControlPoints[controlPointNumber].Position;
+ for (int i = 0; i < numPtsOut; i++) {
+ pntsOut[i] = position;
+ if (!hitBoxRelativeCoordOut.IsEmpty)
+ hitBoxRelativeCoordOut[i] = Vector3.Zero;
+ if (!hitBoxIndexOut.IsEmpty)
+ hitBoxIndexOut[i] = -1;
+ }
+ }
int GetControllingObjectHitBoxInfo(ParticleCollection particles, int controlPointNumber, Span hitBoxOutputBuffer) => 0;
diff --git a/Source.Particles/ParticleCollection.cs b/Source.Particles/ParticleCollection.cs
index 7623e30a..db615770 100644
--- a/Source.Particles/ParticleCollection.cs
+++ b/Source.Particles/ParticleCollection.cs
@@ -1,6 +1,1450 @@
+using Source.Common;
+using Source.Common.MaterialSystem;
+using Source.Common.Mathematics;
+
+using System.Numerics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Runtime.Intrinsics;
+
+using static Source.Particles.ParticleConstants;
+
namespace Source.Particles;
+public struct ParticleControlPoint
+{
+ public Vector3 Position;
+ public Vector3 PrevPosition;
+ public Vector3 ForwardVector;
+ public Vector3 UpVector;
+ public Vector3 RightVector;
+ public Vector3 Velocity;
+ public float Radius;
+ public float Density;
+ public float Duration;
+ public object? Object;
+ public int Parent;
+}
+
+public struct PathParameters
+{
+ public int StartControlPointNumber;
+ public int EndControlPointNumber;
+ public int BulgeControl;
+ public float Bulge;
+ public float MidPoint;
+
+ public void ClampControlPointIndices() {
+ StartControlPointNumber = Math.Max(0, Math.Min(MAX_PARTICLE_CONTROL_POINTS - 1, StartControlPointNumber));
+ EndControlPointNumber = Math.Max(0, Math.Min(MAX_PARTICLE_CONTROL_POINTS - 1, EndControlPointNumber));
+ }
+}
+
public class ParticleCollection
{
+ public const int NUM_COLLISION_CACHE_MODES = 4;
+ const int CONSTANT_FLOATS = MAX_PARTICLE_ATTRIBUTES * 12;
+
+ static readonly float[] RandomFloats = LoadRandomFloats();
+
+ static float[] LoadRandomFloats() {
+ float[] floats = new float[MAX_RANDOM_FLOATS];
+ using Stream stream = typeof(ParticleCollection).Assembly.GetManifestResourceStream("Source.Particles.random_floats.bin")!;
+ stream.ReadExactly(MemoryMarshal.AsBytes(floats.AsSpan()));
+ return floats;
+ }
+
+ public static ReadOnlySpan RandomFloatTable => RandomFloats;
+
+ public int PaddedActiveParticles;
+ public float CurTime;
+ public int ActiveParticles;
+ public float Dt;
+ public float PreviousDt = 0.05f;
+ public float NextSleepTime;
+
+ public ParticleSystemMgr? Mgr;
public ParticleSystemDefinition? Def;
+ public int AllocatedParticles;
+ public int MaxAllowedParticles;
+ public bool Dormant;
+ public bool EmissionStopped;
+ public bool RequiresOrderInvariance;
+
+ public int LocalLightingCP = -1;
+ public Color LocalLighting = new(255, 255, 255, 255);
+
+ public readonly ParticleControlPoint[] ControlPoints = new ParticleControlPoint[MAX_PARTICLE_CONTROL_POINTS];
+ public readonly ModelHitBoxesInfo[] ControlPointHitBoxes = new ModelHitBoxesInfo[MAX_PARTICLE_CONTROL_POINTS];
+
+ public byte[]? OperatorContextData;
+ public ParticleCollection? Next;
+ public ParticleCollection? Prev;
+
+ public readonly object?[] CollisionCacheData = new object?[NUM_COLLISION_CACHE_MODES];
+ public ParticleCollection? Parent;
+ public ParticleCollection? Children;
+
+ protected bool BoundsValid;
+ protected Vector3 MinBounds;
+ protected Vector3 MaxBounds;
+ protected int HighestCP;
+ protected int TargetCP;
+
+ float[] Memory = [];
+ readonly int[] AttributeOffsets = new int[MAX_PARTICLE_ATTRIBUTES];
+ readonly int[] InitialAttributeOffsets = new int[MAX_PARTICLE_ATTRIBUTES];
+ readonly int[] ParticleFloatStrides = new int[MAX_PARTICLE_ATTRIBUTES];
+ readonly int[] ParticleInitialFloatStrides = new int[MAX_PARTICLE_ATTRIBUTES];
+
+ int PerParticleInitializedAttributeMask;
+ int PerParticleUpdatedAttributeMask;
+ int PerParticleReadInitialAttributeMask;
+
+ ulong ControlPointReadMask;
+ int ParticleFlags = PCFLAGS_FIRST_FRAME;
+ bool IsScrubbable;
+ bool IsRunningInitializers;
+ bool IsRunningOperators;
+ bool IsTranslucent_;
+ bool IsTwoPass_;
+ bool AnyUsesPowerOfTwoFrameBufferTexture;
+ bool AnyUsesFullFrameBufferTexture;
+ bool IsBatchable_;
+ bool UsesPowerOfTwoFrameBufferTexture_;
+ bool UsesFullFrameBufferTexture_;
+
+ int DrawnFrames;
+ int SimulatedFrames;
+
+ Vector3 Center;
+
+ int UniqueParticleId;
+
+ int RandomQueryCount;
+ int RandomSeed;
+ int OperatorRandomSampleOffset_;
+
+ internal int NumParticlesToKill;
+ internal int[]? ParticleKillList;
+
+ ParticleCollection? NextDef;
+ ParticleCollection? PrevDef;
+
+ public ParticleCollection() {
+ for (int i = 0; i < MAX_PARTICLE_CONTROL_POINTS; i++) {
+ ref ParticleControlPoint cp = ref ControlPoints[i];
+ cp.ForwardVector = new(0, 1, 0);
+ cp.UpVector = new(0, 0, 1);
+ cp.RightVector = new(1, 0, 0);
+ cp.Density = 1.0f;
+ ControlPointHitBoxes[i] = new();
+ }
+ Array.Fill(InitialAttributeOffsets, -1);
+ }
+
+ public Vector128 CurTime4 => Vector128.Create(CurTime);
+
+ public bool Init(ParticleSystemMgr mgr, string? particleSystemName) {
+ if (particleSystemName == null)
+ return false;
+
+ ParticleSystemDefinition? def = mgr.FindParticleSystem(particleSystemName);
+ if (def == null) {
+ Warning($"Attempted to create unknown particle system type \"{particleSystemName}\"!\n");
+ return false;
+ }
+ return Init(mgr, def);
+ }
+
+ public bool Init(ParticleSystemMgr mgr, ParticleSystemDefinition? def) {
+ if (def == null) {
+ Warning("Particlelib: Missing precache for particle system type \"unknown\"!\n");
+ def = mgr.FindParticleSystem("error");
+ if (def == null)
+ return false;
+ }
+ Init(def, 0.0f, 0);
+ return IsValid();
+ }
+
+ internal void Init(ParticleSystemDefinition def, float delay, int randomSeed) {
+ Def = def;
+ Mgr = def.Mgr;
+ LinkIntoDefList();
+ InitStorage(def);
+
+ IsScrubbable = randomSeed != 0;
+ if (randomSeed == 0)
+ RandomSeed = RuntimeHelpers.GetHashCode(this) + (int)(uint)MSTime;
+ else
+ RandomSeed = randomSeed;
+
+ SetAttributeToConstant(PARTICLE_ATTRIBUTE_XYZ, 0.0f, 0.0f, 0.0f);
+ SetAttributeToConstant(PARTICLE_ATTRIBUTE_PREV_XYZ, 0.0f, 0.0f, 0.0f);
+ SetAttributeToConstant(PARTICLE_ATTRIBUTE_LIFE_DURATION, 1.0f);
+ SetAttributeToConstant(PARTICLE_ATTRIBUTE_RADIUS, def.ConstantRadius);
+ SetAttributeToConstant(PARTICLE_ATTRIBUTE_ROTATION, def.ConstantRotation);
+ SetAttributeToConstant(PARTICLE_ATTRIBUTE_ROTATION_SPEED, def.ConstantRotationSpeed);
+ SetAttributeToConstant(PARTICLE_ATTRIBUTE_TINT_RGB, def.ConstantColor.R * 0.003921569f, def.ConstantColor.G * 0.003921569f, def.ConstantColor.G * 0.003921569f);
+ SetAttributeToConstant(PARTICLE_ATTRIBUTE_ALPHA, def.ConstantColor.A * 0.003921569f);
+ SetAttributeToConstant(PARTICLE_ATTRIBUTE_CREATION_TIME, 0.0f);
+ SetAttributeToConstant(PARTICLE_ATTRIBUTE_SEQUENCE_NUMBER, def.ConstantSequenceNumber);
+ SetAttributeToConstant(PARTICLE_ATTRIBUTE_SEQUENCE_NUMBER1, def.ConstantSequenceNumber1);
+ SetAttributeToConstant(PARTICLE_ATTRIBUTE_TRAIL_LENGTH, 0.1f);
+ SetAttributeToConstant(PARTICLE_ATTRIBUTE_PARTICLE_ID, 0);
+ SetAttributeToConstant(PARTICLE_ATTRIBUTE_YAW, 0);
+ SetAttributeToConstant(PARTICLE_ATTRIBUTE_ALPHA2, 1.0f);
+
+ CurTime = -delay;
+
+ if (def.ContextDataSize != 0)
+ OperatorContextData = new byte[def.ContextDataSize];
+
+ NextSleepTime = Mgr.GetLastSimulationTime() + def.NoDrawTimeToGoToSleep;
+
+ ReadOnlySpan> olists = [def.Operators, def.Renderers, def.Initializers, def.Emitters, def.ForceGenerators, def.Constraints];
+ ReadOnlySpan> offsetLists = [def.OperatorsCtxOffsets, def.RenderersCtxOffsets, def.InitializersCtxOffsets, def.EmittersCtxOffsets, def.ForceGeneratorsCtxOffsets, def.ConstraintsCtxOffsets];
+ for (int i = 0; i < olists.Length; i++) {
+ for (int j = 0; j < olists[i].Count; j++)
+ olists[i][j].InitializeContextData(this, ContextSpan(offsetLists[i][j]));
+ }
+
+ ControlPointReadMask = def.ControlPointReadMask;
+
+ foreach (ParticleChildrenInfo child in def.Children) {
+ if (randomSeed != 0)
+ randomSeed += 129;
+
+ float childDelay = child.Delay - CurTime;
+ ParticleCollection? childCollection = child.UseNameBasedLookup
+ ? Mgr.CreateParticleCollection(child.Name, childDelay, randomSeed)
+ : Mgr.CreateParticleCollection(child.Id, childDelay, randomSeed);
+
+ if (childCollection == null)
+ continue;
+
+ childCollection.Parent = this;
+ childCollection.Next = null;
+ if (Children == null)
+ Children = childCollection;
+ else {
+ ParticleCollection tail = Children;
+ while (tail.Next != null)
+ tail = tail.Next;
+ tail.Next = childCollection;
+ childCollection.Prev = tail;
+ }
+ ControlPointReadMask |= childCollection.ControlPointReadMask;
+ }
+
+ if (Def != null && Def.IsPrecached && Def.Material.Get() != null) {
+ IsTranslucent_ = ComputeIsTranslucent();
+ IsTwoPass_ = ComputeIsTranslucent() && ContainsOpaqueCollections();
+ IsBatchable_ = ComputeIsBatchable();
+ LabelTextureUsage();
+ AnyUsesPowerOfTwoFrameBufferTexture = ComputeUsesPowerOfTwoFrameBufferTexture();
+ AnyUsesFullFrameBufferTexture = ComputeUsesFullFrameBufferTexture();
+ RequiresOrderInvariance = ComputeRequiresOrderInvariance();
+ }
+ }
+
+ public void Destroy() {
+ UnlinkFromDefList();
+
+ ParticleCollection? child = Children;
+ while (child != null) {
+ ParticleCollection? next = child.Next;
+ child.Destroy();
+ Children = next;
+ child = next;
+ }
+
+ Memory = [];
+ OperatorContextData = null;
+ Array.Clear(CollisionCacheData);
+ foreach (ModelHitBoxesInfo info in ControlPointHitBoxes) {
+ info.HitBoxes = null;
+ info.PrevBoxes = null;
+ }
+ Def = null;
+ }
+
+ void InitStorage(ParticleSystemDefinition def) {
+ int maxParticles = def.MaxParticles;
+ int allocated;
+ if (maxParticles < MAX_PARTICLES_IN_A_SYSTEM)
+ allocated = ((maxParticles + 3) / 4) * 4 + 4;
+ else {
+ allocated = MAX_PARTICLES_IN_A_SYSTEM + 4;
+ maxParticles = MAX_PARTICLES_IN_A_SYSTEM;
+ }
+ AllocatedParticles = allocated;
+ MaxAllowedParticles = maxParticles;
+
+ PerParticleInitializedAttributeMask = def.PerParticleInitializedAttributeMask;
+ PerParticleUpdatedAttributeMask = def.PerParticleUpdatedAttributeMask;
+ int perParticleAttributeMask = PerParticleInitializedAttributeMask | PerParticleUpdatedAttributeMask;
+ PerParticleReadInitialAttributeMask = def.InitialAttributeReadMask & def.PerParticleUpdatedAttributeMask & def.PerParticleInitializedAttributeMask;
+ int constantInitialMask = def.InitialAttributeReadMask & def.PerParticleInitializedAttributeMask & ~def.PerParticleUpdatedAttributeMask;
+
+ int floatsPerParticle = 0;
+ int initialFloatsPerParticle = 0;
+ for (int bit = 0; bit < MAX_PARTICLE_ATTRIBUTES; bit++) {
+ int attrSize = AttributeSize(bit);
+ if ((perParticleAttributeMask & (1 << bit)) != 0)
+ floatsPerParticle += attrSize;
+ if ((PerParticleReadInitialAttributeMask & (1 << bit)) != 0)
+ initialFloatsPerParticle += attrSize;
+ }
+
+ Memory = new float[CONSTANT_FLOATS + (floatsPerParticle + initialFloatsPerParticle) * allocated];
+
+ int cursor = CONSTANT_FLOATS;
+ int initialCursor = CONSTANT_FLOATS + floatsPerParticle * allocated;
+ for (int bit = 0; bit < MAX_PARTICLE_ATTRIBUTES; bit++) {
+ int attrSize = AttributeSize(bit);
+ if ((perParticleAttributeMask & (1 << bit)) == 0) {
+ ParticleFloatStrides[bit] = 0;
+ AttributeOffsets[bit] = ConstantOffset(bit);
+ }
+ else {
+ ParticleFloatStrides[bit] = attrSize * 4;
+ AttributeOffsets[bit] = cursor;
+ cursor += allocated * attrSize;
+ }
+
+ if ((def.InitialAttributeReadMask & (1 << bit)) == 0) {
+ InitialAttributeOffsets[bit] = -1;
+ ParticleInitialFloatStrides[bit] = 0;
+ }
+ else if ((PerParticleReadInitialAttributeMask & (1 << bit)) != 0) {
+ InitialAttributeOffsets[bit] = initialCursor;
+ ParticleInitialFloatStrides[bit] = attrSize * 4;
+ initialCursor += attrSize * allocated;
+ }
+ else if ((constantInitialMask & (1 << bit)) != 0) {
+ InitialAttributeOffsets[bit] = AttributeOffsets[bit];
+ ParticleInitialFloatStrides[bit] = ParticleFloatStrides[bit];
+ }
+ else {
+ InitialAttributeOffsets[bit] = ConstantOffset(bit);
+ ParticleInitialFloatStrides[bit] = 0;
+ }
+ }
+ }
+
+ static int AttributeSize(int attribute) => (ATTRIBUTES_WHICH_ARE_VEC3S_MASK & (1 << attribute)) != 0 ? 3 : 1;
+ static int ConstantOffset(int attribute) => 12 * attribute;
+
+ Span ContextSpan(int offset) => OperatorContextData.AsSpan(offset);
+
+ public string GetName() => Def?.GetName() ?? "";
+ public bool IsValid() => Def != null && Def.GetMaterial() != null;
+ public int GetGroupID() => Def!.GroupID;
+
+ void LinkIntoDefList() {
+ PrevDef = null;
+ NextDef = Def!.FirstCollection;
+ Def.FirstCollection = this;
+ if (NextDef != null)
+ NextDef.PrevDef = this;
+ }
+
+ public void UnlinkFromDefList() {
+ if (Def == null)
+ return;
+
+ if (Def.FirstCollection == this)
+ Def.FirstCollection = NextDef;
+ else
+ PrevDef!.NextDef = NextDef;
+
+ if (NextDef != null)
+ NextDef.PrevDef = PrevDef;
+
+ NextDef = null;
+ PrevDef = null;
+ }
+
+ public ParticleCollection? GetNextCollectionUsingSameDef() => NextDef;
+
+ public Span AttributeMemory => Memory;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public int GetAttributeIndex(int attribute, int particleNumber)
+ => AttributeOffsets[attribute] + ParticleFloatStrides[attribute] * (particleNumber / 4) + (particleNumber & 3);
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public int GetInitialAttributeIndex(int attribute, int particleNumber)
+ => InitialAttributeOffsets[attribute] + ParticleInitialFloatStrides[attribute] * (particleNumber / 4) + (particleNumber & 3);
+
+ public int GetAttributeOffset(int attribute, out int floatStride) {
+ floatStride = ParticleFloatStrides[attribute];
+ return AttributeOffsets[attribute];
+ }
+
+ public int GetInitialAttributeOffset(int attribute, out int floatStride) {
+ floatStride = ParticleInitialFloatStrides[attribute];
+ return InitialAttributeOffsets[attribute];
+ }
+
+ public float GetFloatAttributeValue(int attribute, int particleNumber) => Memory[GetAttributeIndex(attribute, particleNumber)];
+ public int GetIntAttributeValue(int attribute, int particleNumber) => BitConverter.SingleToInt32Bits(Memory[GetAttributeIndex(attribute, particleNumber)]);
+
+ public Vector3 GetVectorAttributeValue(int attribute, int particleNumber) {
+ int index = GetAttributeIndex(attribute, particleNumber);
+ return new(Memory[index], Memory[index + 4], Memory[index + 8]);
+ }
+
+ public ref float GetFloatAttributeRefForWrite(int attribute, int particleNumber) => ref Memory[GetAttributeIndex(attribute, particleNumber)];
+ public ref int GetIntAttributeRefForWrite(int attribute, int particleNumber) => ref Unsafe.As(ref Memory[GetAttributeIndex(attribute, particleNumber)]);
+
+ public void SetVectorAttribute(int attribute, int particleNumber, Vector3 v) {
+ int index = GetAttributeIndex(attribute, particleNumber);
+ Memory[index] = v.X;
+ Memory[index + 4] = v.Y;
+ Memory[index + 8] = v.Z;
+ }
+
+ public float GetInitialFloatAttributeValue(int attribute, int particleNumber) => Memory[GetInitialAttributeIndex(attribute, particleNumber)];
+
+ public Vector3 GetInitialVectorAttributeValue(int attribute, int particleNumber) {
+ int index = GetInitialAttributeIndex(attribute, particleNumber);
+ return new(Memory[index], Memory[index + 4], Memory[index + 8]);
+ }
+
+ public ref float GetInitialFloatAttributeRefForWrite(int attribute, int particleNumber) => ref Memory[GetInitialAttributeIndex(attribute, particleNumber)];
+
+ public Span GetConstantAttributeMemory(int attribute) => Memory.AsSpan(ConstantOffset(attribute), 12);
+
+ void SetAttributeToConstant(int attribute, float value) => Memory.AsSpan(ConstantOffset(attribute), 4).Fill(value);
+
+ void SetAttributeToConstant(int attribute, float x, float y, float z) {
+ Span constant = Memory.AsSpan(ConstantOffset(attribute), 12);
+ constant[..4].Fill(x);
+ constant[4..8].Fill(y);
+ constant[8..].Fill(z);
+ }
+
+ public void FillAttributeWithConstant(int attribute, float value) {
+ int offset = GetAttributeOffset(attribute, out int stride);
+ for (int i = 0; i < PaddedActiveParticles; i++) {
+ Memory.AsSpan(offset, 4).Fill(value);
+ offset += stride;
+ }
+ }
+
+ public void SwapPosAndPrevPos()
+ => (AttributeOffsets[PARTICLE_ATTRIBUTE_XYZ], AttributeOffsets[PARTICLE_ATTRIBUTE_PREV_XYZ]) = (AttributeOffsets[PARTICLE_ATTRIBUTE_PREV_XYZ], AttributeOffsets[PARTICLE_ATTRIBUTE_XYZ]);
+
+ public void SetNActiveParticles(int count) {
+ ActiveParticles = count;
+ PaddedActiveParticles = (count + 3) / 4;
+ }
+
+ public void KillParticle(int particleIndex) => ParticleKillList![NumParticlesToKill++] = particleIndex;
+
+ public bool HasAttachedKillList() => ParticleKillList != null;
+
+ public void LoanKillListTo(ParticleCollection borrower) {
+ borrower.NumParticlesToKill = 0;
+ borrower.ParticleKillList = ParticleKillList;
+ }
+
+ public bool ReadsControlPoint(int point) => (ControlPointReadMask & (1UL << point)) != 0;
+
+ public void ResetControlPoints() {
+ HighestCP = 0;
+ for (ParticleCollection? i = Children; i != null; i = i.Next)
+ i.ResetControlPoints();
+ }
+
+ public int GetControlPointIndex() => TargetCP;
+
+ public void SetControlPointIndex(int whichPoint) {
+ HighestCP = Math.Max(HighestCP, whichPoint);
+ TargetCP = whichPoint;
+ for (ParticleCollection? i = Children; i != null; i = i.Next)
+ i.SetControlPointIndex(whichPoint);
+ }
+
+ public void SetControlPoint(int whichPoint, in Vector3 v) {
+ HighestCP = Math.Max(HighestCP, whichPoint);
+ ControlPoints[whichPoint].Position = v;
+ for (ParticleCollection? i = Children; i != null; i = i.Next)
+ i.SetControlPoint(whichPoint, v);
+ }
+
+ public void SetControlPointObject(int whichPoint, object? obj) {
+ ControlPoints[whichPoint].Object = obj;
+ for (ParticleCollection? i = Children; i != null; i = i.Next)
+ i.SetControlPointObject(whichPoint, obj);
+ }
+
+ public void SetControlPointOrientation(int whichPoint, in Vector3 forward, in Vector3 right, in Vector3 up) {
+ if (MathF.Abs(Vector3.Dot(forward, up)) <= 0.1f && MathF.Abs(Vector3.Dot(forward, right)) <= 0.1f && MathF.Abs(Vector3.Dot(right, up)) <= 0.1f) {
+ ref ParticleControlPoint cp = ref ControlPoints[whichPoint];
+ cp.ForwardVector = forward;
+ cp.UpVector = up;
+ cp.RightVector = right;
+
+ for (ParticleCollection? i = Children; i != null; i = i.Next)
+ i.SetControlPointOrientation(whichPoint, forward, right, up);
+ }
+ else
+ Warning($"Attempt to set particle collection {GetName()} to invalid orientation matrix\n");
+ }
+
+ public void SetControlPointOrientation(int whichPoint, in Quaternion q) {
+ MathLib.QuaternionMatrix(in q, out Matrix3x4 mat);
+ MathLib.MatrixGetColumn(in mat, 0, out Vector3 forward);
+ MathLib.MatrixGetColumn(in mat, 1, out Vector3 left);
+ MathLib.MatrixGetColumn(in mat, 2, out Vector3 up);
+ SetControlPointOrientation(whichPoint, forward, -left, up);
+ }
+
+ public Vector3 TransformAxis(in Vector3 srcAxis, bool localSpace, int controlPointNumber = 0) {
+ if (!localSpace)
+ return srcAxis;
+
+ ref ParticleControlPoint cp = ref ControlPoints[controlPointNumber];
+ return srcAxis.X * cp.RightVector + srcAxis.Y * cp.ForwardVector + srcAxis.Z * cp.UpVector;
+ }
+
+ public void SetControlPointForwardVector(int whichPoint, in Vector3 v) {
+ ControlPoints[whichPoint].ForwardVector = v;
+ for (ParticleCollection? i = Children; i != null; i = i.Next)
+ i.SetControlPointForwardVector(whichPoint, v);
+ }
+
+ public void SetControlPointUpVector(int whichPoint, in Vector3 v) {
+ ControlPoints[whichPoint].UpVector = v;
+ for (ParticleCollection? i = Children; i != null; i = i.Next)
+ i.SetControlPointUpVector(whichPoint, v);
+ }
+
+ public void SetControlPointRightVector(int whichPoint, in Vector3 v) {
+ ControlPoints[whichPoint].RightVector = v;
+ for (ParticleCollection? i = Children; i != null; i = i.Next)
+ i.SetControlPointRightVector(whichPoint, v);
+ }
+
+ public void SetControlPointParent(int whichPoint, int n) {
+ ControlPoints[whichPoint].Parent = n;
+ for (ParticleCollection? i = Children; i != null; i = i.Next)
+ i.SetControlPointParent(whichPoint, n);
+ }
+
+ public void SetControlPointVelocity(int whichPoint, Vector3 velocity) {
+ HighestCP = Math.Max(HighestCP, whichPoint);
+ ControlPoints[whichPoint].Velocity = velocity;
+ for (ParticleCollection? i = Children; i != null; i = i.Next)
+ i.SetControlPointVelocity(whichPoint, velocity);
+ }
+
+ public void SetControlPointDensity(int whichPoint, float density) {
+ HighestCP = Math.Max(HighestCP, whichPoint);
+ ControlPoints[whichPoint].Density = density;
+ for (ParticleCollection? i = Children; i != null; i = i.Next)
+ i.SetControlPointDensity(whichPoint, density);
+ }
+
+ public void SetControlPointDuration(int whichPoint, float duration) {
+ HighestCP = Math.Max(HighestCP, whichPoint);
+ ControlPoints[whichPoint].Duration = duration;
+ for (ParticleCollection? i = Children; i != null; i = i.Next)
+ i.SetControlPointDuration(whichPoint, duration);
+ }
+
+ public void SetControlPointRadius(int whichPoint, float radius) {
+ HighestCP = Math.Max(HighestCP, whichPoint);
+ ControlPoints[whichPoint].Radius = radius;
+ for (ParticleCollection? i = Children; i != null; i = i.Next)
+ i.SetControlPointRadius(whichPoint, radius);
+ }
+
+ public ref readonly ParticleControlPoint ControlPoint(int index) => ref ControlPoints[index];
+ public ref readonly Vector3 GetControlPointAtCurrentTime(int controlPoint) => ref ControlPoints[controlPoint].Position;
+
+ public void GetControlPointOrientationAtCurrentTime(int controlPoint, out Vector3 forward, out Vector3 right, out Vector3 up) {
+ ref ParticleControlPoint cp = ref ControlPoints[controlPoint];
+ forward = cp.ForwardVector;
+ right = cp.RightVector;
+ up = cp.UpVector;
+ }
+
+ public int GetControlPointParent(int controlPoint) => ControlPoints[controlPoint].Parent;
+ public float GetControlPointRadiusAtCurrentTime(int controlPoint) => ControlPoints[controlPoint].Radius;
+ public float GetControlPointDensityAtCurrentTime(int controlPoint) => ControlPoints[controlPoint].Density;
+ public float GetControlPointDurationAtCurrentTime(int controlPoint) => ControlPoints[controlPoint].Duration;
+ public Vector3 GetControlPointVelocityAtCurrentTime(int controlPoint) => ControlPoints[controlPoint].Velocity;
+
+ public void GetControlPointAtTime(int controlPoint, float time, out Vector3 controlPointOut) {
+ if (controlPoint > HighestCP)
+ DevWarning(2, $"Warning : Particle system ({GetName()}) using unassigned ControlPoint {controlPoint}!\n");
+
+ ref ParticleControlPoint cp = ref ControlPoints[controlPoint];
+ if (Dt == 0.0f) {
+ controlPointOut = cp.Position;
+ return;
+ }
+
+ float t = (time + Dt - CurTime) / Dt;
+ if (t <= 0.0f)
+ t = 0.0f;
+ controlPointOut = new(
+ (cp.Position.X - cp.PrevPosition.X) * t + cp.PrevPosition.X,
+ (cp.Position.Y - cp.PrevPosition.Y) * t + cp.PrevPosition.Y,
+ t * (cp.Position.Z - cp.PrevPosition.Z) + cp.PrevPosition.Z
+ );
+ }
+
+ public void GetControlPointAtPrevTime(int controlPoint, out Vector3 controlPointOut) => controlPointOut = ControlPoints[controlPoint].PrevPosition;
+
+ public void GetControlPointOrientationAtTime(int controlPoint, float time, out Vector3 forward, out Vector3 right, out Vector3 up)
+ => GetControlPointOrientationAtCurrentTime(controlPoint, out forward, out right, out up);
+
+ public void GetControlPointTransformAtCurrentTime(int controlPoint, out Matrix3x4 mat)
+ => BuildControlPointTransform(controlPoint, ControlPoints[controlPoint].Position, out mat);
+
+ public void GetControlPointTransformAtTime(int controlPoint, float time, out Matrix3x4 mat) {
+ GetControlPointAtTime(controlPoint, time, out Vector3 position);
+ BuildControlPointTransform(controlPoint, position, out mat);
+ }
+
+ void BuildControlPointTransform(int controlPoint, in Vector3 position, out Matrix3x4 mat) {
+ ref ParticleControlPoint cp = ref ControlPoints[controlPoint];
+ mat = new(
+ cp.ForwardVector.X, -cp.RightVector.X, cp.UpVector.X, position.X,
+ cp.ForwardVector.Y, -cp.RightVector.Y, cp.UpVector.Y, position.Y,
+ cp.ForwardVector.Z, -cp.RightVector.Z, cp.UpVector.Z, position.Z
+ );
+ }
+
+ public int GetHighestControlPoint() => HighestCP;
+
+ public void GetBounds(out Vector3 min, out Vector3 max) {
+ min = MinBounds;
+ max = MaxBounds;
+ }
+
+ public bool HasMoved() {
+ if (Def == null)
+ return false;
+
+ for (int i = 0; i <= HighestCP; i++) {
+ if ((Def.ControlPointReadMask & (1UL << i)) != 0 && ControlPoints[i].PrevPosition != ControlPoints[i].Position)
+ return true;
+ }
+
+ for (ParticleCollection? child = Children; child != null; child = child.Next) {
+ if (child.HasMoved())
+ return true;
+ }
+ return false;
+ }
+
+ public int OperatorRandomSampleOffset() => OperatorRandomSampleOffset_;
+
+ public int RandomInt(int randomSampleId, int min, int max) {
+ float rand = RandomFloats[(RandomSeed + randomSampleId) & RANDOM_FLOAT_MASK];
+ rand *= max + 1 - min;
+ return (int)rand + min;
+ }
+
+ public float RandomFloat(int randomSampleId, float min, float max) {
+ float rand = RandomFloats[(RandomSeed + randomSampleId) & RANDOM_FLOAT_MASK];
+ rand *= max - min;
+ rand += min;
+ return rand;
+ }
+
+ public Vector128 RandomFloat(Vector128 particleId, int randomSampleOffset) {
+ int ofs = RandomSeed + randomSampleOffset;
+ return Vector128.Create(
+ RandomFloats[(ofs + particleId[0]) & RANDOM_FLOAT_MASK],
+ RandomFloats[(ofs + particleId[1]) & RANDOM_FLOAT_MASK],
+ RandomFloats[(ofs + particleId[2]) & RANDOM_FLOAT_MASK],
+ RandomFloats[(ofs + particleId[3]) & RANDOM_FLOAT_MASK]
+ );
+ }
+
+ public float RandomFloatExp(int randomSampleId, float min, float max, float exponent) {
+ float rand = RandomFloats[(RandomSeed + randomSampleId) & RANDOM_FLOAT_MASK];
+ rand = MathF.Pow(rand, exponent);
+ rand *= max - min;
+ rand += min;
+ return rand;
+ }
+
+ public void RandomVector(int randomSampleId, float min, float max, out Vector3 vector) {
+ float delta = max - min;
+ int baseId = RandomSeed + randomSampleId;
+ vector.X = RandomFloats[baseId & RANDOM_FLOAT_MASK] * delta + min;
+ vector.Y = RandomFloats[(baseId + 1) & RANDOM_FLOAT_MASK] * delta + min;
+ vector.Z = RandomFloats[(baseId + 2) & RANDOM_FLOAT_MASK] * delta + min;
+ }
+
+ public void RandomVector(int randomSampleId, in Vector3 vecMin, in Vector3 vecMax, out Vector3 vector) {
+ int baseId = RandomSeed + randomSampleId;
+ vector.X = RandomFloat(baseId, vecMin.X, vecMax.X);
+ vector.Y = RandomFloat(baseId + 1, vecMin.Y, vecMax.Y);
+ vector.Z = RandomFloat(baseId + 2, vecMin.Z, vecMax.Z);
+ }
+
+ public float RandomVectorInUnitSphere(int randomSampleId, out Vector3 vector) {
+ float r0 = RandomFloats[(randomSampleId + RandomSeed) & RANDOM_FLOAT_MASK] * 0.9999f + 0.0001f;
+ float r1 = RandomFloats[(RandomSeed + 1 + randomSampleId) & RANDOM_FLOAT_MASK] * 0.9999f + 0.0001f;
+ float r2 = RandomFloats[(RandomSeed + 2 + randomSampleId) & RANDOM_FLOAT_MASK] * 0.9999f + 0.0001f;
+
+ (float sinPhi, float cosPhi) = MathF.SinCos(MathF.Acos(1.0f - (r0 + r0)));
+ (float sinTheta, float cosTheta) = MathF.SinCos(r1 * 6.2831855f);
+ float radius = MathF.Cbrt(r2);
+
+ vector.Z = cosPhi * radius;
+ vector.X = sinPhi * radius * cosTheta;
+ vector.Y = sinPhi * radius * sinTheta;
+ return radius;
+ }
+
+ public int RandomInt(int min, int max) => RandomInt(RandomQueryCount++, min, max);
+ public float RandomFloat(float min, float max) => RandomFloat(RandomQueryCount++, min, max);
+ public float RandomFloatExp(float min, float max, float exponent) => RandomFloatExp(RandomQueryCount++, min, max, exponent);
+ public void RandomVector(float min, float max, out Vector3 vector) => RandomVector(RandomQueryCount++, min, max, out vector);
+ public void RandomVector(in Vector3 vecMin, in Vector3 vecMax, out Vector3 vector) => RandomVector(RandomQueryCount++, vecMin, vecMax, out vector);
+ public float RandomVectorInUnitSphere(out Vector3 vector) => RandomVectorInUnitSphere(RandomQueryCount++, out vector);
+
+ static float FadeInOut(float fadeInStart, float fadeInEnd, float fadeOutStart, float fadeOutEnd, float curTime) {
+ if (fadeInStart > curTime || (fadeOutEnd > 0.0f && curTime > fadeOutEnd))
+ return 0.0f;
+
+ if (fadeInEnd <= fadeInStart)
+ fadeInEnd = fadeInStart;
+ if (fadeOutStart <= fadeInEnd)
+ fadeOutStart = fadeInEnd;
+ if (fadeOutEnd <= fadeOutStart)
+ fadeOutEnd = fadeOutStart;
+
+ float strength;
+ if (fadeInEnd <= fadeInStart || fadeInEnd <= curTime)
+ strength = 1.0f;
+ else {
+ strength = (curTime - fadeInStart) / (fadeInEnd - fadeInStart);
+ if (strength >= 1.0f)
+ strength = 1.0f;
+ }
+
+ if (fadeOutStart < fadeOutEnd && fadeOutStart < curTime) {
+ float fadeOut = (curTime - fadeOutEnd) / (fadeOutStart - fadeOutEnd);
+ if (fadeOut <= strength)
+ strength = fadeOut;
+ }
+ return strength;
+ }
+
+ public bool CheckIfOperatorShouldRun(ParticleOperatorInstance op, out float curStrength) {
+ float time = CurTime;
+ if (op.OpFadeOscillatePeriod > 0.0f)
+ time = (CurTime / op.OpFadeOscillatePeriod) % 1.0f;
+
+ curStrength = FadeInOut(op.OpStartFadeInTime, op.OpEndFadeInTime, op.OpStartFadeOutTime, op.OpEndFadeOutTime, time);
+ return curStrength > 0.0f;
+ }
+
+ public void Restart() {
+ ParticleSystemDefinition def = Def!;
+ for (int i = 0; i < def.Emitters.Count; i++)
+ def.Emitters[i].Restart(this, ContextSpan(def.EmittersCtxOffsets[i]));
+
+ for (ParticleCollection? child = Children; child != null; child = child.Next)
+ child.Restart();
+ }
+
+ void UpdatePrevControlPoints(float dt) {
+ PreviousDt = dt;
+ for (int i = 0; i <= HighestCP; i++)
+ ControlPoints[i].PrevPosition = ControlPoints[i].Position;
+ ParticleFlags |= PCFLAGS_PREV_CONTROL_POINTS_INITIALIZED;
+ }
+
+ public void InitializeNewParticles(int firstParticle, int particleCount, uint inittedMask) {
+ ParticleSystemDefinition def = Def!;
+ int attrsLeftToInit = (PerParticleInitializedAttributeMask | PerParticleUpdatedAttributeMask) & ~(int)inittedMask;
+
+ int count = def.Initializers.Count;
+ if (count > 0) {
+ for (int i = 0; i < count; i++) {
+ ParticleOperatorInstance op = def.Initializers[i];
+ int written = (int)op.GetWrittenAttributes();
+ if ((attrsLeftToInit & written) == 0 || op.InitMultipleOverride())
+ continue;
+
+ RunInitializer(op, ContextSpan(def.InitializersCtxOffsets[i]), firstParticle, particleCount, attrsLeftToInit);
+ attrsLeftToInit &= ~written;
+ }
+
+ for (int i = 0; i < count; i++) {
+ ParticleOperatorInstance op = def.Initializers[i];
+ int written = (int)op.GetWrittenAttributes();
+ if (!op.InitMultipleOverride())
+ continue;
+
+ RunInitializer(op, ContextSpan(def.InitializersCtxOffsets[i]), firstParticle, particleCount, attrsLeftToInit);
+ attrsLeftToInit &= ~written;
+ }
+ }
+
+ if (attrsLeftToInit != 0)
+ InitParticleAttributes(firstParticle, particleCount, attrsLeftToInit);
+
+ if (PerParticleReadInitialAttributeMask != 0)
+ CopyInitialAttributeValues(firstParticle, particleCount);
+ }
+
+ void RunInitializer(ParticleOperatorInstance op, Span context, int firstParticle, int particleCount, int attrsLeftToInit) {
+ if (IsScrubbable && !op.IsScrubSafe()) {
+ for (int p = firstParticle; p < firstParticle + particleCount; p++)
+ op.InitNewParticlesScalar(this, p, 1, attrsLeftToInit, context);
+ }
+ else
+ op.InitNewParticles(this, firstParticle, particleCount, attrsLeftToInit, context);
+ }
+
+ void InitParticleAttributes(int startParticle, int numParticles, int attrsLeftToInit) {
+ for (int p = startParticle; p < startParticle + numParticles; p++) {
+ for (int attr = 0; attr < MAX_PARTICLE_ATTRIBUTES; attr++) {
+ if ((attrsLeftToInit & (1 << attr)) == 0)
+ continue;
+
+ int index = GetAttributeIndex(attr, p);
+ if (attr == PARTICLE_ATTRIBUTE_PARTICLE_ID) {
+ Memory[index] = BitConverter.Int32BitsToSingle((UniqueParticleId + RandomSeed) & RANDOM_FLOAT_MASK);
+ UniqueParticleId++;
+ }
+ else if (attr == PARTICLE_ATTRIBUTE_CREATION_TIME)
+ Memory[index] = CurTime;
+ else {
+ int constant = ConstantOffset(attr);
+ Memory[index] = Memory[constant];
+ if (ParticleFloatStrides[attr] == 12) {
+ Memory[index + 4] = Memory[constant + 4];
+ Memory[index + 8] = Memory[constant + 8];
+ }
+ }
+ }
+ }
+ }
+
+ void CopyInitialAttributeValues(int startParticle, int numParticles) {
+ for (int p = startParticle; p < startParticle + numParticles; p++) {
+ for (int attr = 0; attr < MAX_PARTICLE_ATTRIBUTES; attr++) {
+ if ((PerParticleReadInitialAttributeMask & (1 << attr)) == 0)
+ continue;
+
+ int src = GetAttributeIndex(attr, p);
+ int dst = GetInitialAttributeIndex(attr, p);
+ Memory[dst] = Memory[src];
+ if (ParticleFloatStrides[attr] == 12) {
+ Memory[dst + 4] = Memory[src + 4];
+ Memory[dst + 8] = Memory[src + 8];
+ }
+ }
+ }
+ }
+
+ public void SkipToTime(float t) {
+ if (t <= CurTime)
+ return;
+
+ UpdatePrevControlPoints(t - CurTime);
+ CurTime = t;
+ ParticleFlags &= ~PCFLAGS_FIRST_FRAME;
+
+ ParticleSystemDefinition def = Def!;
+ for (int i = 0; i < def.Emitters.Count; i++)
+ def.Emitters[i].SkipToTime(t, this, ContextSpan(def.EmittersCtxOffsets[i]));
+
+ int childIndex = 0;
+ for (ParticleCollection? child = Children; child != null; child = child.Next)
+ child.SkipToTime(t - def.Children[childIndex++].Delay);
+ }
+
+ void SimulateFirstFrame() {
+ Dt = 0.0f;
+ DrawnFrames = 0;
+ SimulatedFrames = 1;
+
+ if ((ParticleFlags & PCFLAGS_PREV_CONTROL_POINTS_INITIALIZED) == 0)
+ UpdatePrevControlPoints(0.05f);
+
+ OperatorRandomSampleOffset_ = 0;
+ ParticleSystemDefinition def = Def!;
+ for (int i = 0; i < def.Operators.Count; i++) {
+ ParticleOperatorInstance op = def.Operators[i];
+ if (op.ShouldRunBeforeEmitters() && CheckIfOperatorShouldRun(op, out float strength)) {
+ op.Operate(this, strength, ContextSpan(def.OperatorsCtxOffsets[i]));
+ UpdatePrevControlPoints(0.05f);
+ }
+ OperatorRandomSampleOffset_ += 17;
+ }
+
+ int initialParticles = Math.Min(def.InitialParticles, MaxAllowedParticles);
+ if (initialParticles < 1)
+ return;
+
+ SetNActiveParticles(initialParticles);
+ InitializeNewParticles(0, initialParticles, 0);
+ }
+
+ public void Simulate(float dt, bool updateBboxOnly) {
+ if (dt < 0.0f || Def == null)
+ return;
+
+ if (CurTime < 0.0f) {
+ if (dt >= 1e-22f) {
+ CurTime += dt;
+ UpdatePrevControlPoints(dt);
+ }
+ return;
+ }
+
+ if ((ParticleFlags & PCFLAGS_FIRST_FRAME) != 0) {
+ SimulateFirstFrame();
+ ParticleFlags &= ~PCFLAGS_FIRST_FRAME;
+ }
+
+ if (dt < 1e-22f)
+ return;
+
+ bool attachedKillList = false;
+ if (ParticleKillList == null) {
+ Mgr!.AttachKillList(this);
+ attachedKillList = true;
+ }
+
+ if (!updateBboxOnly)
+ RunSimulationSteps(dt);
+
+ for (ParticleCollection? child = Children; child != null; child = child.Next) {
+ child.NumParticlesToKill = 0;
+ child.ParticleKillList = ParticleKillList;
+ child.Simulate(dt, updateBboxOnly);
+ child.ParticleKillList = null;
+ }
+
+ if (attachedKillList)
+ Mgr!.DetachKillList(this);
+
+ UpdatePrevControlPoints(dt);
+ BloatBoundsUsingControlPoint();
+ }
+
+ void RunSimulationSteps(float dt) {
+ ParticleSystemDefinition def = Def!;
+ SimulatedFrames++;
+
+ float maxTimeStep = def.MaximumTimeStep;
+ float maxDt;
+ if (maxTimeStep <= 0.0f) {
+ maxTimeStep = 0.1f;
+ maxDt = 1.0f;
+ }
+ else
+ maxDt = maxTimeStep * 10.0f;
+
+ float remaining = dt;
+ if (def.MaximumSimTime != 0.0f && DrawnFrames <= def.MinimumFrames) {
+ if (dt + CurTime > def.MaximumSimTime) {
+ remaining = def.MaximumSimTime - CurTime;
+ if (remaining < def.MinimumSimTime)
+ remaining = def.MinimumSimTime;
+ }
+ DrawnFrames++;
+ }
+
+ if (remaining >= maxDt)
+ remaining = maxDt;
+
+ while (remaining > 0.0f) {
+ OperatorRandomSampleOffset_ = 0;
+ float step = remaining <= maxTimeStep ? remaining : maxTimeStep;
+ remaining -= step;
+ Dt = step;
+ CurTime += step;
+
+ for (int i = 0; i < def.Operators.Count; i++) {
+ ParticleOperatorInstance op = def.Operators[i];
+ if (!op.ShouldRunBeforeEmitters() || !CheckIfOperatorShouldRun(op, out float strength))
+ continue;
+
+ op.Operate(this, strength, ContextSpan(def.OperatorsCtxOffsets[i]));
+ if (NumParticlesToKill != 0)
+ ApplyKillList();
+ OperatorRandomSampleOffset_ += 17;
+ }
+
+ int prevActive = ActiveParticles;
+ for (int i = 0; i < def.Emitters.Count; i++) {
+ ParticleOperatorInstance emitter = def.Emitters[i];
+ if (CheckIfOperatorShouldRun(emitter, out float strength)) {
+ uint inittedMask = emitter.Emit(this, strength, ContextSpan(def.EmittersCtxOffsets[i]));
+ if (ActiveParticles != prevActive)
+ InitializeNewParticles(prevActive, ActiveParticles - prevActive, inittedMask);
+ }
+ prevActive = ActiveParticles;
+ }
+
+ OperatorRandomSampleOffset_ = 0;
+ if (prevActive == 0)
+ continue;
+
+ for (int i = 0; i < def.Operators.Count; i++) {
+ ParticleOperatorInstance op = def.Operators[i];
+ if (op.ShouldRunBeforeEmitters() || !CheckIfOperatorShouldRun(op, out float strength))
+ continue;
+
+ op.Operate(this, strength, ContextSpan(def.OperatorsCtxOffsets[i]));
+ if (NumParticlesToKill != 0) {
+ ApplyKillList();
+ if (ActiveParticles == 0)
+ break;
+ }
+ OperatorRandomSampleOffset_ += 17;
+ }
+ }
+ }
+
+ void MoveParticle(int initialIndex, int newIndex) {
+ int newVec = (newIndex & 3) + (newIndex >> 2) * 12;
+ int oldVec = (initialIndex & 3) + (initialIndex >> 2) * 12;
+
+ for (int attr = 0; attr < MAX_PARTICLE_ATTRIBUTES; attr++) {
+ MoveAttribute(AttributeOffsets[attr], ParticleFloatStrides[attr], initialIndex, newIndex, oldVec, newVec);
+ MoveAttribute(InitialAttributeOffsets[attr], ParticleInitialFloatStrides[attr], initialIndex, newIndex, oldVec, newVec);
+ }
+ }
+
+ void MoveAttribute(int offset, int stride, int initialIndex, int newIndex, int oldVec, int newVec) {
+ if (stride == 4)
+ Memory[offset + newIndex] = Memory[offset + initialIndex];
+ else if (stride == 12) {
+ Memory[offset + newVec] = Memory[offset + oldVec];
+ Memory[offset + newVec + 4] = Memory[offset + oldVec + 4];
+ Memory[offset + newVec + 8] = Memory[offset + oldVec + 8];
+ }
+ }
+
+ void ApplyKillList() {
+ int leftInKillList = NumParticlesToKill;
+ if (leftInKillList == 0)
+ return;
+
+ int activeNow = ActiveParticles;
+ int[] killList = ParticleKillList!;
+ int slot = 0;
+
+ while (leftInKillList != 0 && killList[leftInKillList - 1] >= activeNow)
+ leftInKillList--;
+
+ if (RequiresOrderInvariance) {
+ int remaining = leftInKillList - 1;
+ int finalCount = activeNow - leftInKillList;
+ int writeIndex = killList[slot++];
+ for (int readIndex = writeIndex + 1; readIndex < activeNow; readIndex++) {
+ if (remaining >= 1 && killList[slot] == readIndex) {
+ slot++;
+ remaining--;
+ continue;
+ }
+ MoveParticle(readIndex, writeIndex++);
+ }
+ activeNow = finalCount;
+ }
+ else if (leftInKillList != 0) {
+ int killIndex = killList[slot];
+ while (true) {
+ if (leftInKillList - 1 == 0) {
+ activeNow--;
+ if (killIndex != activeNow)
+ MoveParticle(activeNow, killIndex);
+ break;
+ }
+
+ int last = leftInKillList - 1;
+ bool tailConsumed = false;
+ while (true) {
+ int previous = activeNow;
+ activeNow = previous - 1;
+ if (killList[slot + last] != activeNow)
+ break;
+ last--;
+ if (last == 0) {
+ activeNow = previous - 2;
+ tailConsumed = true;
+ break;
+ }
+ }
+
+ if (tailConsumed) {
+ if (killIndex != activeNow)
+ MoveParticle(activeNow, killIndex);
+ break;
+ }
+
+ if (activeNow == killIndex)
+ break;
+
+ MoveParticle(activeNow, killIndex);
+ leftInKillList = last;
+ killIndex = killList[++slot];
+ }
+ }
+
+ ActiveParticles = activeNow;
+ NumParticlesToKill = 0;
+ PaddedActiveParticles = (activeNow + 3) / 4;
+ }
+
+ public void StopEmission(bool infiniteOnly = false, bool removeAllParticles = false, bool wakeOnStop = false) {
+ if (Def == null)
+ return;
+
+ Dormant = false;
+ if (wakeOnStop)
+ NextSleepTime = Math.Max(Mgr!.GetLastSimulationTime() + 10.0f, NextSleepTime);
+
+ EmissionStopped = true;
+ for (int i = 0; i < Def.Emitters.Count; i++)
+ Def.Emitters[i].StopEmission(this, ContextSpan(Def.EmittersCtxOffsets[i]), infiniteOnly);
+
+ if (removeAllParticles) {
+ ActiveParticles = 0;
+ PaddedActiveParticles = 0;
+ }
+
+ for (ParticleCollection? child = Children; child != null; child = child.Next)
+ child.StopEmission(infiniteOnly, removeAllParticles, false);
+ }
+
+ public void StartEmission(bool infiniteOnly = false) {
+ if (Def == null)
+ return;
+
+ EmissionStopped = false;
+ StartEmissionInternal(infiniteOnly);
+ }
+
+ void StartEmissionInternal(bool infiniteOnly) {
+ ParticleSystemDefinition def = Def!;
+ for (int i = 0; i < def.Emitters.Count; i++)
+ def.Emitters[i].StartEmission(this, ContextSpan(def.EmittersCtxOffsets[i]), infiniteOnly);
+
+ for (ParticleCollection? child = Children; child != null; child = child.Next) {
+ if (child.Def != null) {
+ child.EmissionStopped = false;
+ child.StartEmissionInternal(infiniteOnly);
+ }
+ }
+
+ NextSleepTime = Mgr!.GetLastSimulationTime() + def.NoDrawTimeToGoToSleep;
+ }
+
+ public void SetDormant(bool dormant) {
+ if (Dormant == dormant)
+ return;
+
+ if (!EmissionStopped) {
+ if (dormant) {
+ StopEmission();
+ Dormant = dormant;
+ return;
+ }
+ }
+ else if (dormant)
+ return;
+
+ StartEmission();
+ Dormant = dormant;
+ }
+
+ public bool IsFinished() {
+ if (Def == null)
+ return true;
+
+ if ((ParticleFlags & PCFLAGS_FIRST_FRAME) != 0 || ActiveParticles != 0 || Dormant)
+ return false;
+
+ for (int i = 0; i < Def.Emitters.Count; i++) {
+ if (Def.Emitters[i].MayCreateMoreParticles(this, ContextSpan(Def.EmittersCtxOffsets[i])))
+ return false;
+ }
+
+ for (ParticleCollection? child = Children; child != null; child = child.Next) {
+ if (!child.IsFinished())
+ return false;
+ }
+ return true;
+ }
+
+ public void RecomputeBounds() {
+ int count = ActiveParticles;
+ if (count == 0) {
+ BoundsValid = false;
+ MinBounds = new(float.MaxValue);
+ MaxBounds = new(-float.MaxValue);
+ Center = Vector3.Zero;
+ return;
+ }
+
+ const float BIG = 1e23f;
+ int offset = GetAttributeOffset(PARTICLE_ATTRIBUTE_XYZ, out int stride);
+
+ Span minX = stackalloc float[4], minY = stackalloc float[4], minZ = stackalloc float[4];
+ Span maxX = stackalloc float[4], maxY = stackalloc float[4], maxZ = stackalloc float[4];
+ Span sumX = stackalloc float[4], sumY = stackalloc float[4], sumZ = stackalloc float[4];
+ minX.Fill(BIG); minY.Fill(BIG); minZ.Fill(BIG);
+ maxX.Fill(-BIG); maxY.Fill(-BIG); maxZ.Fill(-BIG);
+
+ int blocks = count / 4;
+ for (int b = 0; b < blocks; b++) {
+ for (int lane = 0; lane < 4; lane++) {
+ float x = Memory[offset + lane], y = Memory[offset + 4 + lane], z = Memory[offset + 8 + lane];
+ minX[lane] = MathF.Min(minX[lane], x); maxX[lane] = MathF.Max(maxX[lane], x); sumX[lane] += x;
+ minY[lane] = MathF.Min(minY[lane], y); maxY[lane] = MathF.Max(maxY[lane], y); sumY[lane] += y;
+ minZ[lane] = MathF.Min(minZ[lane], z); maxZ[lane] = MathF.Max(maxZ[lane], z); sumZ[lane] += z;
+ }
+ offset += stride;
+ }
+
+ BoundsValid = true;
+ Vector3 min = new(HorizontalMin(minX), HorizontalMin(minY), HorizontalMin(minZ));
+ Vector3 max = new(HorizontalMax(maxX), HorizontalMax(maxY), HorizontalMax(maxZ));
+ float totalX = sumX[3] + sumX[2] + sumX[1] + sumX[0];
+ float totalY = sumY[1] + sumY[0] + sumY[2] + sumY[3];
+ float totalZ = sumZ[3] + sumZ[2] + sumZ[0] + sumZ[1];
+
+ for (int lane = 0; lane < (count & 3); lane++) {
+ float x = Memory[offset + lane], y = Memory[offset + 4 + lane], z = Memory[offset + 8 + lane];
+ if (x <= min.X) min.X = x;
+ if (max.X <= x) max.X = x;
+ if (y <= min.Y) min.Y = y;
+ if (max.Y <= y) max.Y = y;
+ if (z <= min.Z) min.Z = z;
+ if (max.Z <= z) max.Z = z;
+ totalX += x;
+ totalY += y;
+ totalZ += z;
+ }
+
+ MinBounds = min + Def!.BoundingBoxMin;
+ MaxBounds = max + Def.BoundingBoxMax;
+ float oneOverCount = 1.0f / count;
+ Center = new(totalX * oneOverCount, totalY * oneOverCount, totalZ * oneOverCount);
+ }
+
+ static float HorizontalMin(ReadOnlySpan v) {
+ float a = v[0] <= v[1] ? v[0] : v[1];
+ float b = v[3] <= v[2] ? v[3] : v[2];
+ return a <= b ? a : b;
+ }
+
+ static float HorizontalMax(ReadOnlySpan v) {
+ float a = v[1] <= v[0] ? v[0] : v[1];
+ float b = v[2] <= v[3] ? v[3] : v[2];
+ return b <= a ? a : b;
+ }
+
+ protected void BloatBoundsUsingControlPoint() {
+ RecomputeBounds();
+
+ if (SimulatedFrames > 2) {
+ for (int i = 0; i <= HighestCP; i++) {
+ if ((Def!.ControlPointReadMask & (1UL << i)) == 0)
+ continue;
+
+ Vector3 position = ControlPoints[i].Position;
+ MinBounds = Vector3.Min(MinBounds, position);
+ MaxBounds = Vector3.Max(MaxBounds, position);
+ }
+ }
+
+ for (ParticleCollection? child = Children; child != null; child = child.Next) {
+ MinBounds = Vector3.Min(MinBounds, child.MinBounds);
+ MaxBounds = Vector3.Max(MaxBounds, child.MaxBounds);
+ }
+ }
+
+ public void CalculatePathValues(in PathParameters pathIn, float timeStamp, out Vector3 startPnt, out Vector3 midPnt, out Vector3 endPnt) {
+ GetControlPointAtTime(pathIn.StartControlPointNumber, timeStamp, out startPnt);
+ GetControlPointAtTime(pathIn.EndControlPointNumber, timeStamp, out endPnt);
+
+ Vector3 delta = endPnt - startPnt;
+ midPnt = new(pathIn.MidPoint * delta.X + startPnt.X, pathIn.MidPoint * delta.Y + startPnt.Y, pathIn.MidPoint * delta.Z + startPnt.Z);
+
+ if (pathIn.BulgeControl == 0) {
+ float bulge = pathIn.Bulge;
+ float bulge2 = bulge + bulge;
+ midPnt.X = midPnt.X + RandomFloats[RandomSeed & RANDOM_FLOAT_MASK] * bulge2 - bulge;
+ midPnt.Y = midPnt.Y - bulge + RandomFloats[(RandomSeed + 1) & RANDOM_FLOAT_MASK] * bulge2;
+ midPnt.Z = RandomFloats[(RandomSeed + 2) & RANDOM_FLOAT_MASK] * bulge2 + (midPnt.Z - bulge);
+ return;
+ }
+
+ int controlPoint = pathIn.BulgeControl == 2 ? pathIn.EndControlPointNumber : pathIn.StartControlPointNumber;
+ Vector3 forward = ControlPoints[controlPoint].ForwardVector;
+ float deltaLength = delta.Length();
+ float offset = deltaLength > 1e-6f ? 1.0f - MathF.Abs(Vector3.Dot(delta, forward) / deltaLength) : 0.0f;
+
+ float forwardLength = forward.Length();
+ if (forwardLength > 1e-6f) {
+ float scale = offset * pathIn.Bulge * deltaLength / forwardLength;
+ midPnt += forward * scale;
+ }
+ }
+
+ public void UpdateHitBoxInfo(int controlPointNumber) {
+ ModelHitBoxesInfo info = ControlPointHitBoxes[controlPointNumber];
+ if (CurTime == info.LastUpdateTime)
+ return;
+
+ info.LastUpdateTime = CurTime;
+ info.HitBoxes ??= new ModelHitBoxInfo[ModelHitBoxesInfo.MAX_HITBOXES];
+ info.PrevBoxes ??= new ModelHitBoxInfo[ModelHitBoxesInfo.MAX_HITBOXES];
+
+ info.PrevLastUpdateTime = info.LastUpdateTime;
+ info.NumPrevHitBoxes = info.NumHitBoxes;
+ (info.HitBoxes, info.PrevBoxes) = (info.PrevBoxes, info.HitBoxes);
+ info.NumHitBoxes = Mgr!.Query().GetControllingObjectHitBoxInfo(this, controlPointNumber, info.HitBoxes);
+ }
+
+ IMaterial? PrecachedMaterial() => Def != null && Def.IsPrecached ? Def.Material.Get() : null;
+
+ public bool IsTranslucent() => IsTranslucent_;
+ public bool IsTwoPass() => IsTwoPass_;
+ public bool IsBatchable() => IsBatchable_;
+
+ public bool UsesPowerOfTwoFrameBufferTexture(bool thisFrame) {
+ if (!AnyUsesPowerOfTwoFrameBufferTexture || !thisFrame)
+ return AnyUsesPowerOfTwoFrameBufferTexture;
+ if (ActiveParticles != 0 && UsesPowerOfTwoFrameBufferTexture_)
+ return true;
+ for (ParticleCollection? child = Children; child != null; child = child.Next) {
+ if (child.SystemContainsParticlesWithBoolSet(c => c.UsesPowerOfTwoFrameBufferTexture_))
+ return true;
+ }
+ return false;
+ }
+
+ public bool UsesFullFrameBufferTexture(bool thisFrame) {
+ if (!AnyUsesFullFrameBufferTexture || !thisFrame)
+ return AnyUsesFullFrameBufferTexture;
+ if (ActiveParticles != 0 && UsesFullFrameBufferTexture_)
+ return true;
+ for (ParticleCollection? child = Children; child != null; child = child.Next) {
+ if (child.SystemContainsParticlesWithBoolSet(c => c.UsesFullFrameBufferTexture_))
+ return true;
+ }
+ return false;
+ }
+
+ bool SystemContainsParticlesWithBoolSet(Func field) {
+ if (ActiveParticles != 0 && field(this))
+ return true;
+ for (ParticleCollection? child = Children; child != null; child = child.Next) {
+ if (child.SystemContainsParticlesWithBoolSet(field))
+ return true;
+ }
+ return false;
+ }
+
+ void LabelTextureUsage() {
+ if (Def != null) {
+ IMaterial material = Def.Material.Get()!;
+ UsesPowerOfTwoFrameBufferTexture_ = material.NeedsPowerOfTwoFrameBufferTexture(false);
+ UsesFullFrameBufferTexture_ = material.NeedsFullFrameBufferTexture(false);
+ }
+ for (ParticleCollection? child = Children; child != null; child = child.Next)
+ child.LabelTextureUsage();
+ }
+
+ bool ComputeUsesPowerOfTwoFrameBufferTexture() {
+ if (Def == null)
+ return false;
+ if (Def.Material.Get()!.NeedsPowerOfTwoFrameBufferTexture(false))
+ return true;
+ for (ParticleCollection? child = Children; child != null; child = child.Next) {
+ if (child.AnyUsesPowerOfTwoFrameBufferTexture)
+ return true;
+ }
+ return false;
+ }
+
+ bool ComputeUsesFullFrameBufferTexture() {
+ if (Def == null)
+ return false;
+ if (Def.Material.Get()!.NeedsFullFrameBufferTexture(false))
+ return true;
+ for (ParticleCollection? child = Children; child != null; child = child.Next) {
+ if (child.AnyUsesFullFrameBufferTexture)
+ return true;
+ }
+ return false;
+ }
+
+ bool ContainsOpaqueCollections() {
+ if (Def == null)
+ return false;
+ if (PrecachedMaterial()?.IsTranslucent() != true)
+ return true;
+ for (ParticleCollection? child = Children; child != null; child = child.Next) {
+ if (child.ContainsOpaqueCollections())
+ return true;
+ }
+ return false;
+ }
+
+ bool ComputeIsTranslucent() {
+ if (Def == null)
+ return false;
+ if (PrecachedMaterial()?.IsTranslucent() == true)
+ return true;
+ for (ParticleCollection? child = Children; child != null; child = child.Next) {
+ if (child.IsTranslucent_)
+ return true;
+ }
+ return false;
+ }
+
+ bool ComputeIsBatchable() {
+ if (PrecachedMaterial() != null) {
+ foreach (ParticleOperatorInstance renderer in Def!.Renderers) {
+ if (!renderer.IsBatchable())
+ return false;
+ }
+ }
+ for (ParticleCollection? child = Children; child != null; child = child.Next) {
+ if (!child.IsBatchable_)
+ return false;
+ }
+ return true;
+ }
+
+ bool ComputeRequiresOrderInvariance() {
+ if (PrecachedMaterial() != null) {
+ foreach (ParticleOperatorInstance renderer in Def!.Renderers) {
+ if (renderer.RequiresOrderInvariance())
+ return true;
+ }
+ }
+ for (ParticleCollection? child = Children; child != null; child = child.Next) {
+ if (child.RequiresOrderInvariance)
+ return true;
+ }
+ return false;
+ }
+
+ public int GetRendererCount() => PrecachedMaterial() != null ? Def!.Renderers.Count : 0;
+ public ParticleOperatorInstance? GetRenderer(int i) => PrecachedMaterial() != null ? Def!.Renderers[i] : null;
+ public Span GetRendererContext(int i) => PrecachedMaterial() != null ? ContextSpan(Def!.RenderersCtxOffsets[i]) : default;
}
diff --git a/Source.Particles/ParticleOperator.cs b/Source.Particles/ParticleOperator.cs
index ac233407..be6920f4 100644
--- a/Source.Particles/ParticleOperator.cs
+++ b/Source.Particles/ParticleOperator.cs
@@ -62,12 +62,48 @@ internal void SetDefinition(IParticleOperatorDefinition def, Guid id) {
public virtual void InitParams(ParticleSystemDefinition def, Element element) { }
public virtual int GetRequiredContextBytes() => 0;
+ public virtual void InitializeContextData(ParticleCollection particles, Span context) { }
public abstract uint GetWrittenAttributes();
public abstract uint GetReadAttributes();
public virtual ulong GetReadControlPointMask() => 0;
public virtual uint GetReadInitialAttributes() => 0;
+ public virtual void Operate(ParticleCollection particles, float opStrength, Span context) { }
+
+ public virtual uint Emit(ParticleCollection particles, float opCurStrength, Span context) => 0;
+ public virtual void StopEmission(ParticleCollection particles, Span context, bool infiniteOnly = false) { }
+ public virtual void StartEmission(ParticleCollection particles, Span context, bool infiniteOnly = false) { }
+ public virtual void Restart(ParticleCollection particles, Span context) { }
+ public virtual bool MayCreateMoreParticles(ParticleCollection particles, Span context) => false;
+ public virtual void SkipToTime(float time, ParticleCollection particles, Span context) { }
+
+ public virtual void InitNewParticlesScalar(ParticleCollection particles, int firstParticle, int numParticles, int attributeWriteMask, Span context) { }
+ public virtual void InitNewParticlesBlock(ParticleCollection particles, int startBlock, int numBlocks, int attributeWriteMask, Span context)
+ => InitNewParticlesScalar(particles, 4 * startBlock, 4 * numBlocks, attributeWriteMask, context);
+
+ public void InitNewParticles(ParticleCollection particles, int firstParticle, int particleCount, int attributeWriteMask, Span context) {
+ if (particleCount == 0)
+ return;
+
+ if (particleCount < 16) {
+ InitNewParticlesScalar(particles, firstParticle, particleCount, attributeWriteMask, context);
+ return;
+ }
+
+ if ((firstParticle & 3) != 0) {
+ int head = 4 - (firstParticle & 3);
+ InitNewParticlesScalar(particles, firstParticle, head, attributeWriteMask, context);
+ particleCount -= head;
+ firstParticle += head;
+ }
+
+ InitNewParticlesBlock(particles, firstParticle / 4, particleCount / 4, attributeWriteMask, context);
+
+ if ((particleCount & 3) != 0)
+ InitNewParticlesScalar(particles, firstParticle + (particleCount & ~3), particleCount & 3, attributeWriteMask, context);
+ }
+
public virtual bool IsBatchable() => true;
public virtual bool IsFinalConstraint() => false;
public virtual bool InitMultipleOverride() => false;
diff --git a/Source.Particles/ParticleSystemDefinition.cs b/Source.Particles/ParticleSystemDefinition.cs
index 5d1e25a8..1251696a 100644
--- a/Source.Particles/ParticleSystemDefinition.cs
+++ b/Source.Particles/ParticleSystemDefinition.cs
@@ -108,7 +108,7 @@ public sealed class ParticleSystemDefinition(ParticleSystemMgr mgr)
public static IDmxElementUnpackStructure GetUnpackStructure() => UnpackStructure;
- readonly ParticleSystemMgr Mgr = mgr;
+ internal readonly ParticleSystemMgr Mgr = mgr;
public int InitialParticles;
public int PerParticleUpdatedAttributeMask;
diff --git a/Source.Particles/ParticleSystemMgr.cs b/Source.Particles/ParticleSystemMgr.cs
index 6b06c784..e1a80d55 100644
--- a/Source.Particles/ParticleSystemMgr.cs
+++ b/Source.Particles/ParticleSystemMgr.cs
@@ -176,6 +176,65 @@ public string GetParticleSystemNameFromIndex(int index) {
public ParticleSystemDefinition? FindParticleSystem(string? name) => Dictionary!.FindParticleSystem(name);
public ParticleSystemDefinition? FindParticleSystem(Guid id) => Dictionary!.FindParticleSystem(id);
+ public ParticleCollection? CreateParticleCollection(string? name, float delay = 0.0f, int randomSeed = 0) {
+ if (name == null)
+ return null;
+
+ ParticleSystemDefinition? def = Dictionary!.FindParticleSystem(name);
+ if (def == null) {
+ Warning($"Attempted to create unknown particle system type {name}\n");
+ return null;
+ }
+
+ ParticleCollection collection = new();
+ collection.Init(def, delay, randomSeed);
+ return collection;
+ }
+
+ public ParticleCollection? CreateParticleCollection(Guid id, float delay = 0.0f, int randomSeed = 0) {
+ if (id == Guid.Empty)
+ return null;
+
+ ParticleSystemDefinition? def = Dictionary!.FindParticleSystem(id);
+ if (def == null) {
+ Warning($"Attempted to create unknown particle system id {id}\n");
+ return null;
+ }
+
+ ParticleCollection collection = new();
+ collection.Init(def, delay, randomSeed);
+ return collection;
+ }
+
+ const int NUM_KILL_LISTS = 16;
+ readonly int[]?[] FreeKillLists = new int[]?[NUM_KILL_LISTS];
+ int NumFreeKillLists = -1;
+ readonly Lock KillListLock = new();
+
+ internal void AttachKillList(ParticleCollection particles) {
+ lock (KillListLock) {
+ if (NumFreeKillLists < 0) {
+ for (int i = 0; i < NUM_KILL_LISTS; i++)
+ FreeKillLists[i] = new int[MAX_PARTICLES_IN_A_SYSTEM];
+ NumFreeKillLists = NUM_KILL_LISTS;
+ }
+
+ if (NumFreeKillLists == 0)
+ Error("Out of particle kill lists!\n");
+
+ particles.NumParticlesToKill = 0;
+ particles.ParticleKillList = FreeKillLists[--NumFreeKillLists];
+ FreeKillLists[NumFreeKillLists] = null;
+ }
+ }
+
+ internal void DetachKillList(ParticleCollection particles) {
+ lock (KillListLock) {
+ FreeKillLists[NumFreeKillLists++] = particles.ParticleKillList;
+ particles.ParticleKillList = null;
+ }
+ }
+
public void PrecacheParticleSystem(string? name) {
if (string.IsNullOrEmpty(name))
return;
diff --git a/Source.Particles/Source.Particles.csproj b/Source.Particles/Source.Particles.csproj
index fa070bcd..6b418435 100644
--- a/Source.Particles/Source.Particles.csproj
+++ b/Source.Particles/Source.Particles.csproj
@@ -5,6 +5,9 @@
+
+
+
From 98dae7fa1e5b452d62471bbfb6d4feab5ebb778a Mon Sep 17 00:00:00 2001
From: Earu <20880060+Earu@users.noreply.github.com>
Date: Thu, 12 Nov 2026 19:40:21 +0400
Subject: [PATCH 4/8] particle client glue: effect dispatch, lua bindings, anim
events and model particles
- TE effect dispatch with ClientEffectRegistration and EffectDispatch string table
- ParticleEffect / ParticleEffectStop callbacks, DispatchParticleEffect and StopParticleEffects
- C_ParticleSystem think, CNewParticleEffect, ParticleProperty and ParticleMgr hooks
- lua: CreateParticleSystem(NoEntity), CNewParticleEffect methods, Entity particle methods, ParticleEffect(Attach), game.AddParticles
- AE_CL_CREATE/STOP/ADD_CP particle anim events and model keyvalue particles
- implement GetModelKeyValueText
- EffectData defaults Scale=1 and AllowOverride=true
- replace randomfloats .bin with inline RandomFloats.cs
---
Game.Client/C_BaseAnimating.cs | 150 ++++++-
Game.Client/C_BaseEntity.cs | 11 +-
Game.Client/C_ParticleSystem.cs | 136 +++++-
Game.Client/C_TEEffectDispatch.cs | 49 ++-
Game.Client/ClientEntityList.cs | 7 +
Game.Client/GarrysMod/LuaParticleEffect.cs | 415 +++++++++++++++++++
Game.Client/HLClient.cs | 16 +-
Game.Client/NewParticleEffect.cs | 313 ++++++++++++++
Game.Client/ParticleMgr.cs | 199 ++++++++-
Game.Client/ParticleProperty.cs | 400 ++++++++++++++++++
Game.Shared/EffectData.cs | 22 +-
Game.Shared/EventList.cs | 4 +
Game.Shared/GarrysMod/LuaEntity.cs | 6 +
Game.Shared/GarrysMod/LuaGame.cs | 5 +-
Game.Shared/GarrysMod/LuaGlobalFunctions.cs | 21 +
Game.Shared/ParticleParse.cs | 128 ++++++
Game.Shared/ParticleSystemQuery.cs | 126 ++++++
Source.Common/Mathematics/MathLib.cs | 6 +
Source.Particles/ParticleCollection.cs | 11 +-
Source.Particles/ParticleSystemDefinition.cs | 5 +-
Source.Particles/ParticleSystemMgr.cs | 6 +-
Source.Particles/RandomFloats.cs | 263 ++++++++++++
Source.Particles/Source.Particles.csproj | 3 -
23 files changed, 2263 insertions(+), 39 deletions(-)
create mode 100644 Game.Client/GarrysMod/LuaParticleEffect.cs
create mode 100644 Game.Client/NewParticleEffect.cs
create mode 100644 Game.Client/ParticleProperty.cs
create mode 100644 Game.Shared/ParticleSystemQuery.cs
create mode 100644 Source.Particles/RandomFloats.cs
diff --git a/Game.Client/C_BaseAnimating.cs b/Game.Client/C_BaseAnimating.cs
index c6ff6d8d..1a3675f4 100644
--- a/Game.Client/C_BaseAnimating.cs
+++ b/Game.Client/C_BaseAnimating.cs
@@ -286,6 +286,24 @@ public void Dispose() {
BoneMergeCache? BoneMergeCache;
+ public void GetBoneTransform(int bone, out Matrix3x4 boneToWorld) {
+ BoneCache cache = GetBoneCache(null);
+ ref Matrix3x4 matrix = ref cache.GetCachedBone(bone);
+ if (Unsafe.IsNullRef(ref matrix)) {
+ MathLib.MatrixCopy(EntityToWorldTransform(), out boneToWorld);
+ return;
+ }
+ MathLib.MatrixCopy(matrix, out boneToWorld);
+ }
+
+ public bool GetRootBone(out Matrix3x4 rootBone) {
+ if (IsEffectActive(EntityEffects.BoneMerge) && GetMoveParent() != null && BoneMergeCache != null)
+ return BoneMergeCache.GetRootBone(out rootBone);
+
+ GetBoneTransform(0, out rootBone);
+ return true;
+ }
+
static long ModelBoneCounter;
long MostRecentModelBoneCounter;
long MostRecentBoneSetupRequest;
@@ -408,12 +426,84 @@ public virtual void FireEvent(in Vector3 origin, in QAngle angles, int ev, strin
case (int)AnimEventId.AE_CL_STOPSOUND:
StopSound(GetSoundSourceIndex(), options);
break;
+ case (int)AnimEventId.AE_CL_CREATE_PARTICLE_EFFECT: {
+ int attachment = -1;
+ nexttoken(out ReadOnlySpan token, options, ' ', out ReadOnlySpan next);
+ ReadOnlySpan mtoken = ModifyEventParticles(token);
+ if (mtoken.IsEmpty)
+ return;
+ string particleEffect = mtoken.ToString();
+
+ nexttoken(out token, next, ' ', out next);
+ int attachType = GetAttachTypeFromString(token);
+ if (attachType == -1) {
+ Warning($"Invalid attach type specified for particle effect anim event. Trying to spawn effect '{particleEffect}' with attach type of '{token}'\n");
+ return;
+ }
+
+ nexttoken(out token, next, ' ', out _);
+ if (!token.IsEmpty) {
+ attachment = atoi(token);
+ if (token[0] != '0' && attachment == 0) {
+ attachment = LookupAttachment(token);
+ if (attachment <= 0) {
+ Warning($"Failed to find attachment point specified for particle effect anim event. Trying to spawn effect '{particleEffect}' on attachment named '{token}'\n");
+ return;
+ }
+ }
+ }
+
+ ParticleProp().Create(particleEffect, (ParticleAttachment)attachType, attachment);
+ }
+ break;
+ case (int)AnimEventId.AE_CL_STOP_PARTICLE_EFFECT: {
+ nexttoken(out ReadOnlySpan token, options, ' ', out ReadOnlySpan next);
+ string particleEffect = token.ToString();
+ nexttoken(out token, next, ' ', out _);
+ ParticleProp().StopParticlesNamed(particleEffect, token.Equals("instantly", StringComparison.OrdinalIgnoreCase));
+ }
+ break;
+ case (int)AnimEventId.AE_CL_ADD_PARTICLE_EFFECT_CP: {
+ nexttoken(out ReadOnlySpan token, options, ' ', out ReadOnlySpan next);
+ string particleEffect = token.ToString();
+
+ nexttoken(out token, next, ' ', out next);
+ int controlPoint = atoi(token);
+
+ nexttoken(out token, next, ' ', out next);
+ int attachType = GetAttachTypeFromString(token);
+ if (attachType == -1) {
+ Warning($"Invalid attach type specified for particle effect anim event. Trying to spawn effect '{particleEffect}' with attach type of '{token}'\n");
+ return;
+ }
+
+ nexttoken(out token, next, ' ', out _);
+ int attachment = atoi(token);
+ if ((token.IsEmpty || token[0] != '0') && attachment == 0) {
+ attachment = LookupAttachment(token);
+ if (attachment == -1) {
+ Warning($"Failed to find attachment point specified for particle effect anim event. Trying to spawn effect '{particleEffect}' on attachment named '{token}'\n");
+ return;
+ }
+ }
+
+ int effectIndex = ParticleProp().FindEffect(particleEffect);
+ if (effectIndex == -1) {
+ Warning($"Failed to find specified particle effect. Trying to add CP to '{particleEffect}' on attachment named '{token}'\n");
+ return;
+ }
+
+ ParticleProp().AddControlPoint(effectIndex, controlPoint, this, (ParticleAttachment)attachType, attachment);
+ }
+ break;
case CL_EVENT_SOUND:
FireObsoleteEvent(in origin, in angles, ev, options);
break;
}
}
+ public virtual ReadOnlySpan ModifyEventParticles(ReadOnlySpan token) => token;
+
public virtual void FireObsoleteEvent(in Vector3 origin, in QAngle angles, int ev, string options) {
switch (ev) {
case CL_EVENT_SOUND: {
@@ -556,7 +646,51 @@ protected virtual void ApplyBoneMatrixTransform(ref Matrix3x4 transform) {
}
}
- public void DelayedInitModelEffects() { /* todo */ }
+ public void InitModelEffects() {
+ DelayInitModelEffects = true;
+ ParticleProp().StopParticlesInvolving(this);
+ HasAttachedParticles = false;
+ }
+
+ public void DelayedInitModelEffects() {
+ if (!ShouldDraw())
+ return;
+
+ DelayInitModelEffects = false;
+
+ ReadOnlySpan keyValueText = modelinfo.GetModelKeyValueText(GetModel());
+ KeyValues modelKeyValues = new("");
+ if (keyValueText.IsEmpty || !modelKeyValues.LoadFromBuffer(modelinfo.GetModelName(GetModel()), keyValueText))
+ return;
+
+ KeyValues? allParticleEffects = modelKeyValues.FindKey("Particles");
+ if (allParticleEffects == null)
+ return;
+
+ for (KeyValues? singleEffect = allParticleEffects.GetFirstSubKey(); singleEffect != null; singleEffect = singleEffect.GetNextKey()) {
+ string particleEffect = singleEffect.GetString("name", "").ToString();
+ ReadOnlySpan attachmentName = singleEffect.GetString("attachment_point", "");
+ ReadOnlySpan attachTypeName = singleEffect.GetString("attachment_type", "");
+
+ int attachType = GetAttachTypeFromString(attachTypeName);
+ if (attachType == -1) {
+ Warning($"Invalid attach type specified for particle effect in model '{GetModelName()}' keyvalues section. Trying to spawn effect '{particleEffect}' with attach type of '{attachTypeName}'\n");
+ return;
+ }
+
+ int attachment = atoi(attachmentName);
+ if ((attachmentName.IsEmpty || attachmentName[0] != '0') && attachment == 0) {
+ attachment = LookupAttachment(attachmentName);
+ if (attachment <= 0) {
+ Warning($"Failed to find attachment point specified for particle effect in model '{GetModelName()}' keyvalues section. Trying to spawn effect '{particleEffect}' on attachment named '{attachmentName}'\n");
+ return;
+ }
+ }
+
+ ParticleProp().Create(particleEffect, (ParticleAttachment)attachType, attachment);
+ HasAttachedParticles = true;
+ }
+ }
public void ClearRagdoll() { /* todo */ }
public override void Simulate() {
@@ -1168,6 +1302,8 @@ public static class SequenceProxy
SetPoseParameter(hdr, i, 0.0f);
}
+ InitModelEffects();
+
EyeAttachment = LookupAttachment("eyes");
if (ShouldInterpolate())
@@ -1339,15 +1475,15 @@ public C_BaseAnimating() {
DynamicModelPending = false;
ResetSequenceInfoOnLoad = false;
- InitModelEffects = false;
DelayInitModelEffects = false;
+ HasAttachedParticles = false;
Cycle = 0;
OldCycle = 0;
}
bool DelayInitModelEffects;
- bool InitModelEffects;
+ bool HasAttachedParticles;
bool DynamicModelAllowed;
bool DynamicModelPending;
@@ -1470,6 +1606,14 @@ public override void PostDataUpdate(DataUpdateType updateType) {
iv_Cycle.Reset();
}
}
+
+ bool shouldDraw = ShouldDraw();
+ if (shouldDraw && shouldDraw != OldShouldDraw)
+ InitModelEffects();
+ else if (!shouldDraw && HasAttachedParticles) {
+ ParticleProp().StopParticlesInvolving(this);
+ HasAttachedParticles = false;
+ }
}
[Flags]
diff --git a/Game.Client/C_BaseEntity.cs b/Game.Client/C_BaseEntity.cs
index a34dd59b..ce035382 100644
--- a/Game.Client/C_BaseEntity.cs
+++ b/Game.Client/C_BaseEntity.cs
@@ -285,6 +285,10 @@ public partial class C_BaseEntity : IClientEntity
public virtual C_BaseAnimating? GetBaseAnimating() => null;
+ readonly ParticleProperty Particles = new();
+ public ParticleProperty ParticleProp() => Particles;
+ public virtual void OnNewParticleEffect(string particleName, CNewParticleEffect newParticleEffect) { }
+
public virtual bool IsWorld() => EntIndex() == 0;
public virtual bool IsPlayer() => false;
public virtual bool IsBaseCombatCharacter() => false;
@@ -783,6 +787,7 @@ private static void RecvProxy_MoveType(ref readonly RecvProxyData data, object i
public float Gravity;
public C_BaseEntity() {
+ ParticleProp().Init(this);
GMOD_EHANDLEForModify() = new();
AddVar(this, DA_Origin, IV_Origin, LatchFlags.LatchSimulationVar);
AddVar(this, DA_Rotation, IV_Rotation, LatchFlags.LatchSimulationVar);
@@ -1473,6 +1478,8 @@ public virtual void Term() {
DestroyModelInstance();
RemoveFromLeafSystem();
RemoveFromAimEntsList();
+
+ Particles.StopEmission(null, false, true);
}
public bool OnPredictedEntityRemove(bool isbeingremoved, C_BaseEntity predicted) {
@@ -1867,6 +1874,8 @@ protected void MarkMessageReceived() {
public void SetDormant(bool dormant) {
Dormant = dormant;
UpdateVisibility();
+
+ ParticleProp().OwnerSetDormantTo(dormant);
}
public ref readonly BaseHandle GetClientHandle() => ref RefEHandle;
@@ -2596,7 +2605,7 @@ private void RemoveAllDecals() {
public bool DestroyedOnRecreateEntities;
public void SetDestroyedOnRecreateEntities() {
- // ParticleProp().StopEmission(null, false);
+ ParticleProp().StopEmissionAndDestroyImmediately();
DestroyedOnRecreateEntities = true;
}
diff --git a/Game.Client/C_ParticleSystem.cs b/Game.Client/C_ParticleSystem.cs
index cab86ef4..15728ad3 100644
--- a/Game.Client/C_ParticleSystem.cs
+++ b/Game.Client/C_ParticleSystem.cs
@@ -2,6 +2,9 @@
using Source;
using Source.Common;
+using Source.Common.Mathematics;
+
+using System.Numerics;
namespace Game.Client;
@@ -36,5 +39,136 @@ public partial class C_ParticleSystem : C_BaseEntity
public InlineArrayNewMaxControlPoints ControlPointParents = new();
[NetworkVar("m_bWeatherEffect")]
public bool WeatherEffect;
-}
+ bool OldActive;
+
+ public override void PreDataUpdate(DataUpdateType updateType) {
+ OldActive = Active;
+
+ base.PreDataUpdate(updateType);
+ }
+
+ public override void PostDataUpdate(DataUpdateType updateType) {
+ base.PostDataUpdate(updateType);
+
+ if (updateType == DataUpdateType.Created) {
+ if (Active)
+ SetNextClientThink(gpGlobals.CurTime);
+ }
+ else if (OldActive != Active) {
+ if (Active)
+ SetNextClientThink(gpGlobals.CurTime);
+ else
+ ParticleProp().StopEmission();
+ }
+ }
+
+ public override void ClientThink() {
+ if (!Active)
+ return;
+
+ ReadOnlySpan name = HLClient.GetParticleSystemNameFromIndex(EffectIndex);
+ if (name.IsEmpty)
+ return;
+
+ if (!GameRules.g_pGameRules!.AllowMapParticleEffect(name))
+ return;
+
+ if (WeatherEffect && !GameRules.g_pGameRules.AllowWeatherParticles())
+ return;
+
+ CNewParticleEffect? effect = ParticleProp().Create(name.ToString(), ParticleAttachment.AbsOriginFollow);
+ AssertMsg(effect != null, $"Particle system couldn't make {name}");
+ if (effect == null)
+ return;
+
+ for (int i = 0; i < InlineArrayNewMaxControlPoints.kMAXCONTROLPOINTS; ++i) {
+ C_BaseEntity? onEntity = ControlPointEnts[i].Get();
+ if (onEntity != null)
+ ParticleProp().AddControlPoint(effect, i + 1, onEntity, ParticleAttachment.AbsOriginFollow);
+
+ AssertMsg(ControlPointParents[i] <= InlineArrayNewMaxControlPoints.kMAXCONTROLPOINTS, $"Particle system specified bogus control point parent ({ControlPointParents[i]}) for point {i}.");
+
+ if (ControlPointParents[i] != 0)
+ effect.SetControlPointParent(i + 1, ControlPointParents[i]);
+ }
+
+ ParticleProp().OnParticleSystemUpdated(effect, 0.0f);
+
+ float timeDelta = (float)(gpGlobals.CurTime - (float)StartTime);
+ if (timeDelta > 0.01f)
+ effect.SkipToTime(timeDelta);
+ }
+
+ static void ParticleEffectCallback(EffectData data) {
+ if (EffectData.SuppressingParticleEffects())
+ return;
+
+ string name = HLClient.GetParticleSystemNameFromIndex(data.HitBox).ToString();
+
+ CNewParticleEffect? effect;
+ if ((data.Flags & PARTICLE_DISPATCH_FROM_ENTITY) != 0) {
+ if (!data.Entity.IsValid())
+ return;
+ C_BaseEntity? ent = Instance(data.Entity);
+ if (ent == null || ent.IsDormant())
+ return;
+
+ if ((data.Flags & PARTICLE_DISPATCH_RESET_PARTICLES) != 0)
+ ent.ParticleProp().StopEmission();
+
+ Vector3 offset = Vector3.Zero;
+ ParticleAttachment attachType = (ParticleAttachment)data.DamageType;
+ if (attachType == ParticleAttachment.AbsOriginFollow || attachType == ParticleAttachment.PointFollow || attachType == ParticleAttachment.RootBoneFollow)
+ offset = data.Start;
+
+ effect = ent.ParticleProp().Create(name, attachType, data.AttachmentIndex, offset);
+ if (effect == null)
+ return;
+
+ effect.AddRef();
+ if (effect.IsValid() && attachType == ParticleAttachment.CustomOrigin)
+ SetupCustomOrigin(effect, data);
+ }
+ else {
+ if (GameRules.g_pGameRules != null)
+ name = GameRules.g_pGameRules.TranslateEffectForVisionFilter("particles", name).ToString();
+
+ effect = CNewParticleEffect.Create(null, name);
+ effect.AddRef();
+ if (effect.IsValid())
+ SetupCustomOrigin(effect, data);
+ }
+
+ if (effect.IsValid()) {
+ if (data.HasCustomColors) {
+ effect.SetControlPoint(EffectData.CUSTOM_COLOR_CP1, data.CustomColors.Color1);
+ effect.SetControlPoint(EffectData.CUSTOM_COLOR_CP2, data.CustomColors.Color2);
+ }
+
+ if (data.HasControlPoint1)
+ effect.SetControlPoint(1, data.ControlPoint1.Offset);
+ }
+
+ effect.Release();
+ }
+
+ static void SetupCustomOrigin(CNewParticleEffect effect, EffectData data) {
+ effect.SetSortOrigin(data.Origin);
+ effect.SetControlPoint(0, data.Origin);
+ effect.SetControlPoint(1, data.Start);
+ MathLib.AngleVectors(data.Angles, out Vector3 forward, out Vector3 right, out Vector3 up);
+ effect.SetControlPointOrientation(0, forward, right, up);
+ }
+
+ static readonly ClientEffectRegistration ClientEffectReg_ParticleEffectCallback = new("ParticleEffect", ParticleEffectCallback);
+
+ static void ParticleEffectStopCallback(EffectData data) {
+ if (!data.Entity.IsValid())
+ return;
+ C_BaseEntity? ent = Instance(data.Entity);
+ ent?.ParticleProp().StopEmission();
+ }
+
+ static readonly ClientEffectRegistration ClientEffectReg_ParticleEffectStopCallback = new("ParticleEffectStop", ParticleEffectStopCallback);
+}
diff --git a/Game.Client/C_TEEffectDispatch.cs b/Game.Client/C_TEEffectDispatch.cs
index 83407e24..eaa72cf7 100644
--- a/Game.Client/C_TEEffectDispatch.cs
+++ b/Game.Client/C_TEEffectDispatch.cs
@@ -3,7 +3,25 @@
using Source.Common;
using System.Numerics;
-namespace Game.Client;
+namespace Game.Client;
+
+public delegate void ClientEffectCallback(EffectData data);
+
+public sealed class ClientEffectRegistration
+{
+ public static ClientEffectRegistration? Head;
+
+ public readonly string EffectName;
+ public readonly ClientEffectCallback Function;
+ public readonly ClientEffectRegistration? Next;
+
+ public ClientEffectRegistration(string effectName, ClientEffectCallback fn) {
+ EffectName = effectName;
+ Function = fn;
+ Next = Head;
+ Head = this;
+ }
+}
[NetworkName("CTEEffectDispatch")]
public partial class C_TEEffectDispatch : C_BaseTempEntity
@@ -15,11 +33,36 @@ public partial class C_TEEffectDispatch : C_BaseTempEntity
[NetworkVar("m_EffectData")]
public readonly EffectData EffectData = new();
+
+ public override void PostDataUpdate(DataUpdateType updateType) {
+ ReadOnlySpan effectName = HLClient.g_pStringTableEffectDispatch!.GetString(EffectData.EffectName);
+ if (!effectName.IsEmpty)
+ DispatchEffectToCallback(effectName, EffectData);
+ }
}
public static partial class TempEnts
{
- public static void TE_DispatchEffect(IRecipientFilter filter, float delay, in Vector3 pos, ReadOnlySpan name, EffectData data) {
- throw new NotImplementedException();
+ public static void DispatchEffectToCallback(ReadOnlySpan effectName, EffectData data) {
+ if (g_Lua == null)
+ return;
+
+ for (ClientEffectRegistration? reg = ClientEffectRegistration.Head; reg != null; reg = reg.Next) {
+ if (effectName.Equals(reg.EffectName, StringComparison.OrdinalIgnoreCase)) {
+ reg.Function(data);
+ return;
+ }
+ }
+
+ DevMsg($"DispatchEffect: effect '{effectName}' not found on client\n");
}
+
+ public static void TE_DispatchEffect(IRecipientFilter filter, float delay, in Vector3 pos, ReadOnlySpan name, EffectData data) => DispatchEffectToCallback(name, data);
+
+ public static void DispatchEffect(ReadOnlySpan name, EffectData data) {
+ PASFilter filter = new(data.Origin);
+ DispatchEffect(name, data, filter);
+ }
+
+ public static void DispatchEffect(ReadOnlySpan name, EffectData data, C_RecipientFilter filter) => te.DispatchEffect(filter, 0.0f, data.Origin, name, data);
}
diff --git a/Game.Client/ClientEntityList.cs b/Game.Client/ClientEntityList.cs
index 3c063110..a199bab9 100644
--- a/Game.Client/ClientEntityList.cs
+++ b/Game.Client/ClientEntityList.cs
@@ -67,6 +67,13 @@ public void Release() {
MaxUsedServerIndex = -1;
}
+ public BaseHandle EntIndexToHandle(int entnum) {
+ if (entnum < -1)
+ return INVALID_CLIENTENTITY_HANDLE;
+ IClientUnknown? unk = GetListedEntity(entnum);
+ return unk != null ? unk.GetRefEHandle() : INVALID_CLIENTENTITY_HANDLE;
+ }
+
public IClientUnknown? GetClientUnknownFromHandle(in BaseHandle ent) {
return (IClientUnknown?)LookupEntity(ent);
}
diff --git a/Game.Client/GarrysMod/LuaParticleEffect.cs b/Game.Client/GarrysMod/LuaParticleEffect.cs
new file mode 100644
index 00000000..8b80a4cb
--- /dev/null
+++ b/Game.Client/GarrysMod/LuaParticleEffect.cs
@@ -0,0 +1,415 @@
+using Game.Shared;
+
+using Source.Common.GarrysMod.Lua;
+using Source.Common.Mathematics;
+using Source.Particles;
+
+using System.Numerics;
+
+namespace Game.Client.GarrysMod;
+
+public static partial class LuaParticleEffect
+{
+ [LuaClass(typeof(CNewParticleEffect), NullError = "Tried to use a NULL CNewParticleEffect!")]
+ public static readonly LuaClass LC_CNewParticleEffect = new("CNewParticleEffect", LuaType.ParticleSystem, null, null);
+
+ public static void Push_NewParticleEffect(CNewParticleEffect effect) => LC_CNewParticleEffect.Push(effect);
+
+ static CNewParticleEffect? Get_ValidEffect(ILuaInterface lua) {
+ CNewParticleEffect? effect = LC_CNewParticleEffect.Get(1) as CNewParticleEffect;
+ if (effect == null)
+ lua.Error("Tried to use a NULL CNewParticleEffect!");
+ return effect.IsValid() ? effect : null;
+ }
+
+ internal static int ClampAttachType(double value) => Math.Clamp((int)value, 0, (int)ParticleAttachment.RootBoneFollow);
+
+ [LuaGlobal]
+ static int CreateParticleSystem(ILuaInterface lua) {
+ C_BaseEntity ent = LuaEntity.Get_Entity(1, false)!;
+ int attachType = ClampAttachType(lua.CheckNumber(3));
+ int attachment = (int)lua.CheckNumberOpt(4, 0);
+ Vector3 offset = lua.GetType(5) == LuaType.Nil ? Vector3.Zero : LuaVector.Get_Vector(5);
+ string name = lua.CheckString(2);
+
+ CNewParticleEffect? effect = ent.ParticleProp().Create(name, (ParticleAttachment)attachType, attachment, offset);
+ if (effect == null || !effect.IsValid())
+ return 0;
+
+ Push_NewParticleEffect(effect);
+ return 1;
+ }
+
+ [LuaGlobal]
+ static int CreateParticleSystemNoEntity(ILuaInterface lua) {
+ string name = lua.CheckString(1);
+ Vector3 pos = LuaVector.Get_Vector(2);
+ QAngle ang = lua.GetType(3) == LuaType.Nil ? MathLibConsts.vec3_angle : LuaAngle.Get_Angle(3);
+
+ CNewParticleEffect effect = CNewParticleEffect.Create(null, name);
+ effect.AddRef();
+ effect.Release();
+ if (!effect.IsValid())
+ return 0;
+
+ effect.SetSortOrigin(pos);
+ effect.SetControlPoint(0, pos);
+ effect.SetControlPoint(1, pos);
+ if (lua.GetType(3) != LuaType.Nil) {
+ MathLib.AngleVectors(ang, out Vector3 forward, out Vector3 right, out Vector3 up);
+ effect.SetControlPointOrientation(0, forward, right, up);
+ }
+
+ Push_NewParticleEffect(effect);
+ return 1;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect____tostring(ILuaInterface lua) {
+ if (LC_CNewParticleEffect.Get(1) is CNewParticleEffect effect && effect.IsValid())
+ lua.PushString($"CNewParticleEffect [{effect.GetEffectName()}]");
+ else
+ lua.PushString("CNewParticleEffect [NULL]");
+ return 1;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__IsValid(ILuaInterface lua) {
+ lua.PushBool(LC_CNewParticleEffect.Get(1) is CNewParticleEffect effect && effect.IsValid());
+ return 1;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__IsFinished(ILuaInterface lua) {
+ CNewParticleEffect? effect = Get_ValidEffect(lua);
+ if (effect == null)
+ return 0;
+ lua.PushBool(effect.IsFinished());
+ return 1;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__IsViewModelEffect(ILuaInterface lua) {
+ CNewParticleEffect? effect = Get_ValidEffect(lua);
+ if (effect == null)
+ return 0;
+ lua.PushBool(effect.GetIsViewModelEffect());
+ return 1;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__SetIsViewModelEffect(ILuaInterface lua) {
+ Get_ValidEffect(lua)?.SetIsViewModelEffect(lua.GetBool(2));
+ return 0;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__GetShouldSimulate(ILuaInterface lua) {
+ CNewParticleEffect? effect = Get_ValidEffect(lua);
+ if (effect == null)
+ return 0;
+ lua.PushBool(effect.ShouldSimulate());
+ return 1;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__SetShouldSimulate(ILuaInterface lua) {
+ Get_ValidEffect(lua)?.SetShouldSimulate(lua.GetBool(2));
+ return 0;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__SetControlPoint(ILuaInterface lua) {
+ CNewParticleEffect? effect = Get_ValidEffect(lua);
+ if (effect == null)
+ return 0;
+ int point = (int)lua.CheckNumber(2);
+ if ((uint)point < ParticleConstants.MAX_PARTICLE_CONTROL_POINTS)
+ effect.SetControlPoint(point, LuaVector.Get_Vector(3));
+ return 0;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__SetControlPointEntity(ILuaInterface lua) {
+ CNewParticleEffect? effect = Get_ValidEffect(lua);
+ if (effect == null)
+ return 0;
+ int point = (int)lua.CheckNumber(2);
+ if ((uint)point < ParticleConstants.MAX_PARTICLE_CONTROL_POINTS)
+ effect.SetControlPointEntity(point, LuaEntity.Get_Entity(3, false));
+ return 0;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__SetControlPointForwardVector(ILuaInterface lua) {
+ CNewParticleEffect? effect = Get_ValidEffect(lua);
+ if (effect == null)
+ return 0;
+ int point = (int)lua.CheckNumber(2);
+ if ((uint)point < ParticleConstants.MAX_PARTICLE_CONTROL_POINTS)
+ effect.SetControlPointForwardVector(point, LuaVector.Get_Vector(3));
+ return 0;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__SetControlPointRightVector(ILuaInterface lua) {
+ CNewParticleEffect? effect = Get_ValidEffect(lua);
+ if (effect == null)
+ return 0;
+ int point = (int)lua.CheckNumber(2);
+ if ((uint)point < ParticleConstants.MAX_PARTICLE_CONTROL_POINTS)
+ effect.SetControlPointRightVector(point, LuaVector.Get_Vector(3));
+ return 0;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__SetControlPointUpVector(ILuaInterface lua) {
+ CNewParticleEffect? effect = Get_ValidEffect(lua);
+ if (effect == null)
+ return 0;
+ int point = (int)lua.CheckNumber(2);
+ if ((uint)point < ParticleConstants.MAX_PARTICLE_CONTROL_POINTS)
+ effect.SetControlPointUpVector(point, LuaVector.Get_Vector(3));
+ return 0;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__SetControlPointParent(ILuaInterface lua) {
+ CNewParticleEffect? effect = Get_ValidEffect(lua);
+ if (effect == null)
+ return 0;
+ int point = (int)lua.CheckNumber(2);
+ if ((uint)point >= ParticleConstants.MAX_PARTICLE_CONTROL_POINTS)
+ return 0;
+ int parent = (int)lua.CheckNumber(3);
+ if ((uint)parent < ParticleConstants.MAX_PARTICLE_CONTROL_POINTS)
+ effect.SetControlPointParent(point, parent);
+ return 0;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__SetControlPointOrientation(ILuaInterface lua) {
+ CNewParticleEffect? effect = Get_ValidEffect(lua);
+ if (effect == null)
+ return 0;
+ int point = (int)lua.CheckNumber(2);
+ if ((uint)point >= ParticleConstants.MAX_PARTICLE_CONTROL_POINTS)
+ return 0;
+
+ if (lua.GetType(3) == LuaType.Angle) {
+ QAngle ang = LuaAngle.Get_Angle(3);
+ MathLib.AngleVectors(ang, out Vector3 forward, out Vector3 right, out Vector3 up);
+ effect.SetControlPointOrientation(point, forward, right, up);
+ return 0;
+ }
+
+ Vector3 upVec = LuaVector.Get_Vector(5);
+ Vector3 rightVec = LuaVector.Get_Vector(4);
+ Vector3 forwardVec = LuaVector.Get_Vector(3);
+ effect.SetControlPointOrientation(point, forwardVec, rightVec, upVec);
+ return 0;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__SetSortOrigin(ILuaInterface lua) {
+ Get_ValidEffect(lua)?.SetSortOrigin(LuaVector.Get_Vector(2));
+ return 0;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__GetEffectName(ILuaInterface lua) {
+ CNewParticleEffect? effect = Get_ValidEffect(lua);
+ if (effect == null)
+ return 0;
+ lua.PushString(effect.GetEffectName());
+ return 1;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__GetOwner(ILuaInterface lua) {
+ CNewParticleEffect? effect = Get_ValidEffect(lua);
+ if (effect == null)
+ return 0;
+ LuaEntity.Push_Entity(effect.GetOwner());
+ return 1;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__GetRenderBounds(ILuaInterface lua) {
+ CNewParticleEffect? effect = Get_ValidEffect(lua);
+ if (effect == null)
+ return 0;
+ effect.GetRenderBounds(out Vector3 mins, out Vector3 maxs);
+ LuaVector.Push_Vector(mins);
+ LuaVector.Push_Vector(maxs);
+ return 2;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__GetHighestControlPoint(ILuaInterface lua) {
+ CNewParticleEffect? effect = Get_ValidEffect(lua);
+ if (effect == null)
+ return 0;
+ lua.PushNumber(effect.GetHighestControlPoint());
+ return 1;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__GetAutoUpdateBBox(ILuaInterface lua) {
+ CNewParticleEffect? effect = Get_ValidEffect(lua);
+ if (effect == null)
+ return 0;
+ lua.PushBool(effect.GetAutoUpdateBBox());
+ return 1;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__StartEmission(ILuaInterface lua) {
+ CNewParticleEffect? effect = Get_ValidEffect(lua);
+ if (effect == null)
+ return 0;
+ bool infiniteOnly = lua.GetType(2) == LuaType.Bool && lua.GetBool(2);
+ effect.StartEmission(infiniteOnly);
+ return 0;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__StopEmission(ILuaInterface lua) {
+ CNewParticleEffect? effect = Get_ValidEffect(lua);
+ if (effect == null)
+ return 0;
+ bool infiniteOnly = lua.GetType(2) == LuaType.Bool && lua.GetBool(2);
+ bool removeAllParticles = lua.GetType(3) == LuaType.Bool && lua.GetBool(3);
+ bool wakeOnStop = lua.GetType(4) == LuaType.Bool && lua.GetBool(4);
+ effect.StopEmission(infiniteOnly, removeAllParticles, wakeOnStop);
+ return 0;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__Restart(ILuaInterface lua) {
+ Get_ValidEffect(lua)?.Restart();
+ return 0;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__SetShouldDraw(ILuaInterface lua) {
+ Get_ValidEffect(lua)?.SetShouldDraw(lua.GetBool(2));
+ return 0;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__AddControlPoint(ILuaInterface lua) {
+ CNewParticleEffect? effect = Get_ValidEffect(lua);
+ C_BaseEntity? owner = effect?.GetOwner();
+ if (effect == null || owner == null)
+ return 0;
+
+ int point = (int)lua.CheckNumber(2);
+ if ((uint)point >= ParticleConstants.MAX_PARTICLE_CONTROL_POINTS)
+ return 0;
+
+ int attachType = ClampAttachType(lua.CheckNumber(4));
+ string? attachmentName = lua.GetType(5) == LuaType.Nil ? null : lua.CheckString(5);
+ Vector3 offset = lua.GetType(6) == LuaType.Nil ? Vector3.Zero : LuaVector.Get_Vector(6);
+ C_BaseEntity ent = LuaEntity.Get_Entity(3, false)!;
+
+ owner.ParticleProp().AddControlPoint(effect, point, ent, (ParticleAttachment)attachType, attachmentName, offset);
+ return 0;
+ }
+
+ [LuaMethod]
+ static int CNewParticleEffect__StopEmissionAndDestroyImmediately(ILuaInterface lua) {
+ CNewParticleEffect? effect = Get_ValidEffect(lua);
+ if (effect == null)
+ return 0;
+
+ C_BaseEntity? owner = effect.GetOwner();
+ if (owner != null) {
+ owner.ParticleProp().StopEmissionAndDestroyImmediately(effect);
+ return 0;
+ }
+
+ effect.StopEmission(false, true, false);
+ return 0;
+ }
+}
+
+public static partial class LuaEntity
+{
+ [LuaMethod]
+ static int Entity__CreateParticleEffect(ILuaInterface lua) {
+ C_BaseEntity ent = Get_Entity(1, false)!;
+ int attachType = 0;
+ if (lua.GetType(3) == LuaType.Number)
+ attachType = LuaParticleEffect.ClampAttachType(lua.CheckNumber(3));
+
+ ParticleProperty prop = ent.ParticleProp();
+ CNewParticleEffect? effect = prop.Create(lua.CheckString(2), (ParticleAttachment)attachType, 0, Vector3.Zero);
+ if (effect == null)
+ return 0;
+
+ LuaObject options = new();
+ options.SetFromStack(3);
+ if (options.isTable()) {
+ for (int i = 1; i < ParticleConstants.MAX_PARTICLE_CONTROL_POINTS; i++) {
+ LuaObject entry = new();
+ options.GetMember(i, entry);
+ if (!entry.isTable()) {
+ entry.UnReference();
+ break;
+ }
+
+ C_BaseEntity? pointEntity = null;
+ LuaObject entityObj = new();
+ entry.GetMember("entity", entityObj);
+ if (entityObj.isEntity())
+ pointEntity = entityObj.GetEntity() as C_BaseEntity;
+ entityObj.UnReference();
+
+ int pointAttachType = LuaParticleEffect.ClampAttachType(entry.GetMemberInt("attachtype", 0));
+ prop.AddControlPoint(effect, i - 1, pointEntity, (ParticleAttachment)pointAttachType);
+
+ LuaObject position = new();
+ entry.GetMember("position", position);
+ if (position.isVector())
+ effect.SetControlPoint(i - 1, position.GetVector());
+ position.UnReference();
+
+ entry.UnReference();
+ }
+ }
+ options.UnReference();
+
+ LuaParticleEffect.Push_NewParticleEffect(effect);
+ return 1;
+ }
+
+ [LuaMethod]
+ static int Entity__StopParticleEmission(ILuaInterface lua) {
+ Get_Entity(1, false)!.ParticleProp().StopEmission();
+ return 0;
+ }
+
+ [LuaMethod]
+ static int Entity__StopParticlesNamed(ILuaInterface lua) {
+ C_BaseEntity ent = Get_Entity(1, false)!;
+ bool forceRemoveInstantly = lua.GetType(3) == LuaType.Bool && lua.GetBool(3);
+ ent.ParticleProp().StopParticlesNamed(lua.CheckString(2), forceRemoveInstantly);
+ return 0;
+ }
+
+ [LuaMethod]
+ static int Entity__StopParticlesWithNameAndAttachment(ILuaInterface lua) {
+ C_BaseEntity ent = Get_Entity(1, false)!;
+ bool forceRemoveInstantly = lua.GetType(3) == LuaType.Bool && lua.GetBool(3);
+ int attachment = (int)lua.CheckNumber(3);
+ ent.ParticleProp().StopParticlesWithNameAndAttachment(lua.CheckString(2), attachment, forceRemoveInstantly);
+ return 0;
+ }
+
+ [LuaMethod]
+ static int Entity__StopAndDestroyParticles(ILuaInterface lua) {
+ Get_Entity(1, false)!.ParticleProp().StopEmissionAndDestroyImmediately();
+ return 0;
+ }
+}
diff --git a/Game.Client/HLClient.cs b/Game.Client/HLClient.cs
index 9d57f041..f77f88f2 100644
--- a/Game.Client/HLClient.cs
+++ b/Game.Client/HLClient.cs
@@ -82,6 +82,7 @@ public void LevelInitPreEntity(ReadOnlySpan mapname) {
ParseParticleEffectsMap(mapname, true);
modemanager.LevelInit(mapname);
+ ParticleMgr.Instance.LevelInit();
ResetToneMapping(1.0f);
IGameSystem.LevelInitPreEntityAllSystems(mapname);
#if GMOD_DLL
@@ -140,8 +141,8 @@ public bool Init() {
get.IntroScreen()!.Update("Initializing Objects", true);
get.IntroScreen()!.Update("Initializing Particles", true);
#endif
- g_pParticleSystemMgr.Init(null, filesystem);
- ParseParticleEffects(true, false);
+ if (!ParticleMgr.Instance.Init(ParticleMgr.MAX_TOTAL_PARTICLES, materials))
+ return false;
#if GMOD_DLL
get.IntroScreen()!.Update("Initializing VGUI", true);
get.IntroScreen()!.Update("Adding Game Systems", true);
@@ -210,7 +211,7 @@ public bool Init() {
public void Shutdown() {
ClientVoiceMgr_Shutdown();
- g_pParticleSystemMgr.UncacheAllParticleSystems();
+ ParticleMgr.Instance.Term();
#if GMOD_DLL
Game.Client.GarrysMod.GarrysMod.Lua.Kill();
get.MenuSystem()?.Shutdown();
@@ -244,6 +245,7 @@ public bool CanShowSpeakerLabels() {
public static bool g_bLevelInitialized;
public static INetworkStringTable? g_pStringTableClientSideChoreoScenes;
public static INetworkStringTable? g_pStringTableMaterials;
+ public static INetworkStringTable? g_pStringTableEffectDispatch;
public static INetworkStringTable? g_pStringTableParticleEffectNames;
public static void PrecacheParticleSystem(ReadOnlySpan particleSystemName) {
@@ -330,7 +332,9 @@ public void InstallStringTableCallback(ReadOnlySpan tableName) {
case "Materials":
g_pStringTableMaterials = networkstringtable.FindTable(tableName);
break;
- case "EffectDispatch": Warning("FIXME: EffectDispatch string table not being processed yet\n"); break;
+ case "EffectDispatch":
+ g_pStringTableEffectDispatch = networkstringtable.FindTable(tableName);
+ break;
// I don't think InfoPanel is a thing?
case "Scenes":
g_pStringTableClientSideChoreoScenes = networkstringtable.FindTable(tableName);
@@ -433,6 +437,8 @@ private void OnRenderStart() {
beams.UpdateTempEntBeams();
}
+ ParticleMgr.Instance.Simulate((float)gpGlobals.FrameTime);
+
C_BaseEntity.CalcAimEntPositions();
C_BaseEntity.AddVisibleEntities();
@@ -580,7 +586,7 @@ public void LevelShutdown() {
view.LevelShutdown();
beams.ClearBeams();
- // ParticleMgr().RemoveAllEffects();
+ ParticleMgr.Instance.RemoveAllEffects();
// StopAllRumbleEffects();
diff --git a/Game.Client/NewParticleEffect.cs b/Game.Client/NewParticleEffect.cs
new file mode 100644
index 00000000..beefbe18
--- /dev/null
+++ b/Game.Client/NewParticleEffect.cs
@@ -0,0 +1,313 @@
+using Game.Shared;
+
+using Source;
+using Source.Common;
+using Source.Common.Engine;
+using Source.Common.Mathematics;
+using Source.Particles;
+
+using System.Numerics;
+using System.Runtime.CompilerServices;
+
+using static Source.Particles.ParticleConstants;
+
+namespace Game.Client;
+
+public class CNewParticleEffect : ParticleCollection, IClientUnknown, IClientRenderable
+{
+ public CNewParticleEffect? NextEffect;
+ public CNewParticleEffect? PrevEffect;
+
+ protected string? DebugName;
+
+ bool DontRemove;
+ bool RemoveFlag;
+ bool Drawn;
+ bool NeedsBBoxUpdate;
+ bool IsFirstFrame;
+ bool AutoUpdateBBox;
+ bool Allocated;
+ bool ShouldSimulate_;
+ bool ShouldPerformCullCheck_;
+
+ Vector3 SortOrigin;
+ EHANDLE Owner = new();
+ readonly StrongBox[] ControlPointOwners = new StrongBox[MAX_PARTICLE_CONTROL_POINTS];
+
+ Vector3 LastMin;
+ Vector3 LastMax;
+
+ bool ViewModelEffect;
+ bool ShouldDraw_;
+
+ int RefCount;
+
+ ClientRenderHandle_t RenderHandle_ = INVALID_CLIENT_RENDER_HANDLE;
+
+ public CNewParticleEffect(C_BaseEntity? owner, ParticleSystemDefinition? effect) {
+ for (int i = 0; i < MAX_PARTICLE_CONTROL_POINTS; i++)
+ ControlPointOwners[i] = new(new EHANDLE());
+ Owner.Set(owner);
+ Init(g_pParticleSystemMgr, effect);
+ Construct();
+ }
+
+ public CNewParticleEffect(C_BaseEntity? owner, string? effectName) {
+ for (int i = 0; i < MAX_PARTICLE_CONTROL_POINTS; i++)
+ ControlPointOwners[i] = new(new EHANDLE());
+ Owner.Set(owner);
+ Init(g_pParticleSystemMgr, effectName);
+ Construct();
+ }
+
+ void Construct() {
+ SortOrigin = Vector3.Zero;
+
+ DontRemove = false;
+ RemoveFlag = false;
+ Drawn = false;
+ NeedsBBoxUpdate = false;
+ IsFirstFrame = true;
+ AutoUpdateBBox = false;
+ Allocated = true;
+ ShouldSimulate_ = true;
+ ShouldPerformCullCheck_ = false;
+
+ RefCount = 0;
+ ParticleMgr.Instance.AddEffect(this);
+ LastMax = new(-1.0e6f, -1.0e6f, -1.0e6f);
+ LastMin = new(1.0e6f, 1.0e6f, 1.0e6f);
+ MinBounds = new(1.0e6f, 1.0e6f, 1.0e6f);
+ MaxBounds = new(-1.0e6f, -1.0e6f, -1.0e6f);
+ DebugName = null;
+
+ ViewModelEffect = Def != null && Def.IsViewModelEffect();
+ ShouldDraw_ = true;
+ }
+
+ public static CNewParticleEffect Create(C_BaseEntity? owner, string? particleSystemName, string? debugName = null) {
+ CNewParticleEffect ret = new(owner, particleSystemName);
+ ret.DebugName = debugName ?? particleSystemName;
+ ret.SetDynamicallyAllocated(true);
+ return ret;
+ }
+
+ public static CNewParticleEffect Create(C_BaseEntity? owner, ParticleSystemDefinition def, string? debugName = null) {
+ CNewParticleEffect ret = new(owner, def);
+ ret.DebugName = debugName ?? def.GetName();
+ ret.SetDynamicallyAllocated(true);
+ return ret;
+ }
+
+ public void AddRef() => ++RefCount;
+
+ public void Release() {
+ Assert(RefCount > 0);
+ --RefCount;
+
+ if (RefCount == 0 && Allocated && IsFinished())
+ SetRemoveFlag();
+ }
+
+ public void NotifyRemove() {
+ if (!Allocated)
+ return;
+
+ Allocated = false;
+ Owner.Get()?.ParticleProp().OnParticleSystemDeleted(this);
+ g_Lua?.ReleaseUserTypeObject(this);
+ Destroy();
+ }
+
+ public int IsReleased() => RefCount == 0 ? 1 : 0;
+
+ public void SetSortOrigin(in Vector3 sortOrigin) => SortOrigin = sortOrigin;
+ public ref readonly Vector3 GetSortOrigin() => ref SortOrigin;
+
+ public bool ShouldDraw() => true;
+ public void SetShouldDraw(bool shouldDraw) => ShouldDraw_ = shouldDraw;
+ public bool GetShouldDraw() => ShouldDraw_;
+ public bool IsTransparent() => IsTranslucent();
+ public bool UsesPowerOfTwoFrameBufferTexture() => UsesPowerOfTwoFrameBufferTexture(true);
+ public bool UsesFullFrameBufferTexture() => UsesFullFrameBufferTexture(true);
+
+ public ref readonly QAngle GetRenderAngles() => ref MathLibConsts.vec3_angle;
+
+ static Matrix3x4 RenderableToWorldMat;
+ public ref readonly Matrix3x4 RenderableToWorldTransform() {
+ MathLib.SetIdentityMatrix(out RenderableToWorldMat);
+ MathLib.PositionMatrix(GetRenderOrigin(), ref RenderableToWorldMat);
+ return ref RenderableToWorldMat;
+ }
+
+ public ref readonly Vector3 GetRenderOrigin() => ref SortOrigin;
+
+ public string GetEffectName() => GetName();
+
+ public void SetDontRemove(bool set) => DontRemove = set;
+ public void SetDrawn(bool drawn) => Drawn = drawn;
+ public void SetFirstFrameFlag(bool first) => IsFirstFrame = first;
+ public void SetDynamicallyAllocated(bool dynamic = true) => Allocated = dynamic;
+ public void SetNeedsBBoxUpdate(bool needsUpdate) => NeedsBBoxUpdate = needsUpdate;
+ public void SetAutoUpdateBBox(bool needsUpdate) => AutoUpdateBBox = needsUpdate;
+ public void SetRemoveFlag() => RemoveFlag = true;
+ public bool GetRemoveFlag() => RemoveFlag;
+ public bool GetFirstFrameFlag() => IsFirstFrame;
+ public bool GetNeedsBBoxUpdate() => NeedsBBoxUpdate;
+ public bool GetAutoUpdateBBox() => AutoUpdateBBox;
+ public bool ShouldPerformCullCheck() => ShouldPerformCullCheck_;
+ public void MarkShouldPerformCullCheck(bool enable) => ShouldPerformCullCheck_ = enable;
+ public C_BaseEntity? GetOwner() => Owner.Get();
+ public void SetOwner(C_BaseEntity? owner) => Owner.Set(owner);
+ public void SetIsViewModelEffect(bool isViewModelEffect) => ViewModelEffect = isViewModelEffect;
+ public bool GetIsViewModelEffect() => ViewModelEffect;
+ public bool ShouldSimulate() => ShouldSimulate_;
+ public void SetShouldSimulate(bool sim) => ShouldSimulate_ = sim;
+
+ public ref readonly EHANDLE GetControlPointEntity(int whichPoint) => ref ControlPointOwners[whichPoint].Value;
+
+ public void SetControlPointEntity(int whichPoint, C_BaseEntity? entity) {
+ if ((uint)whichPoint >= MAX_PARTICLE_CONTROL_POINTS) {
+ Warning($"CNewParticleEffect::SetControlPointEntity invalid control point {whichPoint}\n");
+ return;
+ }
+
+ if (entity != null) {
+ SetControlPointObject(whichPoint, ControlPointOwners[whichPoint]);
+ ControlPointOwners[whichPoint].Value.Set(entity);
+ }
+ else
+ SetControlPointObject(whichPoint, null);
+ }
+
+ public void Update(float timeDelta) => Owner.Get()?.ParticleProp().OnParticleSystemUpdated(this, timeDelta);
+
+ public CNewParticleEffect? ReplaceWith(string? particleSystemName) {
+ StopEmission(false, true, true);
+ if (string.IsNullOrEmpty(particleSystemName))
+ return null;
+
+ CNewParticleEffect newEffect = Create(GetOwner(), particleSystemName, particleSystemName);
+ if (!newEffect.IsValid())
+ return newEffect;
+
+ for (int i = 0; i < MAX_PARTICLE_CONTROL_POINTS; ++i) {
+ if (!ReadsControlPoint(i))
+ continue;
+
+ newEffect.SetControlPoint(i, GetControlPointAtCurrentTime(i));
+ GetControlPointOrientationAtCurrentTime(i, out Vector3 forward, out Vector3 right, out Vector3 up);
+ newEffect.SetControlPointOrientation(i, forward, right, up);
+ newEffect.SetControlPointParent(i, GetControlPointParent(i));
+ }
+
+ C_BaseEntity? owner = Owner.Get();
+ if (owner == null)
+ return newEffect;
+
+ owner.ParticleProp().ReplaceParticleEffect(this, newEffect);
+ return newEffect;
+ }
+
+ public void SetParticleCullRadius(float radius) { }
+
+ public bool RecalculateBoundingBox() {
+ BloatBoundsUsingControlPoint();
+ if (MaxBounds.X < MinBounds.X) {
+ MaxBounds = MinBounds = GetSortOrigin();
+ return false;
+ }
+ return true;
+ }
+
+ public void GetRenderBounds(out Vector3 mins, out Vector3 maxs) {
+ mins = MinBounds - GetRenderOrigin();
+ maxs = MaxBounds - GetRenderOrigin();
+ }
+
+ public void DetectChanges() {
+ if (RenderHandle_ == INVALID_CLIENT_RENDER_HANDLE)
+ return;
+
+ float buffer = ParticleMgr.cl_particleeffect_aabb_buffer.GetFloat();
+ float extraBuffer = buffer * 1.3f;
+
+ if (MinBounds.X < LastMin.X ||
+ MinBounds.Y < LastMin.Y ||
+ MinBounds.Z < LastMin.Z ||
+
+ MinBounds.X > (LastMin.X + extraBuffer) ||
+ MinBounds.Y > (LastMin.Y + extraBuffer) ||
+ MinBounds.Z > (LastMin.Z + extraBuffer) ||
+
+ MaxBounds.X > LastMax.X ||
+ MaxBounds.Y > LastMax.Y ||
+ MaxBounds.Z > LastMax.Z ||
+
+ MaxBounds.X < (LastMax.X - extraBuffer) ||
+ MaxBounds.Y < (LastMax.Y - extraBuffer) ||
+ MaxBounds.Z < (LastMax.Z - extraBuffer)
+ ) {
+ clientLeafSystem.RenderableChanged(RenderHandle_);
+ LastMin = MinBounds - new Vector3(buffer, buffer, buffer);
+ LastMax = MaxBounds + new Vector3(buffer, buffer, buffer);
+ }
+ }
+
+ public int DrawModel(StudioFlags flags) => 0;
+
+ public IClientUnknown GetIClientUnknown() => this;
+ public ICollideable? GetCollideable() => null;
+ public IClientNetworkable? GetClientNetworkable() => null;
+ public IClientRenderable? GetClientRenderable() => this;
+ public IClientEntity? GetIClientEntity() => null;
+ public IClientThinkable? GetClientThinkable() => null;
+
+ public void SetRefEHandle(in BaseHandle handle) => Assert(false);
+ public ref readonly BaseHandle GetRefEHandle() {
+ Assert(false);
+ return ref Unsafe.NullRef();
+ }
+
+ public ClientShadowHandle_t GetShadowHandle() => ClientRenderableGlobals.CLIENTSHADOW_INVALID_HANDLE;
+ public ref ClientRenderHandle_t RenderHandle() => ref RenderHandle_;
+ public Model? GetModel() => null;
+ public int GetBody() => 0;
+ public int GetSkin() => 0;
+ public bool UsesFlexDelayedWeights() => false;
+ public void ComputeFxBlend() { }
+ public int GetFxBlend() => 255;
+ public void GetColorModulation(Span color) => color[..3].Fill(1.0f);
+ public bool LODTest() => true;
+ public bool SetupBones(Span boneToWorldOut, int maxBones, int boneMask, TimeUnit_t currentTime) => true;
+ public void SetupWeights(Span boneToWorld, Span flexWeights, Span flexDelayedWeights) { }
+ public void DoAnimationEvents() { }
+ public IPVSNotify? GetPVSNotifyInterface() => null;
+ public void GetRenderBoundsWorldspace(out Vector3 mins, out Vector3 maxs) => IClientLeafSystemEngine.DefaultRenderBoundsWorldspace(this, out mins, out maxs);
+ public void GetShadowRenderBounds(out Vector3 mins, out Vector3 maxs, ShadowType shadowType) => GetRenderBounds(out mins, out maxs);
+ public bool ShouldReceiveProjectedTextures(ShadowFlags flags) => false;
+ public bool GetShadowCastDistance(ref float dist, ShadowType shadowType) => false;
+ public bool GetShadowCastDirection(ref Vector3 direction, ShadowType shadowType) => false;
+ public bool IsShadowDirty() => false;
+ public void MarkShadowDirty(bool dirty) { }
+ public IClientRenderable? GetShadowParent() => null;
+ public IClientRenderable? FirstShadowChild() => null;
+ public IClientRenderable? NextShadowPeer() => null;
+ public ShadowType ShadowCastType() => ShadowType.None;
+ public void CreateModelInstance() { }
+ public ModelInstanceHandle_t GetModelInstance() => MODEL_INSTANCE_INVALID;
+ public int LookupAttachment(ReadOnlySpan attachmentName) => -1;
+ public bool GetAttachment(int number, out Vector3 origin, out QAngle angles) {
+ origin = default;
+ angles = default;
+ return false;
+ }
+ public bool GetAttachment(int number, out Matrix3x4 matrix) {
+ matrix = default;
+ return false;
+ }
+ public Span GetRenderClipPlane() => default;
+ public void OnThreadedDrawSetup() { }
+ public void RecordToolMessage() { }
+ public bool IgnoresZBuffer() => false;
+}
diff --git a/Game.Client/ParticleMgr.cs b/Game.Client/ParticleMgr.cs
index a3406e57..aa7bf956 100644
--- a/Game.Client/ParticleMgr.cs
+++ b/Game.Client/ParticleMgr.cs
@@ -1,8 +1,12 @@
-using Source.Common;
-using System;
-using System.Collections.Generic;
+using Game.Shared;
+
+using Source;
+using Source.Common;
+using Source.Common.Commands;
+using Source.Common.Engine;
+using Source.Common.MaterialSystem;
+
using System.Numerics;
-using System.Text;
namespace Game.Client;
@@ -15,3 +19,190 @@ public struct ParticleLightInfo
[NetworkVar("m_flIntensity")]
public float Intensity;
}
+
+public struct ParticleSimListEntry
+{
+ public CNewParticleEffect NewParticleEffect;
+ public bool BoundingBoxOnly;
+}
+
+public sealed class ParticleMgr
+{
+ public const int MAX_TOTAL_PARTICLES = 16384;
+
+ public static readonly ParticleMgr Instance = new();
+
+ public static readonly ConVar r_DrawParticles = new("r_drawparticles", "1", FCvar.Cheat, "Enable/disable particle rendering");
+ public static readonly ConVar cl_particleeffect_aabb_buffer = new("cl_particleeffect_aabb_buffer", "2", FCvar.Cheat, "Add this amount to a particle effect's bbox in the leaf system so if it's growing slowly, it won't have to be reinserted as often.");
+ static readonly ConVar r_particle_timescale = new("r_particle_timescale", "1.0", FCvar.Cheat | FCvar.DevelopmentOnly);
+
+ CNewParticleEffect? NewEffectsHead;
+ IMaterialSystem? MaterialSystem;
+ bool UpdatingEffects;
+ bool RenderParticleSystems_ = true;
+
+ static float ThreadedPSystemTimeStep;
+
+ public bool Init(int count, IMaterialSystem materials) {
+ Term();
+
+ MaterialSystem = materials;
+
+ g_pParticleSystemMgr.Init(ParticleSystemQuery.g_pParticleSystemQuery, filesystem);
+
+ ParseParticleEffects(true, false);
+
+ return true;
+ }
+
+ public void Term() {
+ NewEffectsHead = null;
+
+ g_pParticleSystemMgr.UncacheAllParticleSystems();
+ MaterialSystem?.UncacheUnusedMaterials();
+ MaterialSystem = null;
+ }
+
+ public void LevelInit() => g_pParticleSystemMgr.SetLastSimulationTime(gpGlobals.CurTime);
+
+ public void RenderParticleSystems(bool enable) => RenderParticleSystems_ = enable;
+ public bool ShouldRenderParticleSystems() => RenderParticleSystems_;
+
+ public void AddEffect(CNewParticleEffect effect) {
+ effect.PrevEffect = null;
+ effect.NextEffect = NewEffectsHead;
+ if (NewEffectsHead != null)
+ NewEffectsHead.PrevEffect = effect;
+ NewEffectsHead = effect;
+
+ clientLeafSystem.CreateRenderableHandle(effect);
+ if (effect.IsValid() && effect.Def!.IsViewModelEffect())
+ clientLeafSystem.SetRenderGroup(effect.RenderHandle(), RenderGroup.ViewModelTranslucent);
+ }
+
+ public void RemoveEffect(CNewParticleEffect effect) {
+ Assert(!UpdatingEffects);
+
+ clientLeafSystem.RemoveRenderable(effect.RenderHandle());
+
+ if (effect.PrevEffect != null)
+ effect.PrevEffect.NextEffect = effect.NextEffect;
+ else if (NewEffectsHead == effect)
+ NewEffectsHead = effect.NextEffect;
+ if (effect.NextEffect != null)
+ effect.NextEffect.PrevEffect = effect.PrevEffect;
+ effect.NextEffect = null;
+ effect.PrevEffect = null;
+
+ effect.NotifyRemove();
+ }
+
+ public void RemoveAllNewEffects() {
+ for (CNewParticleEffect? newEffect = NewEffectsHead; newEffect != null;) {
+ CNewParticleEffect? nextEffect = newEffect.NextEffect;
+ for (C_BaseEntity? ent = cl_entitylist.FirstBaseEntity(); ent != null; ent = cl_entitylist.NextBaseEntity(ent))
+ ent.ParticleProp().OnParticleSystemDeleted(newEffect);
+
+ RemoveEffect(newEffect);
+ newEffect = nextEffect;
+ }
+ }
+
+ public void RemoveAllEffects() => RemoveAllNewEffects();
+
+ public void Simulate(float timeDelta) {
+ if (MaterialSystem == null) {
+ Assert(false);
+ return;
+ }
+
+ UpdateAllEffects(timeDelta);
+ }
+
+ static void ProcessPSystem(in ParticleSimListEntry entry) {
+ CNewParticleEffect newEffect = entry.NewParticleEffect;
+ bool updateBboxOnly = entry.BoundingBoxOnly;
+
+ if (newEffect.GetNeedsBBoxUpdate()) {
+ if (!newEffect.GetAutoUpdateBBox() || newEffect.RecalculateBoundingBox())
+ newEffect.SetNeedsBBoxUpdate(false);
+ }
+
+ newEffect.SetDrawn(false);
+
+ if (newEffect.GetFirstFrameFlag()) {
+ newEffect.Simulate(0.0f, updateBboxOnly);
+ newEffect.SetFirstFrameFlag(false);
+ }
+ else if (newEffect.ShouldSimulate())
+ newEffect.Simulate(ThreadedPSystemTimeStep, updateBboxOnly);
+
+ if (newEffect.IsFinished())
+ newEffect.SetRemoveFlag();
+ }
+
+ void BuildParticleSimList(List list) {
+ double now = g_pParticleSystemMgr.GetLastSimulationTime();
+ for (CNewParticleEffect? newEffect = NewEffectsHead; newEffect != null; newEffect = newEffect.NextEffect) {
+ bool skip = false;
+ bool needsBboxUpdate = false;
+
+ if (now >= newEffect.NextSleepTime && newEffect.ActiveParticles > 0)
+ skip = true;
+ if (newEffect.GetRemoveFlag())
+ skip = true;
+
+ if (skip) {
+ needsBboxUpdate = newEffect.HasMoved();
+ skip = !needsBboxUpdate;
+ }
+
+ if (!skip)
+ list.Add(new() { NewParticleEffect = newEffect, BoundingBoxOnly = needsBboxUpdate });
+ }
+ }
+
+ readonly List ParticlesToSimulate = [];
+
+ void UpdateNewEffects(float timeDelta) {
+ timeDelta *= r_particle_timescale.GetFloat();
+
+ g_pParticleSystemMgr.SetLastSimulationTime(gpGlobals.CurTime);
+
+ ThreadedPSystemTimeStep = timeDelta;
+
+ for (CNewParticleEffect? newEffect = NewEffectsHead; newEffect != null; newEffect = newEffect.NextEffect)
+ newEffect.Update(ThreadedPSystemTimeStep);
+
+ ParticlesToSimulate.Clear();
+ BuildParticleSimList(ParticlesToSimulate);
+ int count = ParticlesToSimulate.Count;
+
+ if (count != 0) {
+ DirtySpatialPartitionEntityList.UpdateDirtySpatialPartitionEntities();
+ for (int i = 0; i < count; i++)
+ ProcessPSystem(ParticlesToSimulate[i]);
+ }
+
+ for (int i = 0; i < count; i++)
+ ParticlesToSimulate[i].NewParticleEffect.DetectChanges();
+ }
+
+ void UpdateAllEffects(float timeDelta) {
+ UpdatingEffects = true;
+
+ if (timeDelta > 0.1f)
+ timeDelta = 0.1f;
+
+ UpdateNewEffects(timeDelta);
+
+ UpdatingEffects = false;
+
+ for (CNewParticleEffect? newEffect = NewEffectsHead; newEffect != null;) {
+ CNewParticleEffect? nextEffect = newEffect.NextEffect;
+ if (newEffect.GetRemoveFlag())
+ RemoveEffect(newEffect);
+ newEffect = nextEffect;
+ }
+ }
+}
diff --git a/Game.Client/ParticleProperty.cs b/Game.Client/ParticleProperty.cs
new file mode 100644
index 00000000..23bb0097
--- /dev/null
+++ b/Game.Client/ParticleProperty.cs
@@ -0,0 +1,400 @@
+using Game.Shared;
+
+using Source;
+using Source.Common;
+using Source.Common.Commands;
+using Source.Common.Mathematics;
+using Source.Particles;
+
+using System.Numerics;
+
+using static Source.Particles.ParticleConstants;
+
+namespace Game.Client;
+
+public sealed class ParticlePropertyControlPoint
+{
+ public int ControlPoint;
+ public ParticleAttachment AttachType = ParticleAttachment.AbsOriginFollow;
+ public int AttachmentPoint;
+ public Vector3 OriginOffset;
+ public EHANDLE Entity = new();
+}
+
+public sealed class ParticleEffectList
+{
+ public readonly List ControlPoints = [];
+ CNewParticleEffect? ParticleEffect_;
+
+ public CNewParticleEffect? ParticleEffect {
+ get => ParticleEffect_;
+ set {
+ value?.AddRef();
+ ParticleEffect_?.Release();
+ ParticleEffect_ = value;
+ }
+ }
+
+ public void MarkDeleted() => ParticleEffect_ = null;
+}
+
+public sealed class ParticleProperty
+{
+ public const int INVALID_PARTICLE_ATTACHMENT = 0;
+
+ public static readonly ConVar cl_particle_batch_mode = new("cl_particle_batch_mode", "1");
+
+ C_BaseEntity? Outer;
+ readonly List ParticleEffects = [];
+ long DormancyChangedAtFrame;
+
+ public ParticleProperty() => Init(null);
+
+ public void Init(C_BaseEntity? entity) => Outer = entity;
+ public C_BaseEntity? GetOuter() => Outer;
+
+ void RemoveEffectAt(int index) {
+ ParticleEffectList entry = ParticleEffects[index];
+ ParticleEffects.RemoveAt(index);
+ entry.ParticleEffect = null;
+ }
+
+ static int GetParticleAttachment(C_BaseEntity? entity, ReadOnlySpan attachmentName, ReadOnlySpan particleName) {
+ C_BaseAnimating? animating = entity?.GetBaseAnimating();
+ Assert(animating != null);
+ if (animating == null)
+ return INVALID_PARTICLE_ATTACHMENT;
+
+ return animating.LookupAttachment(attachmentName);
+ }
+
+ public CNewParticleEffect? Create(string particleName, ParticleAttachment attachType, ReadOnlySpan attachmentName) {
+ int attachment = GetParticleAttachment(GetOuter(), attachmentName, particleName);
+ if (attachment == INVALID_PARTICLE_ATTACHMENT)
+ return null;
+
+ return Create(particleName, attachType, attachment);
+ }
+
+ public CNewParticleEffect? Create(string particleName, ParticleAttachment attachType, int attachmentPoint = INVALID_PARTICLE_ATTACHMENT, Vector3 originOffset = default) {
+ if (GameRules.g_pGameRules != null)
+ particleName = GameRules.g_pGameRules.TranslateEffectForVisionFilter("particles", particleName).ToString();
+
+ int batchMode = cl_particle_batch_mode.GetInt();
+ ParticleSystemDefinition? def = g_pParticleSystemMgr.FindParticleSystem(particleName);
+ bool requestedBatch = (batchMode == 2) || ((batchMode == 1) && def != null && def.ShouldBatch);
+ if (attachType == ParticleAttachment.CustomOrigin && requestedBatch) {
+ int index = FindEffect(particleName);
+ if (index >= 0) {
+ CNewParticleEffect effect = ParticleEffects[index].ParticleEffect!;
+ effect.Restart();
+ return effect;
+ }
+ }
+
+ if (def == null) {
+ Warning($"Attempting to create unknown particle system '{particleName}' \n");
+ return null;
+ }
+
+ ParticleEffectList newEffect = new();
+ ParticleEffects.Add(newEffect);
+ int effectIndex = ParticleEffects.Count - 1;
+ newEffect.ParticleEffect = CNewParticleEffect.Create(Outer, def);
+
+ if (!newEffect.ParticleEffect!.IsValid()) {
+ Warning($"Attempting to create particle system '{particleName}' with unprecached material!\n");
+ ParticleMgr.Instance.RemoveEffect(newEffect.ParticleEffect);
+ return null;
+ }
+
+ AddControlPoint(effectIndex, 0, GetOuter(), attachType, attachmentPoint, originOffset);
+
+ Outer?.OnNewParticleEffect(particleName, newEffect.ParticleEffect);
+
+ return newEffect.ParticleEffect;
+ }
+
+ public void AddControlPoint(CNewParticleEffect effect, int point, C_BaseEntity? entity, ParticleAttachment attachType, string? attachmentName = null, Vector3 originOffset = default) {
+ int attachment = INVALID_PARTICLE_ATTACHMENT;
+ if (attachmentName != null)
+ attachment = GetParticleAttachment(entity, attachmentName, effect.GetEffectName());
+
+ for (int i = 0; i < ParticleEffects.Count; i++) {
+ if (ParticleEffects[i].ParticleEffect == effect)
+ AddControlPoint(i, point, entity, attachType, attachment, originOffset);
+ }
+ }
+
+ public void AddControlPoint(int effectIndex, int point, C_BaseEntity? entity, ParticleAttachment attachType, int attachmentPoint = INVALID_PARTICLE_ATTACHMENT, Vector3 originOffset = default) {
+ Assert(effectIndex >= 0 && effectIndex < ParticleEffects.Count);
+ ParticleEffectList effect = ParticleEffects[effectIndex];
+ Assert(effect.ControlPoints.Count < MAX_PARTICLE_CONTROL_POINTS);
+
+ ParticlePropertyControlPoint? newPoint = null;
+ int index = point;
+ foreach (ParticlePropertyControlPoint existing in effect.ControlPoints) {
+ if (existing.ControlPoint == point)
+ newPoint = existing;
+ }
+
+ if (newPoint == null) {
+ newPoint = new();
+ effect.ControlPoints.Add(newPoint);
+ index = effect.ControlPoints.Count - 1;
+ }
+
+ newPoint.ControlPoint = point;
+ newPoint.Entity.Set(entity);
+ newPoint.AttachType = attachType;
+ newPoint.AttachmentPoint = attachmentPoint;
+ newPoint.OriginOffset = originOffset;
+
+ UpdateParticleEffect(effect, true, index);
+ }
+
+ public void SetControlPointParent(CNewParticleEffect effect, int whichControlPoint, int parentIdx) => effect.SetControlPointParent(whichControlPoint, parentIdx);
+ public void SetControlPointParent(int effectIndex, int whichControlPoint, int parentIdx) { }
+
+ public CNewParticleEffect? GetParticleEffectFromIdx(int idx) => ParticleEffects[idx].ParticleEffect;
+
+ public void ReplaceParticleEffect(CNewParticleEffect oldEffect, CNewParticleEffect newEffect) {
+ for (int i = 0; i < ParticleEffects.Count; ++i) {
+ if (oldEffect != ParticleEffects[i].ParticleEffect)
+ continue;
+
+ ParticleEffects[i].ParticleEffect = newEffect;
+ UpdateParticleEffect(ParticleEffects[i], true);
+ }
+ }
+
+ public void StopEmission(CNewParticleEffect? effect = null, bool wakeOnStop = false, bool destroyAsleepSystems = false) {
+ bool removeInstantly = DormancyChangedAtFrame == gpGlobals.FrameCount;
+
+ if (effect != null) {
+ if (FindEffect(effect) != -1)
+ effect.StopEmission(false, removeInstantly, wakeOnStop);
+ return;
+ }
+
+ double now = g_pParticleSystemMgr.GetLastSimulationTime();
+ for (int i = ParticleEffects.Count - 1; i >= 0; i--) {
+ CNewParticleEffect tmp = ParticleEffects[i].ParticleEffect!;
+ bool removeSystem = removeInstantly || (destroyAsleepSystems && now >= tmp.NextSleepTime);
+ if (removeSystem) {
+ RemoveEffectAt(i);
+ tmp.SetOwner(null);
+ }
+ tmp.StopEmission(false, removeSystem, !removeSystem && wakeOnStop);
+ }
+ }
+
+ public void StopEmissionAndDestroyImmediately(CNewParticleEffect? effect = null) {
+ if (effect != null) {
+ int index = FindEffect(effect);
+ if (index != -1) {
+ RemoveEffectAt(index);
+ effect.SetOwner(null);
+ effect.StopEmission(false, true);
+ }
+ return;
+ }
+
+ for (int i = ParticleEffects.Count - 1; i >= 0; i--) {
+ CNewParticleEffect tmp = ParticleEffects[i].ParticleEffect!;
+ RemoveEffectAt(i);
+ tmp.SetOwner(null);
+ tmp.StopEmission(false, true);
+ }
+ }
+
+ public void StopParticlesInvolving(C_BaseEntity entity) {
+ Assert(entity != null);
+
+ bool removeInstantly = DormancyChangedAtFrame == gpGlobals.FrameCount;
+
+ foreach (ParticleEffectList part in ParticleEffects) {
+ for (int j = 0; j < part.ControlPoints.Count; ++j) {
+ if (part.ControlPoints[j].Entity.Get() == entity) {
+ part.ParticleEffect!.StopEmission(false, removeInstantly);
+ part.ControlPoints.RemoveAt(j);
+ break;
+ }
+ }
+ }
+ }
+
+ public void StopParticlesNamed(string? effectName, bool forceRemoveInstantly = false, bool inverse = false) {
+ if (string.IsNullOrEmpty(effectName))
+ return;
+
+ ParticleSystemDefinition? def = g_pParticleSystemMgr.FindParticleSystem(effectName);
+ AssertMsg(def != null, $"Could not find particle definition {effectName}");
+ if (def == null)
+ return;
+
+ bool removeInstantly = DormancyChangedAtFrame == gpGlobals.FrameCount;
+ removeInstantly |= forceRemoveInstantly;
+
+ foreach (ParticleEffectList part in ParticleEffects) {
+ CNewParticleEffect effect = part.ParticleEffect!;
+ bool matches = effect.Def == def;
+ if (matches == !inverse)
+ effect.StopEmission(false, removeInstantly);
+ }
+ }
+
+ public void StopParticlesWithNameAndAttachment(string effectName, int attachmentPoint, bool forceRemoveInstantly = false) {
+ ParticleSystemDefinition? def = g_pParticleSystemMgr.FindParticleSystem(effectName);
+ AssertMsg(def != null, $"Could not find particle definition {effectName}");
+ if (def == null)
+ return;
+
+ bool removeInstantly = DormancyChangedAtFrame == gpGlobals.FrameCount;
+ removeInstantly |= forceRemoveInstantly;
+
+ foreach (ParticleEffectList part in ParticleEffects) {
+ CNewParticleEffect effect = part.ParticleEffect!;
+ if (effect.Def != def)
+ continue;
+
+ foreach (ParticlePropertyControlPoint point in part.ControlPoints) {
+ if (point.AttachmentPoint == attachmentPoint) {
+ effect.StopEmission(false, removeInstantly);
+ break;
+ }
+ }
+ }
+ }
+
+ public void OnParticleSystemUpdated(CNewParticleEffect effect, float timeDelta) {
+ int index = FindEffect(effect);
+ Assert(index != -1);
+ if (index == -1)
+ return;
+
+ UpdateParticleEffect(ParticleEffects[index]);
+ }
+
+ public void OnParticleSystemDeleted(CNewParticleEffect effect) {
+ int index = FindEffect(effect);
+ if (index == -1)
+ return;
+
+ ParticleEffects[index].MarkDeleted();
+ ParticleEffects.RemoveAt(index);
+ }
+
+ public void OwnerSetDormantTo(bool dormant) {
+ DormancyChangedAtFrame = gpGlobals.FrameCount;
+
+ foreach (ParticleEffectList part in ParticleEffects)
+ part.ParticleEffect!.SetDormant(dormant);
+ }
+
+ int FindEffect(CNewParticleEffect effect) {
+ for (int i = 0; i < ParticleEffects.Count; i++) {
+ if (ParticleEffects[i].ParticleEffect == effect)
+ return i;
+ }
+ return -1;
+ }
+
+ public int FindEffect(ReadOnlySpan effectName, int start = 0) {
+ for (int i = start; i < ParticleEffects.Count; i++) {
+ if (effectName.Equals(ParticleEffects[i].ParticleEffect!.GetName(), StringComparison.OrdinalIgnoreCase))
+ return i;
+ }
+ return -1;
+ }
+
+ void UpdateParticleEffect(ParticleEffectList effect, bool initializing = false, int onlyThisControlPoint = -1) {
+ if (onlyThisControlPoint != -1) {
+ UpdateControlPoint(effect, onlyThisControlPoint, initializing);
+ return;
+ }
+
+ for (int i = 0; i < effect.ControlPoints.Count; i++)
+ UpdateControlPoint(effect, i, initializing);
+ }
+
+ void UpdateControlPoint(ParticleEffectList effectList, int pointIndex, bool initializing) {
+ ParticlePropertyControlPoint point = effectList.ControlPoints[pointIndex];
+ CNewParticleEffect effect = effectList.ParticleEffect!;
+
+ if (effect.Def != null && effect.Def.IsScreenSpaceEffect() && pointIndex == 0) {
+ effect.SetControlPointOrientation(point.ControlPoint, new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1));
+ effect.SetControlPoint(point.ControlPoint, Vector3.Zero);
+ return;
+ }
+
+ C_BaseEntity? entity = point.Entity.Get();
+ if (entity == null) {
+ if (point.AttachType == ParticleAttachment.WorldOrigin && initializing) {
+ effect.SetControlPointOrientation(point.ControlPoint, new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1));
+ effect.SetControlPoint(point.ControlPoint, point.OriginOffset);
+ effect.SetSortOrigin(point.OriginOffset);
+ }
+
+ effect.SetControlPointEntity(point.ControlPoint, null);
+ return;
+ }
+
+ if (!initializing && entity.GetMoveParent() == null && (point.AttachType == ParticleAttachment.AbsOrigin || point.AttachType == ParticleAttachment.Point))
+ return;
+
+ if (point.AttachType == ParticleAttachment.CustomOrigin)
+ return;
+
+ Vector3 origin = default, forward = default, right = default, up = default;
+
+ switch (point.AttachType) {
+ case ParticleAttachment.Point:
+ case ParticleAttachment.PointFollow: {
+ C_BaseAnimating? animating = entity.GetBaseAnimating();
+ if (animating != null) {
+ if (!animating.GetAttachment(point.AttachmentPoint, out Matrix3x4 attachmentToWorld)) {
+ DevWarning($"Cannot update control point {point.AttachmentPoint} for effect '{effect.GetEffectName()}'.\n");
+ attachmentToWorld = animating.RenderableToWorldTransform();
+ }
+
+ MathLib.MatrixVectors(attachmentToWorld, out forward, out right, out up);
+ MathLib.MatrixGetColumn(attachmentToWorld, 3, out origin);
+
+ if (effect.Def != null && effect.Def.IsViewModelEffect())
+ C_BaseViewModel.FormatViewModelAttachment(ref origin, true);
+ }
+ }
+ break;
+
+ case ParticleAttachment.RootBoneFollow: {
+ C_BaseAnimating? animating = entity.GetBaseAnimating();
+ if (animating != null && animating.GetRootBone(out Matrix3x4 rootBone)) {
+ MathLib.MatrixVectors(rootBone, out forward, out right, out up);
+ MathLib.MatrixGetColumn(rootBone, 3, out origin);
+ }
+ }
+ break;
+
+ default:
+ origin = entity.GetAbsOrigin() + point.OriginOffset;
+ entity.GetVectors(out forward, out right, out up);
+ break;
+ }
+
+ effect.SetControlPointOrientation(point.ControlPoint, forward, right, up);
+ effect.SetControlPointEntity(point.ControlPoint, entity);
+ effect.SetControlPoint(point.ControlPoint, origin);
+ effect.SetSortOrigin(origin);
+ }
+
+ public void DebugPrintEffects() {
+ for (int i = 0; i < ParticleEffects.Count; ++i) {
+ CNewParticleEffect? effect = ParticleEffects[i].ParticleEffect;
+ if (effect == null)
+ continue;
+
+ Msg($"({i}) EffectName \"{effect.GetEffectName()}\" Dormant? {(effect.Dormant ? "yes" : "no")} Emission Stopped? {(effect.EmissionStopped ? "yes" : "no")} \n");
+ }
+ }
+}
diff --git a/Game.Shared/EffectData.cs b/Game.Shared/EffectData.cs
index 0fdba776..a6af0f6e 100644
--- a/Game.Shared/EffectData.cs
+++ b/Game.Shared/EffectData.cs
@@ -32,7 +32,7 @@ public partial class EffectData
new(nameof(Material)) { Bits = 13, Flags = PropFlags.Unsigned },
new(nameof(DamageType)) { Bits = 32, Flags = PropFlags.Unsigned },
new(nameof(HitBox)) { Bits = 12, Flags = PropFlags.Unsigned },
- new(nameof(EntIndex)) { Bits = Constants.MAX_EDICT_BITS, Flags = PropFlags.Unsigned },
+ new(nameof(EntIndex)) { Bits = Constants.MAX_EDICT_BITS, Flags = PropFlags.Unsigned, Proxy = typeof(EntIndexProxy) },
new(nameof(Color)) { Bits = 8, Flags = PropFlags.Unsigned },
new(nameof(Radius)) { Bits = 10, Flags = PropFlags.RoundDown, Low = 0.0f, High = 1023.0f },
nameof(HasCustomColors),
@@ -51,6 +51,18 @@ public static class SurfacePropProxy
#endif
}
+ public static class EntIndexProxy
+ {
+#if CLIENT_DLL
+ public static void Recv(ref readonly RecvProxyData data, object instance, IFieldAccessor field) {
+ EffectData effectData = (EffectData)instance;
+ int entIndex = data.Value.Int;
+ effectData.EntIndex = entIndex;
+ effectData.Entity = entIndex < 0 ? Game.Client.ClientEntityGlobals.INVALID_CLIENTENTITY_HANDLE : Game.Client.SourceDllMain.cl_entitylist.EntIndexToHandle(entIndex);
+ }
+#endif
+ }
+
public const int SUBINCH_PRECISION = 3;
public const int MAX_EFFECT_FLAG_BITS = 8;
public const int CUSTOM_COLOR_CP1 = 9;
@@ -71,7 +83,7 @@ public static class SurfacePropProxy
[NetworkVar("m_flMagnitude")]
public float Magnitude;
[NetworkVar("m_flScale")]
- public float Scale;
+ public float Scale = 1.0f;
[NetworkVar("m_nAttachmentIndex")]
public int AttachmentIndex;
[NetworkVar("m_nSurfaceProp")]
@@ -105,8 +117,12 @@ public static class SurfacePropProxy
[NetworkVar("m_ControlPoint1")]
public ParticleEffectsControlPoint ControlPoint1;
[NetworkVar("m_bAllowOverride")]
- public bool AllowOverride;
+ public bool AllowOverride = true;
public EffectData Copy() => (EffectData)MemberwiseClone();
+
+ static bool SuppressParticleEffects_;
+ public static bool SuppressingParticleEffects() => SuppressParticleEffects_;
+ public static void SuppressParticleEffects(bool suppress) => SuppressParticleEffects_ = suppress;
}
#endif
diff --git a/Game.Shared/EventList.cs b/Game.Shared/EventList.cs
index b4890785..d0a7dcd7 100644
--- a/Game.Shared/EventList.cs
+++ b/Game.Shared/EventList.cs
@@ -62,6 +62,8 @@ public enum AnimEventId
AE_SV_DUSTTRAIL,
AE_CL_CREATE_PARTICLE_EFFECT,
+ AE_CL_STOP_PARTICLE_EFFECT,
+ AE_CL_ADD_PARTICLE_EFFECT_CP,
AE_RAGDOLL,
@@ -250,6 +252,8 @@ public static void RegisterSharedEvents() {
REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_SV_DUSTTRAIL, AnimEventType.Server);
REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_CL_CREATE_PARTICLE_EFFECT, AnimEventType.Client);
+ REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_CL_STOP_PARTICLE_EFFECT, AnimEventType.Client);
+ REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_CL_ADD_PARTICLE_EFFECT_CP, AnimEventType.Client);
REGISTER_SHARED_ANIMEVENT(AnimEventId.AE_RAGDOLL, AnimEventType.Server);
diff --git a/Game.Shared/GarrysMod/LuaEntity.cs b/Game.Shared/GarrysMod/LuaEntity.cs
index 3609fe6b..9e0e7a68 100644
--- a/Game.Shared/GarrysMod/LuaEntity.cs
+++ b/Game.Shared/GarrysMod/LuaEntity.cs
@@ -84,6 +84,12 @@ public static void RemoveQueuedEntities() {
ProcessingRemoveList = false;
}
+ [LuaMethod]
+ static int Entity__StopParticles(ILuaInterface lua) {
+ StopParticleEffects(Get_Entity(1, false));
+ return 0;
+ }
+
[LuaMethod]
static int Entity__IsMarkedForDeletion(ILuaInterface lua) {
BaseEntity ent = Get_Entity(1, false)!;
diff --git a/Game.Shared/GarrysMod/LuaGame.cs b/Game.Shared/GarrysMod/LuaGame.cs
index 5d6aedcb..72c68cb1 100644
--- a/Game.Shared/GarrysMod/LuaGame.cs
+++ b/Game.Shared/GarrysMod/LuaGame.cs
@@ -19,9 +19,8 @@ public static partial class LuaGame
[LuaFunction]
static int AddParticles(ILuaInterface lua) {
string file = g_Lua!.CheckString(1);
- if (LuaFileLibrary.IsFileAccessAllowed(file, "GAME", false, false)) {
- // GMOD_LoadParticleConfigFile(file); // TODO!
- }
+ if (LuaFileLibrary.IsFileAccessAllowed(file, "GAME", false, false))
+ GMOD_LoadParticleConfigFile(file);
return 0;
}
diff --git a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs
index 706fdd3f..1a926127 100644
--- a/Game.Shared/GarrysMod/LuaGlobalFunctions.cs
+++ b/Game.Shared/GarrysMod/LuaGlobalFunctions.cs
@@ -179,6 +179,27 @@ static int PrecacheParticleSystem(ILuaInterface lua) {
return 0;
}
+#if CLIENT_DLL || GAME_DLL
+ [LuaGlobal]
+ static int ParticleEffect(ILuaInterface lua) {
+ QAngle angles = LuaAngle.Get_Angle(3);
+ Vector3 start = LuaVector.Get_Vector(2);
+ Vector3 origin = LuaVector.Get_Vector(2);
+ BaseEntity? entity = LuaEntity.Get_Entity(4, true);
+ DispatchParticleEffect(lua.CheckString(1), origin, start, angles, entity);
+ return 0;
+ }
+
+ [LuaGlobal]
+ static int ParticleEffectAttach(ILuaInterface lua) {
+ int attachment = (int)lua.CheckNumber(4);
+ BaseEntity? entity = LuaEntity.Get_Entity(3, true);
+ int attachType = (int)lua.CheckNumber(2);
+ DispatchParticleEffect(lua.CheckString(1), (ParticleAttachment)attachType, entity, attachment, false);
+ return 0;
+ }
+#endif
+
[LuaGlobal]
static int CompileFile(ILuaInterface lua) {
bool showErrors = true;
diff --git a/Game.Shared/ParticleParse.cs b/Game.Shared/ParticleParse.cs
index fb1f202d..2fbc8cee 100644
--- a/Game.Shared/ParticleParse.cs
+++ b/Game.Shared/ParticleParse.cs
@@ -2,10 +2,17 @@
using Source.Common;
using Source.Common.Formats.Keyvalues;
+using Source.Common.Mathematics;
using Source.Particles;
using System.Numerics;
+#if CLIENT_DLL
+using Game.Client;
+#elif GAME_DLL
+using Game.Server;
+#endif
+
namespace Game.Shared;
public enum ParticleAttachment : byte
@@ -71,6 +78,12 @@ public static void ParseParticleEffects(bool loadSheets, bool precache) {
g_pParticleSystemMgr.DecommitTempMemory();
}
+ public static void GMOD_LoadParticleConfigFile(string file) {
+ g_pParticleSystemMgr.ShouldLoadSheets(true);
+ g_pParticleSystemMgr.ReadParticleConfigFile(file, true, false);
+ g_pParticleSystemMgr.DecommitTempMemory();
+ }
+
public static void ParseParticleEffectsMap(ReadOnlySpan mapName, bool loadSheets) {
List files = [];
string mapManifestFilename = mapName.IsEmpty ? "" : $"maps/{mapName}_particles.txt";
@@ -110,6 +123,121 @@ public static void ParseParticleEffectsMap(ReadOnlySpan mapName, bool load
g_pParticleSystemMgr.DecommitTempMemory();
}
+ static readonly string?[] AttachmentNames = [
+ "start_at_origin",
+ "follow_origin",
+ "start_at_customorigin",
+ "start_at_attachment",
+ "follow_attachment",
+ "follow_rootbone",
+ null,
+ ];
+
+ public static int GetAttachTypeFromString(ReadOnlySpan str) {
+ if (str.IsEmpty)
+ return -1;
+
+ for (int i = 0; i < (int)ParticleAttachment.Max; i++) {
+ if (AttachmentNames[i] != null && str.Equals(AttachmentNames[i], StringComparison.OrdinalIgnoreCase))
+ return i;
+ }
+
+ return -1;
+ }
+
+ public const int PARTICLE_DISPATCH_FROM_ENTITY = 1 << 0;
+ public const int PARTICLE_DISPATCH_RESET_PARTICLES = 1 << 1;
+
+ static int ParticleSystemIndex(ReadOnlySpan particleName) {
+#if CLIENT_DLL
+ return Game.Client.HLClient.GetParticleSystemIndex(particleName);
+#else
+ return Game.Server.GameInterface.GetParticleSystemIndex(particleName);
+#endif
+ }
+
+ static void SetEffectEntity(EffectData data, BaseEntity? entity) {
+#if CLIENT_DLL
+ data.Entity = entity != null ? entity.GetRefEHandle() : new BaseHandle();
+#else
+ data.EntIndex = entity != null ? entity.EntIndex() : 0;
+#endif
+ }
+
+ public static void DispatchParticleEffect(ReadOnlySpan particleName, ParticleAttachment attachType, BaseEntity? entity, ReadOnlySpan attachmentName, bool resetAllParticlesOnEntity = false) {
+ int attachment = -1;
+ BaseAnimating? animating = entity?.GetBaseAnimating();
+ if (animating != null) {
+ attachment = animating.LookupAttachment(attachmentName);
+ if (attachment <= 0)
+ return;
+ }
+
+ DispatchParticleEffect(particleName, attachType, entity, attachment, resetAllParticlesOnEntity);
+ }
+
+ public static void DispatchParticleEffect(ReadOnlySpan particleName, ParticleAttachment attachType, BaseEntity? entity = null, int attachmentPoint = -1, bool resetAllParticlesOnEntity = false) {
+ EffectData data = new();
+
+ data.HitBox = ParticleSystemIndex(particleName);
+ if (entity != null) {
+ SetEffectEntity(data, entity);
+ data.Flags |= PARTICLE_DISPATCH_FROM_ENTITY;
+ data.Origin = entity.GetAbsOrigin();
+ }
+ data.DamageType = (int)attachType;
+ data.AttachmentIndex = attachmentPoint;
+
+ if (resetAllParticlesOnEntity)
+ data.Flags |= PARTICLE_DISPATCH_RESET_PARTICLES;
+
+#if GAME_DLL
+ if ((data.Flags & PARTICLE_DISPATCH_FROM_ENTITY) != 0 && (attachType == ParticleAttachment.AbsOriginFollow || attachType == ParticleAttachment.PointFollow || attachType == ParticleAttachment.RootBoneFollow)) {
+ ReliableBroadcastRecipientFilter filter = new();
+ DispatchEffect("ParticleEffect", data, filter);
+ return;
+ }
+#endif
+ DispatchEffect("ParticleEffect", data);
+ }
+
+ public static void DispatchParticleEffect(int effectIndex, in Vector3 origin, in Vector3 start, in QAngle angles, BaseEntity? entity = null) {
+ EffectData data = new() {
+ HitBox = effectIndex,
+ Origin = origin,
+ Start = start,
+ Angles = angles
+ };
+
+ SetEffectEntity(data, entity);
+ if (entity != null) {
+ data.Flags |= PARTICLE_DISPATCH_FROM_ENTITY;
+ data.DamageType = (int)ParticleAttachment.CustomOrigin;
+ }
+
+ DispatchEffect("ParticleEffect", data);
+ }
+
+ public static void DispatchParticleEffect(ReadOnlySpan particleName, in Vector3 origin, in QAngle angles, BaseEntity? entity = null)
+ => DispatchParticleEffect(ParticleSystemIndex(particleName), origin, origin, angles, entity);
+
+ public static void DispatchParticleEffect(ReadOnlySpan particleName, in Vector3 origin, in Vector3 start, in QAngle angles, BaseEntity? entity = null)
+ => DispatchParticleEffect(ParticleSystemIndex(particleName), origin, start, angles, entity);
+
+ public static void StopParticleEffects(BaseEntity? entity) {
+ EffectData data = new();
+
+ if (entity != null)
+ SetEffectEntity(data, entity);
+
+#if GAME_DLL
+ ReliableBroadcastRecipientFilter filter = new();
+ DispatchEffect("ParticleEffectStop", data, filter);
+#else
+ DispatchEffect("ParticleEffectStop", data);
+#endif
+ }
+
#if GAME_DLL
public static void PrecacheStandardParticleSystems() {
for (int i = 0; i < g_pParticleSystemMgr.GetParticleSystemCount(); i++) {
diff --git a/Game.Shared/ParticleSystemQuery.cs b/Game.Shared/ParticleSystemQuery.cs
new file mode 100644
index 00000000..bdb13b98
--- /dev/null
+++ b/Game.Shared/ParticleSystemQuery.cs
@@ -0,0 +1,126 @@
+using Source;
+using Source.Common;
+using Source.Common.Formats.BSP;
+using Source.Particles;
+
+using System.Numerics;
+
+#if CLIENT_DLL
+using Game.Client;
+#elif GAME_DLL
+using Game.Server;
+#endif
+
+namespace Game.Shared;
+
+public sealed class ParticleSystemQuery : IParticleSystemQuery
+{
+ public static readonly ParticleSystemQuery g_pParticleSystemQuery = new();
+
+ static readonly object LightMutex = new();
+
+ public void GetLightingAtPoint(in Vector3 origin, out Color tint) {
+#if CLIENT_DLL
+ if (engine.IsInGame()) {
+ Vector3 totalColor;
+ lock (LightMutex)
+ totalColor = engine.GetLightForPoint(origin, true);
+
+ tint = default;
+ tint.SetColor((int)(totalColor.X * 255), (int)(totalColor.Y * 255), (int)(totalColor.Z * 255), 0);
+ return;
+ }
+#endif
+ tint = new(255, 255, 255, 255);
+ }
+
+ public void TraceLine(in Vector3 absStart, in Vector3 absEnd, Mask mask, IHandleEntity? ignore, int collisionGroup, ref GameTrace trace) {
+ bool doTrace = false;
+#if CLIENT_DLL
+ doTrace = engine.IsInGame();
+#endif
+ if (doTrace) {
+ Util.TraceLine(absStart, absEnd, mask, ignore, (CollisionGroup)collisionGroup, out Trace tempTrace);
+ trace.StartPos = tempTrace.StartPos;
+ trace.EndPos = tempTrace.EndPos;
+ trace.Plane = tempTrace.Plane;
+ trace.Fraction = tempTrace.Fraction;
+ trace.Contents = tempTrace.Contents;
+ trace.DispFlags = tempTrace.DispFlags;
+ trace.AllSolid = tempTrace.AllSolid;
+ trace.StartSolid = tempTrace.StartSolid;
+ }
+ else {
+ trace.StartSolid = false;
+ trace.Fraction = 1.0f;
+ }
+ }
+
+ public bool MovePointInsideControllingObject(ParticleCollection particles, object? obj, ref Vector3 pnt) {
+#if CLIENT_DLL
+ if (obj is not C_BaseEntity entity)
+ return true;
+
+ Ray ray = default;
+ ray.Init(pnt, pnt);
+ Trace tr = default;
+ enginetrace.ClipRayToEntity(in ray, Mask.All, entity, ref tr);
+ return tr.StartSolid;
+#else
+ return true;
+#endif
+ }
+
+ static readonly (string Name, CollisionGroup Group)[] NameMap = [
+ ("NONE", CollisionGroup.None),
+ ("DEBRIS", CollisionGroup.Debris),
+ ("INTERACTIVE", CollisionGroup.Interactive),
+ ("NPC", CollisionGroup.NPC),
+ ("ACTOR", CollisionGroup.NPCActor),
+ ("PASSABLE", CollisionGroup.PassableDoor),
+ ];
+
+ public int GetCollisionGroupFromName(ReadOnlySpan collisionGroupName) {
+ foreach ((string name, CollisionGroup group) in NameMap) {
+ if (collisionGroupName.Equals(name, StringComparison.OrdinalIgnoreCase))
+ return (int)group;
+ }
+ return (int)CollisionGroup.None;
+ }
+
+ public Vector3 GetLocalPlayerPos() {
+#if CLIENT_DLL
+ C_BasePlayer? player = C_BasePlayer.GetLocalPlayer();
+#elif GAME_DLL
+ BasePlayer? player = AI_UtilsGlobals.AI_GetSinglePlayer();
+#else
+ object? player = null;
+#endif
+#if CLIENT_DLL || GAME_DLL
+ if (player == null)
+ return Vector3.Zero;
+ return player.WorldSpaceCenter();
+#else
+ return Vector3.Zero;
+#endif
+ }
+
+ public void GetLocalPlayerEyeVectors(out Vector3 forward, out Vector3 right, out Vector3 up) {
+#if CLIENT_DLL
+ C_BasePlayer? player = C_BasePlayer.GetLocalPlayer();
+#elif GAME_DLL
+ BasePlayer? player = AI_UtilsGlobals.AI_GetSinglePlayer();
+#endif
+#if CLIENT_DLL || GAME_DLL
+ if (player != null) {
+ player.EyeVectors(out forward, out right, out up);
+ return;
+ }
+#endif
+ forward = Vector3.Zero;
+ right = Vector3.Zero;
+ up = Vector3.Zero;
+ }
+
+ public float GetPixelVisibility(ref int queryHandle, in Vector3 origin, float scale) => 0.0f;
+}
diff --git a/Source.Common/Mathematics/MathLib.cs b/Source.Common/Mathematics/MathLib.cs
index 31438bfc..f729696d 100644
--- a/Source.Common/Mathematics/MathLib.cs
+++ b/Source.Common/Mathematics/MathLib.cs
@@ -2359,6 +2359,12 @@ public static void MatrixGetColumn(in Matrix3x4 inMatrix, int column, out Vector
outVec.Y = inMatrix[1][column];
outVec.Z = inMatrix[2][column];
}
+ public static void MatrixVectors(in Matrix3x4 matrix, out Vector3 forward, out Vector3 right, out Vector3 up) {
+ MatrixGetColumn(matrix, 0, out forward);
+ MatrixGetColumn(matrix, 1, out right);
+ MatrixGetColumn(matrix, 2, out up);
+ right *= -1.0f;
+ }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void PositionMatrix(in Vector3 position, ref Matrix3x4 mat) {
MatrixSetColumn(in position, 3, ref mat);
diff --git a/Source.Particles/ParticleCollection.cs b/Source.Particles/ParticleCollection.cs
index db615770..ed876b86 100644
--- a/Source.Particles/ParticleCollection.cs
+++ b/Source.Particles/ParticleCollection.cs
@@ -45,14 +45,7 @@ public class ParticleCollection
public const int NUM_COLLISION_CACHE_MODES = 4;
const int CONSTANT_FLOATS = MAX_PARTICLE_ATTRIBUTES * 12;
- static readonly float[] RandomFloats = LoadRandomFloats();
-
- static float[] LoadRandomFloats() {
- float[] floats = new float[MAX_RANDOM_FLOATS];
- using Stream stream = typeof(ParticleCollection).Assembly.GetManifestResourceStream("Source.Particles.random_floats.bin")!;
- stream.ReadExactly(MemoryMarshal.AsBytes(floats.AsSpan()));
- return floats;
- }
+ static readonly float[] RandomFloats = Source.Particles.RandomFloats.Table;
public static ReadOnlySpan RandomFloatTable => RandomFloats;
@@ -61,7 +54,7 @@ static float[] LoadRandomFloats() {
public int ActiveParticles;
public float Dt;
public float PreviousDt = 0.05f;
- public float NextSleepTime;
+ public double NextSleepTime;
public ParticleSystemMgr? Mgr;
public ParticleSystemDefinition? Def;
diff --git a/Source.Particles/ParticleSystemDefinition.cs b/Source.Particles/ParticleSystemDefinition.cs
index 1251696a..ff2cdba3 100644
--- a/Source.Particles/ParticleSystemDefinition.cs
+++ b/Source.Particles/ParticleSystemDefinition.cs
@@ -104,7 +104,8 @@ public sealed class ParticleSystemDefinition(ParticleSystemMgr mgr)
.Float("time to sleep when not drawn", "8", (d, v) => d.NoDrawTimeToGoToSleep = v)
.Bool("Sort particles", "1", (d, v) => d.ShouldSort = v)
.Bool("batch particle systems", "0", (d, v) => d.ShouldBatch = v)
- .Bool("view model effect", "0", (d, v) => d.ViewModelEffect = v);
+ .Bool("view model effect", "0", (d, v) => d.ViewModelEffect = v)
+ .Bool("screen space effect", "0", (d, v) => d.ScreenSpaceEffect = v);
public static IDmxElementUnpackStructure GetUnpackStructure() => UnpackStructure;
@@ -139,6 +140,7 @@ public sealed class ParticleSystemDefinition(ParticleSystemMgr mgr)
public float MinimumSimTime;
public int MinimumFrames;
public bool ViewModelEffect;
+ public bool ScreenSpaceEffect;
public int ContextDataSize;
public Guid Id;
@@ -178,6 +180,7 @@ public sealed class ParticleSystemDefinition(ParticleSystemMgr mgr)
public IMaterial? GetMaterial() => Material.Get();
public bool ShouldAlwaysPrecache() => AlwaysPrecache;
public bool IsViewModelEffect() => ViewModelEffect;
+ public bool IsScreenSpaceEffect() => ScreenSpaceEffect;
public float GetCullRadius() => CullRadius;
public float GetCullFillCost() => CullFillCost;
public int GetCullControlPoint() => CullControlPoint;
diff --git a/Source.Particles/ParticleSystemMgr.cs b/Source.Particles/ParticleSystemMgr.cs
index e1a80d55..6604bc71 100644
--- a/Source.Particles/ParticleSystemMgr.cs
+++ b/Source.Particles/ParticleSystemMgr.cs
@@ -21,7 +21,7 @@ public sealed class ParticleSystemMgr
IParticleSystemQuery Query_ = new DefaultParticleSystemQuery();
IFileSystem? FileSystem;
IMaterial? ShadowDepthMaterial;
- float LastSimulationTime;
+ double LastSimulationTime;
bool DidInit;
bool UsingDefaultQuery = true;
bool ShouldLoadSheets_ = true;
@@ -72,8 +72,8 @@ public void AddParticleOperator(ParticleFunctionType opType, IParticleOperatorDe
public void DecommitTempMemory() { }
- public void SetLastSimulationTime(float time) => LastSimulationTime = time;
- public float GetLastSimulationTime() => LastSimulationTime;
+ public void SetLastSimulationTime(double time) => LastSimulationTime = time;
+ public double GetLastSimulationTime() => LastSimulationTime;
public bool ReadParticleConfigFile(string fileName, bool precache, bool decommitTempMemory = true) {
if (fileName.StartsWith('!')) {
diff --git a/Source.Particles/RandomFloats.cs b/Source.Particles/RandomFloats.cs
new file mode 100644
index 00000000..fcc8acb9
--- /dev/null
+++ b/Source.Particles/RandomFloats.cs
@@ -0,0 +1,263 @@
+namespace Source.Particles;
+
+public static class RandomFloats
+{
+ public static readonly float[] Table = [
+ 0.336914f, 0.671387f, 0.539307f, 0.165039f, 0.258301f, 0.146973f, 0.475342f, 0.993408f, 0.88208f, 0.733887f, 0.152588f, 0.192871f, 0.873291f, 0.637939f, 0.859131f, 0.836914f,
+ 0.277344f, 0.026367f, 0.864502f, 0.327393f, 0.428711f, 0.684082f, 0.916992f, 0.935547f, 0.643311f, 0.082764f, 0.033447f, 0.086182f, 0.575684f, 0.121826f, 0.342285f, 0.419189f,
+ 0.409424f, 0.17749f, 0.049072f, 0.25293f, 0.459717f, 0.561035f, 0.581543f, 0.470703f, 0.662842f, 0.936035f, 0.912354f, 0.965332f, 0.523682f, 0.661865f, 0.484131f, 0.030029f,
+ 0.958984f, 0.370605f, 0.626709f, 0.736084f, 0.241943f, 0.307129f, 0.969482f, 0.269287f, 0.21582f, 0.995605f, 0.300781f, 0.984375f, 0.621338f, 0.785645f, 0.432373f, 0.895264f,
+ 0.098389f, 0.857178f, 0.220947f, 0.981689f, 0.667969f, 0.898682f, 0.603027f, 0.588623f, 0.206055f, 0.536133f, 0.245361f, 0.999023f, 0.758545f, 0.1521f, 0.015869f, 0.546387f,
+ 0.101563f, 0.92041f, 0.56665f, 0.793457f, 0.077148f, 0.675049f, 0.032715f, 0.645264f, 0.654053f, 0.536377f, 0.599121f, 0.300537f, 0.404053f, 0.115967f, 0.646484f, 0.162842f,
+ 0.88623f, 0.412109f, 0.55249f, 0.63208f, 0.623291f, 0.846436f, 0.313965f, 0.505859f, 0.487305f, 0.644287f, 0.517578f, 0.89209f, 0.14624f, 0.21875f, 0.484619f, 0.904785f,
+ 0.551758f, 0.809814f, 0.721191f, 0.871582f, 0.847656f, 0.062256f, 0.647949f, 0.708252f, 0.690186f, 0.59375f, 0.061768f, 0.406982f, 0.169434f, 0.874756f, 0.139893f, 0.792236f,
+ 0.783691f, 0.855957f, 0.198975f, 0.706299f, 0.594971f, 0.739746f, 0.307373f, 0.123291f, 0.480713f, 0.0271f, 0.697266f, 0.534424f, 0.070068f, 0.641602f, 0.4729f, 0.598145f,
+ 0.21167f, 0.977051f, 0.145264f, 0.311279f, 0.975098f, 0.904297f, 0.999268f, 0.725586f, 0.039307f, 0.669434f, 0.578369f, 0.285889f, 0.867188f, 0.982666f, 0.797119f, 0.755371f,
+ 0.950195f, 0.383789f, 0.42627f, 0.337402f, 0.075439f, 0.841553f, 0.794678f, 0.074707f, 0.02124f, 0.627686f, 0.036377f, 0.921143f, 0.229248f, 0.20874f, 0.69873f, 0.622803f,
+ 0.943848f, 0.673828f, 0.826416f, 0.10791f, 0.366943f, 0.352539f, 0.256592f, 0.930176f, 0.556885f, 0.378418f, 0.205566f, 0.286133f, 0.623047f, 0.986328f, 0.781494f, 0.974609f,
+ 0.239014f, 0.883789f, 0.859375f, 0.884277f, 0.856445f, 0.521484f, 0.332764f, 0.489746f, 0.880615f, 0.553955f, 0.961182f, 0.360352f, 0.48999f, 0.175781f, 0.777832f, 0.02002f,
+ 0.346436f, 0.250732f, 0.094482f, 0.900146f, 0.185547f, 0.317139f, 0.686768f, 0.517334f, 0.350342f, 0.774902f, 0.978027f, 0.81958f, 0.967773f, 0.811523f, 0.038574f, 0.791504f,
+ 0.196045f, 0.543701f, 0.705566f, 0.586426f, 0.585449f, 0.016846f, 0.413086f, 0.583496f, 0.772461f, 0.728271f, 0.289307f, 0.482666f, 0.389404f, 0.302002f, 0.331055f, 0.759277f,
+ 0.885742f, 0.745605f, 0.444092f, 0.341797f, 0.607422f, 0.436279f, 0.102783f, 0.874023f, 0.868408f, 0.662109f, 0.287354f, 0.918701f, 0.892334f, 0.685791f, 0.500244f, 0.433594f,
+ 0.664795f, 0.734863f, 0.93335f, 0.078369f, 0.808105f, 0.790039f, 0.404541f, 0.005371f, 0.976318f, 0.800537f, 0.482178f, 0.472412f, 0.656494f, 0.835449f, 0.713135f, 0.629395f,
+ 0.468506f, 0.03833f, 0.143555f, 0.375f, 0.140381f, 0.427734f, 0.822754f, 0.26709f, 0.253662f, 0.68335f, 0.788818f, 0.531738f, 0.2146f, 0.87793f, 0.659668f, 0.640381f,
+ 0.954346f, 0.227539f, 0.167969f, 0.491211f, 0.084473f, 0.272949f, 0.96167f, 0.06543f, 0.696045f, 0.625732f, 0.177734f, 0.782715f, 0.934814f, 0.385742f, 0.401611f, 0.018555f,
+ 0.686279f, 0.749023f, 0.114014f, 0.106689f, 0.501709f, 0.471924f, 0.151855f, 0.088623f, 0.677734f, 0.425293f, 0.910645f, 0.483398f, 0.872314f, 0.782471f, 0.16333f, 0.574463f,
+ 0.119385f, 0.80957f, 0.94751f, 0.19751f, 0.887207f, 0.577637f, 0.021484f, 0.020508f, 0.641846f, 0.321533f, 0.95752f, 0.893555f, 0.625488f, 0.424072f, 0.612793f, 0.003906f,
+ 0.060059f, 0.388184f, 0.724365f, 0.195068f, 0.263184f, 0.919434f, 0.094971f, 0.550781f, 0.997559f, 0.763916f, 0.300293f, 0.530029f, 0.583984f, 0.767578f, 0.745361f, 0.69165f,
+ 0.17041f, 0.762695f, 0.949463f, 0.349365f, 0.757324f, 0.30249f, 0.498047f, 0.397217f, 0.213379f, 0.019775f, 0.587402f, 0.562988f, 0.573975f, 0.36084f, 0.320313f, 0.258545f,
+ 0.948486f, 0.186279f, 0.976563f, 0.19043f, 0.865723f, 0.162598f, 0.547607f, 0.339111f, 0.39209f, 0.273193f, 0.714844f, 0.797363f, 0.403564f, 0.449219f, 0.747314f, 0.844238f,
+ 0.835205f, 0.110596f, 0.134033f, 0.214355f, 0.766113f, 0.109131f, 0.013184f, 0.875f, 0.737061f, 0.320801f, 0.639893f, 0.744141f, 0.751465f, 0.127197f, 0.011963f, 0.353027f,
+ 0.693359f, 0.440674f, 0.26416f, 0.780029f, 0.529785f, 0.800781f, 0.671143f, 0.332031f, 0.400635f, 0.981445f, 0.770264f, 0.435059f, 0.29834f, 0.437988f, 0.163574f, 0.271973f,
+ 0.039551f, 0.043457f, 0.866943f, 0.009766f, 0.651123f, 0.84668f, 0.653076f, 0.125732f, 0.530762f, 0.868896f, 0.268799f, 0.958008f, 0.142578f, 0.461914f, 0.303955f, 0.010986f,
+ 0.62085f, 0.522217f, 0.510986f, 0.338135f, 0.914551f, 0.411865f, 0.604004f, 0.706543f, 0.238525f, 0.510254f, 0.103271f, 0.632324f, 0.422119f, 0.440186f, 0.265137f, 0.2771f,
+ 0.221924f, 0.201172f, 0.599365f, 0.244629f, 0.177002f, 0.293945f, 0.368652f, 0.649902f, 0.100586f, 0.622559f, 0.905762f, 0.209961f, 0.257324f, 0.249512f, 0.428467f, 0.369141f,
+ 0.166016f, 0.635986f, 0.79834f, 0.940918f, 0.993896f, 0.803467f, 0.320068f, 0.929443f, 0.650146f, 0.058594f, 0.065918f, 0.609375f, 0.616943f, 0.379639f, 0.221191f, 0.200684f,
+ 0.486084f, 0.4375f, 0.871338f, 0.795898f, 0.863037f, 0.700684f, 0.51709f, 0.821533f, 0.319092f, 0.397461f, 0.852295f, 0.864014f, 0.591797f, 0.514404f, 0.925049f, 0.71582f,
+ 0.384766f, 0.734131f, 0.89917f, 0.703125f, 0.210938f, 0.783203f, 0.687012f, 0.850586f, 0.532471f, 0.025635f, 0.975342f, 0.852051f, 0.612305f, 0.910889f, 0.159668f, 0.407227f,
+ 0.669678f, 0.096924f, 0.733398f, 0.304688f, 0.015625f, 0.372803f, 0.32959f, 0.858398f, 0.033203f, 0.830811f, 0.914307f, 0.022949f, 0.451416f, 0.106201f, 0.664551f, 0.895752f,
+ 0.366455f, 0.230225f, 0.595459f, 0.296631f, 0.291992f, 0.375488f, 0.952393f, 0.052734f, 0.132813f, 0.549805f, 0.828125f, 0.065674f, 0.318848f, 0.031494f, 0.605713f, 0.534912f,
+ 0.611328f, 0.259766f, 0.445068f, 0.660156f, 0.848633f, 0.055176f, 0.32373f, 0.122803f, 0.69751f, 0.097412f, 0.989014f, 0.348877f, 0.536865f, 0.442139f, 0.269043f, 0.762451f,
+ 0.92627f, 0.118896f, 0.45874f, 0.496094f, 0.253906f, 0.084717f, 0.648926f, 0.754639f, 0.648438f, 0.488281f, 0.533691f, 0.048828f, 0.050781f, 0.847168f, 0.431152f, 0.638184f,
+ 0.938232f, 0.092285f, 0.970215f, 0.037354f, 0.852539f, 0.58667f, 0.729248f, 0.227295f, 0.48291f, 0.051025f, 0.135254f, 0.08252f, 0.8125f, 0.391602f, 0.598389f, 0.605957f,
+ 0.949707f, 0.4646f, 0.86377f, 0.024902f, 0.989502f, 0.937012f, 0.435547f, 0.565186f, 0.37085f, 0.801758f, 0.143311f, 0.354492f, 0.715088f, 0.423828f, 0.796387f, 0.384033f,
+ 0.093018f, 0.813965f, 0.356201f, 0.535889f, 0.229492f, 0.553711f, 0.080811f, 0.711426f, 0.082275f, 0.713623f, 0.097168f, 0.8479f, 0.197754f, 0.057617f, 0.970703f, 0.282959f,
+ 0.252686f, 0.082031f, 0.847412f, 0.274658f, 0.806641f, 0.027588f, 0.844727f, 0.748535f, 0.66748f, 0.200195f, 0.814941f, 0.912598f, 0.463379f, 0.304199f, 0.815918f, 0.481445f,
+ 0.345947f, 0.936279f, 0.851318f, 0.796631f, 0.119141f, 0.328369f, 0.185303f, 0.911621f, 0.5271f, 0.342529f, 0.6521f, 0.435303f, 0.537354f, 0.051758f, 0.998535f, 0.597168f,
+ 0.031006f, 0.056396f, 0.003174f, 0.702637f, 0.262207f, 0.433838f, 0.052002f, 0.776367f, 0.993652f, 0.836182f, 0.055908f, 0.694092f, 0.768311f, 0.073242f, 0.908203f, 0.548584f,
+ 0.873535f, 0.205078f, 0.551514f, 0.726074f, 0.302979f, 0.136475f, 0.381348f, 0.702393f, 0.054932f, 0.796143f, 0.079346f, 0.049561f, 0.539795f, 0.731201f, 0.175049f, 0.570068f,
+ 0.171631f, 0.899902f, 0.467041f, 0.623779f, 0.913086f, 0.38623f, 0.451904f, 0.878418f, 0.880371f, 0.316406f, 0.468994f, 0.145752f, 0.920166f, 0.162354f, 0.944092f, 0.816162f,
+ 0.887695f, 0.802246f, 0.546631f, 0.803955f, 0.491455f, 0.064453f, 0.284424f, 0.153564f, 0.29126f, 0.730713f, 0.173584f, 0.942383f, 0.640137f, 0.480469f, 0.552979f, 0.413818f,
+ 0.222656f, 0.364502f, 0.736816f, 0.351074f, 0.245605f, 0.183105f, 0.697754f, 0.30835f, 0.467285f, 0.33374f, 0.400391f, 0.301514f, 0.601074f, 0.874512f, 0.571289f, 0.994873f,
+ 0.438721f, 0.865234f, 0.79541f, 0.476807f, 0.409912f, 0.651855f, 0.375244f, 0.139404f, 0.776611f, 0.713379f, 0.406494f, 0.359619f, 0.635742f, 0.261963f, 0.210449f, 0.669922f,
+ 0.612061f, 0.363281f, 0.013916f, 0.504639f, 0.11377f, 0.814697f, 0.82666f, 0.016602f, 0.079834f, 0.668945f, 0.453125f, 0.591553f, 0.258789f, 0.345703f, 0.27124f, 0.198486f,
+ 0.239258f, 0.97583f, 0.203613f, 0.974121f, 0.408691f, 0.775391f, 0.071777f, 0.503418f, 0.483887f, 0.223877f, 0.80542f, 0.813721f, 0.32666f, 0.327148f, 0.616455f, 0.615479f,
+ 0.430176f, 0.153076f, 0.979736f, 0.611572f, 0.543457f, 0.095459f, 0.897461f, 0.40625f, 0.657471f, 0.108887f, 0.00293f, 0.959961f, 0.396973f, 0.901367f, 0.572998f, 0.056152f,
+ 0.630371f, 0.762939f, 0.910156f, 0.96582f, 0.397705f, 0.171143f, 0.401367f, 0.453857f, 0.493896f, 0.837158f, 0.636719f, 0.596436f, 0.645752f, 0.894043f, 0.990479f, 0.885254f,
+ 0.863525f, 0.650391f, 0.761963f, 0.947266f, 0.57373f, 0.94165f, 0.212891f, 0.805664f, 0.153809f, 0.957275f, 0.044678f, 0.743408f, 0.57959f, 0.240967f, 0.172363f, 0.056641f,
+ 0.327637f, 0.787842f, 0.431885f, 0.652344f, 0.616699f, 0.62915f, 0.893311f, 0.691406f, 0.054199f, 0.840088f, 0.930664f, 0.708008f, 0.398193f, 0.98877f, 0.959717f, 0.666992f,
+ 0.000244f, 0.696777f, 0.365967f, 0.547119f, 0.12793f, 0.141113f, 0.348633f, 0.531494f, 0.584961f, 0.398926f, 0.728516f, 0.709229f, 0.391113f, 0.265869f, 0.244141f, 0.9729f,
+ 0.663086f, 0.258057f, 0.317871f, 0.740723f, 0.704834f, 0.138672f, 0.819092f, 0.802002f, 0.563232f, 0.072754f, 0.085938f, 0.868652f, 0.52124f, 0.206543f, 0.696533f, 0.420654f,
+ 0.897705f, 0.783936f, 0.067627f, 0.686035f, 0.537598f, 0.6604f, 0.78418f, 0.292725f, 0.444336f, 0.128662f, 0.862793f, 0.260742f, 0.789551f, 0.820557f, 0.319824f, 0.045166f,
+ 0.483154f, 0.533203f, 0.022705f, 0.249756f, 0.20166f, 0.124023f, 0.966064f, 0.11792f, 0.129395f, 0.241699f, 0.585205f, 0.481201f, 0.904053f, 0.627441f, 0.979004f, 0.041992f,
+ 0.619141f, 0.525879f, 0.682373f, 0.497803f, 0.907471f, 0.303711f, 0.562012f, 0.495117f, 0.500488f, 0.674072f, 0.552734f, 0.249023f, 0.088867f, 0.293213f, 0.22168f, 0.457031f,
+ 0.187988f, 0.950439f, 0.453369f, 0.01416f, 0.881348f, 0.050049f, 0.686523f, 0.476318f, 0.52417f, 0.552246f, 0.077393f, 0.621826f, 0.829834f, 0.030518f, 0.295654f, 0.215088f,
+ 0.438965f, 0.271729f, 0.384277f, 0.580322f, 0.191895f, 0.09668f, 0.281982f, 0.984131f, 0.675537f, 0.638672f, 0.329834f, 0.426025f, 0.768799f, 0.484375f, 0.287598f, 0.694824f,
+ 0.82251f, 0.351563f, 0.736328f, 0.905029f, 0.755127f, 0.661377f, 0.138916f, 0.236572f, 0.662354f, 0.299316f, 0.90625f, 0.77124f, 0.68042f, 0.039063f, 0.029297f, 0.246338f,
+ 0.876221f, 0.506348f, 0.474365f, 0.476074f, 0.289063f, 0.514648f, 0.751221f, 0.909424f, 0.921631f, 0.121094f, 0.628174f, 0.171875f, 0.881836f, 0.819824f, 0.002441f, 0.955811f,
+ 0.407715f, 0.288818f, 0.690918f, 0.193359f, 0.090088f, 0.46167f, 0.057861f, 0.597412f, 0.247559f, 0.479492f, 0.2229f, 0.106934f, 0.147705f, 0.750977f, 0.322754f, 0.435791f,
+ 0.672852f, 0.795654f, 0.036621f, 0.125488f, 0.036865f, 0.224854f, 0.012695f, 0.023438f, 0.19165f, 0.81665f, 0.381592f, 0.448975f, 0.112305f, 0.944336f, 0.017822f, 0.64502f,
+ 0.113037f, 0.881104f, 0.157715f, 0.692383f, 0.331299f, 0.177979f, 0.771729f, 0.223145f, 0.854004f, 0.698242f, 0.821777f, 0.341553f, 0.638428f, 0.161133f, 0.040039f, 0.592529f,
+ 0.679932f, 0.55835f, 0.36377f, 0.423584f, 0.710938f, 0.219482f, 0.738037f, 0.339844f, 0.433105f, 0.104736f, 0.65332f, 0.688965f, 0.087402f, 0.593994f, 0.387451f, 0.111328f,
+ 0.254639f, 0.34668f, 0.615234f, 0.588379f, 0.273682f, 0.141602f, 0.418701f, 0.294678f, 0.569336f, 0.442383f, 0.598877f, 0.075684f, 0.677979f, 0.76123f, 0.919189f, 0.861572f,
+ 0.320557f, 0.790771f, 0.064697f, 0.144531f, 0.93457f, 0.721436f, 0.684814f, 0.251465f, 0.762207f, 0.76709f, 0.528076f, 0.385498f, 0.269531f, 0.879639f, 0.576416f, 0.419434f,
+ 0.875732f, 0.672607f, 0.823242f, 0.785156f, 0.877686f, 0.432861f, 0.41626f, 0.066406f, 0.233643f, 0.703857f, 0.719482f, 0.352783f, 0.837646f, 0.615967f, 0.593018f, 0.137451f,
+ 0.199951f, 0.712891f, 0.885498f, 0.923828f, 0.777588f, 0.669189f, 0.546875f, 0.400146f, 0.374023f, 0.455322f, 0.577881f, 0.328125f, 0.95459f, 0.680908f, 0.836426f, 0.699219f,
+ 0.803711f, 0.350586f, 0.259277f, 0.878174f, 0.798096f, 0.904541f, 0.314453f, 0.820313f, 0.949951f, 0.125f, 0.782227f, 0.008057f, 0.303467f, 0.976074f, 0.189941f, 0.216064f,
+ 0.069092f, 0.070557f, 0.680176f, 0.983643f, 0.182861f, 0.65625f, 0.133545f, 0.389893f, 0.277588f, 0.229004f, 0.148438f, 0.193115f, 0.5625f, 0.835938f, 0.172607f, 0.550293f,
+ 0.290527f, 0.146729f, 0.334229f, 0.334717f, 0.707031f, 0.023193f, 0.969727f, 0.593262f, 0.708496f, 0.884766f, 0.329346f, 0.362305f, 0.305176f, 0.072021f, 0.591309f, 0.13501f,
+ 0.43457f, 0.394287f, 0.239746f, 0.532715f, 0.751709f, 0.760986f, 0.08374f, 0.763184f, 0.765381f, 0.230713f, 0.312988f, 0.819336f, 0.338623f, 0.619385f, 0.152832f, 0.971436f,
+ 0.656982f, 0.585693f, 0.089844f, 0.513184f, 0.732178f, 0.548828f, 0.980469f, 0.022461f, 0.34082f, 0.411377f, 0.829346f, 0.644531f, 0.804443f, 0.086914f, 0.468018f, 0.368164f,
+ 0.243408f, 0.824463f, 0.35083f, 0.416748f, 0.025879f, 0.156494f, 0.98999f, 0.12915f, 0.814453f, 0.574707f, 0.790527f, 0.296387f, 0.510498f, 0.990234f, 0.480957f, 0.56543f,
+ 0.550537f, 0.461182f, 0.359863f, 0.966553f, 0.31665f, 0.1875f, 0.032959f, 0.460693f, 0.692871f, 0.294434f, 0.857666f, 0.217041f, 0.128174f, 0.207764f, 0.309814f, 0.846924f,
+ 0.531982f, 0.047607f, 0.555664f, 0.19873f, 0.049316f, 0.576904f, 0.709473f, 0.518799f, 0.069336f, 0.601563f, 0.228516f, 0.048096f, 0.47998f, 0.108643f, 0.080566f, 0.386719f,
+ 0.5354f, 0.465088f, 0.472168f, 0.105957f, 0.310059f, 0.489014f, 0.987549f, 0.406006f, 0.673096f, 0.366211f, 0.681885f, 0.509766f, 0.600342f, 0.506592f, 0.558594f, 0.875488f,
+ 0.413574f, 0.083984f, 0.015137f, 0.559082f, 0.09375f, 0.805176f, 0.933838f, 0.775635f, 0.826172f, 0.45166f, 0.779785f, 0.158691f, 0.346191f, 0.601318f, 0.407471f, 0.54541f,
+ 0.712646f, 0.845947f, 0.741211f, 0.337891f, 0.393799f, 0.407959f, 0.095703f, 0.817139f, 0.198242f, 0.818359f, 0.272461f, 0.05127f, 0.350098f, 0.445557f, 0.485352f, 0.168945f,
+ 0.855469f, 0.427246f, 0.189453f, 0.646973f, 0.648193f, 0.717041f, 0.737305f, 0.222168f, 0.704346f, 0.235352f, 0.126221f, 0.617676f, 0.108154f, 0.287842f, 0.237549f, 0.544678f,
+ 0.761719f, 0.832764f, 0.78125f, 0.501221f, 0.168213f, 0.262451f, 0.325684f, 0.39624f, 0.970459f, 0.631348f, 0.134277f, 0.337158f, 0.006592f, 0.217529f, 0.333496f, 0.698486f,
+ 0.810059f, 0.391846f, 0.361572f, 0.265625f, 0.919922f, 0.408447f, 0.299561f, 0.524414f, 0.07666f, 0.233887f, 0.147217f, 0.247803f, 0.720459f, 0.655273f, 0.178711f, 0.642822f,
+ 0.076904f, 0.408936f, 0.113281f, 0.201416f, 0.730957f, 0.200439f, 0.88501f, 0.100342f, 0.369385f, 0.395264f, 0.54248f, 0.94043f, 0.684326f, 0.666504f, 0.22876f, 0.699463f,
+ 0.127441f, 0.212646f, 0.835693f, 0.029785f, 0.656006f, 0.354736f, 0.278564f, 0.3396f, 0.549561f, 0.149658f, 0.593506f, 0.298096f, 0.492432f, 0.447754f, 0.264648f, 0.634766f,
+ 0.166992f, 0.515137f, 0.382568f, 0.142822f, 0.783447f, 0.953125f, 0.439697f, 0.267822f, 0.121338f, 0.73584f, 0.087891f, 0.507568f, 0.595703f, 0.655518f, 0.610107f, 0.541748f,
+ 0.645508f, 0.057373f, 0.624512f, 0.191406f, 0.832031f, 0.702148f, 0.330566f, 0.087646f, 0.242188f, 0.099854f, 0.307861f, 0.430908f, 0.68457f, 0.939453f, 0.03125f, 0.924805f,
+ 0.462646f, 0.120361f, 0.545654f, 0.789063f, 0.719971f, 0.072266f, 0.353271f, 0.996826f, 0.62793f, 0.093994f, 0.920654f, 0.058105f, 0.430664f, 0.403076f, 0.448486f, 0.589111f,
+ 0.524658f, 0.148682f, 0.671875f, 0.470947f, 0.851807f, 0.367188f, 0.749268f, 0.746582f, 0.429199f, 0.466064f, 0.519531f, 0.645996f, 0.125977f, 0.549072f, 0.547363f, 0.294189f,
+ 0.254883f, 0.634277f, 0.66333f, 0.52832f, 0.178955f, 0.730225f, 0.063232f, 0.979248f, 0.733154f, 0.543945f, 0.668213f, 0.228027f, 0.896729f, 0.16748f, 0.55127f, 0.174316f,
+ 0.271484f, 0.519043f, 0.310791f, 0.664307f, 0.984619f, 0.534668f, 0.541992f, 0.604492f, 0.946045f, 0.870117f, 0.161865f, 0.660889f, 0.587646f, 0.770996f, 0.573486f, 0.035156f,
+ 0.895996f, 0.812988f, 0.452881f, 0.854248f, 0.404297f, 0.371094f, 0.561768f, 0.132324f, 0.009033f, 0.954834f, 0.522461f, 0.134521f, 0.538574f, 0.145996f, 0.968994f, 0.620117f,
+ 0.582275f, 0.609863f, 0.325195f, 0.620361f, 0.070801f, 0.633301f, 0.116455f, 0.236084f, 0.48584f, 0.519287f, 0.264404f, 0.008301f, 0.632568f, 0.091553f, 0.142334f, 0.050537f,
+ 0.358154f, 0.126953f, 0.572021f, 0.471436f, 0.017334f, 0.754883f, 0.735596f, 0.313232f, 0.780518f, 0.903809f, 0.314209f, 0.324951f, 0.188721f, 0.586182f, 0.421875f, 0.565918f,
+ 0.179443f, 0.723389f, 0.242676f, 0.592773f, 0.818604f, 0.501465f, 0.092529f, 0.126709f, 0.250244f, 0.787354f, 0.104248f, 0.758301f, 0.395508f, 0.804932f, 0.09082f, 0.828857f,
+ 0.014893f, 0.899414f, 0.716797f, 0.942871f, 0.839111f, 0.493164f, 0.625244f, 0.867432f, 0.50415f, 0.71875f, 0.725098f, 0.365479f, 0.256104f, 0.653564f, 0.355469f, 0.808838f,
+ 0.933594f, 0.525146f, 0.80835f, 0.454346f, 0.775879f, 0.184326f, 0.052979f, 0.658936f, 0.243896f, 0.799072f, 0.603516f, 0.85498f, 0.947021f, 0.004639f, 0.503174f, 0.003418f,
+ 0.682617f, 0.49292f, 0.887451f, 0.924316f, 0.475098f, 0.766602f, 0.91748f, 0.964111f, 0.971191f, 0.14502f, 0.071289f, 0.7229f, 0.144775f, 0.335205f, 0.61377f, 0.643066f,
+ 0.186035f, 0.081299f, 0.393311f, 0.123047f, 0.261719f, 0.196533f, 0.43335f, 0.263916f, 0.935303f, 0.278076f, 0.732422f, 0.328613f, 0.937988f, 0.706787f, 0.467529f, 0.203857f,
+ 0.279541f, 0.957764f, 0.600586f, 0.226074f, 0.213867f, 0.563721f, 0.132568f, 0.80249f, 0.318359f, 0.0354f, 0.606201f, 0.72168f, 0.735352f, 0.917725f, 0.045898f, 0.173828f,
+ 0.486328f, 0.241211f, 0.243164f, 0.181152f, 0.637695f, 0.670166f, 0.964844f, 0.367676f, 0.826904f, 0.903076f, 0.457764f, 0.04126f, 0.161377f, 0.955322f, 0.752197f, 0.769043f,
+ 0.163818f, 0.117188f, 0.971924f, 0.611084f, 0.560303f, 0.31958f, 0.194824f, 0.325928f, 0.477051f, 0.264893f, 0.043213f, 0.002686f, 0.69043f, 0.89624f, 0.40918f, 0.765137f,
+ 0.741455f, 0.689941f, 0.860107f, 0.70459f, 0.983887f, 0.869629f, 0.452637f, 0.376953f, 0.839355f, 0.951416f, 0.378906f, 0.042969f, 0.287109f, 0.064209f, 0.195801f, 0.494385f,
+ 0.720947f, 0.139648f, 0.570313f, 0.25f, 0.181396f, 0.461426f, 0.921875f, 0.939209f, 0.690674f, 0.393555f, 0.693115f, 0.614502f, 0.322266f, 0.720215f, 0.636475f, 0.84082f,
+ 0.958496f, 0.931641f, 0.063965f, 0.77002f, 0.298828f, 0.606445f, 0.886719f, 0.506104f, 0.95874f, 0.525635f, 0.297119f, 0.567871f, 0.358643f, 0.365234f, 0.187012f, 0.570801f,
+ 0.116211f, 0.786621f, 0.336182f, 0.388428f, 0.91333f, 0.494141f, 0.696289f, 0.848145f, 0.699951f, 0.59668f, 0.276123f, 0.015381f, 0.685303f, 0.67749f, 0.463623f, 0.866699f,
+ 0.283447f, 0.909912f, 0.215332f, 0.062012f, 0.495361f, 0.307617f, 0.46582f, 0.005127f, 0.937256f, 0.606934f, 0.465332f, 0.37915f, 0.685547f, 0.111084f, 0.753662f, 0.516113f,
+ 0.412354f, 0.05835f, 0.553223f, 0.181885f, 0.963867f, 0.639648f, 0.50293f, 0.018799f, 0.588867f, 0.974365f, 0.657227f, 0.122559f, 0.773926f, 0.526367f, 0.243652f, 0.25415f,
+ 0.618408f, 0.589355f, 0.657959f, 0.209229f, 0.670898f, 0.621582f, 0.523926f, 0.57251f, 0.053223f, 0.093262f, 0.187744f, 0.291504f, 0.083496f, 0.22998f, 0.109375f, 0.340332f,
+ 0.496582f, 0.659424f, 0.626221f, 0.18335f, 0.059814f, 0.711914f, 0.526611f, 0.425781f, 0.995361f, 0.784424f, 0.170654f, 0.275146f, 0.402344f, 0.972656f, 0.624268f, 0.923584f,
+ 0.744385f, 0.9021f, 0.361816f, 0.682861f, 0.97168f, 0.441895f, 0.186768f, 0.144043f, 0.80127f, 0.85376f, 0.099121f, 0.584717f, 0.443604f, 0.423096f, 0.855225f, 0.976807f,
+ 0.326904f, 0.614014f, 0.337646f, 0.821289f, 0.109863f, 0.405762f, 0.000732f, 0.157471f, 0.377441f, 0.987793f, 0.766846f, 0.05957f, 0.434814f, 0.186523f, 0.332275f, 0.214844f,
+ 0.07251f, 0.640625f, 0.280029f, 0.105469f, 0.280762f, 0.946533f, 0.845703f, 0.02832f, 0.044922f, 0.60376f, 0.059082f, 0.255371f, 0.143799f, 0.678711f, 0.182129f, 0.085205f,
+ 0.915771f, 0.610352f, 0.457275f, 0.617188f, 0.060547f, 0.774658f, 0.82959f, 0.854492f, 0.313721f, 0.592041f, 0.156006f, 0.469482f, 0.743896f, 0.750732f, 0.00415f, 0.352051f,
+ 0.853271f, 0.313477f, 0.456543f, 0.841797f, 0.00708f, 0.389648f, 0.849365f, 0.942627f, 0.561279f, 0.391357f, 0.214111f, 0.164551f, 0.554199f, 0.246582f, 0.012939f, 0.364746f,
+ 0.10498f, 0.046387f, 0.002197f, 0.42041f, 0.802979f, 0.156738f, 0.028076f, 0.115479f, 0.405029f, 0.708984f, 0.782959f, 0.851074f, 0.748291f, 0.088135f, 0.681152f, 0.099365f,
+ 0.624756f, 0.338379f, 0.64209f, 0.221436f, 0.997314f, 0.54834f, 0.259521f, 0.464111f, 0.016113f, 0.793945f, 0.773193f, 0.930908f, 0.316895f, 0.522705f, 0.755615f, 0.361328f,
+ 0.923096f, 0.323242f, 0.487061f, 0.474854f, 0.800293f, 0.025391f, 0.417236f, 0.89502f, 0.700195f, 0.508789f, 0.031982f, 0.467773f, 0.890137f, 0.450684f, 0.710693f, 0.204834f,
+ 0.724121f, 0.707764f, 0.425537f, 0.233154f, 0.716064f, 0.668701f, 0.255615f, 0.388672f, 0.893799f, 0.224609f, 0.978516f, 0.195557f, 0.145508f, 0.499268f, 0.890625f, 0.49585f,
+ 0.362793f, 0.900879f, 0.902344f, 0.882324f, 0.811279f, 0.579346f, 0.128418f, 0.126465f, 0.283936f, 0.406738f, 0.588135f, 0.281738f, 0.358887f, 0.946289f, 0.641357f, 0.616211f,
+ 0.747559f, 0.651611f, 0.87207f, 0.858887f, 0.834717f, 0.694336f, 0.005615f, 0.744873f, 0.83667f, 0.643799f, 0.602539f, 0.020996f, 0.107422f, 0.055664f, 0.961426f, 0.900391f,
+ 0.867676f, 0.133057f, 0.99585f, 0.737549f, 0.807617f, 0.289795f, 0.354004f, 0.972168f, 0.13916f, 0.58252f, 0.497314f, 0.514893f, 0.759033f, 0.778564f, 0.128906f, 0.862549f,
+ 0.60083f, 0.070313f, 0.966797f, 0.0979f, 0.252197f, 0.758789f, 0.529541f, 0.840576f, 0.373291f, 0.268066f, 0.72876f, 0.376221f, 0.394775f, 0.434082f, 0.840332f, 0.729004f,
+ 0.759521f, 0.908691f, 0.884521f, 0.504883f, 0.460449f, 0.288086f, 0.983398f, 0.213623f, 0.816406f, 0.716553f, 0.629883f, 0.414307f, 0.158936f, 0.828369f, 0.008545f, 0.780762f,
+ 0.364014f, 0.204102f, 0.465576f, 0.675781f, 0.66626f, 0.503906f, 0.299072f, 0.171387f, 0.511475f, 0.072998f, 0.809326f, 0.248291f, 0.182373f, 0.853516f, 0.364258f, 0.466797f,
+ 0.399902f, 0.001465f, 0.722412f, 0.830566f, 0.115234f, 0.740967f, 0.566406f, 0.068115f, 0.140869f, 0.107178f, 0.242432f, 0.290039f, 0.07959f, 0.591064f, 0.620605f, 0.515381f,
+ 0.229736f, 0.770752f, 0.707275f, 0.455811f, 0.114502f, 0.485596f, 0.628418f, 0.590088f, 0.175293f, 0.289551f, 0.077637f, 0.787109f, 0.04248f, 0.357666f, 0.790283f, 0.512451f,
+ 0.447998f, 0.825195f, 0.724609f, 0.893066f, 0.769287f, 0.739014f, 0.101318f, 0.152344f, 0.096436f, 0.752441f, 0.494873f, 0.020752f, 0.297852f, 0.036133f, 0.907227f, 0.477295f,
+ 0.869385f, 0.74292f, 0.952148f, 0.7146f, 0.053711f, 0.687744f, 0.660645f, 0.633545f, 0.439453f, 0.888428f, 0.908936f, 0.443848f, 0.030273f, 0.885986f, 0.284912f, 0.238281f,
+ 0.933105f, 0.34375f, 0.963623f, 0.19458f, 0.996338f, 0.473877f, 0.545166f, 0.931885f, 0.399658f, 0.871826f, 0.398438f, 0.4104f, 0.344482f, 0.921387f, 0.85083f, 0.94458f,
+ 0.250977f, 0.150879f, 0.834229f, 0.267578f, 0.734375f, 0.939697f, 0.913574f, 0.63623f, 0.283691f, 0.94873f, 0.306885f, 0.557861f, 0.764648f, 0.253418f, 0.582764f, 0.505615f,
+ 0.340088f, 0.26123f, 0.727783f, 0.016357f, 0.658447f, 0.559326f, 0.102051f, 0.714111f, 0.535645f, 0.650635f, 0.622314f, 0.383545f, 0.916748f, 0.955566f, 0.116943f, 0.018311f,
+ 0.750244f, 0.208252f, 0.773438f, 0.281006f, 0.095215f, 0.928467f, 0.426514f, 0.177246f, 0.219727f, 0.36792f, 0.495605f, 0.443115f, 0.380127f, 0.175537f, 0.452148f, 0.641113f,
+ 0.786133f, 0.602295f, 0.784668f, 0.034912f, 0.061523f, 0.962891f, 0.715332f, 0.580078f, 0.363525f, 0.533936f, 0.009277f, 0.740479f, 0.285156f, 0.402832f, 0.821045f, 0.441406f,
+ 0.568848f, 0.33667f, 0.185791f, 0.211182f, 0.218994f, 0.492676f, 0.205811f, 0.655029f, 0.784912f, 0.67627f, 0.709717f, 0.335449f, 0.081787f, 0.529053f, 0.794434f, 0.30127f,
+ 0.449951f, 0.929932f, 0.232178f, 0.717773f, 0.548096f, 0.644775f, 0.59082f, 0.77417f, 0.458252f, 0.560059f, 0.117432f, 0.007324f, 0.630859f, 0.096191f, 0.182617f, 0.905273f,
+ 0.848389f, 0.587158f, 0.699707f, 0.390137f, 0.618896f, 0.597656f, 0.812744f, 0.998291f, 0.590576f, 0.991699f, 0.838379f, 0.331543f, 0.166504f, 0.993164f, 0.525391f, 0.811768f,
+ 0.629639f, 0.312744f, 0.2854f, 0.608643f, 0.512939f, 0.621094f, 0.953369f, 0.965576f, 0.223633f, 0.29541f, 0.133301f, 0.267334f, 0.678223f, 0.439941f, 0.01001f, 0.693604f,
+ 0.619629f, 0.306641f, 0.47583f, 0.952637f, 0.074951f, 0.218262f, 0.873047f, 0.469238f, 0.236328f, 0.791992f, 0.310303f, 0.355957f, 0.450928f, 0.27417f, 0.509033f, 0.421143f,
+ 0.683105f, 0.8396f, 0.466309f, 0.986084f, 0.516602f, 0.691895f, 0.105713f, 0.724854f, 0.695068f, 0.026123f, 0.579834f, 0.617432f, 0.107666f, 0.208984f, 0.496338f, 0.673584f,
+ 0.448242f, 0.940674f, 0.999756f, 0.384521f, 0.053955f, 0.807373f, 0.165283f, 0.906006f, 0.838623f, 0.844482f, 0.335693f, 0.483643f, 0.133789f, 0.437012f, 0.778809f, 0.544434f,
+ 0.755859f, 0.508301f, 0.712402f, 0.705322f, 0.634033f, 0.129883f, 0.013672f, 0.377686f, 0.661133f, 0.456787f, 0.888672f, 0.947998f, 0.043701f, 0.356445f, 0.366699f, 0.470215f,
+ 0.17627f, 0.63916f, 0.239502f, 0.557373f, 0.342773f, 0.968506f, 0.185059f, 0.518311f, 0.378174f, 0.279053f, 0.663818f, 0.67334f, 0.001221f, 0.437744f, 0.188232f, 0.317383f,
+ 0.203369f, 0.252441f, 0.226318f, 0.188477f, 0.1604f, 0.703613f, 0.265381f, 0.940186f, 0.833252f, 0.636963f, 0.429932f, 0.638916f, 0.208008f, 0.968262f, 0.343262f, 0.130127f,
+ 0.650879f, 0.563965f, 0.689697f, 0.044434f, 0.387207f, 0.447021f, 0.773682f, 0.151611f, 0.463867f, 0.210693f, 0.889893f, 0.674316f, 0.261475f, 0.927734f, 0.90332f, 0.124268f,
+ 0.713867f, 0.234619f, 0.992432f, 0.119629f, 0.606689f, 0.183838f, 0.555176f, 0.266113f, 0.618652f, 0.4021f, 0.20459f, 0.083008f, 0.995117f, 0.226563f, 0.417725f, 0.633789f,
+ 0.581299f, 0.906494f, 0.948975f, 0.561523f, 0.679443f, 0.768555f, 0.095947f, 0.667725f, 0.376709f, 0.075928f, 0.827637f, 0.118164f, 0.502197f, 0.057129f, 0.871094f, 0.602051f,
+ 0.891113f, 0.206299f, 0.890381f, 0.581787f, 0.35376f, 0.371338f, 0.653809f, 0.834473f, 0.917236f, 0.856201f, 0.939941f, 0.273926f, 0.834961f, 0.322021f, 0.38208f, 0.990967f,
+ 0.28125f, 0.564453f, 0.633057f, 0.001709f, 0.61499f, 0.502686f, 0.838867f, 0.219238f, 0.266846f, 0.355225f, 0.0625f, 0.075195f, 0.703369f, 0.071045f, 0.907715f, 0.260254f,
+ 0.160645f, 0.216553f, 0.863281f, 0.277832f, 0.623535f, 0.883301f, 0.099609f, 0.197998f, 0.000977f, 0.590332f, 0.488037f, 0.259033f, 0.918213f, 0.427979f, 0.599854f, 0.263428f,
+ 0.913818f, 0.365723f, 0.327881f, 0.912842f, 0.837891f, 0.815186f, 0.255127f, 0.764893f, 0.760254f, 0.093506f, 0.73999f, 0.830322f, 0.067383f, 0.138428f, 0.535156f, 0.680664f,
+ 0.103516f, 0.817871f, 0.200928f, 0.929688f, 0.248535f, 0.180664f, 0.781982f, 0.966309f, 0.86084f, 0.469727f, 0.57666f, 0.436035f, 0.167236f, 0.975586f, 0.450439f, 0.027832f,
+ 0.897217f, 0.679688f, 0.666748f, 0.060303f, 0.131592f, 0.400879f, 0.125244f, 0.14209f, 0.706055f, 0.402588f, 0.963379f, 0.711182f, 0.831299f, 0.697998f, 0.898193f, 0.532959f,
+ 0.530273f, 0.356689f, 0.244873f, 0.837402f, 0.300049f, 0.440918f, 0.157227f, 0.911377f, 0.625f, 0.151367f, 0.917969f, 0.962646f, 0.179932f, 0.471191f, 0.286377f, 0.475586f,
+ 0.034668f, 0.748779f, 0.208496f, 0.124512f, 0.47168f, 0.742432f, 0.7771f, 0.812012f, 0.991943f, 0.344727f, 0.822021f, 0.729736f, 0.55957f, 0.276367f, 0.906982f, 0.449707f,
+ 0.06665f, 0.383301f, 0.769775f, 0.416504f, 0.654297f, 0.988525f, 0.358398f, 0.538086f, 0.401855f, 0.385986f, 0.225586f, 0.698975f, 0.90918f, 0.662598f, 0.061035f, 0.098145f,
+ 0.13623f, 0.244385f, 0.542969f, 0.827881f, 0.978271f, 0.723145f, 0.922607f, 0.008789f, 0.571533f, 0.491699f, 0.498535f, 0.687256f, 0.884033f, 0.311768f, 0.042236f, 0.958252f,
+ 0.60498f, 0.237061f, 0.122314f, 0.37793f, 0.575195f, 0.727295f, 0.950684f, 0.608398f, 0.231445f, 0.091064f, 0.630127f, 0.347168f, 0.973389f, 0.123779f, 0.817627f, 0.27832f,
+ 0.150391f, 0.765869f, 0.368408f, 0.793701f, 0.615723f, 0.012451f, 0.956299f, 0.749512f, 0.509521f, 0.529297f, 0.64917f, 0.291016f, 0.956543f, 0.33252f, 0.513672f, 0.916504f,
+ 0.012207f, 0.374512f, 0.932129f, 0.418945f, 0.607178f, 0.347656f, 0.825439f, 0.392578f, 0.667236f, 0.777344f, 0.123535f, 0.357422f, 0.967041f, 0.439209f, 0.248047f, 0.446289f,
+ 0.218506f, 0.445801f, 0.135742f, 0.905518f, 0.915283f, 0.515869f, 0.063477f, 0.740234f, 0.9104f, 0.462158f, 0.614746f, 0.996582f, 0.250488f, 0.368896f, 0.55542f, 0.51416f,
+ 0.102539f, 0.876953f, 0.464355f, 0.315186f, 0.333984f, 0.114258f, 0.110352f, 0.527832f, 0.296143f, 0.786377f, 0.605469f, 0.331787f, 0.377197f, 0.085449f, 0.549316f, 0.796875f,
+ 0.11084f, 0.204346f, 0.419678f, 0.105225f, 0.521973f, 0.772705f, 0.670654f, 0.84375f, 0.830078f, 0.635254f, 0.280518f, 0.886963f, 0.293701f, 0.473389f, 0.507813f, 0.775146f,
+ 0.813232f, 0.986572f, 0.042725f, 0.011475f, 0.134766f, 0.199463f, 0.906738f, 0.256836f, 0.044189f, 0.419922f, 0.815674f, 0.822998f, 0.977783f, 0.760498f, 0.541016f, 0.895508f,
+ 0.681641f, 0.528564f, 0.632813f, 0.813477f, 0.513428f, 0.373535f, 0.305664f, 0.299805f, 0.659912f, 0.460205f, 0.047363f, 0.333252f, 0.372314f, 0.073486f, 0.505127f, 0.771484f,
+ 0.336426f, 0.997803f, 0.158447f, 0.960938f, 0.3479f, 0.449463f, 0.502441f, 0.594238f, 0.13208f, 0.749756f, 0.941895f, 0.005859f, 0.304443f, 0.149902f, 0.564209f, 0.968018f,
+ 0.371826f, 0.199219f, 0.260498f, 0.609619f, 0.089355f, 0.019287f, 0.359131f, 0.41333f, 0.817383f, 0.32251f, 0.806152f, 0.176025f, 0.041748f, 0.555908f, 0.950928f, 0.20752f,
+ 0.898926f, 0.308594f, 0.367432f, 0.799805f, 0.792969f, 0.842041f, 0.742188f, 0.927979f, 0.952881f, 0.370361f, 0.53418f, 0.683594f, 0.380859f, 0.116699f, 0.827148f, 0.665771f,
+ 0.29248f, 0.270508f, 0.676514f, 0.230957f, 0.474609f, 0.600098f, 0.428955f, 0.901855f, 0.199707f, 0.315674f, 0.349854f, 0.93042f, 0.811035f, 0.077881f, 0.064941f, 0.527344f,
+ 0.427002f, 0.459961f, 0.308105f, 0.120605f, 0.46875f, 0.22583f, 0.944824f, 0.010498f, 0.718994f, 0.99707f, 0.726563f, 0.715576f, 0.493652f, 0.894287f, 0.338867f, 0.251221f,
+ 0.789795f, 0.197021f, 0.11499f, 0.603271f, 0.213135f, 0.357178f, 0.902832f, 0.658691f, 0.459229f, 0.224121f, 0.687988f, 0.595947f, 0.862061f, 0.085693f, 0.092041f, 0.360107f,
+ 0.347412f, 0.656738f, 0.379395f, 0.218018f, 0.753906f, 0.170166f, 0.390381f, 0.455566f, 0.858154f, 0.831787f, 0.779297f, 0.76001f, 0.027344f, 0.553467f, 0.328857f, 0.695801f,
+ 0.572266f, 0.443359f, 0.500977f, 0.189209f, 0.424316f, 0.178467f, 0.094238f, 0.013428f, 0.79248f, 0.181641f, 0.998047f, 0.501953f, 0.383057f, 0.079102f, 0.721924f, 0.12207f,
+ 0.870361f, 0.532227f, 0.424561f, 0.674805f, 0.192139f, 0.482422f, 0.306152f, 0.756836f, 0.493408f, 0.843506f, 0.765625f, 0.710449f, 0.321777f, 0.676025f, 0.164307f, 0.567627f,
+ 0.081543f, 0.490479f, 0.571045f, 0.943115f, 0.161621f, 0.330322f, 0.537842f, 0.114746f, 0.450195f, 0.006836f, 0.392334f, 0.053467f, 0.598633f, 0.977539f, 0.111572f, 0.098633f,
+ 0.511963f, 0.06958f, 0.387695f, 0.546143f, 0.941162f, 0.727051f, 0.490234f, 0.861084f, 0.928955f, 0.520508f, 0.115723f, 0.649658f, 0.642578f, 0.295166f, 0.965088f, 0.918457f,
+ 0.918945f, 0.163086f, 0.312012f, 0.462891f, 0.44751f, 0.420166f, 0.665527f, 0.211914f, 0.520996f, 0.846191f, 0.473633f, 0.77832f, 0.736572f, 0.091797f, 0.988281f, 0.436523f,
+ 0.040527f, 0.717529f, 0.318604f, 0.432617f, 0.01123f, 0.614258f, 0.810791f, 0.648682f, 0.56958f, 0.324707f, 0.75f, 0.947754f, 0.155273f, 0.788086f, 0.010742f, 0.249268f,
+ 0.144287f, 0.349609f, 0.520752f, 0.72998f, 0.806396f, 0.059326f, 0.303223f, 0.067139f, 0.421387f, 0.843994f, 0.637207f, 0.858643f, 0.814209f, 0.554932f, 0.251709f, 0.730469f,
+ 0.109619f, 0.630615f, 0.379883f, 0.456055f, 0.274902f, 0.349121f, 0.580811f, 0.723633f, 0.018066f, 0.54126f, 0.387939f, 0.039795f, 0.040771f, 0.960205f, 0.458984f, 0.343994f,
+ 0.141846f, 0.231934f, 0.01709f, 0.791748f, 0.931152f, 0.797852f, 0.731934f, 0.69458f, 0.691162f, 0.276855f, 0.785889f, 0.74585f, 0.942139f, 0.487793f, 0.228271f, 0.807861f,
+ 0.023926f, 0.88916f, 0.140625f, 0.232666f, 0.110107f, 0.315918f, 0.37207f, 0.582031f, 0.121582f, 0.180176f, 0.386475f, 0.058838f, 0.038086f, 0.731445f, 0.202637f, 0.574951f,
+ 0.446533f, 0.050293f, 0.542236f, 0.227051f, 0.194336f, 0.850098f, 0.857422f, 0.937744f, 0.886475f, 0.232422f, 0.542725f, 0.316162f, 0.880859f, 0.797607f, 0.575439f, 0.953613f,
+ 0.066895f, 0.657715f, 0.753174f, 0.283203f, 0.705811f, 0.541504f, 0.220703f, 0.701172f, 0.454102f, 0.032471f, 0.452393f, 0.409668f, 0.926514f, 0.903564f, 0.263672f, 0.7854f,
+ 0.422363f, 0.841064f, 0.410889f, 0.613281f, 0.004883f, 0.426758f, 0.106445f, 0.73877f, 0.291748f, 0.508545f, 0.578125f, 0.565674f, 0.480225f, 0.581055f, 0.415527f, 0.849854f,
+ 0.104004f, 0.184814f, 0.418213f, 0.628662f, 0.324219f, 0.348145f, 0.831543f, 0.63501f, 0.986816f, 0.583008f, 0.124756f, 0.710205f, 0.382813f, 0.545898f, 0.727539f, 0.890869f,
+ 0.869141f, 0.260986f, 0.170898f, 0.654785f, 0.801025f, 0.429443f, 0.442871f, 0.245117f, 0.756104f, 0.772949f, 0.577393f, 0.000488f, 0.631592f, 0.65918f, 0.048584f, 0.956787f,
+ 0.850342f, 0.15332f, 0.627197f, 0.026611f, 0.025146f, 0.522949f, 0.928711f, 0.507324f, 0.028809f, 0.518066f, 0.512207f, 0.031738f, 0.945068f, 0.369873f, 0.692139f, 0.10083f,
+ 0.752686f, 0.190674f, 0.51001f, 0.294922f, 0.741943f, 0.478271f, 0.757568f, 0.953857f, 0.23291f, 0f, 0.746094f, 0.831055f, 0.915039f, 0.738525f, 0.275391f, 0.069824f,
+ 0.35498f, 0.799561f, 0.611816f, 0.363037f, 0.101807f, 0.42334f, 0.934082f, 0.284668f, 0.859863f, 0.351807f, 0.652588f, 0.596191f, 0.519775f, 0.286865f, 0.451172f, 0.962158f,
+ 0.612549f, 0.587891f, 0.887939f, 0.431641f, 0.169922f, 0.302246f, 0.117676f, 0.725342f, 0.049805f, 0.869873f, 0.127686f, 0.677246f, 0.429688f, 0.458008f, 0.172852f, 0.804688f,
+ 0.308838f, 0.248779f, 0.491943f, 0.061279f, 0.037842f, 0.864746f, 0.326172f, 0.520264f, 0.925781f, 0.268311f, 0.412598f, 0.414551f, 0.352295f, 0.701904f, 0.866455f, 0.574219f,
+ 0.074463f, 0.718018f, 0.375732f, 0.704102f, 0.592285f, 0.397949f, 0.23999f, 0.341309f, 0.768066f, 0.019531f, 0.174805f, 0.945313f, 0.290283f, 0.865967f, 0.877441f, 0.029541f,
+ 0.478516f, 0.38916f, 0.827393f, 0.98291f, 0.868164f, 0.608154f, 0.18042f, 0.10376f, 0.257813f, 0.103027f, 0.902588f, 0.67041f, 0.100098f, 0.538818f, 0.045654f, 0.899658f,
+ 0.405518f, 0.220215f, 0.381836f, 0.187256f, 0.321045f, 0.987061f, 0.411133f, 0.761475f, 0.150146f, 0.809082f, 0.44043f, 0.45459f, 0.155762f, 0.800049f, 0.666016f, 0.084229f,
+ 0.810547f, 0.25708f, 0.278809f, 0.410645f, 0.949219f, 0.969971f, 0.948242f, 0.943604f, 0.298584f, 0.092773f, 0.370117f, 0.506836f, 0.499023f, 0.237793f, 0.739258f, 0.168701f,
+ 0.510742f, 0.900635f, 0.460938f, 0.908447f, 0.539063f, 0.531006f, 0.380615f, 0.230469f, 0.159912f, 0.014648f, 0.82373f, 0.931396f, 0.824951f, 0.166748f, 0.324463f, 0.517822f,
+ 0.536621f, 0.490723f, 0.279785f, 0.985352f, 0.165527f, 0.586914f, 0.226807f, 0.326416f, 0.604248f, 0.119873f, 0.148926f, 0.026855f, 0.689453f, 0.282471f, 0.631836f, 0.235596f,
+ 0.828613f, 0.225342f, 0.394531f, 0.877197f, 0.901123f, 0.169678f, 0.39917f, 0.646729f, 0.737793f, 0.021729f, 0.135498f, 0.011719f, 0.911133f, 0.554688f, 0.810303f, 0.954102f,
+ 0.339355f, 0.605225f, 0.361084f, 0.872803f, 0.360596f, 0.5f, 0.15918f, 0.162109f, 0.108398f, 0.47876f, 0.227783f, 0.343018f, 0.486816f, 0.916016f, 0.861816f, 0.938965f,
+ 0.174561f, 0.53833f, 0.078125f, 0.763428f, 0.75708f, 0.071533f, 0.45752f, 0.665039f, 0.194092f, 0.567383f, 0.270752f, 0.859619f, 0.79126f, 0.61792f, 0.888916f, 0.165771f,
+ 0.202881f, 0.515625f, 0.486572f, 0.746826f, 0.470459f, 0.412842f, 0.714355f, 0.017578f, 0.396484f, 0.312256f, 0.311035f, 0.458496f, 0.41748f, 0.922363f, 0.64624f, 0.889648f,
+ 0.607666f, 0.946777f, 0.321289f, 0.445313f, 0.479004f, 0.825684f, 0.272217f, 0.301758f, 0.274414f, 0.212402f, 0.503662f, 0.484863f, 0.36499f, 0.112061f, 0.302734f, 0.097656f,
+ 0.499512f, 0.557617f, 0.742676f, 0.154541f, 0.280273f, 0.595215f, 0.689209f, 0.234375f, 0.24707f, 0.839844f, 0.215576f, 0.362061f, 0.853027f, 0.891846f, 0.262695f, 0.424805f,
+ 0.193604f, 0.856689f, 0.487549f, 0.190186f, 0.881592f, 0.155029f, 0.076172f, 0.201904f, 0.712158f, 0.296875f, 0.314697f, 0.223389f, 0.951904f, 0.416992f, 0.060791f, 0.310547f,
+ 0.981201f, 0.702881f, 0.540283f, 0.385254f, 0.297607f, 0.547852f, 0.168457f, 0.184082f, 0.87085f, 0.178223f, 0.685059f, 0.268555f, 0.088379f, 0.922852f, 0.418457f, 0.340576f,
+ 0.179688f, 0.808594f, 0.041504f, 0.380371f, 0.874268f, 0.131104f, 0.855713f, 0.934326f, 0.747803f, 0.820801f, 0.101074f, 0.920898f, 0.774414f, 0.963135f, 0.73291f, 0.746338f,
+ 0.728027f, 0.540039f, 0.207031f, 0.972412f, 0.983154f, 0.589844f, 0.5896f, 0.664063f, 0.919678f, 0.594482f, 0.174072f, 0.860596f, 0.551025f, 0.479736f, 0.889404f, 0.994629f,
+ 0.562256f, 0.188965f, 0.189697f, 0.007568f, 0.43042f, 0.780273f, 0.038818f, 0.148193f, 0.743164f, 0.579102f, 0.404785f, 0.354248f, 0.150635f, 0.362549f, 0.982178f, 0.345215f,
+ 0.619873f, 0.078857f, 0.212158f, 0.720703f, 0.233398f, 0.257568f, 0.697021f, 0.678955f, 0.748047f, 0.915527f, 0.497559f, 0.505371f, 0.160889f, 0.240479f, 0.718262f, 0.992676f,
+ 0.021973f, 0.05249f, 0.83374f, 0.851563f, 0.138184f, 0.42749f, 0.104492f, 0.644043f, 0.584229f, 0.001953f, 0.991211f, 0.489502f, 0.932373f, 0.511719f, 0.862305f, 0.30957f,
+ 0.068604f, 0.843018f, 0.959229f, 0.046875f, 0.823486f, 0.754395f, 0.560547f, 0.672363f, 0.028564f, 0.07373f, 0.346924f, 0.860352f, 0.731689f, 0.596924f, 0.539551f, 0.982422f,
+ 0.945801f, 0.679199f, 0.481934f, 0.348389f, 0.477539f, 0.991455f, 0.794922f, 0.663574f, 0.490967f, 0.812256f, 0.476563f, 0.047119f, 0.892578f, 0.888184f, 0.793213f, 0.033691f,
+ 0.3125f, 0.523193f, 0.883057f, 0.334473f, 0.492188f, 0.006348f, 0.990723f, 0.084961f, 0.757813f, 0.49707f, 0.172119f, 0.202148f, 0.709961f, 0.624023f, 0.275635f, 0.432129f,
+ 0.75293f, 0.974854f, 0.438232f, 0.164063f, 0.388916f, 0.960693f, 0.878662f, 0.802734f, 0.192383f, 0.824707f, 0.977295f, 0.309082f, 0.513916f, 0.5979f, 0.305908f, 0.390869f,
+ 0.447266f, 0.35791f, 0.75415f, 0.120117f, 0.203125f, 0.113525f, 0.0896f, 0.688477f, 0.335938f, 0.537109f, 0.572754f, 0.091309f, 0.098877f, 0.235107f, 0.956055f, 0.833008f,
+ 0.196777f, 0.010254f, 0.955078f, 0.080322f, 0.390625f, 0.668457f, 0.701416f, 0.643555f, 0.601807f, 0.772217f, 0.035645f, 0.292236f, 0.196289f, 0.375977f, 0.967529f, 0.398682f,
+ 0.732666f, 0.225098f, 0.393066f, 0.682129f, 0.938721f, 0.722168f, 0.907959f, 0.719727f, 0.681396f, 0.980957f, 0.594727f, 0.454834f, 0.53125f, 0.222412f, 0.717285f, 0.845459f,
+ 0.892822f, 0.642334f, 0.479248f, 0.936523f, 0.083252f, 0.879395f, 0.856934f, 0.422852f, 0.442627f, 0.15625f, 0.849609f, 0.076416f, 0.550049f, 0.86499f, 0.926025f, 0.568115f,
+ 0.989258f, 0.70874f, 0.578613f, 0.896484f, 0.805908f, 0.941406f, 0.778076f, 0.745117f, 0.688232f, 0.416016f, 0.24585f, 0.652832f, 0.169189f, 0.571777f, 0.459473f, 0.02417f,
+ 0.879883f, 0.861328f, 0.319336f, 0.146484f, 0.700928f, 0.240234f, 0.154297f, 0.197266f, 0.472656f, 0.651367f, 0.716309f, 0.854736f, 0.544189f, 0.052246f, 0.981934f, 0.372559f,
+ 0.266357f, 0.272705f, 0.035889f, 0.290771f, 0.741699f, 0.359375f, 0.566162f, 0.293457f, 0.431396f, 0.167725f, 0.970947f, 0.266602f, 0.875977f, 0.425049f, 0.743652f, 0.935059f,
+ 0.173096f, 0.634521f, 0.677002f, 0.92749f, 0.988037f, 0.112793f, 0.494629f, 0.70752f, 0.08667f, 0.089111f, 0.943359f, 0.613037f, 0.776123f, 0.832275f, 0.04541f, 0.824219f,
+ 0.062744f, 0.415771f, 0.206787f, 0.569824f, 0.50708f, 0.473145f, 0.401123f, 0.438477f, 0.345459f, 0.217773f, 0.033936f, 0.865479f, 0.376465f, 0.676758f, 0.330078f, 0.973145f,
+ 0.516357f, 0.39502f, 0.464844f, 0.240723f, 0.967285f, 0.231689f, 0.022217f, 0.766357f, 0.776855f, 0.216309f, 0.30542f, 0.158203f, 0.019043f, 0.841309f, 0.054688f, 0.131348f,
+ 0.270264f, 0.51123f, 0.073975f, 0.671631f, 0.718506f, 0.70166f, 0.009521f, 0.980713f, 0.355713f, 0.822266f, 0.023682f, 0.781006f, 0.973877f, 0.509277f, 0.288574f, 0.03418f,
+ 0.500732f, 0.176514f, 0.96875f, 0.678467f, 0.334961f, 0.779541f, 0.985596f, 0.726807f, 0.006104f, 0.647705f, 0.928223f, 0.979492f, 0.477783f, 0.130371f, 0.209473f, 0.695313f,
+ 0.311523f, 0.382324f, 0.504395f, 0.521729f, 0.147461f, 0.909668f, 0.585938f, 0.674561f, 0.74707f, 0.041016f, 0.207275f, 0.323486f, 0.558838f, 0.891357f, 0.526123f, 0.722656f,
+ 0.98584f, 0.48877f, 0.961914f, 0.481689f, 0.801514f, 0.180908f, 0.78833f, 0.758057f, 0.891602f, 0.563477f, 0.466553f, 0.552002f, 0.760742f, 0.577148f, 0.705078f, 0.314941f,
+ 0.852783f, 0.323975f, 0.738281f, 0.297363f, 0.136963f, 0.512695f, 0.356934f, 0.210205f, 0.378662f, 0.848877f, 0.411621f, 0.97876f, 0.723877f, 0.14917f, 0.635498f, 0.734619f,
+ 0.779053f, 0.533447f, 0.610596f, 0.396729f, 0.24292f, 0.44873f, 0.251953f, 0.838135f, 0.695557f, 0.499756f, 0.935791f, 0.788574f, 0.247314f, 0.530518f, 0.524902f, 0.137695f,
+ 0.231201f, 0.216797f, 0.130615f, 0.436768f, 0.980225f, 0.556641f, 0.807129f, 0.927246f, 0.927002f, 0.446777f, 0.599609f, 0.86792f, 0.969238f, 0.217285f, 0.792725f, 0.219971f,
+ 0.444824f, 0.878906f, 0.996094f, 0.540527f, 0.341064f, 0.04834f, 0.688721f, 0.744629f, 0.604736f, 0.584473f, 0.700439f, 0.44458f, 0.037109f, 0.136719f, 0.131836f, 0.237305f,
+ 0.756348f, 0.422607f, 0.901611f, 0.735107f, 0.568359f, 0.756592f, 0.410156f, 0.649414f, 0.875244f, 0.090576f, 0.876465f, 0.191162f, 0.626953f, 0.373779f, 0.864258f, 0.051514f,
+ 0.999512f, 0.763672f, 0.994141f, 0.374756f, 0.911865f, 0.179199f, 0.415283f, 0.046143f, 0.381104f, 0.518555f, 0.675293f, 0.926758f, 0.26001f, 0.95166f, 0.608887f, 0.488525f,
+ 0.580566f, 0.932861f, 0.87915f, 0.318115f, 0.613525f, 0.043945f, 0.040283f, 0.719238f, 0.353516f, 0.647461f, 0.570557f, 0.994385f, 0.602783f, 0.825928f, 0.394043f, 0.003662f,
+ 0.951172f, 0.818848f, 0.786865f, 0.528809f, 0.750488f, 0.255859f, 0.154053f, 0.876709f, 0.154785f, 0.485107f, 0.007813f, 0.453613f, 0.034424f, 0.932617f, 0.897949f, 0.558105f,
+ 0.030762f, 0.17334f, 0.753418f, 0.403809f, 0.434326f, 0.137207f, 0.282227f, 0.080078f, 0.849121f, 0.71167f, 0.065186f, 0.090332f, 0.925293f, 0.883545f, 0.456299f, 0.573242f,
+ 0.583252f, 0.325439f, 0.074219f, 0.047852f, 0.392822f, 0.984863f, 0.330811f, 0.560791f, 0.44165f, 0.23584f, 0.559814f, 0.395752f, 0.234131f, 0.733643f, 0.52002f, 0.833984f,
+ 0.76416f, 0.129639f, 0.446045f, 0.639404f, 0.068848f, 0.024414f, 0.478027f, 0.112549f, 0.276611f, 0.27002f, 0.844971f, 0.527588f, 0.566895f, 0.804199f, 0.896973f, 0.183594f,
+ 0.631104f, 0.924072f, 0.246826f, 0.094727f, 0.304932f, 0.781738f, 0.118408f, 0.842529f, 0.269775f, 0.014404f, 0.626465f, 0.767822f, 0.729492f, 0.190918f, 0.544922f, 0.564697f,
+ 0.99292f, 0.317627f, 0.024658f, 0.925537f, 0.414063f, 0.58374f, 0.569092f, 0.143066f, 0.655762f, 0.759766f, 0.799316f, 0.056885f, 0.273438f, 0.882813f, 0.281494f, 0.795166f,
+ 0.020264f, 0.066162f, 0.523438f, 0.238037f, 0.880127f, 0.157959f, 0.236816f, 0.992188f, 0.924561f, 0.578857f, 0.498291f, 0.130859f, 0.344238f, 0.9646f, 0.798584f, 0.672119f,
+ 0.62207f, 0.794189f, 0.661621f, 0.474121f, 0.399414f, 0.842285f, 0.16626f, 0.220459f, 0.640869f, 0.351318f, 0.764404f, 0.202393f, 0.726318f, 0.498779f, 0.959473f, 0.395996f,
+ 0.929199f, 0.415039f, 0.246094f, 0.301025f, 0.516846f, 0.164795f, 0.141357f, 0.789307f, 0.286621f, 0.343506f, 0.625977f, 0.147949f, 0.654541f, 0.279297f, 0.770508f, 0.9375f,
+ 0.282715f, 0.205322f, 0.833496f, 0.665283f, 0.751953f, 0.964355f, 0.462402f, 0.18457f, 0.195313f, 0.557129f, 0.791016f, 0.882568f, 0.61084f, 0.004395f, 0.787598f, 0.556396f,
+ 0.209717f, 0.408203f, 0.816895f, 0.373047f, 0.369629f, 0.344971f, 0.870605f, 0.12085f, 0.987305f, 0.118652f, 0.658203f, 0.873779f, 0.292969f, 0.692627f, 0.568604f, 0.922119f,
+ 0.469971f, 0.575928f, 0.985107f, 0.28833f, 0.192627f, 0.437256f, 0.414795f, 0.628906f, 0.647217f, 0.540771f, 0.111816f, 0.342041f, 0.420898f, 0.767334f, 0.224365f, 0.739502f,
+ 0.843262f, 0.894531f, 0.91626f, 0.820068f, 0.564941f, 0.256348f, 0.23877f, 0.386963f, 0.960449f, 0.28418f, 0.38501f, 0.6875f, 0.683838f, 0.275879f, 0.945557f, 0.936768f,
+ 0.032227f, 0.60791f, 0.062988f, 0.322998f, 0.241455f, 0.818115f, 0.567139f, 0.973633f, 0.829102f, 0.938477f, 0.046631f, 0.962402f, 0.576172f, 0.309326f, 0.97998f, 0.176758f,
+ 0.421631f, 0.329102f, 0.31543f, 0.333008f, 0.160156f, 0.455078f, 0.562744f, 0.417969f, 0.898438f, 0.771973f, 0.72583f, 0.159424f, 0.254395f, 0.441162f, 0.371582f, 0.102295f,
+ 0.151123f, 0.468262f, 0.637451f, 0.087158f, 0.405273f, 0.063721f, 0.155518f, 0.40332f, 0.989746f, 0.957031f, 0.137939f, 0.543213f, 0.428223f, 0.054443f, 0.872559f, 0.823975f,
+ 0.81543f, 0.609131f, 0.912109f, 0.806885f, 0.067871f, 0.556152f, 0.92334f, 0.769531f, 0.618164f, 0.05542f, 0.803223f, 0.156982f, 0.262939f, 0.693848f, 0.894775f, 0.270996f,
+ 0.463135f, 0.998779f, 0.845215f, 0.149414f, 0.081055f, 0.253174f, 0.037598f, 0.842773f, 0.526855f, 0.306396f, 0.068359f, 0.078613f, 0.211426f, 0.508057f, 0.295898f, 0.496826f,
+ 0.374268f, 0.234863f, 0.83252f, 0.489258f, 0.140137f, 0.193848f, 0.029053f, 0.798828f, 0.914063f, 0.086426f, 0.866211f, 0.85791f, 0.914795f, 0.554443f, 0.285645f, 0.135986f,
+ ];
+}
diff --git a/Source.Particles/Source.Particles.csproj b/Source.Particles/Source.Particles.csproj
index 6b418435..fa070bcd 100644
--- a/Source.Particles/Source.Particles.csproj
+++ b/Source.Particles/Source.Particles.csproj
@@ -5,9 +5,6 @@
-
-
-
From 3f09ede26299ed4001016ae493d1ea9e55cd4a94 Mon Sep 17 00:00:00 2001
From: Earu <20880060+Earu@users.noreply.github.com>
Date: Thu, 12 Nov 2026 20:34:22 +0400
Subject: [PATCH 5/8] particle rendering: spritecard shader,
render_animated_sprites, emitters and render cache
- Spritecard shader (C# + GLSL) ported from the SDK, without depth blending
- C_OP_RenderSprites: spritecard and non-spritecard paths, sorted render list
- render cache batching and DrawRenderCache in opaque renderables
- NewParticleEffect.DrawModel per the GMod decomp
- sheet loading from VTF resource data
- emit_instantaneously and emit_continuously
- Position Within Sphere Random, Lifetime Random, Lifespan Decay, Movement Basic
- material system: IsSpriteCard, user clip transform override, camera position/vectors recompute
---
Game.Assets/sdn/shaders/spritecard_gl460.fs | 175 ++++++
Game.Assets/sdn/shaders/spritecard_gl460.vs | 212 +++++++
Game.Client/C_BasePlayer.cs | 6 +
Game.Client/ClientModeShared.cs | 1 +
Game.Client/IClientMode.cs | 1 +
Game.Client/NewParticleEffect.cs | 76 ++-
Game.Client/ParticleMgr.cs | 2 +
Game.Client/ViewRender.cs | 4 +
Source.Particles/BuiltinParticleEmitters.cs | 333 +++++++++++
.../BuiltinParticleInitializers.cs | 153 +++++
Source.Particles/BuiltinParticleOperators.cs | 136 +++++
Source.Particles/BuiltinParticleRenderers.cs | 562 ++++++++++++++++++
Source.Particles/ParticleCollection.cs | 142 +++++
Source.Particles/ParticleOperator.cs | 16 +
Source.Particles/ParticleSystemMgr.cs | 219 +++++++
Source.Particles/Sheet.cs | 231 +++++++
Source.StdShader.Gl46/Spritecard.cs | 243 ++++++++
17 files changed, 2511 insertions(+), 1 deletion(-)
create mode 100644 Game.Assets/sdn/shaders/spritecard_gl460.fs
create mode 100644 Game.Assets/sdn/shaders/spritecard_gl460.vs
create mode 100644 Source.Particles/BuiltinParticleEmitters.cs
create mode 100644 Source.Particles/BuiltinParticleInitializers.cs
create mode 100644 Source.Particles/BuiltinParticleOperators.cs
create mode 100644 Source.Particles/BuiltinParticleRenderers.cs
create mode 100644 Source.Particles/Sheet.cs
create mode 100644 Source.StdShader.Gl46/Spritecard.cs
diff --git a/Game.Assets/sdn/shaders/spritecard_gl460.fs b/Game.Assets/sdn/shaders/spritecard_gl460.fs
new file mode 100644
index 00000000..d9a3711b
--- /dev/null
+++ b/Game.Assets/sdn/shaders/spritecard_gl460.fs
@@ -0,0 +1,175 @@
+#version 460
+// STATIC: "DUALSEQUENCE" "0..1"
+// STATIC: "SEQUENCE_BLEND_MODE" "0..2"
+// STATIC: "ADDBASETEXTURE2" "0..1"
+// STATIC: "MAXLUMFRAMEBLEND1" "0..1"
+// STATIC: "MAXLUMFRAMEBLEND2" "0..1"
+// STATIC: "EXTRACTGREENALPHA" "0..1"
+// STATIC: "COLORRAMP" "0..1"
+// STATIC: "ANIMBLEND" "0..1"
+// STATIC: "ADDSELF" "0..1"
+
+#define COMBINE_MODE_AVERAGE 0
+#define COMBINE_MODE_USE_FIRST_AS_ALPHA_MASK_ON_SECOND 1
+#define COMBINE_MODE_USE_FIRST_OVER_SECOND 2
+
+layout(location = 0) in vec2 vs_TexCoord0;
+layout(location = 1) in vec2 vs_TexCoord1;
+layout(location = 2) in vec4 vs_Color;
+layout(location = 3) in vec4 vs_BlendFactor0;
+layout(location = 4) in vec2 vs_TexCoord2;
+layout(location = 5) in vec4 vs_BlendFactor1;
+layout(location = 6) in vec2 vs_Seq2TexCoord0;
+layout(location = 7) in vec2 vs_Seq2TexCoord1;
+
+layout(std140, binding = 3) uniform source_pixel_sharedUBO {
+ bool isAlphaTesting;
+ int alphaTestFunc;
+ float alphaTestRef;
+};
+
+layout(std140, binding = 6) uniform source_ps_constants {
+ vec4 ps_const[256];
+};
+
+out vec4 fragColor;
+
+#include "common_gl460.fs"
+
+layout(binding = 0) uniform sampler2D BaseTextureSampler;
+layout(binding = 1) uniform sampler2D ColorRampSampler;
+
+#define g_Parameters ps_const[0]
+#define fAdditiveBlendWeight g_Parameters.x
+#define fOverbrightFactor g_Parameters.y
+#define fAdditiveSelfBlendWeight g_Parameters.z
+
+void main()
+{
+ bool bMaxLumFrameBlend1 = MAXLUMFRAMEBLEND1 != 0;
+ bool bMaxLumFrameBlend2 = MAXLUMFRAMEBLEND2 != 0;
+ bool bExtractGreenAlpha = EXTRACTGREENALPHA != 0;
+ bool bAddBaseTexture2 = ADDBASETEXTURE2 != 0;
+ bool bDualSequence = DUALSEQUENCE != 0;
+ bool bColorRamp = COLORRAMP != 0;
+ int nSequenceBlendMode = SEQUENCE_BLEND_MODE;
+
+ vec4 argbcolor = vs_Color;
+
+ vec4 baseTex0 = texture(BaseTextureSampler, vs_TexCoord0);
+ vec4 baseTex1 = texture(BaseTextureSampler, vs_TexCoord1);
+
+#if ANIMBLEND
+ vec4 blended_rgb = mix(baseTex0, baseTex1, vs_BlendFactor0.x);
+#else
+ vec4 blended_rgb = baseTex0;
+#endif
+
+ if (bMaxLumFrameBlend1)
+ {
+ float lum0 = dot(vec3(0.3, 0.59, 0.11), baseTex0.rgb * (1.0 - vs_BlendFactor0.x));
+ float lum1 = dot(vec3(0.3, 0.59, 0.11), baseTex1.rgb * vs_BlendFactor0.x);
+
+ if (lum0 > lum1)
+ blended_rgb = baseTex0;
+ else
+ blended_rgb = baseTex1;
+ }
+ else if (bExtractGreenAlpha)
+ {
+ blended_rgb = vec4(dot(baseTex0, vs_BlendFactor0) + dot(baseTex1, vs_BlendFactor1));
+ }
+
+#if DUALSEQUENCE
+ if (bDualSequence)
+ {
+ baseTex0 = texture(BaseTextureSampler, vs_Seq2TexCoord0);
+ baseTex1 = texture(BaseTextureSampler, vs_Seq2TexCoord1);
+
+ vec4 rgb2 = mix(baseTex0, baseTex1, vs_BlendFactor0.z);
+
+ if (bMaxLumFrameBlend2)
+ {
+ float tlum0 = dot(vec3(0.3, 0.59, 0.11), baseTex0.rgb * (1.0 - vs_BlendFactor0.x));
+ float tlum1 = dot(vec3(0.3, 0.59, 0.11), baseTex1.rgb * vs_BlendFactor0.x);
+
+ if (tlum0 > tlum1)
+ rgb2 = baseTex0;
+ else
+ rgb2 = baseTex1;
+ }
+
+ if (nSequenceBlendMode == COMBINE_MODE_AVERAGE)
+ {
+ blended_rgb = 0.5 * (blended_rgb + rgb2);
+ }
+ else if (nSequenceBlendMode == COMBINE_MODE_USE_FIRST_AS_ALPHA_MASK_ON_SECOND)
+ {
+ blended_rgb.rgb = rgb2.rgb;
+ }
+ else if (nSequenceBlendMode == COMBINE_MODE_USE_FIRST_OVER_SECOND)
+ {
+ blended_rgb.rgb = mix(blended_rgb.rgb, rgb2.rgb, rgb2.a);
+ }
+ }
+#endif
+
+ if (bColorRamp)
+ {
+ blended_rgb.rgb = texture(ColorRampSampler, vec2(blended_rgb.r, blended_rgb.g)).rgb;
+ }
+
+ blended_rgb.rgb *= fOverbrightFactor;
+
+#if ADDBASETEXTURE2
+ if (bAddBaseTexture2)
+ {
+ blended_rgb.a *= argbcolor.a;
+
+ if (!bColorRamp)
+ {
+ blended_rgb.rgb *= blended_rgb.a;
+ }
+
+ if (bExtractGreenAlpha)
+ {
+ blended_rgb.rgb += fAdditiveBlendWeight * argbcolor.a * blended_rgb.rgb;
+ }
+ else
+ {
+ blended_rgb.rgb += fOverbrightFactor * fAdditiveBlendWeight * argbcolor.a * texture(BaseTextureSampler, vs_TexCoord2).rgb;
+ }
+
+ blended_rgb.rgb *= argbcolor.rgb;
+ }
+ else
+#endif
+ {
+#if ADDSELF
+ blended_rgb.a *= argbcolor.a;
+ blended_rgb.rgb *= blended_rgb.a;
+ blended_rgb.rgb += fOverbrightFactor * fAdditiveSelfBlendWeight * argbcolor.a * blended_rgb.rgb;
+ blended_rgb.rgb *= argbcolor.rgb;
+#else
+ blended_rgb *= argbcolor;
+#endif
+ }
+
+ vec4 result = FinalOutput(blended_rgb, 0.0, PIXEL_FOG_TYPE_NONE, TONEMAP_SCALE_LINEAR);
+
+ if (isAlphaTesting)
+ {
+ switch (alphaTestFunc)
+ {
+ case 0: discard; break;
+ case 1: if (result.a >= alphaTestRef) { discard; } break;
+ case 2: if (result.a != alphaTestRef) { discard; } break;
+ case 3: if (result.a > alphaTestRef) { discard; } break;
+ case 4: if (result.a <= alphaTestRef) { discard; } break;
+ case 5: if (result.a == alphaTestRef) { discard; } break;
+ case 6: if (result.a < alphaTestRef) { discard; } break;
+ }
+ }
+
+ fragColor = result;
+}
diff --git a/Game.Assets/sdn/shaders/spritecard_gl460.vs b/Game.Assets/sdn/shaders/spritecard_gl460.vs
new file mode 100644
index 00000000..f2c3ef06
--- /dev/null
+++ b/Game.Assets/sdn/shaders/spritecard_gl460.vs
@@ -0,0 +1,212 @@
+#version 460
+// STATIC: "ZOOM_ANIMATE_SEQ2" "0..1"
+// STATIC: "DUALSEQUENCE" "0..1"
+// STATIC: "EXTRACTGREENALPHA" "0..1"
+// DYNAMIC: "ORIENTATION" "0..2"
+
+layout(location = 0) in vec3 v_Position;
+layout(location = 2) in vec4 v_Tint;
+layout(location = 10) in vec4 v_TexCoord0;
+layout(location = 11) in vec4 v_TexCoord1;
+layout(location = 12) in vec4 v_Parms;
+layout(location = 13) in vec2 v_CornerID;
+layout(location = 14) in vec4 v_TexCoord2;
+#if DUALSEQUENCE
+layout(location = 15) in vec4 v_Seq2TexCoord0;
+layout(location = 16) in vec4 v_Seq2TexCoord1;
+layout(location = 17) in vec4 v_Parms1;
+#endif
+
+layout(std140, binding = 0) uniform source_matrices {
+ mat4 viewMatrix;
+ mat4 projectionMatrix;
+ mat4 modelMatrix;
+};
+
+layout(std140, binding = 5) uniform source_vs_constants {
+ vec4 vs_const[256];
+};
+
+#include "common_gl460.vs"
+
+const int SHADER_SPECIFIC_CONST_7 = 55;
+const int SHADER_SPECIFIC_CONST_8 = 56;
+const int SHADER_SPECIFIC_CONST_9 = 57;
+
+#define ScaleParms vs_const[SHADER_SPECIFIC_CONST_7]
+#define OLDFRM_SCALE_START (ScaleParms.x)
+#define OLDFRM_SCALE_END (ScaleParms.y)
+
+#define SizeParms vs_const[SHADER_SPECIFIC_CONST_8]
+#define SizeParms2 vs_const[SHADER_SPECIFIC_CONST_9]
+
+#define MINIMUM_SIZE_FACTOR (SizeParms.x)
+#define MAXIMUM_SIZE_FACTOR (SizeParms.y)
+#define START_FADE_SIZE_FACTOR (SizeParms.z)
+#define END_FADE_SIZE_FACTOR (SizeParms.w)
+#define START_FAR_FADE (SizeParms2.x)
+#define FAR_FADE_FACTOR (SizeParms2.y)
+
+#define BLENDFACTOR v_Parms.x
+#define ROTATION v_Parms.y
+#define RADIUS v_Parms.z
+#define YAW v_Parms.w
+
+layout(location = 0) out vec2 vs_TexCoord0;
+layout(location = 1) out vec2 vs_TexCoord1;
+layout(location = 2) out vec4 vs_Color;
+layout(location = 3) out vec4 vs_BlendFactor0;
+layout(location = 4) out vec2 vs_TexCoord2;
+layout(location = 5) out vec4 vs_BlendFactor1;
+layout(location = 6) out vec2 vs_Seq2TexCoord0;
+layout(location = 7) out vec2 vs_Seq2TexCoord1;
+
+#include "common_clipplanes_gl460.vs"
+
+#if ZOOM_ANIMATE_SEQ2
+float getlerpscaled(float l_in, float s0, float s1, float ts)
+{
+ l_in = 2.0 * (l_in - 0.5);
+ l_in *= mix(s0, s1, ts);
+ return 0.5 + 0.5 * l_in;
+}
+
+float getlerpscale_for_old_frame(float l_in, float ts)
+{
+ return getlerpscaled(l_in, OLDFRM_SCALE_START, OLDFRM_SCALE_END, ts);
+}
+
+float getlerpscale_for_new_frame(float l_in, float ts)
+{
+ return getlerpscaled(l_in, 1.0, OLDFRM_SCALE_START, ts);
+}
+#endif
+
+void main()
+{
+ vec4 tint = vec4(GammaToLinear(v_Tint.rgb), v_Tint.a);
+
+ vec2 sc_yaw = vec2(cos(YAW), sin(YAW));
+ vec2 sc = vec2(cos(ROTATION), sin(ROTATION));
+
+ vec2 ix = 2.0 * v_CornerID.xy - 1.0;
+ float x1 = dot(ix, sc);
+ float y1 = sc.x * ix.y - sc.y * ix.x;
+
+ vec4 projPos;
+ vec3 worldPos = (modelMatrix * vec4(v_Position, 1.0)).xyz;
+
+ float rad = RADIUS;
+ vec3 v2p = worldPos - cEyePos;
+ float l = length(v2p);
+ rad = max(rad, MINIMUM_SIZE_FACTOR * l);
+
+ if (rad > START_FADE_SIZE_FACTOR * l)
+ {
+ if (rad > END_FADE_SIZE_FACTOR * l)
+ {
+ tint = vec4(0.0);
+ rad = 0.0;
+ }
+ else
+ {
+ tint *= 1.0 - (rad - START_FADE_SIZE_FACTOR * l) / (END_FADE_SIZE_FACTOR * l - START_FADE_SIZE_FACTOR * l);
+ }
+ }
+
+ float tscale = 1.0 - min(1.0, max(0.0, (l - START_FAR_FADE) * FAR_FADE_FACTOR));
+ tint *= tscale;
+
+ if (tscale <= 0.0)
+ rad = 0.0;
+
+ rad = min(rad, MAXIMUM_SIZE_FACTOR * l);
+
+#if ORIENTATION == 0
+ vec3 viewPos = (viewMatrix * vec4(worldPos, 1.0)).xyz;
+
+ vec3 disp = vec3(-x1, y1, 0.0);
+ float tmpx = disp.x * sc_yaw.x + disp.z * sc_yaw.y;
+ disp.z = disp.z * sc_yaw.x - disp.x * sc_yaw.y;
+ disp.x = tmpx;
+
+ viewPos.xyz += disp * rad;
+
+ projPos = projectionMatrix * vec4(viewPos, 1.0);
+#endif
+
+#if ORIENTATION == 1
+ if (l > rad / 2.0)
+ {
+ vec3 up = vec3(0.0, 0.0, 1.0);
+ vec3 right = normalize(cross(up, v2p));
+ float tmpx = right.x * sc_yaw.x + right.y * sc_yaw.y;
+ right.y = right.y * sc_yaw.x - right.x * sc_yaw.y;
+ right.x = tmpx;
+
+ worldPos += (x1 * rad) * right;
+ worldPos.z += (y1 * rad) * up.z;
+
+ if (l < rad * 2.0)
+ {
+ tint *= smoothstep(rad / 2.0, rad, l);
+ }
+ }
+ projPos = projectionMatrix * viewMatrix * vec4(worldPos, 1.0);
+#endif
+
+#if ORIENTATION == 2
+ vec3 wpos = v_Position + RADIUS * vec3(y1, x1, 0.0);
+ projPos = projectionMatrix * viewMatrix * modelMatrix * vec4(wpos, 1.0);
+#endif
+
+ vs_BlendFactor0 = vec4(BLENDFACTOR, 0.0, 0.0, 0.0);
+ gl_Position = projPos;
+ WriteUserClipDistances(gl_Position);
+
+ vs_TexCoord0 = mix(v_TexCoord0.zw, v_TexCoord0.xy, v_CornerID.xy);
+ vs_TexCoord1 = mix(v_TexCoord1.zw, v_TexCoord1.xy, v_CornerID.xy);
+ vs_TexCoord2 = mix(v_TexCoord2.zw, v_TexCoord2.xy, v_CornerID.xy);
+
+ vs_Seq2TexCoord0 = vec2(0.0);
+ vs_Seq2TexCoord1 = vec2(0.0);
+
+#if DUALSEQUENCE
+ vec2 lerpold = v_CornerID.xy;
+ vec2 lerpnew = v_CornerID.xy;
+
+#if ZOOM_ANIMATE_SEQ2
+ lerpold.x = getlerpscale_for_old_frame(v_CornerID.x, v_Parms1.x);
+ lerpold.y = getlerpscale_for_old_frame(v_CornerID.y, v_Parms1.x);
+ lerpnew.x = getlerpscale_for_new_frame(v_CornerID.x, v_Parms1.x);
+ lerpnew.y = getlerpscale_for_new_frame(v_CornerID.y, v_Parms1.x);
+#endif
+
+ vs_Seq2TexCoord0 = mix(v_Seq2TexCoord0.zw, v_Seq2TexCoord0.xy, lerpold);
+ vs_Seq2TexCoord1 = mix(v_Seq2TexCoord1.zw, v_Seq2TexCoord1.xy, lerpnew);
+
+ vs_BlendFactor0.z = v_Parms1.x;
+#endif
+
+ vs_BlendFactor1 = vec4(0.0);
+
+#if EXTRACTGREENALPHA
+ if (BLENDFACTOR < 0.25)
+ {
+ vs_BlendFactor0.a = BLENDFACTOR * 2.0 + 0.5;
+ vs_BlendFactor0.g = 1.0 - vs_BlendFactor0.a;
+ }
+ else if (BLENDFACTOR < 0.75)
+ {
+ vs_BlendFactor1.g = BLENDFACTOR * 2.0 - 0.5;
+ vs_BlendFactor0.a = 1.0 - vs_BlendFactor1.g;
+ }
+ else
+ {
+ vs_BlendFactor1.a = BLENDFACTOR * 2.0 - 1.5;
+ vs_BlendFactor1.g = 1.0 - vs_BlendFactor1.a;
+ }
+#endif
+
+ vs_Color = tint;
+}
diff --git a/Game.Client/C_BasePlayer.cs b/Game.Client/C_BasePlayer.cs
index 814b7e05..a510094c 100644
--- a/Game.Client/C_BasePlayer.cs
+++ b/Game.Client/C_BasePlayer.cs
@@ -748,6 +748,12 @@ public virtual float GetFOV() {
return vm;
}
+ public virtual C_BaseAnimating? GetRenderedWeaponModel() {
+ if (!ShouldDrawLocalPlayer() && IsLocalPlayer())
+ return GetViewModel(0, true);
+ return GetActiveWeapon();
+ }
+
public IClientVehicle? GetVehicle() {
C_BaseEntity? vehicleEnt = Vehicle.Get();
return vehicleEnt?.GetClientVehicle();
diff --git a/Game.Client/ClientModeShared.cs b/Game.Client/ClientModeShared.cs
index c9a87219..456530cf 100644
--- a/Game.Client/ClientModeShared.cs
+++ b/Game.Client/ClientModeShared.cs
@@ -109,6 +109,7 @@ public void Init() {
public bool IsTyping() => ChatElement!.GetMessageMode() != MessageModeType.None;
public bool ShouldDrawDetailObjects() => true;
+ public bool ShouldDrawParticles() => true;
public void Enable() {
IPanel? root = enginevgui.GetPanel(VGuiPanelType.ClientDll);
diff --git a/Game.Client/IClientMode.cs b/Game.Client/IClientMode.cs
index 87064316..c65c2934 100644
--- a/Game.Client/IClientMode.cs
+++ b/Game.Client/IClientMode.cs
@@ -29,4 +29,5 @@ public interface IClientMode
bool CreateMove(double frametime, ref UserCmd cmd);
void OverrideView(ref ViewSetup setup);
bool ShouldDrawDetailObjects();
+ bool ShouldDrawParticles();
}
diff --git a/Game.Client/NewParticleEffect.cs b/Game.Client/NewParticleEffect.cs
index beefbe18..900a7bd8 100644
--- a/Game.Client/NewParticleEffect.cs
+++ b/Game.Client/NewParticleEffect.cs
@@ -3,6 +3,7 @@
using Source;
using Source.Common;
using Source.Common.Engine;
+using Source.Common.MaterialSystem;
using Source.Common.Mathematics;
using Source.Particles;
@@ -254,7 +255,80 @@ public void DetectChanges() {
}
}
- public int DrawModel(StudioFlags flags) => 0;
+ public int DrawModel(StudioFlags flags) {
+ if (!ParticleMgr.r_DrawParticles.GetBool())
+ return 0;
+
+ if (!clientMode.ShouldDrawParticles() || !ParticleMgr.Instance.ShouldRenderParticleSystems())
+ return 0;
+
+ if ((flags & (StudioFlags.ShadowDepthTexture | StudioFlags.SSAODepthTexture)) != 0)
+ return 0;
+
+ if (Def == null || Def.Material.Get() == null || !Def.IsPrecached || !ShouldDraw_)
+ return 0;
+
+ C_BaseEntity? owner = Owner.Get();
+ if (owner != null && owner.IsDormant())
+ return 0;
+
+ using MatRenderContextPtr renderContext = new(materials);
+
+ if (!Def.ViewModelEffect && !Def.ScreenSpaceEffect) {
+ renderContext.GetWorldSpaceCameraPosition(out Vector3 camera);
+ if (MathLib.CalcSqrDistanceToAABB(MinBounds, MaxBounds, camera) > Def.MaxDrawDistance * Def.MaxDrawDistance) {
+ NextSleepTime = Math.Max(NextSleepTime, g_pParticleSystemMgr.GetLastSimulationTime() + Def.NoDrawTimeToGoToSleep);
+ return 0;
+ }
+ }
+
+ if (Def.ViewModelEffect) {
+ C_BasePlayer? player = C_BasePlayer.GetLocalPlayer();
+ if (player == null || !player.IsAlive() || player.GetRenderedWeaponModel()?.IsViewModel() != true)
+ return 0;
+ }
+
+ if ((flags & StudioFlags.Transparency) != 0) {
+ C_BaseEntity? cameraObject = cl_entitylist.GetEnt(render.GetViewEntity());
+ if (cameraObject != null && ShouldSkipRenderForCamera(cameraObject))
+ return 0;
+
+ renderContext.MatrixMode(MaterialMatrixMode.Model);
+ renderContext.PushMatrix();
+ renderContext.LoadIdentity();
+ Render(renderContext.Context, IsTwoPass(), cameraObject);
+ renderContext.MatrixMode(MaterialMatrixMode.Model);
+ renderContext.PopMatrix();
+ }
+ else
+ g_pParticleSystemMgr.AddToRenderCache(this);
+
+ return 1;
+ }
+
+ bool ShouldSkipRenderForCamera(C_BaseEntity cameraObject) {
+ int skipControlPoint = Def!.SkipRenderControlPoint;
+ if (skipControlPoint == -1 || skipControlPoint > GetHighestControlPoint())
+ return false;
+
+ C_BaseEntity? entity = GetControlPointEntity(skipControlPoint).Get();
+ if (entity == null || input.CAM_IsThirdPerson())
+ return false;
+
+ if (entity == cameraObject)
+ return true;
+
+ C_BaseEntity? rootMoveParent = entity.GetRootMoveParent();
+ if (rootMoveParent == cameraObject)
+ return true;
+
+ C_BasePlayer? player = C_BasePlayer.GetLocalPlayer();
+ if (player != cameraObject)
+ return false;
+
+ BaseEntity? observerTarget = player!.GetObserverTarget();
+ return player.GetObserverMode() == Shared.ObserverMode.InEye && (observerTarget == entity || rootMoveParent == observerTarget);
+ }
public IClientUnknown GetIClientUnknown() => this;
public ICollideable? GetCollideable() => null;
diff --git a/Game.Client/ParticleMgr.cs b/Game.Client/ParticleMgr.cs
index aa7bf956..af9bde41 100644
--- a/Game.Client/ParticleMgr.cs
+++ b/Game.Client/ParticleMgr.cs
@@ -49,6 +49,8 @@ public bool Init(int count, IMaterialSystem materials) {
MaterialSystem = materials;
g_pParticleSystemMgr.Init(ParticleSystemQuery.g_pParticleSystemQuery, filesystem);
+ g_pParticleSystemMgr.AddBuiltinSimulationOperators();
+ g_pParticleSystemMgr.AddBuiltinRenderingOperators();
ParseParticleEffects(true, false);
diff --git a/Game.Client/ViewRender.cs b/Game.Client/ViewRender.cs
index a6fc1939..ae374866 100644
--- a/Game.Client/ViewRender.cs
+++ b/Game.Client/ViewRender.cs
@@ -862,6 +862,8 @@ protected void DrawOpaqueRenderables(RenderDepthMode depthMode) {
render.SetBlend(1);
+ g_pParticleSystemMgr.ResetRenderCache();
+
DrawFlags drawFlags = GetDrawFlags();
#if GMOD_DLL
if (depthMode == RenderDepthMode.Normal && gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PreDrawOpaqueRenderables)) {
@@ -884,6 +886,8 @@ protected void DrawOpaqueRenderables(RenderDepthMode depthMode) {
DrawOpaqueRenderables_DrawStaticProps(RenderGroup.OpaqueStaticHuge + 2 * bucket, depthMode);
}
+ g_pParticleSystemMgr.DrawRenderCache(depthMode != RenderDepthMode.Normal);
+
#if GMOD_DLL
if (depthMode == RenderDepthMode.Normal && gGM != null && gGM.CallWithArgs((int)LUA_POOLEDSTRING.PostDrawOpaqueRenderables)) {
g_Lua!.PushBool(false);
diff --git a/Source.Particles/BuiltinParticleEmitters.cs b/Source.Particles/BuiltinParticleEmitters.cs
new file mode 100644
index 00000000..4f18bebd
--- /dev/null
+++ b/Source.Particles/BuiltinParticleEmitters.cs
@@ -0,0 +1,333 @@
+using System.Numerics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+using static Source.Particles.ParticleConstants;
+
+namespace Source.Particles;
+
+public static class BuiltinParticleEmitters
+{
+ public static bool g_bDontMakeSkipToTimeTakeForever = false;
+
+ public static void AddBuiltInParticleEmitters(ParticleSystemMgr mgr) {
+ mgr.AddParticleOperator(ParticleFunctionType.Emitter, C_OP_InstantaneousEmitter.Definition);
+ mgr.AddParticleOperator(ParticleFunctionType.Emitter, C_OP_ContinuousEmitter.Definition);
+ }
+
+ internal static void StampNewParticles(ParticleCollection particles, int count, float startTime, float step, float endTime) {
+ int startParticle = particles.ActiveParticles;
+ particles.SetNActiveParticles(startParticle + count);
+ float timeStamp = startTime;
+ for (int i = startParticle; i < startParticle + count; i++) {
+ if (step != 0.0f) {
+ timeStamp += step;
+ if (timeStamp >= endTime)
+ timeStamp = endTime;
+ }
+ particles.GetFloatAttributeRefForWrite(PARTICLE_ATTRIBUTE_CREATION_TIME, i) = timeStamp;
+ }
+ }
+}
+
+public sealed class C_OP_InstantaneousEmitter : ParticleOperatorInstance
+{
+ struct Context
+ {
+ public int ActualParticlesToEmit;
+ public int ParticlesToEmit;
+ public float StartTime;
+ public bool Scaled;
+ }
+
+ public int ParticlesToEmit;
+ public int MinParticlesToEmit;
+ public float StartTime;
+ public int PerFrameNum;
+ public int ScaleControlPoint;
+ public int ScaleControlPointField;
+
+ public static readonly ParticleOperatorDefinition Definition = new("emit_instantaneously", ParticleOperatorId.Generic, false,
+ ParticleOperatorUnpack.Begin()
+ .Float("emission_start_time", "0", (o, v) => o.StartTime = v)
+ .Int("num_to_emit_minimum", "-1", (o, v) => o.MinParticlesToEmit = v)
+ .Int("num_to_emit", "100", (o, v) => o.ParticlesToEmit = v)
+ .Int("maximum emission per frame", "-1", (o, v) => o.PerFrameNum = v)
+ .Int("emission count scale control point", "-1", (o, v) => o.ScaleControlPoint = v)
+ .Int("emission count scale control point field", "0", (o, v) => o.ScaleControlPointField = v));
+
+ static ref Context Ctx(Span context) => ref MemoryMarshal.AsRef(context);
+
+ public override uint GetWrittenAttributes() => PARTICLE_ATTRIBUTE_CREATION_TIME_MASK;
+ public override uint GetReadAttributes() => 0;
+ public override ulong GetReadControlPointMask() => ScaleControlPoint < 0 ? 0 : 1UL << (ScaleControlPoint & 63);
+ public override int GetRequiredContextBytes() => Unsafe.SizeOf();
+
+ public override void InitParams(ParticleSystemDefinition def, Datamodel.Element element) {
+ if (MinParticlesToEmit >= 0 && ParticlesToEmit < MinParticlesToEmit)
+ (ParticlesToEmit, MinParticlesToEmit) = (MinParticlesToEmit, ParticlesToEmit);
+ if (PerFrameNum < 0)
+ PerFrameNum = int.MaxValue;
+ ScaleControlPointField = Math.Clamp(ScaleControlPointField, 0, 2);
+ }
+
+ public override void StopEmission(ParticleCollection particles, Span context, bool infiniteOnly = false) {
+ if (!infiniteOnly)
+ Ctx(context).ActualParticlesToEmit = 0;
+ }
+
+ public override void StartEmission(ParticleCollection particles, Span context, bool infiniteOnly = false) {
+ if (infiniteOnly)
+ return;
+ ref Context ctx = ref Ctx(context);
+ ctx.ActualParticlesToEmit = ctx.ParticlesToEmit;
+ SkipToTime(particles.CurTime, particles, context);
+ }
+
+ public override void SkipToTime(float time, ParticleCollection particles, Span context) {
+ ref Context ctx = ref Ctx(context);
+ if (StartTime + 2.0f + ctx.StartTime < time)
+ ctx.ActualParticlesToEmit = 0;
+ }
+
+ public override void InitializeContextData(ParticleCollection particles, Span context) {
+ ref Context ctx = ref Ctx(context);
+ int toEmit = ParticlesToEmit;
+ if (MinParticlesToEmit >= 0)
+ toEmit = (int)((ParticlesToEmit + 1 - MinParticlesToEmit) * particles.RandomFloat(0.0f, 1.0f)) + MinParticlesToEmit;
+ ctx.ParticlesToEmit = toEmit;
+ ctx.ActualParticlesToEmit = toEmit;
+ ctx.StartTime = 0.0f;
+ ctx.Scaled = false;
+ }
+
+ public override void Restart(ParticleCollection particles, Span context) {
+ ref Context ctx = ref Ctx(context);
+ ctx.ActualParticlesToEmit = ctx.ParticlesToEmit;
+ ctx.Scaled = false;
+ ctx.StartTime = particles.CurTime;
+ }
+
+ public override bool MayCreateMoreParticles(ParticleCollection particles, Span context) => Ctx(context).ActualParticlesToEmit > 0;
+
+ public override uint Emit(ParticleCollection particles, float opCurStrength, Span context) {
+ ref Context ctx = ref Ctx(context);
+ int remaining = ctx.ActualParticlesToEmit;
+ if (remaining < 1)
+ return 0;
+
+ float startTime = StartTime + ctx.StartTime;
+ if (startTime > particles.CurTime || ctx.ParticlesToEmit == 0)
+ return 0;
+
+ if (ScaleControlPoint >= 0 && !ctx.Scaled) {
+ Vector3 scale;
+ if (particles.CurTime - particles.PreviousDt <= startTime)
+ particles.GetControlPointAtTime(ScaleControlPoint, startTime, out scale);
+ else
+ particles.GetControlPointAtPrevTime(ScaleControlPoint, out scale);
+ float scaleValue = scale[ScaleControlPointField];
+ ctx.ParticlesToEmit = (int)(ctx.ParticlesToEmit * scaleValue);
+ ctx.Scaled = true;
+ remaining = (int)(ctx.ActualParticlesToEmit * scaleValue);
+ }
+
+ if (remaining < 0)
+ remaining = 0;
+
+ int particlesThisFrame = Math.Min(remaining, PerFrameNum);
+ int allowed = particles.MaxAllowedParticles - particles.ActiveParticles;
+ int actual = Math.Min(ctx.ParticlesToEmit * ParticleSystemMgr.g_nParticle_Multiplier, allowed);
+ actual = Math.Min(actual, particlesThisFrame);
+ ctx.ActualParticlesToEmit = remaining - particlesThisFrame;
+
+ if (actual == 0)
+ return 0;
+
+ BuiltinParticleEmitters.StampNewParticles(particles, actual, startTime, 0.0f, startTime);
+ return PARTICLE_ATTRIBUTE_CREATION_TIME_MASK;
+ }
+}
+
+public sealed class C_OP_ContinuousEmitter : ParticleOperatorInstance
+{
+ struct Context
+ {
+ public float ParticleEmissionCounter;
+ public int ActualParticlesToEmit;
+ public float NextEmitTime;
+ public float StartTime;
+ public bool StoppedEmission;
+ }
+
+ public float EmissionDuration;
+ public float StartTime;
+ public float EmitRate;
+ public float EmissionScale;
+ public bool ScalePerParticle;
+
+ public static readonly ParticleOperatorDefinition Definition = new("emit_continuously", ParticleOperatorId.Generic, false,
+ ParticleOperatorUnpack.Begin()
+ .Float("emission_start_time", "0", (o, v) => o.StartTime = v)
+ .Float("emission_rate", "100", (o, v) => o.EmitRate = v)
+ .Float("emission_duration", "0", (o, v) => o.EmissionDuration = v)
+ .Float("scale emission to used control points", "0.0", (o, v) => o.EmissionScale = v)
+ .Bool("use parent particles for emission scaling", "0", (o, v) => o.ScalePerParticle = v));
+
+ static ref Context Ctx(Span context) => ref MemoryMarshal.AsRef(context);
+
+ public override uint GetWrittenAttributes() => PARTICLE_ATTRIBUTE_CREATION_TIME_MASK;
+ public override uint GetReadAttributes() => 0;
+ public override int GetRequiredContextBytes() => Unsafe.SizeOf();
+
+ public override void InitParams(ParticleSystemDefinition def, Datamodel.Element element) {
+ float rate = EmitRate;
+ if (rate <= 0.0f)
+ rate = 0.0f;
+ if (EmissionDuration < 0.0f)
+ EmissionDuration = 0.0f;
+ EmitRate = ParticleSystemMgr.g_nParticle_Multiplier * rate;
+ }
+
+ public override void StopEmission(ParticleCollection particles, Span context, bool infiniteOnly = false) {
+ if (!infiniteOnly || EmissionDuration == 0.0f)
+ Ctx(context).StoppedEmission = true;
+ }
+
+ public override void StartEmission(ParticleCollection particles, Span context, bool infiniteOnly = false) {
+ if (infiniteOnly && EmissionDuration != 0.0f)
+ return;
+ Ctx(context).StoppedEmission = false;
+ SkipToTime(particles.CurTime, particles, context);
+ }
+
+ public override void InitializeContextData(ParticleCollection particles, Span context) {
+ ref Context ctx = ref Ctx(context);
+ ctx.ParticleEmissionCounter = 0.0f;
+ ctx.ActualParticlesToEmit = 0;
+ ctx.NextEmitTime = StartTime;
+ ctx.StartTime = 0.0f;
+ ctx.StoppedEmission = false;
+ }
+
+ public override void Restart(ParticleCollection particles, Span context) {
+ if (EmissionDuration == 0.0f)
+ return;
+ ref Context ctx = ref Ctx(context);
+ ctx.ParticleEmissionCounter = 0.0f;
+ ctx.ActualParticlesToEmit = 0;
+ ctx.NextEmitTime = particles.CurTime + StartTime;
+ ctx.StartTime = particles.CurTime;
+ }
+
+ public override bool MayCreateMoreParticles(ParticleCollection particles, Span context) {
+ ref Context ctx = ref Ctx(context);
+ if (ctx.StoppedEmission)
+ return false;
+ if (EmitRate <= 0.0f)
+ return false;
+ if (EmissionDuration != 0.0f)
+ return particles.CurTime - particles.Dt <= EmissionDuration + StartTime + ctx.StartTime;
+ return true;
+ }
+
+ float GetEmissionRate(ParticleCollection particles) {
+ float controlPointScale = particles.GetHighestControlPoint() * EmissionScale;
+ float rate = EmitRate;
+ if (particles.CheckIfOperatorShouldRun(this, out float strength))
+ rate *= strength;
+ if (controlPointScale != 0.0f)
+ rate *= controlPointScale;
+ return rate;
+ }
+
+ public override void SkipToTime(float time, ParticleCollection particles, Span context) {
+ ref Context ctx = ref Ctx(context);
+ float startTime = StartTime + ctx.StartTime;
+ if (startTime >= time)
+ return;
+
+ float emissionRate = GetEmissionRate(particles);
+ float currDrawTime = particles.CurTime;
+ float prevDrawTime = currDrawTime - time;
+ if (EmissionDuration != 0.0f && prevDrawTime <= startTime)
+ prevDrawTime = startTime;
+
+ ctx.ActualParticlesToEmit = 0;
+ float deltaTime = currDrawTime - prevDrawTime;
+ if (deltaTime >= 4.0f)
+ deltaTime = 4.0f;
+
+ float toEmit = emissionRate * deltaTime;
+ prevDrawTime = currDrawTime - deltaTime;
+ ctx.ParticleEmissionCounter = toEmit;
+
+ int actual = (int)MathF.Floor(toEmit);
+ int startParticle = particles.ActiveParticles;
+ if (actual + startParticle > particles.MaxAllowedParticles)
+ actual = particles.MaxAllowedParticles - startParticle;
+
+ BuiltinParticleEmitters.StampNewParticles(particles, actual, prevDrawTime, deltaTime / actual, currDrawTime);
+
+ if (BuiltinParticleEmitters.g_bDontMakeSkipToTimeTakeForever)
+ return;
+
+ float t = Math.Max(currDrawTime - particles.Def!.NoDrawTimeToGoToSleep, prevDrawTime);
+ particles.CurTime = t;
+ for (; t < currDrawTime; t += 0.1f)
+ particles.Simulate(0.1f, false);
+ }
+
+ public override uint Emit(ParticleCollection particles, float opCurStrength, Span context) {
+ ref Context ctx = ref Ctx(context);
+
+ float controlPointScale = particles.GetHighestControlPoint() * EmissionScale;
+ float emissionRate = opCurStrength * EmitRate;
+ if (ScalePerParticle) {
+ float scale = EmissionScale;
+ if (particles.Parent != null)
+ scale *= particles.Parent.ActiveParticles;
+ emissionRate *= scale;
+ }
+ else if (controlPointScale != 0.0f)
+ emissionRate *= controlPointScale;
+
+ if (emissionRate == 0.0f || EmitRate <= 0.0f || ctx.StoppedEmission)
+ return 0;
+
+ float currDrawTime = particles.CurTime;
+ float prevDrawTime = StartTime + ctx.StartTime;
+ if (EmissionDuration == 0.0f) {
+ if (currDrawTime < prevDrawTime)
+ return 0;
+ prevDrawTime = currDrawTime - particles.Dt;
+ }
+ else {
+ float endTime = EmissionDuration + prevDrawTime;
+ float frameStart = currDrawTime - particles.Dt;
+ if (endTime < frameStart)
+ return 0;
+ if (currDrawTime < prevDrawTime)
+ return 0;
+ if (prevDrawTime <= frameStart)
+ prevDrawTime = frameStart;
+ if (endTime <= currDrawTime)
+ currDrawTime = endTime;
+ }
+
+ float deltaTime = currDrawTime - prevDrawTime;
+ ctx.ParticleEmissionCounter += emissionRate * deltaTime;
+
+ int toEmit = (int)(MathF.Floor(ctx.ParticleEmissionCounter) - ctx.ActualParticlesToEmit);
+ ctx.ActualParticlesToEmit += toEmit;
+ if (toEmit == 0)
+ return 0;
+
+ int actual = Math.Min(toEmit, particles.MaxAllowedParticles - particles.ActiveParticles);
+ if (actual == 0)
+ return 0;
+
+ BuiltinParticleEmitters.StampNewParticles(particles, actual, prevDrawTime, deltaTime / actual, currDrawTime);
+ return PARTICLE_ATTRIBUTE_CREATION_TIME_MASK;
+ }
+}
diff --git a/Source.Particles/BuiltinParticleInitializers.cs b/Source.Particles/BuiltinParticleInitializers.cs
new file mode 100644
index 00000000..973413ed
--- /dev/null
+++ b/Source.Particles/BuiltinParticleInitializers.cs
@@ -0,0 +1,153 @@
+using Source.Common.Mathematics;
+
+using System.Numerics;
+
+using static Source.Particles.ParticleConstants;
+
+namespace Source.Particles;
+
+public static class BuiltinParticleInitializers
+{
+ public static void AddBuiltInParticleInitializers(ParticleSystemMgr mgr) {
+ mgr.AddParticleOperator(ParticleFunctionType.Initializer, C_INIT_CreateWithinSphere.Definition);
+ mgr.AddParticleOperator(ParticleFunctionType.Initializer, C_INIT_RandomLifeTime.Definition);
+ }
+}
+
+public sealed class C_INIT_CreateWithinSphere : ParticleOperatorInstance
+{
+ public float RadiusMin;
+ public float RadiusMax;
+ public Vector3 DistanceBias;
+ public Vector3 DistanceBiasAbs;
+ public int ControlPointNumber;
+ public float SpeedMin;
+ public float SpeedMax;
+ public float SpeedRandExp;
+ public bool LocalCoords;
+ public Vector3 LocalCoordinateSystemSpeedMin;
+ public Vector3 LocalCoordinateSystemSpeedMax;
+ public int CreateInModel;
+ public bool UseHighestEndCP;
+ public float EndCPGrowthTime;
+ bool HasDistanceBias;
+ bool HasDistanceBiasAbs;
+
+ public static readonly ParticleOperatorDefinition Definition = new("Position Within Sphere Random", ParticleOperatorId.PiPosition, false,
+ ParticleOperatorUnpack.Begin()
+ .Float("distance_min", "0", (o, v) => o.RadiusMin = v)
+ .Float("distance_max", "0", (o, v) => o.RadiusMax = v)
+ .Vector3("distance_bias", "1 1 1", (o, v) => o.DistanceBias = v)
+ .Vector3("distance_bias_absolute_value", "0 0 0", (o, v) => o.DistanceBiasAbs = v)
+ .Bool("bias in local system", "0", (o, v) => o.LocalCoords = v)
+ .Int("control_point_number", "0", (o, v) => o.ControlPointNumber = v)
+ .Float("speed_min", "0", (o, v) => o.SpeedMin = v)
+ .Float("speed_max", "0", (o, v) => o.SpeedMax = v)
+ .Float("speed_random_exponent", "1", (o, v) => o.SpeedRandExp = v)
+ .Vector3("speed_in_local_coordinate_system_min", "0 0 0", (o, v) => o.LocalCoordinateSystemSpeedMin = v)
+ .Vector3("speed_in_local_coordinate_system_max", "0 0 0", (o, v) => o.LocalCoordinateSystemSpeedMax = v)
+ .Int("create in model", "0", (o, v) => o.CreateInModel = v)
+ .Bool("randomly distribute to highest supplied Control Point", "0", (o, v) => o.UseHighestEndCP = v)
+ .Float("randomly distribution growth time", "0", (o, v) => o.EndCPGrowthTime = v));
+
+ public override uint GetWrittenAttributes() => PARTICLE_ATTRIBUTE_XYZ_MASK | PARTICLE_ATTRIBUTE_PREV_XYZ_MASK;
+ public override uint GetReadAttributes() => PARTICLE_ATTRIBUTE_CREATION_TIME_MASK;
+
+ public override ulong GetReadControlPointMask() {
+ ulong mask = 1UL << (ControlPointNumber & 63);
+ return UseHighestEndCP ? (ulong)-(long)mask : mask;
+ }
+
+ public override void InitParams(ParticleSystemDefinition def, Datamodel.Element element) {
+ ControlPointNumber = Math.Clamp(ControlPointNumber, 0, MAX_PARTICLE_CONTROL_POINTS - 1);
+ HasDistanceBias = DistanceBias.X != 1.0f || DistanceBias.Y != 1.0f || DistanceBias.Z != 1.0f;
+ HasDistanceBiasAbs = DistanceBiasAbs.X != 0.0f || DistanceBiasAbs.Y != 0.0f || DistanceBiasAbs.Z != 0.0f;
+ }
+
+ public override void InitNewParticlesScalar(ParticleCollection particles, int firstParticle, int numParticles, int attributeWriteMask, Span context) {
+ for (int p = firstParticle; p < firstParticle + numParticles; p++) {
+ float creationTime = particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_CREATION_TIME, p);
+
+ int currentControlPoint = ControlPointNumber;
+ if (UseHighestEndCP) {
+ float currentEndCP = EndCPGrowthTime != 0.0f ? Math.Min(particles.CurTime, EndCPGrowthTime) / EndCPGrowthTime : 1.0f;
+ currentControlPoint = particles.RandomInt(ControlPointNumber, (int)MathF.Floor(particles.GetHighestControlPoint() * currentEndCP));
+ }
+
+ Vector3 randomPosition = default;
+ Vector3 randomDirection = default;
+ for (int tries = 10; ; ) {
+ float length = particles.RandomVectorInUnitSphere(out randomPosition);
+
+ if (HasDistanceBiasAbs) {
+ if (DistanceBiasAbs.X != 0.0f)
+ randomPosition.X = MathF.Abs(randomPosition.X);
+ if (DistanceBiasAbs.Y != 0.0f)
+ randomPosition.Y = MathF.Abs(randomPosition.Y);
+ if (DistanceBiasAbs.Z != 0.0f)
+ randomPosition.Z = MathF.Abs(randomPosition.Z);
+ }
+
+ randomPosition *= DistanceBias;
+ randomDirection = randomPosition * (1.0f / MathF.Sqrt(randomPosition.LengthSquared() + 1e-10f));
+ randomPosition = randomDirection * ((RadiusMax - RadiusMin) * length + RadiusMin);
+
+ if (!HasDistanceBias || !LocalCoords) {
+ particles.GetControlPointAtTime(currentControlPoint, creationTime, out Vector3 controlPoint);
+ randomPosition += controlPoint;
+ }
+ else {
+ particles.GetControlPointTransformAtTime(currentControlPoint, creationTime, out Matrix3x4 transform);
+ MathLib.VectorTransform(in randomPosition, in transform, out randomPosition);
+ }
+
+ if (CreateInModel == 0)
+ break;
+ if (particles.Mgr!.Query().MovePointInsideControllingObject(particles, particles.ControlPoints[currentControlPoint].Object, ref randomPosition))
+ break;
+ if (--tries == 0)
+ break;
+ }
+
+ particles.SetVectorAttribute(PARTICLE_ATTRIBUTE_XYZ, p, randomPosition);
+
+ if ((attributeWriteMask & PARTICLE_ATTRIBUTE_PREV_XYZ_MASK) == 0)
+ continue;
+
+ Vector3 offset = Vector3.Zero;
+ if (SpeedMax > 0.0f) {
+ float randomSpeed = particles.RandomFloatExp(SpeedMin, SpeedMax, SpeedRandExp);
+ offset -= randomSpeed * randomDirection;
+ }
+
+ ref readonly ParticleControlPoint cp = ref particles.ControlPoint(currentControlPoint);
+ offset -= particles.RandomFloat(LocalCoordinateSystemSpeedMin.X, LocalCoordinateSystemSpeedMax.X) * cp.ForwardVector;
+ offset -= particles.RandomFloat(LocalCoordinateSystemSpeedMin.Y, LocalCoordinateSystemSpeedMax.Y) * cp.RightVector;
+ offset -= particles.RandomFloat(LocalCoordinateSystemSpeedMin.Z, LocalCoordinateSystemSpeedMax.Z) * cp.UpVector;
+
+ offset *= particles.PreviousDt;
+ particles.SetVectorAttribute(PARTICLE_ATTRIBUTE_PREV_XYZ, p, randomPosition + offset);
+ }
+ }
+}
+
+public sealed class C_INIT_RandomLifeTime : ParticleOperatorInstance
+{
+ public float LifetimeMin;
+ public float LifetimeMax;
+ public float LifetimeRandExponent;
+
+ public static readonly ParticleOperatorDefinition Definition = new("Lifetime Random", ParticleOperatorId.Generic, false,
+ ParticleOperatorUnpack.Begin()
+ .Float("lifetime_min", "0", (o, v) => o.LifetimeMin = v)
+ .Float("lifetime_max", "0", (o, v) => o.LifetimeMax = v)
+ .Float("lifetime_random_exponent", "1", (o, v) => o.LifetimeRandExponent = v));
+
+ public override uint GetWrittenAttributes() => PARTICLE_ATTRIBUTE_LIFE_DURATION_MASK;
+ public override uint GetReadAttributes() => 0;
+
+ public override void InitNewParticlesScalar(ParticleCollection particles, int firstParticle, int numParticles, int attributeWriteMask, Span context) {
+ for (int p = firstParticle; p < firstParticle + numParticles; p++)
+ particles.GetFloatAttributeRefForWrite(PARTICLE_ATTRIBUTE_LIFE_DURATION, p) = particles.RandomFloatExp(LifetimeMin, LifetimeMax, LifetimeRandExponent);
+ }
+}
diff --git a/Source.Particles/BuiltinParticleOperators.cs b/Source.Particles/BuiltinParticleOperators.cs
new file mode 100644
index 00000000..ba78ee81
--- /dev/null
+++ b/Source.Particles/BuiltinParticleOperators.cs
@@ -0,0 +1,136 @@
+using Source.Common.Mathematics;
+
+using System.Numerics;
+
+using static Source.Particles.ParticleConstants;
+
+namespace Source.Particles;
+
+public static class BuiltinParticleOperators
+{
+ public static void AddBuiltInParticleOperators(ParticleSystemMgr mgr) {
+ mgr.AddParticleOperator(ParticleFunctionType.Operator, C_OP_Decay.Definition);
+ mgr.AddParticleOperator(ParticleFunctionType.Operator, C_OP_BasicMovement.Definition);
+ }
+}
+
+public sealed class C_OP_Decay : ParticleOperatorInstance
+{
+ public static readonly ParticleOperatorDefinition Definition = new("Lifespan Decay", ParticleOperatorId.Generic, false,
+ ParticleOperatorUnpack.Begin());
+
+ public override uint GetWrittenAttributes() => 0;
+ public override uint GetReadAttributes() => PARTICLE_ATTRIBUTE_CREATION_TIME_MASK | PARTICLE_ATTRIBUTE_LIFE_DURATION_MASK;
+
+ public override void Operate(ParticleCollection particles, float opStrength, Span context) {
+ int limit = particles.PaddedActiveParticles * 4;
+ for (int i = 0; i < limit; i++) {
+ float lifeDuration = particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_LIFE_DURATION, i);
+ float age = particles.CurTime - particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_CREATION_TIME, i);
+ if (lifeDuration <= age || lifeDuration <= 0.0f)
+ particles.KillParticle(i);
+ }
+ }
+}
+
+public sealed class C_OP_BasicMovement : ParticleOperatorInstance
+{
+ public Vector3 Gravity;
+ public float Drag;
+ public int MaxConstraintPasses;
+
+ public static readonly ParticleOperatorDefinition Definition = new("Movement Basic", ParticleOperatorId.Generic, false,
+ ParticleOperatorUnpack.Begin()
+ .Vector3("gravity", "0 0 0", (o, v) => o.Gravity = v)
+ .Float("drag", "0", (o, v) => o.Drag = v)
+ .Int("max constraint passes", "3", (o, v) => o.MaxConstraintPasses = v));
+
+ public override uint GetWrittenAttributes() => PARTICLE_ATTRIBUTE_XYZ_MASK | PARTICLE_ATTRIBUTE_PREV_XYZ_MASK;
+ public override uint GetReadAttributes() => 0;
+
+ static readonly FourVectors[] PerParticleForceAccumulator = new FourVectors[MAX_PARTICLES_IN_A_SYSTEM / 4 + 1];
+ static readonly bool[] ConstraintSatisfied = new bool[MAX_PARTICLE_CONTROL_POINTS];
+ static readonly bool[] FinalConstraint = new bool[MAX_PARTICLE_CONTROL_POINTS];
+
+ public override void Operate(ParticleCollection particles, float opStrength, Span context) {
+ ParticleSystemDefinition def = particles.Def!;
+ float dt = particles.Dt;
+ float adjustedDrag = MathF.Exp(dt * 30.0f * MathF.Log(1.0f - Math.Max(Drag, 0.0f))) * (dt / particles.PreviousDt);
+ int blocks = particles.PaddedActiveParticles;
+
+ FourVectors gravity = new(Gravity);
+ int accumulatorStride;
+ if (def.ForceGenerators.Count == 0) {
+ PerParticleForceAccumulator[0] = gravity;
+ accumulatorStride = 0;
+ }
+ else {
+ PerParticleForceAccumulator.AsSpan(0, blocks).Fill(gravity);
+ for (int i = 0; i < def.ForceGenerators.Count; i++) {
+ ParticleOperatorInstance op = def.ForceGenerators[i];
+ if (particles.CheckIfOperatorShouldRun(op, out float strength))
+ op.AddForces(PerParticleForceAccumulator.AsSpan(0, blocks), particles, blocks, strength, particles.OperatorContextData.AsSpan(def.ForceGeneratorsCtxOffsets[i]));
+ }
+ accumulatorStride = 1;
+ }
+
+ float dtSquared = dt * dt;
+ Span memory = particles.AttributeMemory;
+ int xyz = particles.GetAttributeOffset(PARTICLE_ATTRIBUTE_XYZ, out int xyzStride);
+ int prevXyz = particles.GetAttributeOffset(PARTICLE_ATTRIBUTE_PREV_XYZ, out int prevXyzStride);
+
+ for (int block = 0, accumulator = 0; block < blocks; block++, accumulator += accumulatorStride) {
+ ref FourVectors force = ref PerParticleForceAccumulator[accumulator];
+ for (int lane = 0; lane < 4; lane++) {
+ for (int axis = 0; axis < 3; axis++) {
+ float accel = axis switch { 0 => force.x[lane], 1 => force.y[lane], _ => force.z[lane] };
+ ref float prev = ref memory[prevXyz + axis * 4 + lane];
+ float cur = memory[xyz + axis * 4 + lane];
+ prev = (cur - prev) * adjustedDrag + accel * dtSquared + cur;
+ }
+ }
+ xyz += xyzStride;
+ prevXyz += prevXyzStride;
+ }
+
+ particles.SwapPosAndPrevPos();
+
+ int constraintCount = def.Constraints.Count;
+ if (constraintCount == 0 || particles.PaddedActiveParticles == 0)
+ return;
+
+ for (int i = 0; i < constraintCount; i++) {
+ ParticleOperatorInstance op = def.Constraints[i];
+ FinalConstraint[i] = op.IsFinalConstraint();
+ ConstraintSatisfied[i] = false;
+ op.SetupConstraintPerFrameData(particles, particles.OperatorContextData.AsSpan(def.ConstraintsCtxOffsets[i]));
+ }
+
+ for (int pass = 0; pass < MaxConstraintPasses; pass++) {
+ for (int i = 0; i < constraintCount; i++) {
+ if (ConstraintSatisfied[i])
+ continue;
+ ConstraintSatisfied[i] = true;
+
+ ParticleOperatorInstance op = def.Constraints[i];
+ if (FinalConstraint[i] || !particles.CheckIfOperatorShouldRun(op, out _))
+ continue;
+ if (!op.EnforceConstraint(0, particles.PaddedActiveParticles, particles, particles.OperatorContextData.AsSpan(def.ConstraintsCtxOffsets[i]), particles.ActiveParticles))
+ continue;
+
+ for (int j = 0; j < constraintCount; j++) {
+ if (j != i)
+ ConstraintSatisfied[j] = false;
+ }
+ }
+ }
+
+ for (int i = 0; i < constraintCount; i++) {
+ if (!FinalConstraint[i])
+ continue;
+ ParticleOperatorInstance op = def.Constraints[i];
+ if (particles.CheckIfOperatorShouldRun(op, out _))
+ op.EnforceConstraint(0, particles.PaddedActiveParticles, particles, particles.OperatorContextData.AsSpan(def.ConstraintsCtxOffsets[i]), particles.ActiveParticles);
+ }
+ }
+}
diff --git a/Source.Particles/BuiltinParticleRenderers.cs b/Source.Particles/BuiltinParticleRenderers.cs
new file mode 100644
index 00000000..785cc049
--- /dev/null
+++ b/Source.Particles/BuiltinParticleRenderers.cs
@@ -0,0 +1,562 @@
+using Source.Common.MaterialSystem;
+using Source.Common.Mathematics;
+
+using System.Numerics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+using static Source.Particles.ParticleConstants;
+
+namespace Source.Particles;
+
+public static class BuiltinParticleRenderers
+{
+ public static void AddBuiltInParticleRenderers(ParticleSystemMgr mgr) {
+ mgr.AddParticleOperator(ParticleFunctionType.Renderer, C_OP_RenderSprites.Definition);
+ }
+
+ internal static readonly SheetSequenceSample DefaultSheetSequence = CreateDefaultSheetSequence();
+
+ static SheetSequenceSample CreateDefaultSheetSequence() {
+ SheetSequenceSample sample = default;
+ for (int i = 0; i < Sheet.MAX_IMAGES_PER_FRAME_IN_MEMORY; i++)
+ sample.TextureCoordData[i] = new() { LeftU0 = 0, TopV0 = 0, RightU0 = 1, BottomV0 = 1, LeftU1 = 0, TopV1 = 0, RightU1 = 1, BottomV1 = 1 };
+ sample.BlendFactor = 1.0f;
+ return sample;
+ }
+
+ internal static ref readonly SheetSequenceSample SampleOrDefault(ref readonly SheetSequenceSample sample) {
+ if (Unsafe.IsNullRef(in sample))
+ return ref DefaultSheetSequence;
+ return ref sample;
+ }
+
+ internal static byte UnitToByte(float value) => (byte)((int)MathF.Round(value * 255.0f) & 0xFF);
+
+ internal static Vector3 ApplyCameraBias(Vector3 position, in Vector3 camera, float cameraBias) {
+ if (cameraBias == 0.0f)
+ return position;
+ Vector3 delta = camera - position;
+ float invLength = 1.0f / MathF.Sqrt(delta.LengthSquared() + 1e-10f);
+ return position + delta * cameraBias * invLength;
+ }
+
+ internal static void SetupParticleVisibility(ParticleCollection particles, ref ParticleVisibilityData visibilityData, in ParticleVisibilityInputs inputs, ref int queryHandle) {
+ float visibility = particles.Mgr!.Query().GetPixelVisibility(ref queryHandle, particles.GetControlPointAtCurrentTime(inputs.CPin), inputs.ProxyRadius);
+
+ if (inputs.InputMax == inputs.InputMin) {
+ bool max = inputs.InputMax <= visibility;
+ visibilityData.AlphaVisibility = max ? inputs.AlphaScaleMax : inputs.AlphaScaleMin;
+ visibilityData.RadiusVisibility = max ? inputs.RadiusScaleMax : inputs.RadiusScaleMin;
+ }
+ else {
+ float fraction = Math.Clamp((visibility - inputs.InputMin) / (inputs.InputMax - inputs.InputMin), 0.0f, 1.0f);
+ visibilityData.AlphaVisibility = inputs.AlphaScaleMin + (inputs.AlphaScaleMax - inputs.AlphaScaleMin) * fraction;
+ visibilityData.RadiusVisibility = inputs.RadiusScaleMin + (inputs.RadiusScaleMax - inputs.RadiusScaleMin) * fraction;
+ }
+
+ visibilityData.CameraBias = inputs.CameraBias;
+ }
+}
+
+struct SpriteRenderInfo
+{
+ public ParticleCollection Particles;
+ public Sheet? Sheet;
+ public float AgeScale;
+ public float AgeScale2;
+ public int VertexOffset;
+}
+
+public sealed class C_OP_RenderSprites : ParticleRenderOperatorInstance
+{
+ struct Context
+ {
+ public TokenCache OrientationVarToken;
+ public TokenCache OrientationMatrixVarToken;
+ public ParticleVisibilityData VisibilityData;
+ public int QueryHandle;
+ }
+
+ public float AnimationRate;
+ public bool FitCycleToLifetime;
+ public int OrientationType;
+ public int OrientationControlPoint;
+ public float AnimationRate2;
+ public bool AnimateInFPS;
+
+ public static readonly ParticleOperatorDefinition Definition = new("render_animated_sprites", ParticleOperatorId.Generic, false,
+ ParticleOperatorUnpack.BeginRender()
+ .Float("animation rate", ".1", (o, v) => o.AnimationRate = v)
+ .Bool("animation_fit_lifetime", "0", (o, v) => o.FitCycleToLifetime = v)
+ .Int("orientation_type", "0", (o, v) => o.OrientationType = v)
+ .Int("orientation control point", "-1", (o, v) => o.OrientationControlPoint = v)
+ .Float("second sequence animation rate", "0", (o, v) => o.AnimationRate2 = v)
+ .Bool("use animation rate as FPS", "0", (o, v) => o.AnimateInFPS = v));
+
+ static ref Context Ctx(Span context) => ref MemoryMarshal.AsRef(context);
+
+ public override uint GetWrittenAttributes() => 0;
+ public override uint GetReadAttributes() => 0x23db;
+ public override ulong GetReadControlPointMask() => OrientationControlPoint < 0 ? 0 : 1UL << (OrientationControlPoint & 63);
+ public override int GetRequiredContextBytes() => Unsafe.SizeOf();
+
+ public override void InitializeContextData(ParticleCollection particles, Span context) {
+ ref Context ctx = ref Ctx(context);
+ ctx.OrientationVarToken = default;
+ ctx.OrientationMatrixVarToken = default;
+ ctx.VisibilityData.UseVisibility = VisibilityInputs.CPin >= 0;
+ ctx.VisibilityData.CameraBias = VisibilityInputs.CameraBias;
+ }
+
+ public override int GetParticlesToRender(ParticleCollection particles, Span context, int firstParticle, int remainingVertices, int remainingIndices, out int vertsUsed, out int indicesUsed) {
+ int count = Math.Min(Math.Min(particles.ActiveParticles - firstParticle, remainingIndices / 6), remainingVertices / 4);
+ vertsUsed = count * 4;
+ indicesUsed = count * 6;
+ return count;
+ }
+
+ SpriteRenderInfo CreateRenderInfo(ParticleCollection particles) => new() {
+ Particles = particles,
+ Sheet = particles.Sheet,
+ AgeScale = AnimationRate * 1024.0f,
+ AgeScale2 = AnimationRate2 * 1024.0f,
+ VertexOffset = 0
+ };
+
+ public override void Render(IMatRenderContext renderContext, ParticleCollection particles, Span context) {
+ ref Context ctx = ref Ctx(context);
+ IMaterial material = particles.Def!.GetMaterial()!;
+
+ if (ctx.VisibilityData.UseVisibility)
+ BuiltinParticleRenderers.SetupParticleVisibility(particles, ref ctx.VisibilityData, VisibilityInputs, ref ctx.QueryHandle);
+
+ material.FindVarFast("$orientation", ref ctx.OrientationVarToken)?.SetIntValue(OrientationType);
+
+ renderContext.Bind(material);
+
+ if (!material.IsSpriteCard()) {
+ switch (OrientationType) {
+ case 0: RenderNonSpriteCardCameraFacing(particles, ref ctx, renderContext, material); break;
+ case 1: RenderNonSpriteCardZRotating(particles, ref ctx, renderContext, material); break;
+ case 2: RenderNonSpriteCardOriented(particles, ref ctx, renderContext, material, false); break;
+ case 3: RenderNonSpriteCardOriented(particles, ref ctx, renderContext, material, true); break;
+ }
+ return;
+ }
+
+ if (OrientationType == 2) {
+ IMaterialVar? matrixVar = material.FindVarFast("$orientationMatrix", ref ctx.OrientationMatrixVarToken);
+ if (matrixVar != null) {
+ if (OrientationControlPoint < 0)
+ matrixVar.SetMatrixValue(Matrix4x4.Identity);
+ else {
+ particles.GetControlPointTransformAtCurrentTime(OrientationControlPoint, out Matrix3x4 transform);
+ matrixVar.SetMatrixValue((Matrix4x4)transform);
+ }
+ }
+ }
+
+ SpriteRenderInfo info = CreateRenderInfo(particles);
+
+ int maxVertices = renderContext.GetMaxVerticesToRender(material);
+ int maxIndices = renderContext.GetMaxIndicesToRender();
+ int maxParticlesInBatch = Math.Min(maxVertices / 4, maxIndices / 6);
+
+ ParticleRenderData[] sortList = particles.GetRenderList(renderContext, true, out int particleCount, ctx.VisibilityData);
+ int sortEnd = particleCount;
+
+ renderContext.GetWorldSpaceCameraPosition(out Vector3 camera);
+
+ while (particleCount != 0) {
+ int particlesInBatch = Math.Min(maxParticlesInBatch, particleCount);
+ particleCount -= particlesInBatch;
+
+ IMesh mesh = renderContext.GetDynamicMesh(true)!;
+ particles.Mgr!.TallyParticlesRendered(particlesInBatch * 4 * 3);
+
+ MeshBuilder meshBuilder = new();
+ meshBuilder.Begin(mesh, MaterialPrimitiveType.Triangles, particlesInBatch * 4, particlesInBatch * 6);
+ info.VertexOffset = 0;
+
+ bool twoSequence = meshBuilder.TextureCoordinateSize(5) != 0;
+ for (int i = 0; i < particlesInBatch; i++) {
+ ref ParticleRenderData entry = ref sortList[--sortEnd];
+ if (twoSequence)
+ RenderTwoSequenceSpriteCard(ref meshBuilder, ref ctx, ref info, entry.Index, entry, camera);
+ else
+ RenderSpriteCard(ref meshBuilder, ref ctx, ref info, entry.Index, entry, camera);
+ }
+
+ meshBuilder.End();
+ mesh.Draw();
+ }
+ }
+
+ public override void RenderUnsorted(ParticleCollection particles, Span context, IMatRenderContext renderContext, ref MeshBuilder meshBuilder, int vertexOffset, int firstParticle, int particleCount) {
+ ref Context ctx = ref Ctx(context);
+ IMaterial material = particles.Def!.GetMaterial()!;
+
+ if (!material.IsSpriteCard()) {
+ switch (OrientationType) {
+ case 1: RenderUnsortedNonSpriteCardZRotating(particles, ref ctx, renderContext, ref meshBuilder, vertexOffset, firstParticle, particleCount); break;
+ case 2: RenderUnsortedNonSpriteCardOriented(particles, ref ctx, renderContext, ref meshBuilder, vertexOffset, firstParticle, particleCount); break;
+ case 0: Warning($"C_OP_RenderSprites::RenderUnsorted: Attempting to use an unimplemented sprite renderer for system \"{particles.Def.GetName()}\"!\n"); break;
+ }
+ return;
+ }
+
+ SpriteRenderInfo info = CreateRenderInfo(particles);
+ ParticleRenderData[] sortList = particles.GetRenderList(renderContext, false, out int sortCount, ctx.VisibilityData);
+ renderContext.GetWorldSpaceCameraPosition(out Vector3 camera);
+
+ for (int i = 0; i < particleCount; i++)
+ RenderSpriteCard(ref meshBuilder, ref ctx, ref info, firstParticle + i, sortList[sortCount], camera);
+ }
+
+ static void WriteQuadIndices(ref MeshBuilder meshBuilder, ref SpriteRenderInfo info) {
+ int offset = info.VertexOffset;
+ meshBuilder.FastIndex((ushort)offset);
+ meshBuilder.FastIndex((ushort)(offset + 1));
+ meshBuilder.FastIndex((ushort)(offset + 2));
+ meshBuilder.FastIndex((ushort)offset);
+ meshBuilder.FastIndex((ushort)(offset + 2));
+ meshBuilder.FastIndex((ushort)(offset + 3));
+ info.VertexOffset += 4;
+ }
+
+ static ReadOnlySpan CornerIds => [0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f];
+
+ void RenderSpriteCard(ref MeshBuilder meshBuilder, ref Context ctx, ref SpriteRenderInfo info, int particle, in ParticleRenderData sortEntry, in Vector3 camera) {
+ ParticleCollection particles = info.Particles;
+ byte alpha = sortEntry.Alpha;
+
+ Vector3 color = particles.GetVectorAttributeValue(PARTICLE_ATTRIBUTE_TINT_RGB, particle);
+ byte r = BuiltinParticleRenderers.UnitToByte(color.X);
+ byte g = BuiltinParticleRenderers.UnitToByte(color.Y);
+ byte b = BuiltinParticleRenderers.UnitToByte(color.Z);
+ float rotation = particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_ROTATION, particle);
+ float radius = sortEntry.Radius;
+ float yaw = particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_YAW, particle);
+ Vector3 position = BuiltinParticleRenderers.ApplyCameraBias(particles.GetVectorAttributeValue(PARTICLE_ATTRIBUTE_XYZ, particle), camera, ctx.VisibilityData.CameraBias);
+
+ ref readonly SheetSequenceSample sample = ref BuiltinParticleRenderers.DefaultSheetSequence;
+ if (info.Sheet != null) {
+ float ageScale = info.AgeScale;
+ int sequence = (int)particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_SEQUENCE_NUMBER, particle);
+ if (AnimateInFPS)
+ ageScale /= particles.Sheet!.FrameSpan[sequence];
+ sample = ref BuiltinParticleRenderers.SampleOrDefault(in Sheet.GetSampleForSequence(info.Sheet, particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_CREATION_TIME, particle), particles.CurTime, ageScale, sequence));
+ }
+
+ ref readonly SequenceSampleTextureCoords coords0 = ref sample.TextureCoordData[0];
+ ref readonly SequenceSampleTextureCoords coords1 = ref sample.TextureCoordData[1];
+ ReadOnlySpan cornerIds = CornerIds;
+ for (int corner = 0; corner < 4; corner++) {
+ meshBuilder.Position3f(position.X, position.Y, position.Z);
+ meshBuilder.Color4ub(r, g, b, alpha);
+ meshBuilder.TexCoord4f(0, coords0.LeftU0, coords0.TopV0, coords0.RightU0, coords0.BottomV0);
+ meshBuilder.TexCoord4f(1, coords0.LeftU1, coords0.TopV1, coords0.RightU1, coords0.BottomV1);
+ meshBuilder.TexCoord4f(2, sample.BlendFactor, rotation, radius, yaw);
+ meshBuilder.TexCoord2f(3, cornerIds[corner * 2], cornerIds[corner * 2 + 1]);
+ meshBuilder.TexCoord4f(4, coords1.LeftU0, coords1.TopV0, coords1.RightU0, coords1.BottomV0);
+ meshBuilder.AdvanceVertex();
+ }
+
+ WriteQuadIndices(ref meshBuilder, ref info);
+ }
+
+ void RenderTwoSequenceSpriteCard(ref MeshBuilder meshBuilder, ref Context ctx, ref SpriteRenderInfo info, int particle, in ParticleRenderData sortEntry, in Vector3 camera) {
+ ParticleCollection particles = info.Particles;
+ byte alpha = sortEntry.Alpha;
+ float radius = sortEntry.Radius;
+
+ Vector3 color = particles.GetVectorAttributeValue(PARTICLE_ATTRIBUTE_TINT_RGB, particle);
+ byte r = BuiltinParticleRenderers.UnitToByte(color.X);
+ byte g = BuiltinParticleRenderers.UnitToByte(color.Y);
+ byte b = BuiltinParticleRenderers.UnitToByte(color.Z);
+ float rotation = particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_ROTATION, particle);
+ float yaw = particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_YAW, particle);
+ Vector3 position = BuiltinParticleRenderers.ApplyCameraBias(particles.GetVectorAttributeValue(PARTICLE_ATTRIBUTE_XYZ, particle), camera, ctx.VisibilityData.CameraBias);
+
+ ref readonly SheetSequenceSample sample = ref BuiltinParticleRenderers.DefaultSheetSequence;
+ ref readonly SheetSequenceSample sample2 = ref BuiltinParticleRenderers.DefaultSheetSequence;
+ if (info.Sheet != null) {
+ float creationTime = particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_CREATION_TIME, particle);
+ sample = ref BuiltinParticleRenderers.SampleOrDefault(in Sheet.GetSampleForSequence(info.Sheet, creationTime, particles.CurTime, info.AgeScale, (int)particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_SEQUENCE_NUMBER, particle)));
+ sample2 = ref BuiltinParticleRenderers.SampleOrDefault(in Sheet.GetSampleForSequence(info.Sheet, creationTime, particles.CurTime, info.AgeScale2, (int)particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_SEQUENCE_NUMBER1, particle)));
+ }
+
+ ref readonly SequenceSampleTextureCoords coords0 = ref sample.TextureCoordData[0];
+ ref readonly SequenceSampleTextureCoords coords1 = ref sample.TextureCoordData[1];
+ ref readonly SequenceSampleTextureCoords secondCoords = ref sample2.TextureCoordData[0];
+ ReadOnlySpan cornerIds = CornerIds;
+ for (int corner = 0; corner < 4; corner++) {
+ meshBuilder.Position3f(position.X, position.Y, position.Z);
+ meshBuilder.Color4ub(r, g, b, alpha);
+ meshBuilder.TexCoord4f(0, coords0.LeftU0, coords0.TopV0, coords0.RightU0, coords0.BottomV0);
+ meshBuilder.TexCoord4f(1, coords0.LeftU1, coords0.TopV1, coords0.RightU1, coords0.BottomV1);
+ meshBuilder.TexCoord4f(2, sample.BlendFactor, rotation, radius, yaw);
+ meshBuilder.TexCoord2f(3, cornerIds[corner * 2], cornerIds[corner * 2 + 1]);
+ meshBuilder.TexCoord4f(4, coords1.LeftU0, coords1.TopV0, coords1.RightU0, coords1.BottomV0);
+ meshBuilder.TexCoord4f(5, secondCoords.LeftU0, secondCoords.TopV0, secondCoords.RightU0, secondCoords.BottomV0);
+ meshBuilder.TexCoord4f(6, secondCoords.LeftU1, secondCoords.TopV1, secondCoords.RightU1, secondCoords.BottomV1);
+ meshBuilder.TexCoord4f(7, sample2.BlendFactor, 0, 0, 0);
+ meshBuilder.AdvanceVertex();
+ }
+
+ WriteQuadIndices(ref meshBuilder, ref info);
+ }
+
+ ref readonly SheetSequenceSample NonSpriteCardSample(ParticleCollection particles, Sheet? sheet, float ageScale, int particle) {
+ if (sheet == null)
+ return ref BuiltinParticleRenderers.DefaultSheetSequence;
+ return ref BuiltinParticleRenderers.SampleOrDefault(in Sheet.GetSampleForSequence(sheet, particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_CREATION_TIME, particle), particles.CurTime, ageScale, (int)particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_SEQUENCE_NUMBER, particle)));
+ }
+
+ void RenderNonSpriteCardCameraFacing(ParticleCollection particles, ref Context ctx, IMatRenderContext renderContext, IMaterial material) {
+ ParticleRenderData[] sortList = particles.GetRenderList(renderContext, true, out int particleCount, ctx.VisibilityData);
+ int sortEnd = particleCount;
+
+ float cameraBias = ctx.VisibilityData.CameraBias;
+ renderContext.GetWorldSpaceCameraPosition(out Vector3 camera);
+
+ renderContext.GetMatrix(MaterialMatrixMode.View, out Matrix4x4 tempView);
+ renderContext.EnableUserClipTransformOverride(true);
+ renderContext.UserClipTransform(tempView);
+ renderContext.MatrixMode(MaterialMatrixMode.View);
+ renderContext.PushMatrix();
+ renderContext.LoadIdentity();
+
+ int maxVertices = renderContext.GetMaxVerticesToRender(material);
+ int maxIndices = renderContext.GetMaxIndicesToRender();
+ int maxParticlesInBatch = Math.Min(maxVertices / 4, maxIndices / 6);
+ Sheet? sheet = particles.Sheet;
+
+ while (particleCount != 0) {
+ int particlesInBatch = Math.Min(maxParticlesInBatch, particleCount);
+ particleCount -= particlesInBatch;
+
+ particles.Mgr!.TallyParticlesRendered(particlesInBatch * 4);
+ IMesh mesh = renderContext.GetDynamicMesh(true)!;
+ MeshBuilder meshBuilder = new();
+ meshBuilder.Begin(mesh, MaterialPrimitiveType.Quads, particlesInBatch);
+
+ for (int i = 0; i < particlesInBatch; i++) {
+ ref ParticleRenderData entry = ref sortList[--sortEnd];
+ byte alpha = entry.Alpha;
+ if (alpha == 0)
+ continue;
+
+ int particle = entry.Index;
+ float radius = entry.Radius;
+ Vector3 color = particles.GetVectorAttributeValue(PARTICLE_ATTRIBUTE_TINT_RGB, particle);
+ Vector3 worldPosition = BuiltinParticleRenderers.ApplyCameraBias(particles.GetVectorAttributeValue(PARTICLE_ATTRIBUTE_XYZ, particle), camera, cameraBias);
+
+ MathLib.Vector3DMultiplyPosition(in tempView, in worldPosition, out Vector3 viewPosition);
+ if (!float.IsFinite(viewPosition.X))
+ continue;
+
+ float rotation = particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_ROTATION, particle);
+ float ca = MathF.Cos(rotation);
+ float sa = MathF.Sin(rotation);
+
+ ref readonly SheetSequenceSample sample = ref BuiltinParticleRenderers.DefaultSheetSequence;
+ if (sheet != null) {
+ int sequence = (int)particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_SEQUENCE_NUMBER, particle);
+ float ageScale;
+ if (FitCycleToLifetime) {
+ float lifetime = particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_LIFE_DURATION, particle);
+ ageScale = lifetime > 0.0f ? 1024.0f / lifetime : 0.0f;
+ }
+ else {
+ ageScale = AnimationRate * 1024.0f;
+ if (AnimateInFPS)
+ ageScale /= sheet.FrameSpan[sequence];
+ }
+ sample = ref BuiltinParticleRenderers.SampleOrDefault(in Sheet.GetSampleForSequence(sheet, particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_CREATION_TIME, particle), particles.CurTime, ageScale, sequence));
+ }
+ ref readonly SequenceSampleTextureCoords coords = ref sample.TextureCoordData[0];
+
+ byte r = BuiltinParticleRenderers.UnitToByte(color.X);
+ byte g = BuiltinParticleRenderers.UnitToByte(color.Y);
+ byte b = BuiltinParticleRenderers.UnitToByte(color.Z);
+
+ meshBuilder.Position3f(viewPosition.X + (-ca + sa) * radius, viewPosition.Y + (-sa - ca) * radius, viewPosition.Z);
+ meshBuilder.Color4ub(r, g, b, alpha);
+ meshBuilder.TexCoord2f(0, coords.LeftU0, coords.BottomV0);
+ meshBuilder.AdvanceVertex();
+
+ meshBuilder.Position3f(viewPosition.X + (-ca - sa) * radius, viewPosition.Y + (-sa + ca) * radius, viewPosition.Z);
+ meshBuilder.Color4ub(r, g, b, alpha);
+ meshBuilder.TexCoord2f(0, coords.LeftU0, coords.TopV0);
+ meshBuilder.AdvanceVertex();
+
+ meshBuilder.Position3f(viewPosition.X + (ca - sa) * radius, viewPosition.Y + (sa + ca) * radius, viewPosition.Z);
+ meshBuilder.Color4ub(r, g, b, alpha);
+ meshBuilder.TexCoord2f(0, coords.RightU0, coords.TopV0);
+ meshBuilder.AdvanceVertex();
+
+ meshBuilder.Position3f(viewPosition.X + (ca + sa) * radius, viewPosition.Y + (sa - ca) * radius, viewPosition.Z);
+ meshBuilder.Color4ub(r, g, b, alpha);
+ meshBuilder.TexCoord2f(0, coords.RightU0, coords.BottomV0);
+ meshBuilder.AdvanceVertex();
+ }
+
+ meshBuilder.End();
+ mesh.Draw();
+ }
+
+ renderContext.EnableUserClipTransformOverride(false);
+ renderContext.MatrixMode(MaterialMatrixMode.View);
+ renderContext.PopMatrix();
+ }
+
+ static void EmitRotatedQuad(ref MeshBuilder meshBuilder, ref SpriteRenderInfo info, in Vector3 position, in Vector3 right, in Vector3 up, float a, float b, in SequenceSampleTextureCoords coords, bool oriented, byte red, byte green, byte blue, byte alpha) {
+ Span corners = oriented
+ ? [new(a, b), new(-b, a), new(-a, -b), new(b, -a)]
+ : [new(a, b), new(b, -a), new(-a, -b), new(-b, a)];
+ Span texCoords = oriented
+ ? [new(coords.RightU0, coords.BottomV0), new(coords.RightU0, coords.TopV0), new(coords.LeftU0, coords.TopV0), new(coords.LeftU0, coords.BottomV0)]
+ : [new(coords.LeftU0, coords.BottomV0), new(coords.LeftU0, coords.TopV0), new(coords.RightU0, coords.TopV0), new(coords.RightU0, coords.BottomV0)];
+
+ for (int i = 0; i < 4; i++) {
+ Vector3 vertex = position + right * corners[i].X + up * corners[i].Y;
+ meshBuilder.Position3f(vertex.X, vertex.Y, vertex.Z);
+ meshBuilder.Color4ub(red, green, blue, alpha);
+ meshBuilder.TexCoord2f(0, texCoords[i].X, texCoords[i].Y);
+ meshBuilder.AdvanceVertex();
+ }
+
+ WriteQuadIndices(ref meshBuilder, ref info);
+ }
+
+ void RenderNonSpriteCardZRotating(ref MeshBuilder meshBuilder, ref Context ctx, ref SpriteRenderInfo info, int particle, in Vector3 camera, in ParticleRenderData sortEntry) {
+ byte alpha = sortEntry.Alpha;
+ if (alpha == 0)
+ return;
+
+ ParticleCollection particles = info.Particles;
+ float radius = sortEntry.Radius;
+ Vector3 position = BuiltinParticleRenderers.ApplyCameraBias(particles.GetVectorAttributeValue(PARTICLE_ATTRIBUTE_XYZ, particle), camera, ctx.VisibilityData.CameraBias);
+
+ if (Vector3.Distance(position, camera) < radius * 0.5f)
+ return;
+
+ Vector3 color = particles.GetVectorAttributeValue(PARTICLE_ATTRIBUTE_TINT_RGB, particle);
+ float rotation = particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_ROTATION, particle);
+
+ float invLength = 1.0f / MathF.Sqrt(camera.Y * camera.Y + camera.X * camera.X + 1e-10f);
+ Vector3 right = new Vector3(-camera.Y, camera.X, 0.0f) * invLength * radius;
+ Vector3 up = new(0.0f, 0.0f, radius);
+
+ ref readonly SheetSequenceSample sample = ref NonSpriteCardSample(particles, info.Sheet, info.AgeScale, particle);
+
+ float ca = MathF.Cos(rotation);
+ float sa = MathF.Sin(-rotation);
+ EmitRotatedQuad(ref meshBuilder, ref info, position, right, up, -(ca + sa), sa - ca, sample.TextureCoordData[0], false,
+ BuiltinParticleRenderers.UnitToByte(color.X), BuiltinParticleRenderers.UnitToByte(color.Y), BuiltinParticleRenderers.UnitToByte(color.Z), alpha);
+ }
+
+ void RenderNonSpriteCardOriented(ref MeshBuilder meshBuilder, ref Context ctx, ref SpriteRenderInfo info, int particle, in Vector3 camera, in ParticleRenderData sortEntry, bool useYaw) {
+ byte alpha = sortEntry.Alpha;
+ if (alpha == 0)
+ return;
+
+ ParticleCollection particles = info.Particles;
+ float radius = sortEntry.Radius;
+ Vector3 position = BuiltinParticleRenderers.ApplyCameraBias(particles.GetVectorAttributeValue(PARTICLE_ATTRIBUTE_XYZ, particle), camera, ctx.VisibilityData.CameraBias);
+
+ if (Vector3.Distance(position, camera) < radius * 0.5f)
+ return;
+
+ Vector3 color = particles.GetVectorAttributeValue(PARTICLE_ATTRIBUTE_TINT_RGB, particle);
+ float rotation = particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_ROTATION, particle);
+
+ Vector3 right, up;
+ if (OrientationControlPoint < 0) {
+ right = new(1.0f, 0.0f, 0.0f);
+ up = new(0.0f, -1.0f, 0.0f);
+ }
+ else {
+ ref readonly ParticleControlPoint cp = ref particles.ControlPoint(OrientationControlPoint);
+ right = cp.ForwardVector;
+ up = cp.RightVector;
+ }
+
+ if (useYaw) {
+ float yaw = particles.GetFloatAttributeValue(PARTICLE_ATTRIBUTE_YAW, particle);
+ if (yaw != 0.0f) {
+ MathLib.MatrixBuildRotationAboutAxis(out Matrix4x4 rotationMatrix, up, yaw * (180.0f / MathF.PI));
+ MathLib.Vector3DMultiply(in rotationMatrix, in right, out right);
+ }
+ }
+
+ ref readonly SheetSequenceSample sample = ref NonSpriteCardSample(particles, info.Sheet, info.AgeScale, particle);
+
+ float ca = MathF.Cos(rotation);
+ float sa = MathF.Sin(-rotation);
+ EmitRotatedQuad(ref meshBuilder, ref info, position, right * radius, up * radius, ca - sa, -(ca + sa), sample.TextureCoordData[0], true,
+ BuiltinParticleRenderers.UnitToByte(color.X), BuiltinParticleRenderers.UnitToByte(color.Y), BuiltinParticleRenderers.UnitToByte(color.Z), alpha);
+ }
+
+ void RenderNonSpriteCardBatched(ParticleCollection particles, ref Context ctx, IMatRenderContext renderContext, IMaterial material, int orientation, bool useYaw) {
+ renderContext.GetWorldSpaceCameraPosition(out Vector3 camera);
+
+ SpriteRenderInfo info = CreateRenderInfo(particles);
+ info.AgeScale2 = 0.0f;
+
+ ParticleRenderData[] sortList = particles.GetRenderList(renderContext, true, out int particleCount, ctx.VisibilityData);
+ int sortEnd = particleCount;
+
+ int maxVertices = renderContext.GetMaxVerticesToRender(material);
+ int maxIndices = renderContext.GetMaxIndicesToRender();
+ int maxParticlesInBatch = Math.Min(maxVertices / 4, maxIndices / 6);
+
+ while (particleCount != 0) {
+ int particlesInBatch = Math.Min(maxParticlesInBatch, particleCount);
+ particleCount -= particlesInBatch;
+
+ particles.Mgr!.TallyParticlesRendered(particlesInBatch * 4 * 3);
+ IMesh mesh = renderContext.GetDynamicMesh(true)!;
+ MeshBuilder meshBuilder = new();
+ meshBuilder.Begin(mesh, MaterialPrimitiveType.Triangles, particlesInBatch * 4, particlesInBatch * 6);
+ info.VertexOffset = 0;
+
+ for (int i = 0; i < particlesInBatch; i++) {
+ ref ParticleRenderData entry = ref sortList[--sortEnd];
+ if (orientation == 1)
+ RenderNonSpriteCardZRotating(ref meshBuilder, ref ctx, ref info, entry.Index, camera, entry);
+ else
+ RenderNonSpriteCardOriented(ref meshBuilder, ref ctx, ref info, entry.Index, camera, entry, useYaw);
+ }
+
+ meshBuilder.End();
+ mesh.Draw();
+ }
+ }
+
+ void RenderNonSpriteCardZRotating(ParticleCollection particles, ref Context ctx, IMatRenderContext renderContext, IMaterial material)
+ => RenderNonSpriteCardBatched(particles, ref ctx, renderContext, material, 1, false);
+
+ void RenderNonSpriteCardOriented(ParticleCollection particles, ref Context ctx, IMatRenderContext renderContext, IMaterial material, bool useYaw)
+ => RenderNonSpriteCardBatched(particles, ref ctx, renderContext, material, 2, useYaw);
+
+ void RenderUnsortedNonSpriteCardZRotating(ParticleCollection particles, ref Context ctx, IMatRenderContext renderContext, ref MeshBuilder meshBuilder, int vertexOffset, int firstParticle, int particleCount) {
+ renderContext.GetWorldSpaceCameraPosition(out Vector3 camera);
+ SpriteRenderInfo info = CreateRenderInfo(particles);
+ info.VertexOffset = vertexOffset;
+ ParticleRenderData[] sortList = particles.GetRenderList(renderContext, false, out int sortCount, ctx.VisibilityData);
+ for (int i = 0; i < particleCount; i++)
+ RenderNonSpriteCardZRotating(ref meshBuilder, ref ctx, ref info, firstParticle + i, camera, sortList[sortCount]);
+ }
+
+ void RenderUnsortedNonSpriteCardOriented(ParticleCollection particles, ref Context ctx, IMatRenderContext renderContext, ref MeshBuilder meshBuilder, int vertexOffset, int firstParticle, int particleCount) {
+ renderContext.GetWorldSpaceCameraPosition(out Vector3 camera);
+ SpriteRenderInfo info = CreateRenderInfo(particles);
+ info.VertexOffset = vertexOffset;
+ ParticleRenderData[] sortList = particles.GetRenderList(renderContext, false, out int sortCount, ctx.VisibilityData);
+ for (int i = 0; i < particleCount; i++)
+ RenderNonSpriteCardOriented(ref meshBuilder, ref ctx, ref info, firstParticle + i, camera, sortList[sortCount], false);
+ }
+}
diff --git a/Source.Particles/ParticleCollection.cs b/Source.Particles/ParticleCollection.cs
index ed876b86..2c41e4ae 100644
--- a/Source.Particles/ParticleCollection.cs
+++ b/Source.Particles/ParticleCollection.cs
@@ -77,6 +77,7 @@ public class ParticleCollection
public readonly object?[] CollisionCacheData = new object?[NUM_COLLISION_CACHE_MODES];
public ParticleCollection? Parent;
public ParticleCollection? Children;
+ public Sheet? Sheet;
protected bool BoundsValid;
protected Vector3 MinBounds;
@@ -166,6 +167,7 @@ internal void Init(ParticleSystemDefinition def, float delay, int randomSeed) {
Mgr = def.Mgr;
LinkIntoDefList();
InitStorage(def);
+ Sheet = Mgr.FindOrLoadSheet(PrecachedMaterial());
IsScrubbable = randomSeed != 0;
if (randomSeed == 0)
@@ -255,6 +257,7 @@ public void Destroy() {
Memory = [];
OperatorContextData = null;
+ Sheet = null;
Array.Clear(CollisionCacheData);
foreach (ModelHitBoxesInfo info in ControlPointHitBoxes) {
info.HitBoxes = null;
@@ -1440,4 +1443,143 @@ bool ComputeRequiresOrderInvariance() {
public int GetRendererCount() => PrecachedMaterial() != null ? Def!.Renderers.Count : 0;
public ParticleOperatorInstance? GetRenderer(int i) => PrecachedMaterial() != null ? Def!.Renderers[i] : null;
public Span GetRendererContext(int i) => PrecachedMaterial() != null ? ContextSpan(Def!.RenderersCtxOffsets[i]) : default;
+
+ public void Render(IMatRenderContext renderContext, bool translucentOnly = false, object? cameraObject = null) {
+ IMaterial? material = PrecachedMaterial();
+ if (material == null)
+ return;
+
+ NextSleepTime = Math.Max(NextSleepTime, Mgr!.GetLastSimulationTime() + Def!.NoDrawTimeToGoToSleep);
+
+ if (ActiveParticles != 0 && (!translucentOnly || material.IsTranslucent())) {
+ for (int i = 0; i < Def.Renderers.Count; i++) {
+ ParticleOperatorInstance op = Def.Renderers[i];
+ if (!CheckIfOperatorShouldRun(op, out _))
+ continue;
+
+ Span context = ContextSpan(Def.RenderersCtxOffsets[i]);
+ if (!Def.ScreenSpaceEffect) {
+ op.Render(renderContext, this, context);
+ continue;
+ }
+
+ renderContext.MatrixMode(MaterialMatrixMode.View);
+ renderContext.PushMatrix();
+ renderContext.LoadIdentity();
+ renderContext.MatrixMode(MaterialMatrixMode.Projection);
+ renderContext.PushMatrix();
+ renderContext.LoadIdentity();
+ renderContext.Ortho(-100.0, -100.0, 100.0, 100.0, -100.0, 100.0);
+ op.Render(renderContext, this, context);
+ renderContext.MatrixMode(MaterialMatrixMode.View);
+ renderContext.PopMatrix();
+ renderContext.MatrixMode(MaterialMatrixMode.Projection);
+ renderContext.PopMatrix();
+ }
+ }
+
+ for (ParticleCollection? child = Children; child != null; child = child.Next)
+ child.Render(renderContext, translucentOnly, cameraObject);
+ }
+
+ static readonly ParticleRenderData[] SortBuffer = new ParticleRenderData[MAX_PARTICLES_IN_A_SYSTEM + 4];
+
+ public ParticleRenderData[] GetRenderList(IMatRenderContext renderContext, bool sorted, out int particleCount, in ParticleVisibilityData visibilityData) {
+ bool sort = sorted && Def!.ShouldSort;
+ renderContext.GetWorldSpaceCameraPosition(out Vector3 camera);
+ if (camera.X < MinBounds.X || camera.X > MaxBounds.X || camera.Y < MinBounds.Y || camera.Y > MaxBounds.Y || camera.Z < MinBounds.Z || camera.Z > MaxBounds.Z)
+ particleCount = GenerateSortedIndexList(camera, default, false, visibilityData, sort);
+ else {
+ renderContext.GetWorldSpaceCameraVectors(out Vector3 forward, out _, out _);
+ particleCount = GenerateSortedIndexList(camera, forward, true, visibilityData, sort);
+ }
+ return SortBuffer;
+ }
+
+ int GenerateSortedIndexList(Vector3 camera, Vector3 forward, bool cull, in ParticleVisibilityData visibilityData, bool sorted) {
+ int particleCount = ActiveParticles;
+ int blockCount = Math.Max(1, (particleCount + 3) / 4);
+ ParticleRenderData[] output = SortBuffer;
+
+ for (int i = 0; i < blockCount * 4; i++) {
+ Vector3 position = GetVectorAttributeValue(PARTICLE_ATTRIBUTE_XYZ, i);
+ float alpha = GetFloatAttributeValue(PARTICLE_ATTRIBUTE_ALPHA, i) * GetFloatAttributeValue(PARTICLE_ATTRIBUTE_ALPHA2, i);
+ float radius = GetFloatAttributeValue(PARTICLE_ATTRIBUTE_RADIUS, i);
+ if (visibilityData.UseVisibility) {
+ alpha = Math.Clamp(alpha * visibilityData.AlphaVisibility, 0.0f, 1.0f);
+ radius *= visibilityData.RadiusVisibility;
+ }
+
+ Vector3 delta = position - camera;
+ byte alphaByte = (byte)((int)MathF.Round(alpha * 255.0f) & 0xFF);
+ if (cull && !(0.0f <= Vector3.Dot(forward, delta)))
+ alphaByte = 0;
+
+ ref ParticleRenderData entry = ref output[i];
+ entry.SortKey = sorted ? delta.LengthSquared() : 0.0f;
+ entry.Index = i;
+ entry.Radius = radius;
+ entry.Alpha = alphaByte;
+ }
+
+ if (sorted)
+ HeapSortByKey(output, particleCount);
+
+ return particleCount;
+ }
+
+ static int SortKeyBits(in ParticleRenderData data) => BitConverter.SingleToInt32Bits(data.SortKey);
+
+ static void HeapSortByKey(ParticleRenderData[] data, int count) {
+ if (count < 2)
+ return;
+
+ for (int i = 1; i < count; i++) {
+ int node = i;
+ while (node != 0) {
+ int parent = ((node + 1) >> 1) - 1;
+ if (SortKeyBits(data[parent]) >= SortKeyBits(data[node]))
+ break;
+ (data[parent], data[node]) = (data[node], data[parent]);
+ node = parent;
+ }
+ }
+
+ int end = count - 1;
+ (data[0], data[end]) = (data[end], data[0]);
+ while (end != 1) {
+ int parent = 0;
+ int child = 1;
+ while (true) {
+ int pick = child;
+ if (child + 1 < end && SortKeyBits(data[child]) < SortKeyBits(data[child + 1]))
+ pick = child + 1;
+ if (SortKeyBits(data[pick]) <= SortKeyBits(data[parent]))
+ break;
+ (data[parent], data[pick]) = (data[pick], data[parent]);
+ child = pick * 2 + 1;
+ if (child >= end)
+ break;
+ parent = pick;
+ }
+ end--;
+ (data[0], data[end]) = (data[end], data[0]);
+ }
+ }
+}
+
+public struct ParticleRenderData
+{
+ public float SortKey;
+ public int Index;
+ public float Radius;
+ public byte Alpha;
+}
+
+public struct ParticleVisibilityData
+{
+ public float AlphaVisibility;
+ public float RadiusVisibility;
+ public float CameraBias;
+ public bool UseVisibility;
}
diff --git a/Source.Particles/ParticleOperator.cs b/Source.Particles/ParticleOperator.cs
index be6920f4..371f9d21 100644
--- a/Source.Particles/ParticleOperator.cs
+++ b/Source.Particles/ParticleOperator.cs
@@ -1,5 +1,8 @@
using Datamodel;
+using Source.Common.MaterialSystem;
+using Source.Common.Mathematics;
+
namespace Source.Particles;
public interface IParticleOperatorDefinition
@@ -104,6 +107,19 @@ public void InitNewParticles(ParticleCollection particles, int firstParticle, in
InitNewParticlesScalar(particles, firstParticle + (particleCount & ~3), particleCount & 3, attributeWriteMask, context);
}
+ public virtual void AddForces(Span accumulatedForces, ParticleCollection particles, int blocks, float strength, Span context) { }
+
+ public virtual void SetupConstraintPerFrameData(ParticleCollection particles, Span context) { }
+ public virtual bool EnforceConstraint(int startBlock, int endBlock, ParticleCollection particles, Span context, int activeParticles) => false;
+
+ public virtual void Render(IMatRenderContext renderContext, ParticleCollection particles, Span context) { }
+ public virtual int GetParticlesToRender(ParticleCollection particles, Span context, int firstParticle, int remainingVertices, int remainingIndices, out int vertsUsed, out int indicesUsed) {
+ vertsUsed = 0;
+ indicesUsed = 0;
+ return 0;
+ }
+ public virtual void RenderUnsorted(ParticleCollection particles, Span context, IMatRenderContext renderContext, ref MeshBuilder meshBuilder, int vertexOffset, int firstParticle, int particleCount) { }
+
public virtual bool IsBatchable() => true;
public virtual bool IsFinalConstraint() => false;
public virtual bool InitMultipleOverride() => false;
diff --git a/Source.Particles/ParticleSystemMgr.cs b/Source.Particles/ParticleSystemMgr.cs
index 6604bc71..ade05cdc 100644
--- a/Source.Particles/ParticleSystemMgr.cs
+++ b/Source.Particles/ParticleSystemMgr.cs
@@ -258,4 +258,223 @@ public void UncacheAllParticleSystems() {
}
public void RecreateDictionary() => Dictionary = new ParticleSystemDictionary(this);
+
+ readonly Dictionary SheetList = new(StringComparer.OrdinalIgnoreCase);
+
+ public Sheet? FindOrLoadSheet(string fileName, ITexture texture) {
+ if (!ShouldLoadSheets_)
+ return null;
+
+ if (SheetList.TryGetValue(fileName, out Sheet? sheet))
+ return sheet;
+
+ Span data = texture.GetResourceData(VTF_RSRC_SHEET);
+ sheet = data.IsEmpty ? null : new Sheet(data);
+ SheetList[fileName] = sheet;
+ return sheet;
+ }
+
+ public Sheet? FindOrLoadSheet(IMaterial? material) {
+ if (material == null)
+ return null;
+
+ IMaterialVar var = material.FindVar("$basetexture", out bool found, true);
+ if (!found || var == null || !var.IsTexture())
+ return null;
+
+ ITexture? texture = var.GetTextureValue();
+ if (texture == null || texture.IsError())
+ return null;
+
+ return FindOrLoadSheet(new string(texture.GetName()), texture);
+ }
+
+ public void FlushAllSheets() => SheetList.Clear();
+
+ const uint VTF_RSRC_SHEET = 0x10;
+
+ static bool DidAddSimulationOperators;
+ static bool DidAddRenderingOperators;
+
+ public void AddBuiltinSimulationOperators() {
+ if (DidAddSimulationOperators)
+ return;
+ DidAddSimulationOperators = true;
+ BuiltinParticleOperators.AddBuiltInParticleOperators(this);
+ BuiltinParticleInitializers.AddBuiltInParticleInitializers(this);
+ BuiltinParticleEmitters.AddBuiltInParticleEmitters(this);
+ }
+
+ public void AddBuiltinRenderingOperators() {
+ if (DidAddRenderingOperators)
+ return;
+ DidAddRenderingOperators = true;
+ BuiltinParticleRenderers.AddBuiltInParticleRenderers(this);
+ }
+
+ int ParticleVertexCount;
+ int ParticleIndexCount;
+ bool FrameWarningNeeded;
+
+ public void TallyParticlesRendered(int vertexCount, int indexCount = 0) {
+ int previous = ParticleVertexCount;
+ ParticleIndexCount += indexCount;
+ ParticleVertexCount += vertexCount;
+ if (previous + vertexCount > 50000)
+ FrameWarningNeeded = true;
+ }
+
+ sealed class RenderCacheEntry
+ {
+ public IMaterial? Material;
+ public readonly List Collections = [];
+ }
+
+ struct BatchStep
+ {
+ public ParticleCollection Particles;
+ public int RendererIndex;
+ public int FirstParticle;
+ public int ParticleCount;
+ public int VertCount;
+ }
+
+ sealed class RenderCacheBatch
+ {
+ public readonly List Steps = [];
+ public int VertCount;
+ public int IndexCount;
+ }
+
+ readonly List RenderCache = [];
+ readonly List Batches = [];
+
+ public void ResetRenderCache() {
+ foreach (RenderCacheEntry entry in RenderCache)
+ entry.Collections.Clear();
+ }
+
+ public void AddToRenderCache(ParticleCollection particles) {
+ if (!particles.IsValid())
+ return;
+
+ IMaterial material = particles.Def!.GetMaterial()!;
+ if (material.IsTranslucent())
+ return;
+
+ particles.NextSleepTime = Math.Max(particles.NextSleepTime, GetLastSimulationTime() + particles.Def.NoDrawTimeToGoToSleep);
+
+ RenderCacheEntry? cache = null;
+ foreach (RenderCacheEntry entry in RenderCache) {
+ if (entry.Material == material) {
+ cache = entry;
+ break;
+ }
+ }
+
+ if (cache == null) {
+ cache = new() { Material = material };
+ RenderCache.Add(cache);
+ }
+
+ cache.Collections.Add(particles);
+
+ for (ParticleCollection? child = particles.Children; child != null; child = child.Next)
+ AddToRenderCache(child);
+ }
+
+ void BuildBatchList(RenderCacheEntry cache, IMatRenderContext renderContext) {
+ Batches.Clear();
+
+ int maxVertices = renderContext.GetMaxVerticesToRender(cache.Material);
+ int maxIndices = renderContext.GetMaxIndicesToRender();
+
+ RenderCacheBatch batch = new();
+ Batches.Add(batch);
+
+ foreach (ParticleCollection particles in cache.Collections) {
+ int rendererCount = particles.GetRendererCount();
+ if (!particles.IsValid() || rendererCount <= 0)
+ continue;
+
+ for (int i = 0; i < rendererCount; i++) {
+ ParticleOperatorInstance renderer = particles.GetRenderer(i)!;
+ int firstParticle = 0;
+ while (firstParticle < particles.ActiveParticles) {
+ int count = renderer.GetParticlesToRender(particles, particles.GetRendererContext(i), firstParticle, maxVertices, maxIndices, out int vertCount, out int indexCount);
+ int stepFirst = firstParticle;
+ firstParticle += count;
+
+ if (count < 1) {
+ if (batch.VertCount == 0)
+ break;
+ batch = new();
+ Batches.Add(batch);
+ if (firstParticle >= particles.ActiveParticles)
+ break;
+ continue;
+ }
+
+ batch.Steps.Add(new() {
+ Particles = particles,
+ RendererIndex = i,
+ FirstParticle = stepFirst,
+ ParticleCount = count,
+ VertCount = vertCount
+ });
+ batch.VertCount += vertCount;
+ batch.IndexCount += indexCount;
+ }
+ }
+ }
+
+ RenderCacheBatch last = Batches[^1];
+ if (last.VertCount <= 0 || last.IndexCount <= 0)
+ Batches.RemoveAt(Batches.Count - 1);
+ }
+
+ public void DrawRenderCache(bool shadowDepth) {
+ if (RenderCache.Count == 0)
+ return;
+
+ using MatRenderContextPtr renderContext = new(Singleton());
+
+ renderContext.MatrixMode(MaterialMatrixMode.Model);
+ renderContext.PushMatrix();
+ renderContext.LoadIdentity();
+
+ foreach (RenderCacheEntry cache in RenderCache) {
+ if (cache.Collections.Count == 0)
+ continue;
+
+ IMaterial? material = shadowDepth ? ShadowDepthMaterial : cache.Material;
+ BuildBatchList(cache, renderContext.Context);
+ if (Batches.Count == 0)
+ continue;
+
+ renderContext.Bind(material);
+ IMesh mesh = renderContext.GetDynamicMesh(true)!;
+ foreach (RenderCacheBatch batch in Batches) {
+ TallyParticlesRendered(batch.VertCount * 3, batch.IndexCount * 3);
+
+ MeshBuilder meshBuilder = new();
+ meshBuilder.Begin(mesh, MaterialPrimitiveType.Triangles, batch.VertCount, batch.IndexCount);
+
+ int vertexOffset = 0;
+ foreach (BatchStep step in batch.Steps) {
+ ParticleOperatorInstance renderer = step.Particles.GetRenderer(step.RendererIndex)!;
+ renderer.RenderUnsorted(step.Particles, step.Particles.GetRendererContext(step.RendererIndex), renderContext.Context, ref meshBuilder, vertexOffset, step.FirstParticle, step.ParticleCount);
+ vertexOffset += step.VertCount;
+ }
+
+ meshBuilder.End();
+ mesh.Draw();
+ }
+ }
+
+ ResetRenderCache();
+
+ renderContext.MatrixMode(MaterialMatrixMode.Model);
+ renderContext.PopMatrix();
+ }
}
diff --git a/Source.Particles/Sheet.cs b/Source.Particles/Sheet.cs
new file mode 100644
index 00000000..e1d9c7a3
--- /dev/null
+++ b/Source.Particles/Sheet.cs
@@ -0,0 +1,231 @@
+using System.Buffers.Binary;
+using System.Runtime.CompilerServices;
+
+namespace Source.Particles;
+
+public struct SequenceSampleTextureCoords
+{
+ public float LeftU0;
+ public float TopV0;
+ public float RightU0;
+ public float BottomV0;
+
+ public float LeftU1;
+ public float TopV1;
+ public float RightU1;
+ public float BottomV1;
+}
+
+[InlineArray(Sheet.MAX_IMAGES_PER_FRAME_IN_MEMORY)]
+public struct SequenceSampleTextureCoordsArray
+{
+ SequenceSampleTextureCoords Element;
+}
+
+public struct SheetSequenceSample
+{
+ public SequenceSampleTextureCoordsArray TextureCoordData;
+ public float BlendFactor;
+}
+
+public sealed class Sheet
+{
+ public const int MAX_SEQUENCES = 64;
+ public const int SEQUENCE_SAMPLE_COUNT = 1024;
+ public const int MAX_IMAGES_PER_FRAME_ON_DISK = 4;
+ public const int MAX_IMAGES_PER_FRAME_IN_MEMORY = 2;
+
+ public readonly SheetSequenceSample[]?[] Samples = new SheetSequenceSample[]?[MAX_SEQUENCES];
+ public readonly bool[] Clamp = new bool[MAX_SEQUENCES];
+ public readonly bool[] SequenceIsCopyOfAnotherSequence = new bool[MAX_SEQUENCES];
+ public readonly int[] NumFrames = new int[MAX_SEQUENCES];
+ public readonly float[] FrameSpan = new float[MAX_SEQUENCES];
+
+ ref struct Reader(ReadOnlySpan data)
+ {
+ readonly ReadOnlySpan Data = data;
+ int Position;
+
+ public int GetInt() {
+ if (Position + 4 > Data.Length)
+ return 0;
+ int value = BinaryPrimitives.ReadInt32LittleEndian(Data[Position..]);
+ Position += 4;
+ return value;
+ }
+
+ public float GetFloat() {
+ if (Position + 4 > Data.Length)
+ return 0;
+ float value = BinaryPrimitives.ReadSingleLittleEndian(Data[Position..]);
+ Position += 4;
+ return value;
+ }
+ }
+
+ public Sheet(ReadOnlySpan data) {
+ Reader buf = new(data);
+
+ int version = buf.GetInt();
+ int numCoordsPerFrame = version != 0 ? MAX_IMAGES_PER_FRAME_ON_DISK : 1;
+
+ int numSequences = buf.GetInt();
+
+ float[] interpKnot = new float[SEQUENCE_SAMPLE_COUNT];
+ float[] interpValue = new float[SEQUENCE_SAMPLE_COUNT];
+ SheetSequenceSample[] samples = new SheetSequenceSample[SEQUENCE_SAMPLE_COUNT];
+
+ while (numSequences-- != 0) {
+ int sequenceNumber = buf.GetInt();
+ if ((uint)sequenceNumber >= MAX_SEQUENCES) {
+ Warning($"sequence number {sequenceNumber} too high in sheet file!!!\n");
+ return;
+ }
+
+ Clamp[sequenceNumber] = buf.GetInt() != 0;
+ int frameCount = buf.GetInt();
+ NumFrames[sequenceNumber] = frameCount;
+
+ int timeSamples = frameCount == 1 ? 1 : SEQUENCE_SAMPLE_COUNT;
+ SheetSequenceSample[] outSamples = new SheetSequenceSample[timeSamples];
+ Samples[sequenceNumber] = outSamples;
+
+ int totalSequenceTime = (int)buf.GetFloat();
+ float curTime = 0.0f;
+ for (int frame = 0; frame < frameCount && frame < SEQUENCE_SAMPLE_COUNT; frame++) {
+ float thisDuration = buf.GetFloat();
+ interpValue[frame] = frame;
+ interpKnot[frame] = SEQUENCE_SAMPLE_COUNT / (float)totalSequenceTime * curTime;
+
+ ref SheetSequenceSample seq = ref samples[frame];
+ seq.BlendFactor = 0.0f;
+ for (int image = 0; image < numCoordsPerFrame; image++) {
+ float left = buf.GetFloat();
+ float top = buf.GetFloat();
+ float right = buf.GetFloat();
+ float bottom = buf.GetFloat();
+ if (image >= MAX_IMAGES_PER_FRAME_IN_MEMORY)
+ continue;
+
+ ref SequenceSampleTextureCoords s = ref seq.TextureCoordData[image];
+ s.LeftU0 = left;
+ s.TopV0 = top;
+ s.RightU0 = right;
+ s.BottomV0 = bottom;
+ }
+
+ if (numCoordsPerFrame == 1)
+ seq.TextureCoordData[1] = seq.TextureCoordData[0];
+
+ curTime += thisDuration;
+ FrameSpan[sequenceNumber] = curTime;
+ }
+
+ if (frameCount <= 0)
+ continue;
+
+ int knots = Math.Min(frameCount, SEQUENCE_SAMPLE_COUNT);
+ for (int idx = 0; idx < timeSamples; idx++) {
+ GetInterpolationData(interpKnot, interpValue, knots, SEQUENCE_SAMPLE_COUNT, idx, !Clamp[sequenceNumber], out float idxA, out float idxB, out float interp);
+ ref SheetSequenceSample sA = ref samples[(int)idxA];
+ ref SheetSequenceSample sB = ref samples[(int)idxB];
+ ref SheetSequenceSample oseq = ref outSamples[idx];
+
+ oseq.BlendFactor = interp;
+ for (int image = 0; image < MAX_IMAGES_PER_FRAME_IN_MEMORY; image++) {
+ ref SequenceSampleTextureCoords src0 = ref sA.TextureCoordData[image];
+ ref SequenceSampleTextureCoords src1 = ref sB.TextureCoordData[image];
+ ref SequenceSampleTextureCoords o = ref oseq.TextureCoordData[image];
+ o.LeftU0 = src0.LeftU0;
+ o.TopV0 = src0.TopV0;
+ o.RightU0 = src0.RightU0;
+ o.BottomV0 = src0.BottomV0;
+ o.LeftU1 = src1.LeftU0;
+ o.TopV1 = src1.TopV0;
+ o.RightU1 = src1.RightU0;
+ o.BottomV1 = src1.BottomV0;
+ }
+ }
+ }
+
+ for (int first = 0; first < MAX_SEQUENCES; first++) {
+ if (Samples[first] == null)
+ continue;
+
+ for (int i = 0; i < MAX_SEQUENCES; i++) {
+ if (Samples[i] != null)
+ continue;
+
+ Samples[i] = Samples[first];
+ Clamp[i] = Clamp[first];
+ NumFrames[i] = NumFrames[first];
+ SequenceIsCopyOfAnotherSequence[i] = true;
+ }
+ break;
+ }
+ }
+
+ static void GetInterpolationData(ReadOnlySpan