-
Notifications
You must be signed in to change notification settings - Fork 1
/
FilteredNets.cs
647 lines (556 loc) · 19.5 KB
/
FilteredNets.cs
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
using HarmonyLib;
using Steamworks;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;
using JetBrains.Annotations;
using UnityEngine;
public class FilteredNets : Mod
{
private const string HarmonyId = "com.janniksam.raftmods.filterednets";
private const string ModNamePrefix = "<color=#42a7f5>Filtered</color><color=#FF0000>Nets</color>";
private const string ConfigurationSubPath = @"mods\FilteredNets\";
private const string ConfigurationFile = "netfilterMapping.xml";
private readonly string m_configurationPath = Path.Combine(Directory.GetCurrentDirectory(), ConfigurationSubPath);
private static readonly Dictionary<uint, string> m_netSetup = new Dictionary<uint, string>();
private Harmony m_harmony;
private bool m_justJoinedAndNotHost;
[UsedImplicitly]
public void Start()
{
Debug.Log(string.Format("{0} has been loaded!", ModNamePrefix));
m_harmony = new Harmony(HarmonyId);
m_harmony.PatchAll(Assembly.GetExecutingAssembly());
}
[UsedImplicitly]
public void OnModUnload()
{
Debug.Log(string.Format("{0} has been unloaded!", ModNamePrefix));
m_harmony.UnpatchAll(HarmonyId);
Destroy(gameObject);
}
[UsedImplicitly]
public void Update()
{
if (Semih_Network.InMenuScene)
{
return;
}
if (m_justJoinedAndNotHost)
{
TryRequestNetConfigurationFromHost();
}
MessageHandler.ReadP2P_Channel();
}
private void TryRequestNetConfigurationFromHost()
{
var player = RAPI.GetLocalPlayer();
if (player == null)
{
return;
}
Debug.Log(string.Format("{0}: Requesting the current configurations for each net from the host.",
ModNamePrefix));
MessageHandler.SendMessage(
new MessageSyncNetFiltersRequest(
(Messages)MessageHandler.FilteredNetsMessages.SyncNetFiltersRequested));
m_justJoinedAndNotHost = false;
}
private static void ToggleFilterModeForNet(ItemNet net)
{
uint netId = net.itemCollector.ObjectIndex;
if (!m_netSetup.ContainsKey(netId))
{
m_netSetup.Add(netId, NetFilters.All);
}
string currentFilterMode = m_netSetup[netId];
string nextFilterMode = NetFilters.Next(currentFilterMode);
SetNetFilter(netId, nextFilterMode);
MessageHandler.SendMessage(
new MessageItemNetFilterChanged(
(Messages)MessageHandler.FilteredNetsMessages.FilterChanged, netId, nextFilterMode));
}
private static void SetNetFilter(uint netId, string nextFilterMode)
{
m_netSetup[netId] = nextFilterMode;
Debug.Log(string.Format("{0}: Filtermode of net {1} was set to {2}", ModNamePrefix, netId, nextFilterMode));
}
private static string GetCurrentFilter(ItemNet net)
{
var netId = net.itemCollector.ObjectIndex;
if (!m_netSetup.ContainsKey(netId))
{
return NetFilters.All;
}
return m_netSetup[netId];
}
public override void WorldEvent_WorldLoaded()
{
base.WorldEvent_WorldLoaded();
m_netSetup.Clear();
if (!Semih_Network.IsHost)
{
m_justJoinedAndNotHost = true;
return;
}
m_justJoinedAndNotHost = false;
LoadNetFilterMapping();
}
public override void WorldEvent_WorldSaved()
{
base.WorldEvent_WorldSaved();
if (!Semih_Network.IsHost)
{
return;
}
SaveNetFilterMapping();
}
private void LoadNetFilterMapping()
{
var mappings = ReadConfigurationFile();
ApplyFilters(mappings);
}
private static void ApplyFilters(NetFilterMappings mappings)
{
if (mappings == null ||
mappings.Mappings == null)
{
return;
}
uint[] itemNets = FindObjectsOfType<ItemNet>().Select(p => p.itemCollector.ObjectIndex).ToArray();
foreach (var mapping in mappings.Mappings)
{
if (itemNets.Contains(mapping.NetId))
{
if (m_netSetup.ContainsKey(mapping.NetId))
{
m_netSetup[mapping.NetId] = mapping.ActiveNetFilter;
}
else
{
m_netSetup.Add(mapping.NetId, mapping.ActiveNetFilter);
}
}
}
}
private static void SyncFiltersWithPlayers()
{
Debug.Log(string.Format("{0}: Sync was requested. Syncing filters with players...", ModNamePrefix));
var mappings = GetCurrentFilterMapping();
MessageHandler.SendMessage(
new MessageSyncNetFilters(
(Messages)MessageHandler.FilteredNetsMessages.SyncNetFilters, mappings));
}
private NetFilterMappings ReadConfigurationFile()
{
string currentConfigurationFilePath = GetConfigurationFilePath();
if (!File.Exists(currentConfigurationFilePath))
{
return null;
}
return ReadFile<NetFilterMappings>(currentConfigurationFilePath);
}
private void SaveNetFilterMapping()
{
var currentConfigurationFilePath = GetConfigurationFilePath();
var currentConfigurationFileDirectory = Path.GetDirectoryName(currentConfigurationFilePath);
if (currentConfigurationFileDirectory == null)
{
Debug.LogError(string.Format("{0}: Cannot determine save-path.", ModNamePrefix));
return;
}
if (!Directory.Exists(currentConfigurationFileDirectory))
{
Directory.CreateDirectory(currentConfigurationFileDirectory);
}
var netfilterMapping = GetCurrentFilterMapping();
WriteFile(netfilterMapping, currentConfigurationFilePath);
}
private static T ReadFile<T>(string filePath) where T : class
{
try
{
var serializer = new XmlSerializer(typeof(T));
using (var reader = new StreamReader(filePath))
{
return (T)serializer.Deserialize(reader);
}
}
catch (Exception ex)
{
Debug.LogError(string.Format("{0}: Could not read file. Exception: {1}.", ModNamePrefix, ex));
return null;
}
}
private static void WriteFile<T>(T serializableObject, string path) where T : class
{
try
{
var serializer = new XmlSerializer(typeof(T));
using (var writer = new StreamWriter(path))
{
serializer.Serialize(writer, serializableObject);
}
}
catch (Exception ex)
{
Debug.LogError(string.Format("{0}: Could not write file. Exception: {1}.", ModNamePrefix, ex));
}
}
private static NetFilterMappings GetCurrentFilterMapping()
{
return new NetFilterMappings(
m_netSetup.Select(p => new NetFilterMapping
{
NetId = p.Key,
ActiveNetFilter = p.Value
}).ToArray());
}
private string GetConfigurationFilePath()
{
return Path.Combine(m_configurationPath, SaveAndLoad.CurrentGameFileName, ConfigurationFile);
}
private static bool ShouldBeFilteredOut(PickupItem_Networked item, uint netId)
{
if (!m_netSetup.ContainsKey(netId))
{
return false;
}
var filter = m_netSetup[netId];
if (filter == NetFilters.All)
{
return false;
}
string name = GetItemName(item);
if (name == NetFilters.Barrels)
{
return false;
}
return name != filter;
}
private static string GetItemName(PickupItem_Networked item)
{
if (item.PickupItem.dropper != null)
{
return NetFilters.Barrels;
}
string name = "";
if (item.PickupItem.itemInstance.Valid)
{
name = item.PickupItem.itemInstance.UniqueName;
}
else
{
foreach (var cost in item.PickupItem.yieldHandler.yieldAsset.yieldAssets)
{
return cost.item.UniqueName;
}
}
return name;
}
#region Persisting Net Configuration
[Serializable]
public class NetFilterMappings
{
public NetFilterMappings()
{
}
public NetFilterMappings(NetFilterMapping[] mappings)
{
Mappings = mappings;
}
public NetFilterMapping[] Mappings { get; set; }
}
[Serializable]
public class NetFilterMapping
{
public uint NetId { get; set; }
public string ActiveNetFilter { get; set; }
}
#endregion
#region Harmony Patches
[HarmonyPatch(typeof(ItemCollector)), HarmonyPatch("OnTriggerEnter")]
[UsedImplicitly]
public class ItemCollectorEditPatch
{
[UsedImplicitly]
private static bool Prefix(
// ReSharper disable InconsistentNaming
// ReSharper disable SuggestBaseTypeForParameter
ItemCollector __instance,
Collider other,
int ___maxNumberOfItems,
Collider ___collectorCollider)
// ReSharper restore SuggestBaseTypeForParameter
// ReSharper restore InconsistentNaming
{
if (!___collectorCollider.enabled ||
___maxNumberOfItems != 0 &&
__instance.collectedItems.Count >= ___maxNumberOfItems ||
!Helper.ObjectIsOnLayer(other.transform.gameObject, __instance.collectMask))
{
//Skip collection
return false;
}
var itemNet = __instance.GetComponentInParent<ItemNet>();
if (itemNet == null ||
itemNet.itemCollector == null)
{
// this is not an item net, continue with collection algorithm
return true;
}
var item = other.transform.GetComponentInParent<PickupItem_Networked>();
if (item == null)
{
// invalid item, continue with collection algorithm
return true;
}
if (ShouldBeFilteredOut(item, itemNet.itemCollector.ObjectIndex))
{
//Skip collection
return false;
}
// Continue with collection algorithm
return true;
}
}
[HarmonyPatch(typeof(ItemNet)), HarmonyPatch("OnIsRayed")]
[UsedImplicitly]
public class ItemNetEditPatch
{
[UsedImplicitly]
private static bool Prefix
(
// ReSharper disable InconsistentNaming
ItemNet __instance,
CanvasHelper ___canvas,
ref bool ___displayText)
// ReSharper restore InconsistentNaming
{
// This overrides the original logic.
// If the internal logic is changed in the future, this has to change aswell.
if (!Helper.LocalPlayerIsWithinDistance(
__instance.transform.position, Player.UseDistance))
{
// Not within use distance, run old logic
return true;
}
if (MyInput.GetButtonDown("Rotate"))
{
ToggleFilterModeForNet(__instance);
}
___displayText = true;
var toggleFilterText = string.Format("Toggle net filter ({0})", GetCurrentFilter(__instance));
if (__instance.itemCollector.collectedItems.Count > 0)
{
___canvas.displayTextManager.HideDisplayTexts();
LocalizationParameters.itemCount = __instance.itemCollector.collectedItems.Count;
___canvas.displayTextManager.ShowText(
toggleFilterText, MyInput.Keybinds["Rotate"].MainKey, 1,
Helper.GetTerm("Game/CollectItemCount", true), MyInput.Keybinds["Interact"].MainKey, 2);
}
else
{
___canvas.displayTextManager.ShowText(
toggleFilterText, MyInput.Keybinds["Rotate"].MainKey, 1);
}
// skip original logic
return false;
}
}
#endregion
private static class NetFilters
{
public const string All = "Default";
private const string Planks = "Plank";
private const string Plastic = "Plastic";
private const string Thatches = "Thatch";
public const string Barrels = "Barrels";
private static readonly string[] m_allFilters =
{
All,
Planks,
Plastic,
Thatches,
Barrels,
};
internal static string Next(string currentFilterMode)
{
int nextIndex = Array.IndexOf(m_allFilters, currentFilterMode) + 1;
if (nextIndex >= m_allFilters.Length)
{
nextIndex = 0;
}
return m_allFilters[nextIndex];
}
}
#region Networking
private static class MessageHandler
{
private const int FilteredNetsNetworkChannel = 72;
public enum FilteredNetsMessages
{
FilterChanged = 10910,
SyncNetFilters = 10911,
SyncNetFiltersRequested = 10912
}
public static void SendMessage(Message message)
{
if (Semih_Network.IsHost)
{
RAPI.GetLocalPlayer().Network.RPC(message, Target.Other, EP2PSend.k_EP2PSendReliable, (NetworkChannel)FilteredNetsNetworkChannel);
}
else
{
RAPI.GetLocalPlayer().SendP2P(message, EP2PSend.k_EP2PSendReliable, (NetworkChannel)FilteredNetsNetworkChannel);
}
}
public static void ReadP2P_Channel()
{
if (Semih_Network.InMenuScene)
{
return;
}
uint num;
while (SteamNetworking.IsP2PPacketAvailable(out num, FilteredNetsNetworkChannel))
{
byte[] array = new byte[num];
uint num2;
CSteamID cSteamId;
if (!SteamNetworking.ReadP2PPacket(array, num, out num2, out cSteamId, FilteredNetsNetworkChannel))
{
continue;
}
var messages = DeserializeMessages(array);
foreach (var message in messages)
{
if (message == null)
{
continue;
}
Messages type = message.Type;
switch (type)
{
case (Messages)FilteredNetsMessages.FilterChanged:
{
var filterMessage = message as MessageItemNetFilterChanged;
if (filterMessage == null)
{
break;
}
SetNetFilter(filterMessage.ObjectIndex, filterMessage.NewFilter);
break;
}
case (Messages)FilteredNetsMessages.SyncNetFilters:
{
var syncMessage = message as MessageSyncNetFilters;
if (syncMessage == null)
{
break;
}
ApplyFilters(syncMessage.Mappings);
Debug.Log(string.Format("{0}: Synced the item net filters with host...", ModNamePrefix));
break;
}
case (Messages)FilteredNetsMessages.SyncNetFiltersRequested:
{
if (Semih_Network.IsHost)
{
SyncFiltersWithPlayers();
}
break;
}
}
}
}
}
private static Message[] DeserializeMessages(byte[] array)
{
Packet packet;
using (var ms = new MemoryStream(array))
{
var bf = new BinaryFormatter
{
Binder = new PreMergeToMergedDeserializationBinder()
};
packet = bf.Deserialize(ms) as Packet;
}
if (packet == null)
{
return new Message[0];
}
if (packet.PacketType == PacketType.Single)
{
var packetSingle = packet as Packet_Single;
if (packetSingle == null)
{
return new Message[0];
}
return new[]
{
packetSingle.message
};
}
var multiplepackages = packet as Packet_Multiple;
if (multiplepackages == null)
{
return new Message[0];
}
return multiplepackages.messages;
}
}
[Serializable]
public class MessageItemNetFilterChanged : Message
{
public uint ObjectIndex;
public string NewFilter;
public MessageItemNetFilterChanged()
{
}
public MessageItemNetFilterChanged(Messages type, uint objectIndex, string newFilter)
: base(type)
{
ObjectIndex = objectIndex;
NewFilter = newFilter;
}
}
[Serializable]
public class MessageSyncNetFilters : Message
{
public NetFilterMappings Mappings;
public MessageSyncNetFilters()
{
}
public MessageSyncNetFilters(Messages type, NetFilterMappings mappings)
: base(type)
{
Mappings = mappings;
}
}
[Serializable]
public class MessageSyncNetFiltersRequest : Message
{
public MessageSyncNetFiltersRequest()
{
}
public MessageSyncNetFiltersRequest(Messages type)
: base(type)
{
}
}
private sealed class PreMergeToMergedDeserializationBinder : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
string exeAssembly = Assembly.GetExecutingAssembly().FullName;
var typeToDeserialize = Type.GetType(string.Format("{0}, {1}", typeName, exeAssembly));
return typeToDeserialize;
}
}
#endregion
}