Skip to content

Commit c08e479

Browse files
Merge pull request #155 from sors89/upcoming
Patch Terraria.Main.rand into a property
2 parents 81d640d + 5edf3b7 commit c08e479

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
Copyright (C) 2025 sors89
3+
4+
This file is part of Open Terraria API v3 (OTAPI)
5+
6+
This program is free software: you can redistribute it and/or modify
7+
it under the terms of the GNU General Public License as published by
8+
the Free Software Foundation, either version 3 of the License, or
9+
(at your option) any later version.
10+
11+
This program is distributed in the hope that it will be useful,
12+
but WITHOUT ANY WARRANTY; without even the implied warranty of
13+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14+
GNU General Public License for more details.
15+
16+
You should have received a copy of the GNU General Public License
17+
along with this program. If not, see <http://www.gnu.org/licenses/>.
18+
*/
19+
#if !tModLoader && !tModLoaderServer
20+
using ModFramework;
21+
using Mono.Cecil.Cil;
22+
using MonoMod;
23+
using System;
24+
using System.Linq;
25+
26+
/// <summary>
27+
/// @doc Patch Terraria.Main.rand into a property
28+
/// </summary>
29+
[MonoModIgnore]
30+
partial class Rand
31+
{
32+
[Modification(ModType.PreMerge, "Patching Terraria.Main.rand")]
33+
static void PatchMainRand(ModFwModder modder)
34+
{
35+
var rand = modder.GetFieldDefinition(() => Terraria.Main.rand);
36+
var prop = rand.RemapAsProperty(modder);
37+
38+
var csr = modder.GetILCursor(prop.GetMethod);
39+
40+
/*
41+
0 0000 ldsfld string Terraria.Main::'<rand>k__BackingField'
42+
1 0005 ret
43+
*/
44+
45+
var backingField = modder.Module.GetDefinition<Terraria.Main>().Fields.Where(x => x.Name.Contains("<rand>")).First();
46+
47+
csr.GotoNext(i => i.OpCode == OpCodes.Ret);
48+
csr.Emit(OpCodes.Ldnull);
49+
csr.Emit(OpCodes.Nop);
50+
csr.Emit(OpCodes.Newobj, typeof(Terraria.Utilities.UnifiedRandom).GetConstructor(new Type[] { }));
51+
csr.Emit(OpCodes.Stsfld, backingField);
52+
csr.Emit(OpCodes.Ldsfld, backingField);
53+
54+
var nop = csr.Body.Instructions.Where(i => i.OpCode == OpCodes.Nop).First();
55+
nop.OpCode = OpCodes.Bne_Un_S;
56+
nop.Operand = csr.Previous;
57+
}
58+
}
59+
#endif

0 commit comments

Comments
 (0)