From c39379afe82f2a0032f0c0a51d08f53ae9b80e79 Mon Sep 17 00:00:00 2001 From: Yahzy Date: Thu, 19 Nov 2026 01:20:57 +0100 Subject: [PATCH 1/2] Map embedded struct changes to their props in local entity transfer --- Source.Common/DtRecv.cs | 1 + Source.Engine/DtLocalTransfer.cs | 46 +++++++++++++++++++++++++++++--- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/Source.Common/DtRecv.cs b/Source.Common/DtRecv.cs index c6d913f1..f023d148 100644 --- a/Source.Common/DtRecv.cs +++ b/Source.Common/DtRecv.cs @@ -584,6 +584,7 @@ public struct ProxyPath public readonly FastLocalTransferInfo FastLocalTransfer = new(); public int DataTableProxies; public readonly Dictionary PropAccessorToIndexMap = []; + public readonly Dictionary> EmbeddedFieldToIndices = []; } public class ClientSendProp diff --git a/Source.Engine/DtLocalTransfer.cs b/Source.Engine/DtLocalTransfer.cs index 48043c57..95973ad4 100644 --- a/Source.Engine/DtLocalTransfer.cs +++ b/Source.Engine/DtLocalTransfer.cs @@ -41,12 +41,16 @@ public static void TransferEntity(BaseEdict edict, SendTable sendTable, object s Span propIndices = stackalloc ushort[Edict.MAX_CHANGE_OFFSETS * 3]; // This code tries to only copy fields expressly marked as "changed" (by having the field accessors added to the changed-fields list) + int changeOffsets = -1; if (edict.GetChangeInfoSerialNumber() == g_SharedChangeInfo.SerialNumber && !newlyCreated && !justEnteredPVS && dt_UsePartialChangeEnts.GetInt() != 0) { - SendTablePrecalc precalc = sendTable.Precalc!; - - int changeOffsets = MapPropFieldsToIndices(edict, precalc, changeInfo, propIndices); + changeOffsets = MapPropFieldsToIndices(edict, sendTable.Precalc!, changeInfo, propIndices); if (changeOffsets == 0) return; + } + + // -1 when the changed props don't fit in the list (embedded structs map to several props), copy everything then. + if (changeOffsets > 0) { + SendTablePrecalc precalc = sendTable.Precalc!; AddToPartialChangeEntsList(Array.IndexOf(sv.Edicts, edict) /* TODO: Need fast way to do this! */, true); FastSortList(propIndices, changeOffsets); @@ -165,6 +169,31 @@ public static void AddPropOffsetToMap(SendTablePrecalc precalc, int prop, IField return; precalc.PropAccessorToIndexMap[fieldAccessor] = (ushort)prop; + + AddEmbeddedFieldToMap(precalc, prop, fieldAccessor); + } + + // Props inside of an embedded struct (or array) are keyed by their full path, ie. "Fog.Start", but changing the struct + // through its ForModify accessor only reports the root field "Fog". Map the root to the props it contains. + static void AddEmbeddedFieldToMap(SendTablePrecalc precalc, int prop, IFieldAccessor fieldAccessor) { + if (fieldAccessor is not DynamicAccessor accessor) + return; + + string? fieldKey = accessor.FieldKey; + if (fieldKey == null) + return; + + int expressionStart = fieldKey.LastIndexOf('|') + 1; + int rootEnd = fieldKey.AsSpan(expressionStart).IndexOfAny('.', '['); + if (rootEnd <= 0) + return; + + int rootKeyId = FieldKeyRegistry.GetId(fieldKey[..(expressionStart + rootEnd)]); + if (!precalc.EmbeddedFieldToIndices.TryGetValue(rootKeyId, out List? indices)) + precalc.EmbeddedFieldToIndices[rootKeyId] = indices = []; + + if (!indices.Contains((ushort)prop)) + indices.Add((ushort)prop); } public static void BuildPropOffsetToIndexMap(SendTablePrecalc precalc, StandardSendProxies sendProxies) { @@ -208,6 +237,17 @@ static int MapPropFieldsToIndices(BaseEdict edict, SendTablePrecalc precalc, Edi continue; if (!precalc.PropAccessorToIndexMap.TryGetValue(field, out ushort propIndex)) { + // An embedded struct was changed through its ForModify accessor, copy every prop inside of it. + if (field is DynamicAccessor accessor && accessor.FieldIndex == -1 && precalc.EmbeddedFieldToIndices.TryGetValue(accessor.FieldKeyId, out List? embeddedIndices)) { + if (iOut + embeddedIndices.Count > outIndices.Length) + return -1; + + for (int j = 0; j < embeddedIndices.Count; j++) + outIndices[iOut++] = (ushort)(embeddedIndices[j] & ~PROP_INDEX_VECTOR_ELEM_MARKER); + + continue; + } + // Note: this SHOULD be fine // If we can't find a field here, then there isn't a SendProp associated with the CNetworkVar that triggered the change // so the change doesn't matter From 43a93ed40778fcee3a1b4d84a2aaa60099645ad6 Mon Sep 17 00:00:00 2001 From: march <106459595+marchc1@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:19:06 -0800 Subject: [PATCH 2/2] Try to fix this at the source generator --- .../NetworkVarGenerator.FieldAccessors.cs | 9 ++- .../NetworkVarGenerator.Tables.cs | 8 ++- .../NetworkVarGenerator.cs | 56 ++++++++++++++++--- Source.Common/DtRecv.cs | 1 - Source.Engine/DtLocalTransfer.cs | 46 +-------------- 5 files changed, 62 insertions(+), 58 deletions(-) diff --git a/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.FieldAccessors.cs b/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.FieldAccessors.cs index d9833ccb..2d3f2b26 100644 --- a/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.FieldAccessors.cs +++ b/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.FieldAccessors.cs @@ -164,7 +164,7 @@ private static bool IsInvocationNamed(SyntaxNode node, HashSet names) { List conversions = new List(); AddConversions(compilation, path.Type, conversions); - return new FieldAccessorModel("S|" + ownerDisplay + "|" + expression + "|" + (name ?? "\0"), registration, body.ToString(), string.Join("\n", conversions)); + return new FieldAccessorModel("S|" + ownerDisplay + "|" + expression + "|" + (name ?? "\0"), registration, body.ToString(), string.Join("\n", conversions)) { FieldKey = FieldKey("S", path, owner, expression) }; } private static FieldAccessorModel? BuildArray(Compilation compilation, INamedTypeSymbol owner, string expression, bool isList, AccessFailure failure) { @@ -222,7 +222,7 @@ private static bool IsInvocationNamed(SyntaxNode node, HashSet names) { AddConversions(compilation, path.Type, conversions); AddConversions(compilation, element, conversions); - return new FieldAccessorModel("A|" + ownerDisplay + "|" + expression, registration, body.ToString(), string.Join("\n", conversions)); + return new FieldAccessorModel("A|" + ownerDisplay + "|" + expression, registration, body.ToString(), string.Join("\n", conversions)) { FieldKey = FieldKey("A", path, owner, expression) }; } private static ResolvedPath? Resolve(Compilation compilation, INamedTypeSymbol owner, string expression, AccessFailure failure) { @@ -698,11 +698,14 @@ public static FieldAccessorModel Inaccessible(Location location, string member, public string Registration { get; } public string Body { get; } public string Conversions { get; } + public string? FieldKey { get; set; } + public bool PredictionOnly { get; set; } public Location? ErrorLocation { get; private set; } public object[]? ErrorArgs { get; private set; } public bool Equals(FieldAccessorModel? other) - => other != null && Key == other.Key && Registration == other.Registration && Body == other.Body && Conversions == other.Conversions && Equals(ErrorLocation, other.ErrorLocation); + => other != null && Key == other.Key && Registration == other.Registration && Body == other.Body && Conversions == other.Conversions && FieldKey == other.FieldKey + && PredictionOnly == other.PredictionOnly && Equals(ErrorLocation, other.ErrorLocation); public override bool Equals(object? obj) => Equals(obj as FieldAccessorModel); public override int GetHashCode() => Key.GetHashCode(); diff --git a/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.Tables.cs b/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.Tables.cs index 861feef8..66108e0c 100644 --- a/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.Tables.cs +++ b/Source.CodeAnalysis.NetworkVars/NetworkVarGenerator.Tables.cs @@ -424,8 +424,10 @@ private static void EmitTables(SourceProductionContext spc, ImmutableArray m != null); IncrementalValueProvider> collected = properties.Collect(); + IncrementalValueProvider> tables = InitializeTables(context); - context.RegisterSourceOutput(collected, static (spc, models) => Emit(spc, models)); + context.RegisterSourceOutput(collected.Combine(tables), static (spc, data) => Emit(spc, data.Left, data.Right)); - InitializeFieldAccessors(context, collected, InitializeTables(context)); + InitializeFieldAccessors(context, collected, tables); + } + + private static HashSet WholeChangeRootKeys(ImmutableArray tables) { + var sent = new HashSet(); + var roots = new HashSet(); + foreach (TableModel? table in tables) { + if (table == null) + continue; + foreach (FieldAccessorModel accessor in table.Accessors) { + string? key = accessor.FieldKey; + if (key == null || accessor.PredictionOnly) + continue; + sent.Add(key); + int expressionStart = key.LastIndexOf('|') + 1; + int rootEnd = key.IndexOfAny(new[] { '.', '[' }, expressionStart); + if (key[0] == 'A' || rootEnd >= 0) + roots.Add("S" + (rootEnd >= 0 ? key.Substring(1, rootEnd - 1) : key.Substring(1))); + } + } + roots.ExceptWith(sent); + return roots; + } + + private static bool HasWholeStateChanged(INamedTypeSymbol? type) { + for (INamedTypeSymbol? t = type; t != null; t = t.BaseType) { + foreach (ISymbol member in t.GetMembers("NetworkStateChanged")) { + if (member is IMethodSymbol method && method.Parameters.Length == 0) + return true; + } + } + return false; } private static bool HasStateTracking(INamedTypeSymbol? type) { @@ -135,7 +167,8 @@ private static bool IsNetworkArray(ITypeSymbol type) .Select(m => m.Text)), RefReadonly = prop.ReturnsByRefReadonly, BaseHasFields = BaseHasNetworkVarFields(containingType.BaseType), - ForModifyHidesBase = BaseHasForModify(containingType.BaseType, prop.Name) + ForModifyHidesBase = BaseHasForModify(containingType.BaseType, prop.Name), + HasWholeStateChanged = HasWholeStateChanged(containingType) }; } @@ -166,7 +199,8 @@ private static bool BaseHasNetworkVarFields(INamedTypeSymbol? type) { return false; } - private static void Emit(SourceProductionContext spc, ImmutableArray models) { + private static void Emit(SourceProductionContext spc, ImmutableArray models, ImmutableArray tables) { + HashSet wholeChangeRoots = WholeChangeRootKeys(tables); foreach (var group in models .Where(m => m != null) .Select(m => m!) @@ -198,13 +232,13 @@ private static void Emit(SourceProductionContext spc, ImmutableArray props) { + private static string BuildSource(PropertyModel type, List props, HashSet wholeChangeRoots) { var sb = new StringBuilder(); sb.AppendLine("// "); sb.AppendLine("#nullable enable"); @@ -226,6 +260,9 @@ private static string BuildSource(PropertyModel type, List props) string t = p.TypeDisplay; string name = p.PropertyName; string backing = "__nv_" + name; + string stateChanged = p.HasWholeStateChanged && wholeChangeRoots.Contains("S|" + type.TypeFullyQualified + "|" + name) + ? "NetworkStateChanged();" + : "NetworkStateChanged(NetworkVarFields." + name + ");"; sb.Append(indent).Append("private ").Append(t).Append(' ').Append(backing).AppendLine(";"); string accessibility = p.Accessibility.Length == 0 ? "" : p.Accessibility + " "; @@ -236,7 +273,7 @@ private static string BuildSource(PropertyModel type, List props) sb.Append(indent).Append(forModify).Append(t).Append(' ').Append(name).Append("ForModify() => ref ").Append(backing).AppendLine(";"); else { sb.Append(indent).Append(forModify).Append(t).Append(' ').Append(name).AppendLine("ForModify() {"); - sb.Append(indent).Append("\tNetworkStateChanged(NetworkVarFields.").Append(name).AppendLine(");"); + sb.Append(indent).Append('\t').AppendLine(stateChanged); sb.Append(indent).Append("\treturn ref ").Append(backing).AppendLine(";"); sb.Append(indent).AppendLine("}"); } @@ -261,12 +298,12 @@ private static string BuildSource(PropertyModel type, List props) .Append(", (global::System.ReadOnlySpan<").Append(e).Append(">)value, global::System.Collections.Generic.EqualityComparer<").Append(e).AppendLine(">.Default)) {"); } sb.Append(indent).Append("\t\t\t").Append(backing).AppendLine(" = value;"); - sb.Append(indent).Append("\t\t\tNetworkStateChanged(NetworkVarFields.").Append(name).AppendLine(");"); + sb.Append(indent).Append("\t\t\t").AppendLine(stateChanged); sb.Append(indent).AppendLine("\t\t}"); sb.Append(indent).AppendLine("\t}"); sb.Append(indent).AppendLine("}"); sb.Append(indent).Append(forModify).Append(t).Append(' ').Append(name).AppendLine("ForModify() {"); - sb.Append(indent).Append("\tNetworkStateChanged(NetworkVarFields.").Append(name).AppendLine(");"); + sb.Append(indent).Append('\t').AppendLine(stateChanged); sb.Append(indent).Append("\treturn ref ").Append(backing).AppendLine(";"); sb.Append(indent).AppendLine("}"); sb.AppendLine(); @@ -341,6 +378,7 @@ public static PropertyModel ServerFieldError(string fieldName, string typeName, public bool RefReadonly { get; set; } public bool BaseHasFields { get; set; } public bool ForModifyHidesBase { get; set; } + public bool HasWholeStateChanged { get; set; } public Location Location { get; } } } diff --git a/Source.Common/DtRecv.cs b/Source.Common/DtRecv.cs index f023d148..c6d913f1 100644 --- a/Source.Common/DtRecv.cs +++ b/Source.Common/DtRecv.cs @@ -584,7 +584,6 @@ public struct ProxyPath public readonly FastLocalTransferInfo FastLocalTransfer = new(); public int DataTableProxies; public readonly Dictionary PropAccessorToIndexMap = []; - public readonly Dictionary> EmbeddedFieldToIndices = []; } public class ClientSendProp diff --git a/Source.Engine/DtLocalTransfer.cs b/Source.Engine/DtLocalTransfer.cs index 95973ad4..48043c57 100644 --- a/Source.Engine/DtLocalTransfer.cs +++ b/Source.Engine/DtLocalTransfer.cs @@ -41,16 +41,12 @@ public static void TransferEntity(BaseEdict edict, SendTable sendTable, object s Span propIndices = stackalloc ushort[Edict.MAX_CHANGE_OFFSETS * 3]; // This code tries to only copy fields expressly marked as "changed" (by having the field accessors added to the changed-fields list) - int changeOffsets = -1; if (edict.GetChangeInfoSerialNumber() == g_SharedChangeInfo.SerialNumber && !newlyCreated && !justEnteredPVS && dt_UsePartialChangeEnts.GetInt() != 0) { - changeOffsets = MapPropFieldsToIndices(edict, sendTable.Precalc!, changeInfo, propIndices); + SendTablePrecalc precalc = sendTable.Precalc!; + + int changeOffsets = MapPropFieldsToIndices(edict, precalc, changeInfo, propIndices); if (changeOffsets == 0) return; - } - - // -1 when the changed props don't fit in the list (embedded structs map to several props), copy everything then. - if (changeOffsets > 0) { - SendTablePrecalc precalc = sendTable.Precalc!; AddToPartialChangeEntsList(Array.IndexOf(sv.Edicts, edict) /* TODO: Need fast way to do this! */, true); FastSortList(propIndices, changeOffsets); @@ -169,31 +165,6 @@ public static void AddPropOffsetToMap(SendTablePrecalc precalc, int prop, IField return; precalc.PropAccessorToIndexMap[fieldAccessor] = (ushort)prop; - - AddEmbeddedFieldToMap(precalc, prop, fieldAccessor); - } - - // Props inside of an embedded struct (or array) are keyed by their full path, ie. "Fog.Start", but changing the struct - // through its ForModify accessor only reports the root field "Fog". Map the root to the props it contains. - static void AddEmbeddedFieldToMap(SendTablePrecalc precalc, int prop, IFieldAccessor fieldAccessor) { - if (fieldAccessor is not DynamicAccessor accessor) - return; - - string? fieldKey = accessor.FieldKey; - if (fieldKey == null) - return; - - int expressionStart = fieldKey.LastIndexOf('|') + 1; - int rootEnd = fieldKey.AsSpan(expressionStart).IndexOfAny('.', '['); - if (rootEnd <= 0) - return; - - int rootKeyId = FieldKeyRegistry.GetId(fieldKey[..(expressionStart + rootEnd)]); - if (!precalc.EmbeddedFieldToIndices.TryGetValue(rootKeyId, out List? indices)) - precalc.EmbeddedFieldToIndices[rootKeyId] = indices = []; - - if (!indices.Contains((ushort)prop)) - indices.Add((ushort)prop); } public static void BuildPropOffsetToIndexMap(SendTablePrecalc precalc, StandardSendProxies sendProxies) { @@ -237,17 +208,6 @@ static int MapPropFieldsToIndices(BaseEdict edict, SendTablePrecalc precalc, Edi continue; if (!precalc.PropAccessorToIndexMap.TryGetValue(field, out ushort propIndex)) { - // An embedded struct was changed through its ForModify accessor, copy every prop inside of it. - if (field is DynamicAccessor accessor && accessor.FieldIndex == -1 && precalc.EmbeddedFieldToIndices.TryGetValue(accessor.FieldKeyId, out List? embeddedIndices)) { - if (iOut + embeddedIndices.Count > outIndices.Length) - return -1; - - for (int j = 0; j < embeddedIndices.Count; j++) - outIndices[iOut++] = (ushort)(embeddedIndices[j] & ~PROP_INDEX_VECTOR_ELEM_MARKER); - - continue; - } - // Note: this SHOULD be fine // If we can't find a field here, then there isn't a SendProp associated with the CNetworkVar that triggered the change // so the change doesn't matter