Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Readd Building Patches #2069

Closed
wants to merge 56 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
56 commits
Select commit Hold shift + click to select a range
bf7514d
Disable patches for legacy building
tornac1234 Dec 26, 2022
d1f57ae
Created virtual objects for every possible building (and ghosts)
tornac1234 Dec 26, 2022
138441d
Add a singleplayer tester for the alternative building system
tornac1234 Dec 26, 2022
d57e3e8
Fix transpiler pattern matching not adding instructions at the end of…
tornac1234 Dec 29, 2022
23d7f4c
Adapted all of the code to work in simple peer-2-peer
tornac1234 Dec 30, 2022
1247519
Add a first implementation (unfinished and unclean) of the server-sid…
tornac1234 Dec 30, 2022
efcde9d
Added a BuildPieceIdentifier to be able to identify objects under Bas…
tornac1234 Dec 30, 2022
229d9b4
Fix a null exception during RestoreGhost()
tornac1234 Dec 30, 2022
2e41c70
Completed the server-side managing of the build packets (still a bug …
tornac1234 Dec 30, 2022
f0d4a3c
Refactored save data in PersistedWorldData
tornac1234 Dec 30, 2022
4d1301d
Added the required ProtoBufNet attributes to the new data classes
tornac1234 Dec 30, 2022
ce1e55f
Added building restore process to initial sync
tornac1234 Dec 30, 2022
b2d1791
Fix modules not being correctly handled on server-side
tornac1234 Dec 31, 2022
d1e9246
Try improving build piece identifying.
tornac1234 Jan 2, 2023
0dda03f
On the way to deprecate client force-updating bases when it's not val…
tornac1234 Jan 2, 2023
96d7dfb
Replace every ProtoContract/ProtoMember to DataContract/DataMember
tornac1234 Jan 2, 2023
4e0489d
Fix BuildPieceIdentifier being wrongly created for destructed pieces
tornac1234 Jan 5, 2023
f10b980
Fixed cooldowns, and added cooldown cleanup for when they're finished
tornac1234 Jan 8, 2023
d653a57
Made the building queue use safely yielded coroutines
tornac1234 Feb 20, 2023
8c00dbd
Added NitroxId to interior pieces and NitroxEntity to IBaseModules ac…
tornac1234 Feb 27, 2023
1345829
Fix WaterParks NitroxEntity setting
tornac1234 Feb 28, 2023
0c5f780
Fix being able to deconstruct buildings with remote players inside
tornac1234 Mar 1, 2023
191c36e
Add NitroxEntity to VehicleDockingBay of moonpools
tornac1234 Mar 15, 2023
7162dba
First shot at moving buildings to the entity system (a lot to correct…
tornac1234 Mar 29, 2023
2319339
Removed ExistsInGlobalRoot and WaterParkId fields from WorldEntity (r…
tornac1234 Apr 2, 2023
6f324da
Moved the whole building system to the entity system (incomplete but …
tornac1234 Apr 8, 2023
f069ca0
Fix MapRooms not getting a NitroxEntity attached to their functionali…
tornac1234 Apr 10, 2023
2f1f143
Reparent player children of a removed entity to GlobalRoot
tornac1234 Apr 10, 2023
8013cb5
Add sync/persistence for base pieces (not for alien containments tho)…
tornac1234 Apr 16, 2023
6cd3cab
Fix moonpool not spawning vehicle, recursive search for players causi…
tornac1234 Apr 19, 2023
1a41cf1
Add MapRooms as children for bases, that will get their nitrox ids sa…
tornac1234 Apr 20, 2023
c804f14
Fix ghost visual glitch
tornac1234 Apr 20, 2023
532160f
Fixed several edge-cases issues for WaterParks and finished its basic…
tornac1234 May 10, 2023
0fdee30
Fixed vehicles not being correctly docked to moonpools and constructa…
tornac1234 May 10, 2023
374431d
Refactoring (for build-related entities) positions to localpositions …
tornac1234 May 10, 2023
6f99bf2
Added a resync buildings procedure (with a button in the settings) an…
tornac1234 Jun 10, 2023
8ad30d8
Add a safe building mode for both client and server. Also fix the ope…
tornac1234 Jun 15, 2023
f942989
First steps of entity batch spawning applied to item spawning, fixed …
tornac1234 Jun 26, 2023
f301477
Introduced data compression for SavedBase data (drastically reduced t…
tornac1234 Jul 4, 2023
40bf8b9
Deprecated legacy building system.
tornac1234 Jul 8, 2023
cb74608
Mass refactoring (cleaning up the project), moving classes in their o…
tornac1234 Jul 12, 2023
f4a650a
Fix an issue in batch spawning (about ignored exceptions), and vehicl…
tornac1234 Jul 13, 2023
faa9ace
Some cleaning
tornac1234 Jul 13, 2023
78e6916
Replace NitroxEntity.TryGetIdFrom by the implementation from #1908
tornac1234 Jul 13, 2023
490dbbb
Some refactoring + fix operation tracker breaking bug
tornac1234 Jul 16, 2023
852f3bd
Resolved merge conflicts, fixed an issue with metadata update spammin…
tornac1234 Jul 17, 2023
5371422
Some more mass refactoring to avoid having too many util static classes
tornac1234 Jul 19, 2023
8946a43
QOL
Jannify May 22, 2023
5763418
Sync/Mirror cinematic animation for remote player
Jannify May 21, 2023
83f688a
Added waiting for players skip and auto skip intro on DEBUG
Jannify Jun 23, 2023
06a1daa
Added source generator for NitroxPatch boilerplate
Jul 9, 2023
410c98c
Applied HarmonyRegisterPatchGenerator to all applicable patch classes
Jul 15, 2023
5557bea
Added warn log for errors returned by LogHowToConnectAsync
Jul 16, 2023
92daab8
Merge branch 'pr/2063'
Checkerb0ard Jul 30, 2023
b019865
Merge branch 'pr/2043'
Checkerb0ard Jul 30, 2023
c918669
Fix Building errors
Checkerb0ard Jul 30, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Added source generator for NitroxPatch boilerplate
This generator also optimizes how MethodInfos are retrieved during patching.
  • Loading branch information
Measurity committed Jul 27, 2023
commit 06a1daa7288def18aa0b578b44b2c8a08d226d4e
18 changes: 18 additions & 0 deletions Nitrox.Analyzers/Extensions/CompilationExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System;
using System.Linq;
using Microsoft.CodeAnalysis;

namespace Nitrox.Analyzers.Extensions;

internal static class CompilationExtensions
{
/// <summary>
/// Returns the <see cref="INamedTypeSymbol" /> found or null.
/// </summary>
/// <param name="compilation">The compilation that should have the type.</param>
/// <param name="assemblyNameWithoutDll">Assembly name, case sensitive.</param>
/// <param name="fullTypeName">Type name include the namespace, case sensitive.</param>
/// <returns></returns>
public static INamedTypeSymbol HasType(this Compilation compilation, string assemblyNameWithoutDll, string fullTypeName) =>
compilation.GetTypesByMetadataName(fullTypeName).FirstOrDefault(a => a.ContainingAssembly.Name.Equals(assemblyNameWithoutDll, StringComparison.Ordinal));
}
35 changes: 35 additions & 0 deletions Nitrox.Analyzers/Extensions/SyntaxExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace Nitrox.Analyzers.Extensions;

public static class SyntaxExtensions
{
public static bool IsPartialType(this TypeDeclarationSyntax typeSyntax) => typeSyntax.Modifiers.Any(SyntaxKind.PartialKeyword);


public static string GetNamespaceName(this TypeDeclarationSyntax type) => type.Ancestors()
.Select(n => n switch
{
FileScopedNamespaceDeclarationSyntax f => f.Name.ToString(),
NamespaceDeclarationSyntax ns => ns.Name.ToString(),
_ => null
})
.First();

public static string GetReturnTypeName(this MemberDeclarationSyntax member) => member switch
{
FieldDeclarationSyntax field => field.Declaration.ChildNodes().OfType<IdentifierNameSyntax>().FirstOrDefault()?.Identifier.ValueText ?? "",
MethodDeclarationSyntax method => method.ReturnType.ToString(),
_ => ""
};

public static string GetName(this MemberDeclarationSyntax member) => member switch
{
FieldDeclarationSyntax field => field.Declaration.Variables.FirstOrDefault()?.Identifier.ValueText ?? "",
_ => ""
};
}
213 changes: 213 additions & 0 deletions Nitrox.Analyzers/Generators/HarmonyRegisterPatchGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Nitrox.Analyzers.Extensions;

namespace Nitrox.Analyzers.Generators;

/// <summary>
/// Implements the harmony patch registry boilerplate for NitroxPatch inherited types by scanning its static MethodInfo
/// fields and static patch methods.
/// </summary>
[Generator(LanguageNames.CSharp)]
internal sealed class HarmonyRegisterPatchGenerator : IIncrementalGenerator
{
private static readonly string[] harmonyMethodTypes = { "prefix", "postfix", "transpiler", "finalizer", "manipulator" };
private static readonly string[] validTargetMethodNames = { "target_method", "targetmethod", "target", "method" };
private static readonly Lazy<string> generatedCodeAttribute = new(() => $@"[global::System.CodeDom.Compiler.GeneratedCode(""{typeof(HarmonyRegisterPatchGenerator).FullName}"", ""{typeof(HarmonyRegisterPatchGenerator).Assembly.GetName().Version}"")]");

[SuppressMessage("ReSharper", "SuggestVarOrType_Elsewhere")]
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Setup compilation pipeline for assemblies that use NitroxPatch.
var compilationPipeline = context.CompilationProvider.Select((c, _) => c.HasType("NitroxPatcher", "NitroxPatcher.Patches.NitroxPatch") != null);
// Look for partial types inheriting our NitroxPatch type, selecting all the harmony methods and target method infos.
var harmonyMethodsWithTargetMethods = context.SyntaxProvider
.CreateSyntaxProvider(
static (node, _) => IsSyntaxTargetForGeneration(node),
static (context, _) => GetSemanticTargetForGeneration(context))
.Where(r => r is not null)
.WithComparer(NitroxHarmonyType.NitroxHarmonyTypeEqualityComparer.Instance);

// Register the pipeline into the compiler.
var combinedPipeline = harmonyMethodsWithTargetMethods.Combine(compilationPipeline);
context.RegisterSourceOutput(combinedPipeline, static (context, source) => Execute(context, source.Left));
}

private static void Execute(SourceProductionContext context, NitroxHarmonyType nitroxHarmonyType)
{
// Build Patch method implementation.
StringBuilder patchImpl = new();
for (int fieldIndex = 0; fieldIndex < nitroxHarmonyType.MethodInfoFields.Length; fieldIndex++)
{
FieldDeclarationSyntax methodInfoField = nitroxHarmonyType.MethodInfoFields[fieldIndex];
patchImpl.Append("PatchMultiple(harmony, ")
.Append(methodInfoField.GetName());
if (nitroxHarmonyType.HarmonyPatchMethods.Length > 0)
{
patchImpl.Append(", ");
foreach (MethodDeclarationSyntax harmonyPatchMethod in nitroxHarmonyType.HarmonyPatchMethods)
{
patchImpl.Append(harmonyPatchMethod.Identifier.ValueText.ToLowerInvariant())
.Append(": ((Delegate)")
.Append(harmonyPatchMethod.Identifier.ValueText)
.Append(").Method, ");
}
patchImpl.Remove(patchImpl.Length - 2, 2);
}
patchImpl.Append(");");
// Append new line if not last implementation line.
if (fieldIndex < nitroxHarmonyType.MethodInfoFields.Length - 1)
{
patchImpl.AppendLine();
}
}

// Append new code to the compilation.
context.AddSource($"{nitroxHarmonyType.NameSpace}.{nitroxHarmonyType.TypeName}.g.cs", $$"""
#pragma warning disable
using System;
using HarmonyLib;

namespace {{nitroxHarmonyType.NameSpace}};

partial class {{nitroxHarmonyType.TypeName}}
{
{{generatedCodeAttribute.Value}}
public override void Patch(Harmony harmony)
{
{{patchImpl}}
}
}
""");
}

private static bool IsSyntaxTargetForGeneration(SyntaxNode node)
{
if (node is not TypeDeclarationSyntax type)
{
return false;
}
if (!type.IsPartialType())
{
return false;
}
// Skip if not deriving from "NitroxPatch".
if (type.BaseList?.Types.FirstOrDefault(t => t.ToString().Equals("NitroxPatch", StringComparison.Ordinal)) == null)
{
return false;
}
// Skip if "Patch" method is already defined.
if (type.Members.OfType<MethodDeclarationSyntax>().Any(m => m.Modifiers.Any(SyntaxKind.OverrideKeyword) && m.Identifier.ValueText == "Patch"))
{
return false;
}
return true;
}

private static NitroxHarmonyType GetSemanticTargetForGeneration(GeneratorSyntaxContext context)
{
static bool IsValidPatchMethodName(string methodName) => harmonyMethodTypes.Contains(methodName.ToLowerInvariant());

static bool IsValidTargetMethodFieldName(string fieldName)
{
foreach (string n in validTargetMethodNames)
{
if (fieldName.StartsWith(n, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}

TypeDeclarationSyntax type = context.Node as TypeDeclarationSyntax;
if (type == null)
{
return null;
}
ImmutableArray<MemberDeclarationSyntax> members = type.Members.ToImmutableArray();
return new NitroxHarmonyType(type.GetNamespaceName(),
type.Identifier.ValueText,
members.OfType<MethodDeclarationSyntax>()
.Where(m => m.Modifiers.Any(SyntaxKind.StaticKeyword) && IsValidPatchMethodName(m.Identifier.ValueText))
.ToImmutableArray(),
members.OfType<FieldDeclarationSyntax>()
.Where(m => m.Modifiers.Any(SyntaxKind.StaticKeyword) && m.GetReturnTypeName() == "MethodInfo" && IsValidTargetMethodFieldName(m.GetName()))
.ToImmutableArray());
}

internal record NitroxHarmonyType(string NameSpace, string TypeName, ImmutableArray<MethodDeclarationSyntax> HarmonyPatchMethods, ImmutableArray<FieldDeclarationSyntax> MethodInfoFields)
{
internal sealed class NitroxHarmonyTypeEqualityComparer : IEqualityComparer<NitroxHarmonyType>
{
public static IEqualityComparer<NitroxHarmonyType> Instance { get; } = new NitroxHarmonyTypeEqualityComparer();

public bool Equals(NitroxHarmonyType x, NitroxHarmonyType y)
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
if (x.GetType() != y.GetType()) return false;
return string.Equals(x.NameSpace, y.NameSpace) &&
string.Equals(x.TypeName, y.TypeName) &&
x.HarmonyPatchMethods.SequenceEqual(y.HarmonyPatchMethods, HarmonyMethodEqualityComparer.Instance) &&
x.MethodInfoFields.SequenceEqual(y.MethodInfoFields, MethodInfoFieldEqualityComparer.Instance);
}

public int GetHashCode(NitroxHarmonyType obj)
{
unchecked
{
int hashCode = obj.NameSpace != null ? obj.NameSpace.GetHashCode() : 0;
hashCode = (hashCode * 397) ^ (obj.TypeName != null ? obj.TypeName.GetHashCode() : 0);
return hashCode;
}
}
}

private sealed class HarmonyMethodEqualityComparer : IEqualityComparer<MethodDeclarationSyntax>
{
public static IEqualityComparer<MethodDeclarationSyntax> Instance { get; } = new HarmonyMethodEqualityComparer();

public bool Equals(MethodDeclarationSyntax x, MethodDeclarationSyntax y)
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
if (x.GetType() != y.GetType()) return false;
return string.Equals(x.Identifier.ValueText, y.Identifier.ValueText);
}

public int GetHashCode(MethodDeclarationSyntax obj)
{
return obj.Identifier.ValueText.GetHashCode();
}
}

private sealed class MethodInfoFieldEqualityComparer : IEqualityComparer<FieldDeclarationSyntax>
{
public static IEqualityComparer<FieldDeclarationSyntax> Instance { get; } = new MethodInfoFieldEqualityComparer();

public bool Equals(FieldDeclarationSyntax x, FieldDeclarationSyntax y)
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
if (x.GetType() != y.GetType()) return false;
return x.ToString() == y.ToString();
}

public int GetHashCode(FieldDeclarationSyntax obj)
{
return obj.ToString().GetHashCode();
}
}
}
}
4 changes: 0 additions & 4 deletions Nitrox.Analyzers/Nitrox.Analyzers.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,4 @@
-->
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.2.0" PrivateAssets="all" />
</ItemGroup>

<ItemGroup>
<Folder Include="Generators" />
</ItemGroup>
</Project>