forked from ifBars/S1API
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNPC.cs
More file actions
3197 lines (2834 loc) · 136 KB
/
NPC.cs
File metadata and controls
3197 lines (2834 loc) · 136 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#if (IL2CPPMELON)
using S1DevUtilities = Il2CppScheduleOne.DevUtilities;
using S1Interaction = Il2CppScheduleOne.Interaction;
using S1Messaging = Il2CppScheduleOne.Messaging;
using S1Noise = Il2CppScheduleOne.Noise;
using S1Economy = Il2CppScheduleOne.Economy;
using S1Relation = Il2CppScheduleOne.NPCs.Relation;
using S1Responses = Il2CppScheduleOne.NPCs.Responses;
using S1PlayerScripts = Il2CppScheduleOne.PlayerScripts;
using S1ContactApps = Il2CppScheduleOne.UI.Phone.ContactsApp;
using S1WorkspacePopup = Il2CppScheduleOne.UI.WorldspacePopup;
using S1AvatarFramework = Il2CppScheduleOne.AvatarFramework;
using S1Behaviour = Il2CppScheduleOne.NPCs.Behaviour;
using S1Vehicles = Il2CppScheduleOne.Vehicles;
using S1Vision = Il2CppScheduleOne.Vision;
using S1NPCs = Il2CppScheduleOne.NPCs;
using S1Combat = Il2CppScheduleOne.Combat;
using S1Items = Il2CppScheduleOne.ItemFramework;
using S1MapBase = Il2CppScheduleOne.Map;
using S1NPCsSchedules = Il2CppScheduleOne.NPCs.Schedules;
using S1Registry = Il2CppScheduleOne.Registry;
using S1Money = Il2CppScheduleOne.Money;
using ConversationCategoryList = Il2CppSystem.Collections.Generic.List<Il2CppScheduleOne.Messaging.EConversationCategory>;
#elif (MONOMELON || MONOBEPINEX || IL2CPPBEPINEX)
using S1DevUtilities = ScheduleOne.DevUtilities;
using S1Interaction = ScheduleOne.Interaction;
using S1Messaging = ScheduleOne.Messaging;
using S1Noise = ScheduleOne.Noise;
using S1Economy = ScheduleOne.Economy;
using S1Relation = ScheduleOne.NPCs.Relation;
using S1Responses = ScheduleOne.NPCs.Responses;
using S1PlayerScripts = ScheduleOne.PlayerScripts;
using S1ContactApps = ScheduleOne.UI.Phone.ContactsApp;
using S1WorkspacePopup = ScheduleOne.UI.WorldspacePopup;
using S1AvatarFramework = ScheduleOne.AvatarFramework;
using S1Behaviour = ScheduleOne.NPCs.Behaviour;
using S1Vehicles = ScheduleOne.Vehicles;
using S1Vision = ScheduleOne.Vision;
using S1NPCs = ScheduleOne.NPCs;
using S1Combat = ScheduleOne.Combat;
using S1Items = ScheduleOne.ItemFramework;
using S1MapBase = ScheduleOne.Map;
using S1NPCsSchedules = ScheduleOne.NPCs.Schedules;
using S1Registry = ScheduleOne.Registry;
using S1Money = ScheduleOne.Money;
using ConversationCategoryList = System.Collections.Generic.List<ScheduleOne.Messaging.EConversationCategory>;
#endif
#if (IL2CPPBEPINEX || IL2CPPMELON)
using S1Type = Il2CppSystem.Type;
using Il2CppInterop.Runtime;
#else
using S1Type = System.Type;
#endif
#if (IL2CPPBEPINEX || IL2CPPMELON)
using Il2CppSystem.Collections.Generic;
#else
using System.Collections.Generic;
#endif
using System;
using System.Collections;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using HarmonyLib;
#if (IL2CPPMELON)
using Il2CppFishNet;
using Il2CppFishNet.Managing.Object;
using Il2CppFishNet.Object;
#elif (MONOMELON || MONOBEPINEX || IL2CPPBEPINEX)
using FishNet;
using FishNet.Managing.Object;
using FishNet.Object;
#endif
using MelonLoader;
using S1API.Entities.Actions;
using S1API.Entities.Behaviour;
using S1API.Entities.Interfaces;
using S1API.Entities.Schedule;
using S1API.Entities.Customer;
using S1API.Entities.Dealer;
using S1API.Entities.Relation;
using S1API.Internal;
using S1API.Internal.Abstraction;
using S1API.Internal.Entities;
using S1API.Map;
using S1API.Messaging;
using S1API.Logging;
using S1API.Vehicles;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
namespace S1API.Entities
{
/// <summary>
/// Abstract base class for creating custom NPCs with modular architecture supporting both physical and non-physical NPCs.
/// Physical NPCs are visible in the game world with 3D models, movement, and direct interaction.
/// Non-physical NPCs are invisible contacts primarily used for messaging and phone interactions.
/// </summary>
/// <remarks>
/// NPCs provide access to component systems: <see cref="Appearance"/>, <see cref="Dialogue"/>, <see cref="Schedule"/>,
/// <see cref="Customer"/>, <see cref="Relationship"/>, <see cref="Inventory"/>, and <see cref="Movement"/>.
/// Customer, relationship, and schedule configuration must be done in <see cref="ConfigurePrefab"/> for proper save/load behavior.
/// </remarks>
public abstract class NPC : Saveable, IEntity, IHealth
{
private static readonly Log Logger = new Log("NPC");
// Protected members intended to be used by modders.
// Intended to be used from within the class / derived classes ONLY.
private static readonly System.Collections.Generic.Dictionary<System.Type, GameObject> TypeToPrefab = new System.Collections.Generic.Dictionary<System.Type, GameObject>();
private static readonly object TemplateLoadLock = new object();
private static readonly System.Collections.Generic.Dictionary<System.Type, System.Collections.Generic.List<IScheduleActionSpec>> TypeToSchedulePlan = new System.Collections.Generic.Dictionary<System.Type, System.Collections.Generic.List<IScheduleActionSpec>>();
private static readonly System.Collections.Generic.Dictionary<System.Type, System.Action<CustomerDataBuilder>> TypeToCustomerDefaults = new System.Collections.Generic.Dictionary<System.Type, System.Action<CustomerDataBuilder>>();
internal static readonly System.Collections.Generic.Dictionary<System.Type, System.Action<NPCRelationshipDataBuilder>> TypeToRelationshipDefaults = new System.Collections.Generic.Dictionary<System.Type, System.Action<NPCRelationshipDataBuilder>>();
private static readonly System.Collections.Generic.Dictionary<System.Type, System.Action<RandomInventoryItemsBuilder>> TypeToRandomInventoryDefaults = new System.Collections.Generic.Dictionary<System.Type, System.Action<RandomInventoryItemsBuilder>>();
private static readonly System.Collections.Generic.Dictionary<System.Type, System.Action<DealerDataBuilder>> TypeToDealerDefaults = new System.Collections.Generic.Dictionary<System.Type, System.Action<DealerDataBuilder>>();
private static readonly System.Collections.Generic.Dictionary<System.Type, (Vector3 position, Quaternion rotation)> TypeToSpawnPosition = new System.Collections.Generic.Dictionary<System.Type, (Vector3, Quaternion)>();
private static readonly System.Collections.Generic.HashSet<System.Type> CustomerTypes = new System.Collections.Generic.HashSet<System.Type>();
private static readonly System.Collections.Generic.HashSet<System.Type> DealerTypes = new System.Collections.Generic.HashSet<System.Type>();
private static volatile bool _prefabsConfiguredForLocalProcess;
internal static bool PrefabsConfiguredForLocalProcess => _prefabsConfiguredForLocalProcess;
private S1AvatarFramework.Avatar? _runtimeAvatar;
#region Template Prefab Helpers
private static GameObject InstantiateTemplateInstance(System.Type npcType, NPC owner)
{
GameObject prefab = GetOrCreatePerNpcPrefab(npcType, owner);
NetworkObject netPrefab = prefab.GetComponent<NetworkObject>() ?? prefab.AddComponent<NetworkObject>();
NetworkObject spawnableNetPrefab = null;
try
{
var nm = InstanceFinder.NetworkManager;
if (nm != null)
{
PrefabObjects spawnablePrefabs = nm.SpawnablePrefabs;
if (spawnablePrefabs != null)
{
int count = spawnablePrefabs.GetObjectCount();
for (int i = 0; i < count; i++)
{
NetworkObject obj = spawnablePrefabs.GetObject(true, i);
if (obj != null && obj.gameObject != null && obj.gameObject.name == prefab.name)
{
spawnableNetPrefab = obj;
break;
}
}
}
}
}
catch { /* no-op: fallback to local prefab */ }
GameObject prefabToUse = spawnableNetPrefab?.gameObject ?? prefab;
GameObject instance = UnityEngine.Object.Instantiate<GameObject>(prefabToUse);
try
{
var nm = InstanceFinder.NetworkManager;
bool isServer = nm != null && nm.IsServer;
var existingNo = instance.GetComponent<NetworkObject>();
if (isServer)
{
if (existingNo == null)
existingNo = instance.AddComponent<NetworkObject>();
}
else
{
if (existingNo != null)
UnityEngine.Object.Destroy(existingNo);
}
}
catch { }
if (S1NPCs.NPCManager.InstanceExists && S1NPCs.NPCManager.Instance.NPCContainer != null)
{
Transform parent = S1NPCs.NPCManager.Instance.NPCContainer;
if (parent != null && parent.gameObject != null && parent.gameObject.activeInHierarchy)
instance.transform.SetParent(parent, false);
}
instance.name = prefab.name;
return instance;
}
private static GameObject GetOrCreatePerNpcPrefab(System.Type npcType, NPC owner)
{
if (npcType == null)
throw new Exception("NPC type is null for prefab resolution.");
if (TypeToPrefab.TryGetValue(npcType, out var cached) && cached != null)
{
MarkPrefabsConfigured();
return cached;
}
lock (TemplateLoadLock)
{
if (TypeToPrefab.TryGetValue(npcType, out cached) && cached != null)
{
MarkPrefabsConfigured();
return cached;
}
// Prefer a spawnable prefab provided by the base game.
var nm = InstanceFinder.NetworkManager;
if (nm == null)
throw new Exception("NetworkManager not found when resolving NPC prefab.");
PrefabObjects spawnablePrefabs = nm.SpawnablePrefabs;
if (spawnablePrefabs == null)
throw new Exception("SpawnablePrefabs not available on NetworkManager.");
NetworkObject chosen = null;
int count = spawnablePrefabs.GetObjectCount();
// Check if this NPC type is a dealer type by checking the IsDealer property
bool isDealerType = false;
try
{
// Create a temporary instance to check IsDealer property
NPC tempInstance = (NPC)FormatterServices.GetUninitializedObject(npcType);
isDealerType = tempInstance.IsDealer;
}
catch
{
// Fallback to checking if already registered as dealer type
isDealerType = IsDealerType(npcType);
}
if (isDealerType)
{
// First, try to find a prefab named "Dealer"
for (int i = 0; i < count; i++)
{
NetworkObject obj = spawnablePrefabs.GetObject(true, i);
if (obj != null && obj.gameObject != null && obj.gameObject.name == "Dealer")
{
chosen = obj;
break;
}
}
// If "Dealer" was not found, look for any spawnable containing a Dealer component
if (chosen == null)
{
for (int i = 0; i < count; i++)
{
NetworkObject obj = spawnablePrefabs.GetObject(true, i);
if (obj != null && obj.gameObject != null && obj.gameObject.GetComponent<S1Economy.Dealer>() != null)
{
chosen = obj;
break;
}
}
}
}
// If not a dealer type or dealer prefab not found, use CivilianNPC logic
if (chosen == null)
{
for (int i = 0; i < count; i++)
{
NetworkObject obj = spawnablePrefabs.GetObject(true, i);
if (obj != null && obj.gameObject != null && obj.gameObject.name == "CivilianNPC")
{
chosen = obj;
break;
}
}
}
// If "CivilianNPC" was not found, look for any spawnable containing the base NPC component.
// TODO: Migrate to falling back to "BaseNPC"
if (chosen == null)
{
for (int i = 0; i < count; i++)
{
NetworkObject obj = spawnablePrefabs.GetObject(true, i);
if (obj != null && obj.gameObject != null && obj.gameObject.GetComponent<S1NPCs.NPC>() != null)
{
chosen = obj;
break;
}
}
}
if (chosen == null)
{
string expectedPrefabName = isDealerType ? "Dealer" : "CivilianNPC";
string expectedComponent = isDealerType ? "Dealer" : "NPC";
throw new Exception($"Failed to locate a suitable NPC spawnable prefab ({expectedPrefabName} or any with {expectedComponent} component).");
}
// Build a unique per-NPC prefab based on type
NetworkObject prefabNO = UnityEngine.Object.Instantiate<NetworkObject>(chosen);
string prefabName = GetPrefabNameForType(npcType);
prefabNO.gameObject.name = prefabName;
// Ensure template prefab does not execute runtime logic or remain in NPC registry
try
{
// Deactivate template instance to prevent Awake/Start side effects
if (prefabNO != null && prefabNO.gameObject != null)
{
prefabNO.gameObject.SetActive(false);
// Handle registry cleanup for both NPC and Dealer components
var dealerComp = prefabNO.gameObject.GetComponent<S1Economy.Dealer>();
var npcComp = dealerComp != null ? dealerComp as S1NPCs.NPC : prefabNO.gameObject.GetComponent<S1NPCs.NPC>();
if (npcComp != null)
{
var reg = S1NPCs.NPCManager.NPCRegistry;
if (reg != null && reg.Count > 0)
{
for (int i = reg.Count - 1; i >= 0; i--)
{
if (reg[i] == npcComp)
{
reg.RemoveAt(i);
break;
}
}
}
}
}
}
catch { }
// Let the NPC subclass declare required components on the prefab (Customer, actions, etc.)
var builder = new NPCPrefabBuilder(prefabNO.gameObject, npcType);
if (owner != null)
{
owner.ConfigurePrefab(builder);
}
else
{
InvokeConfigurePrefabWithoutInstance(npcType, builder);
}
// Ensure schedule actions exist on the template so NetworkBehaviour indices are stable
try
{
EnsureScheduleActionsOnPrefab(prefabNO.gameObject);
}
catch { }
// If we are pre-registering without an instance owner, ensure baseline Customer exists when applicable
if (owner == null)
{
try
{
// Only add Customer for types that opted-in via EnsureCustomer
if (IsCustomerType(npcType))
{
var existingCustomer = prefabNO.gameObject.GetComponent<S1Economy.Customer>();
if (existingCustomer == null)
{
existingCustomer = prefabNO.gameObject.AddComponent<S1Economy.Customer>();
}
// Apply defaults if the mod registered them
var defaults = GetCustomerDefaultsForType(npcType);
if (defaults != null && existingCustomer != null)
{
var data = BuildCustomerDefaultsForType(npcType);
TrySetCustomerDataOnComponent(existingCustomer, data);
}
}
// Handle dealer conversion: if dealer type, check if we already have a Dealer component
if (IsDealerType(npcType))
{
var existingDealer = prefabNO.gameObject.GetComponent<S1Economy.Dealer>();
// If Dealer already exists (from using Dealer prefab), apply dealer defaults
if (existingDealer != null)
{
var dealerDefaults = BuildDealerDefaultsForType(npcType);
if (dealerDefaults != null)
{
TryApplyDealerDefaults(existingDealer, dealerDefaults);
}
}
else
{
// If we're using CivilianNPC prefab but need dealer functionality, warn
Logger.Warning($"[S1API] NPC {npcType.Name} requested dealer functionality but prefab does not have Dealer component. EnsureDealer() was called before prefab creation.");
}
}
}
catch { }
}
// Register as spawnable so FishNet assigns stable behaviour indices and can network-spawn
try
{
if (spawnablePrefabs != null)
{
bool alreadyRegistered = false;
int existingCount = spawnablePrefabs.GetObjectCount();
for (int i = 0; i < existingCount; i++)
{
NetworkObject existing = spawnablePrefabs.GetObject(true, i);
if (existing != null && existing.gameObject != null && existing.gameObject.name == prefabName)
{
alreadyRegistered = true;
break;
}
}
if (!alreadyRegistered)
spawnablePrefabs.AddObject(prefabNO);
}
}
catch (Exception ex)
{
Logger.Warning($"[S1API] Failed to register {prefabName} in SpawnablePrefabs: {ex.Message}");
}
// Organize the prefab in the scene hierarchy to avoid clutter
NPCPrefabContainer.OrganizePrefab(prefabNO.gameObject, npcType.Name);
TypeToPrefab[npcType] = prefabNO.gameObject;
MarkPrefabsConfigured();
return prefabNO.gameObject;
}
}
private static void InvokeConfigurePrefabWithoutInstance(System.Type npcType, NPCPrefabBuilder builder)
{
if (npcType == null || builder == null)
return;
// Skip if the type did not override ConfigurePrefab
MethodInfo configureMethod = npcType.GetMethod("ConfigurePrefab", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
if (configureMethod == null || configureMethod.DeclaringType == typeof(NPC))
return;
NPC tempInstance = null;
try
{
tempInstance = (NPC)FormatterServices.GetUninitializedObject(npcType);
configureMethod.Invoke(tempInstance, new object[] { builder });
}
finally
{
tempInstance = null;
}
}
private static string GetPrefabNameForType(System.Type npcType)
{
// Avoid path separators, keep name concise, deterministic per type
string typeName = npcType != null ? npcType.Name : "UnknownNPC";
return $"S1API_{typeName}";
}
/// <summary>
/// INTERNAL: Creates a wrapper for a network-spawned custom NPC on clients.
/// Called when a client receives an NPC that was spawned on the server.
/// </summary>
internal static NPC? CreateWrapperForNetworkSpawnedNPC(S1NPCs.NPC baseNpc)
{
if (baseNpc == null)
return null;
try
{
// Check if this is a custom S1API NPC by looking for NPCPrefabIdentity or prefab name
var identity = baseNpc.GetComponent<NPCPrefabIdentity>();
string prefabName = baseNpc.gameObject.name;
// Remove "(Clone)" suffix if present
if (prefabName.EndsWith("(Clone)"))
prefabName = prefabName.Substring(0, prefabName.Length - 7);
// Check if it's an S1API prefab
if (!prefabName.StartsWith("S1API_", StringComparison.Ordinal) && identity == null)
return null;
// Extract type name from prefab name
string typeName = prefabName.StartsWith("S1API_", StringComparison.Ordinal)
? prefabName.Substring(6) // Remove "S1API_" prefix
: null;
if (string.IsNullOrEmpty(typeName))
return null;
// Find the NPC type in loaded assemblies
System.Type npcType = null;
var baseType = typeof(NPC);
var asms = AppDomain.CurrentDomain.GetAssemblies();
for (int ai = 0; ai < asms.Length && npcType == null; ai++)
{
var asm = asms[ai];
if (asm == baseType.Assembly)
continue; // Skip S1API assembly (internal wrappers)
System.Type[] types;
try { types = asm.GetTypes(); } catch { continue; }
for (int ti = 0; ti < types.Length; ti++)
{
var t = types[ti];
if (t == null || t.IsAbstract || !baseType.IsAssignableFrom(t))
continue;
if (t.Name == typeName)
{
npcType = t;
break;
}
}
}
if (npcType == null)
return null;
// Check if wrapper already exists
for (int i = 0; i < All.Count; i++)
{
var existing = All[i];
if (existing != null && existing.S1NPC == baseNpc)
return existing;
}
// Create uninitialized instance (avoids constructor which creates new GameObject)
NPC wrapper = (NPC)FormatterServices.GetUninitializedObject(npcType);
// Use reflection to set readonly fields/properties
bool s1NpcSet = Internal.Utils.ReflectionUtils.TrySetFieldOrProperty(wrapper, "S1NPC", baseNpc);
bool isCustomNpcSet = Internal.Utils.ReflectionUtils.TrySetFieldOrProperty(wrapper, "IsCustomNPC", true);
// gameObject is a readonly auto-property, need to find and set its backing field
bool gameObjectSet = false;
var allFields = Internal.Utils.ReflectionUtils.GetAllFields(npcType, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
for (int fi = 0; fi < allFields.Length; fi++)
{
var field = allFields[fi];
// Try compiler-generated backing field name or direct field name
if ((field.Name == "<gameObject>k__BackingField" || field.Name == "gameObject") &&
field.FieldType == typeof(GameObject))
{
try
{
field.SetValue(wrapper, baseNpc.gameObject);
gameObjectSet = true;
break;
}
catch (Exception ex)
{
Logger.Warning($"CreateWrapperForNetworkSpawnedNPC: Exception setting gameObject backing field '{field.Name}': {ex.Message}");
}
}
}
// Fallback: try the property setter if field wasn't found
if (!gameObjectSet)
gameObjectSet = Internal.Utils.ReflectionUtils.TrySetFieldOrProperty(wrapper, "gameObject", baseNpc.gameObject);
// Validate that critical fields were set
if (!s1NpcSet)
{
Logger.Warning($"CreateWrapperForNetworkSpawnedNPC: Could not set S1NPC field/property for '{baseNpc.ID}'.");
return null;
}
if (!gameObjectSet)
{
Logger.Warning($"CreateWrapperForNetworkSpawnedNPC: Could not set gameObject field/property for '{baseNpc.ID}'. Tried backing field and property setter.");
return null;
}
// Verify the wrapper has the correct references
if (wrapper.S1NPC != baseNpc)
{
Logger.Warning($"CreateWrapperForNetworkSpawnedNPC: S1NPC field not set correctly for '{baseNpc.ID}'.");
return null;
}
if (wrapper.gameObject != baseNpc.gameObject)
{
Logger.Warning($"CreateWrapperForNetworkSpawnedNPC: gameObject field not set correctly for '{baseNpc.ID}'.");
return null;
}
InitializeWrapperStateFromNetworkSpawn(wrapper, baseNpc);
// Add to All list
All.Add(wrapper);
return wrapper;
}
catch (Exception ex)
{
Logger.Warning($"CreateWrapperForNetworkSpawnedNPC: Exception creating wrapper for '{baseNpc?.ID ?? "<null>"}': {ex.Message}");
Logger.Warning($"Stack trace: {ex.StackTrace}");
return null;
}
}
private static void InitializeWrapperStateFromNetworkSpawn(NPC wrapper, S1NPCs.NPC baseNpc)
{
if (wrapper == null || baseNpc == null)
return;
try
{
var runtimeAvatar = baseNpc.Avatar ?? baseNpc.gameObject?.GetComponentInChildren<S1AvatarFramework.Avatar>(true);
wrapper._runtimeAvatar = runtimeAvatar;
wrapper.Appearance = new NPCAppearance(wrapper, runtimeAvatar);
wrapper.RestoreRuntimeAvatarAppearance();
wrapper.RefreshMessagingIcons();
try
{
var registry = S1NPCs.NPCManager.NPCRegistry;
if (registry != null && !registry.Contains(baseNpc))
registry.Add(baseNpc);
}
catch { }
}
catch (Exception ex)
{
Logger.Warning($"InitializeWrapperStateFromNetworkSpawn: Failed for '{baseNpc?.ID ?? "<null>"}': {ex.Message}");
}
}
public void RefreshMessagingIcons()
{
try
{
Sprite sprite = Icon;
if (sprite == null)
return;
var convo = S1NPC?.MSGConversation;
if (convo == null)
return;
var entryRect = convo.entry ?? ResolveConversationRect(convo, "entry");
var containerRect = ResolveConversationRect(convo, "container");
TryApplyIconToRect(entryRect, sprite);
TryApplyIconToRect(containerRect, sprite);
}
catch (Exception ex)
{
Logger.Warning($"RefreshMessagingIcons failed for '{S1NPC?.ID ?? "<null>"}': {ex.Message}");
}
}
private void TryApplyIconToRect(RectTransform rect, Sprite sprite)
{
if (rect == null || sprite == null)
return;
ApplyIconToPath(rect, null, sprite);
ApplyIconToPath(rect, "Icon", sprite);
ApplyIconToPath(rect, "IconMask/Icon", sprite);
}
private static void ApplyIconToPath(RectTransform root, string childPath, Sprite sprite)
{
if (root == null || sprite == null)
return;
Transform target = string.IsNullOrEmpty(childPath) ? root : root.Find(childPath);
if (target == null)
return;
var image = target.GetComponent<Image>();
if (image == null)
return;
image.sprite = sprite;
image.enabled = true;
}
private static RectTransform ResolveConversationRect(S1Messaging.MSGConversation convo, string memberName)
{
if (convo == null || string.IsNullOrEmpty(memberName))
return null;
var value = Internal.Utils.ReflectionUtils.TryGetFieldOrProperty(convo, memberName);
return value as RectTransform;
}
internal static void RegisterSchedulePlanForType(System.Type npcType, System.Collections.Generic.List<IScheduleActionSpec> specs)
{
if (npcType == null || specs == null)
return;
TypeToSchedulePlan[npcType] = specs;
}
/// <summary>
/// Pre-registers a per-type NPC prefab into FishNet spawnables without creating a live instance.
/// Should be called on both server and client before any NPC instances are spawned.
/// </summary>
public static void PreRegisterPrefabForType(System.Type npcType)
{
try
{
GetOrCreatePerNpcPrefab(npcType, null);
}
catch (Exception ex)
{
// Unwrap TargetInvocationException (from reflection) to reveal the actual cause
var inner = ex is System.Reflection.TargetInvocationException tie ? tie.InnerException : ex;
var msg = inner?.Message ?? ex.Message;
var trace = inner?.StackTrace ?? ex.StackTrace;
Logger.Warning($"[S1API] Failed to pre-register NPC prefab for {npcType?.Name}: {msg}");
if (!string.IsNullOrEmpty(trace))
Logger.Warning($"[S1API] Stack trace: {trace}");
}
}
/// <summary>
/// Scans loaded assemblies for subclasses of S1API.Entities.NPC and pre-registers their prefabs.
/// </summary>
public static void PreRegisterAllNpcPrefabs()
{
try
{
// Only pre-register when SpawnablePrefabs is available; otherwise, a warmup will retry shortly
var nm = InstanceFinder.NetworkManager;
var spawnables = nm?.SpawnablePrefabs;
if (spawnables == null)
return;
var baseType = typeof(NPC);
var baseAssembly = baseType.Assembly;
var asms = AppDomain.CurrentDomain.GetAssemblies();
for (int ai = 0; ai < asms.Length; ai++)
{
var asm = asms[ai];
Type[] types;
try { types = asm.GetTypes(); } catch { continue; }
for (int ti = 0; ti < types.Length; ti++)
{
var t = types[ti];
if (t == null || t.IsAbstract)
continue;
if (baseType.IsAssignableFrom(t))
{
// Skip internal S1API NPC wrappers; only pre-register mod-defined types
if (t.Assembly == baseAssembly)
continue;
PreRegisterPrefabForType(t);
}
}
}
// Prefabs are configured for this process once registration has been attempted with spawnables present
MarkPrefabsConfigured();
}
catch (Exception ex)
{
Logger.Error($"[S1API] PreRegisterAllNpcPrefabs failed: {ex.Message}");
Logger.Error($"[S1API] Stack Trace: {ex.StackTrace}");
}
}
internal static void RegisterCustomerDefaultsForType(System.Type npcType, System.Action<CustomerDataBuilder> configure)
{
if (npcType == null || configure == null)
return;
TypeToCustomerDefaults[npcType] = configure;
}
internal static void RegisterCustomerType(System.Type npcType)
{
if (npcType == null)
return;
CustomerTypes.Add(npcType);
}
internal static bool IsCustomerType(System.Type npcType)
{
if (npcType == null)
return false;
return CustomerTypes.Contains(npcType);
}
// Helper accessors for loader-time default application
internal static bool HasCustomerDefaultsForType(System.Type npcType)
{
if (npcType == null)
return false;
return TypeToCustomerDefaults.TryGetValue(npcType, out var cfg) && cfg != null;
}
internal static System.Action<CustomerDataBuilder> GetCustomerDefaultsForType(System.Type npcType)
{
if (npcType == null)
return null;
TypeToCustomerDefaults.TryGetValue(npcType, out var cfg);
return cfg;
}
internal static S1Economy.CustomerData BuildCustomerDefaultsForType(System.Type npcType)
{
var cfg = GetCustomerDefaultsForType(npcType);
if (cfg == null)
return null;
var builder = new CustomerDataBuilder();
cfg(builder);
return builder.BuildInternal();
}
internal static bool TrySetCustomerDataOnComponent(S1Economy.Customer customerComponent, S1Economy.CustomerData data)
{
if (customerComponent == null || data == null)
return false;
try
{
#if MONOMELON
var field = typeof(S1Economy.Customer).GetField("customerData", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
field?.SetValue(customerComponent, data);
var field2 = typeof(S1Economy.Customer).GetField("currentAffinityData", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
field2?.SetValue(customerComponent, data.DefaultAffinityData);
#else
customerComponent.customerData = data;
customerComponent.currentAffinityData = data.DefaultAffinityData;
#endif
return true;
}
catch
{
return false;
}
}
internal static bool TryApplyDealerDefaults(S1Economy.Dealer dealerComponent, DealerDataBuilder.DealerConfigData data)
{
if (dealerComponent == null || data == null)
return false;
try
{
string dealerId = string.Empty;
try
{
dealerId = dealerComponent.ID ?? dealerComponent?.name ?? "<unknown-dealer>";
}
catch
{
dealerId = "<unknown-dealer>";
}
dealerComponent.SigningFee = data.SigningFee;
dealerComponent.Cut = data.Cut;
#if MONOMELON
var dealerTypeField = typeof(S1Economy.Dealer).GetField("DealerType", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
if (dealerTypeField != null)
{
var dealerTypeEnum = Enum.Parse(typeof(S1Economy.EDealerType), data.DealerType.ToString());
dealerTypeField.SetValue(dealerComponent, dealerTypeEnum);
}
#else
dealerComponent.DealerType = (S1Economy.EDealerType)(int)data.DealerType;
#endif
// Note: SellInsufficientQualityItems and SellExcessQualityItems were removed in v0.4.3
// Store Home building reference in NPCPrefabIdentity for resolution in Main scene
// This runs in Menu scene where buildings aren't available yet
string buildingNameToStore = null;
if (data.Home != null)
{
// Try to get name from Building wrapper (works even for deferred wrappers)
buildingNameToStore = data.Home.Name;
}
else if (!string.IsNullOrEmpty(data.HomeName))
{
buildingNameToStore = data.HomeName;
}
if (!string.IsNullOrEmpty(buildingNameToStore))
{
// Store building name in NPCPrefabIdentity for deferred resolution
// Get identity from the NPC GameObject (Dealer inherits from NPC, so dealerComponent IS the NPC)
// Use gameObject.GetComponent to ensure we get the component from the root GameObject
var identity = dealerComponent.gameObject.GetComponent<Internal.Entities.NPCPrefabIdentity>();
if (identity != null)
{
// Set component field (works on Mono, may be null on Il2Cpp)
identity.DealerHomeBuildingName = buildingNameToStore;
// Get prefab name - normalize to match RegisterToStaticCache behavior
string prefabName = dealerComponent.gameObject.name;
if (prefabName.EndsWith("(Clone)"))
prefabName = prefabName.Substring(0, prefabName.Length - 7);
// Register to static cache for Il2Cpp support (this stores in registry)
identity.RegisterToStaticCache(prefabName);
}
else
{
Logger.Warning($"[NPC] TryApplyDealerDefaults: NPCPrefabIdentity component not found on {dealerComponent.gameObject.name} for dealer {dealerId}. Building name '{buildingNameToStore}' will not be stored.");
}
}
else
{
Logger.Warning($"[NPC] TryApplyDealerDefaults: No building name to store for dealer {dealerId}. Home={data.Home != null}, HomeName={data.HomeName ?? "null"}");
}
// Note: CompletedDealsVariable would need to be set via other means
return true;
}
catch (Exception ex)
{
Logger.Error($"[NPC] TryApplyDealerDefaults: Exception applying dealer defaults: {ex.Message}");
Logger.Error($"[NPC] Stack trace: {ex.StackTrace}");
return false;
}
}
internal static void RegisterRelationshipDefaultsForType(System.Type npcType, System.Action<NPCRelationshipDataBuilder> configure)
{
if (npcType == null || configure == null)
return;
TypeToRelationshipDefaults[npcType] = configure;
}
internal static void RegisterDealerDefaultsForType(System.Type npcType, System.Action<DealerDataBuilder> configure)
{
if (npcType == null || configure == null)
return;
TypeToDealerDefaults[npcType] = configure;
}
internal static void RegisterDealerType(System.Type npcType)
{
if (npcType == null)
return;
DealerTypes.Add(npcType);
}
internal static bool IsDealerType(System.Type npcType)
{
if (npcType == null)
return false;
return DealerTypes.Contains(npcType);
}
internal static bool HasDealerDefaultsForType(System.Type npcType)
{
if (npcType == null)
return false;
return TypeToDealerDefaults.TryGetValue(npcType, out var cfg) && cfg != null;
}
internal static System.Action<DealerDataBuilder> GetDealerDefaultsForType(System.Type npcType)
{
if (npcType == null)
return null;
TypeToDealerDefaults.TryGetValue(npcType, out var cfg);
return cfg;
}
internal static DealerDataBuilder.DealerConfigData BuildDealerDefaultsForType(System.Type npcType)
{
var cfg = GetDealerDefaultsForType(npcType);
if (cfg == null)
return null;
var builder = new DealerDataBuilder();
cfg(builder);
return builder.BuildInternal();
}
internal static void RegisterRandomInventoryDefaultsForType(System.Type npcType, System.Action<RandomInventoryItemsBuilder> configure)
{
if (npcType == null || configure == null)
return;
TypeToRandomInventoryDefaults[npcType] = configure;
}
internal static bool HasRandomInventoryDefaultsForType(System.Type npcType)
{
if (npcType == null)
return false;
return TypeToRandomInventoryDefaults.TryGetValue(npcType, out var cfg) && cfg != null;
}
internal static System.Action<RandomInventoryItemsBuilder> GetRandomInventoryDefaultsForType(System.Type npcType)
{
if (npcType == null)
return null;
TypeToRandomInventoryDefaults.TryGetValue(npcType, out var cfg);
return cfg;
}
internal static RandomInventoryItemsBuilder.InventoryDefaultsData BuildRandomInventoryDefaultsForType(System.Type npcType)
{
var cfg = GetRandomInventoryDefaultsForType(npcType);
if (cfg == null)
return null;
var builder = new RandomInventoryItemsBuilder();
cfg(builder);