diff --git a/UndertaleModLib/Models/UndertaleCode.cs b/UndertaleModLib/Models/UndertaleCode.cs index dbedb4abb..8a54c610f 100644 --- a/UndertaleModLib/Models/UndertaleCode.cs +++ b/UndertaleModLib/Models/UndertaleCode.cs @@ -843,6 +843,42 @@ public static uint UnserializeChildObjectCount(UndertaleReader reader) return 0; } + public UndertaleInstruction Clone() + { + return new UndertaleInstruction() + { + Kind = this.Kind, + ComparisonKind = this.ComparisonKind, + Type1 = this.Type1, + Type2 = this.Type2, + TypeInst = this.TypeInst, + Value = ( + this.Value != null + ? ( + this.Value.GetType() == typeof(Reference) + ? new Reference(((Reference)(this.Value)).Target, ((Reference)(this.Value)).Type) + : ( + this.Value.GetType() == typeof(Reference) + ? new Reference(((Reference)(this.Value)).Target) + : ( + this.Value.GetType() == typeof(UndertaleResourceById) + ? new UndertaleResourceById(((UndertaleResourceById)(this.Value)).Resource, ((UndertaleResourceById)(this.Value)).CachedId) + : this.Value + ) + ) + ) + : null + ), + Destination = (this.Destination != null ? new Reference(this.Destination.Target, this.Destination.Type) : null), + Function = (this.Function != null ? new Reference(this.Function.Target, this.Function.Type) : null), + JumpOffset = this.JumpOffset, + JumpOffsetPopenvExitMagic = this.JumpOffsetPopenvExitMagic, + ArgumentsCount = this.ArgumentsCount, + Extra = this.Extra, + SwapExtra = this.SwapExtra, + }; + } + /// public override string ToString() { @@ -1343,6 +1379,35 @@ public void Replace(IList instructions) Append(instructions); } + public void Insert(IList instructions, int index) + { + uint offsetU = 0; + uint address = Instructions[index].Address; + foreach (UndertaleInstruction instr in instructions) + offsetU += instr.CalculateInstructionSize(); + + int offset = (int)offsetU; + + for (int i = 0; i < Instructions.Count; i++) + { + if (UndertaleInstruction.GetInstructionType(Instructions[i].Kind) == UndertaleInstruction.InstructionType.GotoInstruction) + { + if (i < index && Instructions[i].Address + Instructions[i].JumpOffset > address) + { + Instructions[i] = Instructions[i].Clone(); + Instructions[i].JumpOffset += offset; + } + else if (i > index && Instructions[i].Address + Instructions[i].JumpOffset <= address) + { + Instructions[i] = Instructions[i].Clone(); + Instructions[i].JumpOffset -= offset; + } + } + } + + Instructions.InsertRange(index + 1, instructions); + } + /// /// Append GML instructions at the end of this code entry. ///