-
Notifications
You must be signed in to change notification settings - Fork 550
Expand file tree
/
Copy pathDevChipInstance.cs
More file actions
562 lines (473 loc) · 16.9 KB
/
DevChipInstance.cs
File metadata and controls
562 lines (473 loc) · 16.9 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
using System;
using System.Collections.Generic;
using System.Linq;
using DLS.Description;
using DLS.SaveSystem;
using DLS.Simulation;
using UnityEngine;
namespace DLS.Game
{
public class DevChipInstance
{
public readonly List<IMoveable> Elements = new();
public readonly List<WireInstance> Wires = new();
public readonly UndoController UndoController;
// Names of all the chips which contain this chip (either directly, or inside some other subchip)
public readonly HashSet<string> AllParentChipNames = new(ChipDescription.NameComparer);
public ChipDescription LastSavedDescription;
DevPinInstance[] inputPins_cached = Array.Empty<DevPinInstance>();
bool elementsModifiedSinceLastArrayUpdate;
public SimChip SimChip;
bool hasSimChip;
public string ChipName => LastSavedDescription == null ? string.Empty : LastSavedDescription.Name;
public DevChipInstance()
{
UndoController = new UndoController(this);
}
public void SetSimChip(SimChip simChip)
{
hasSimChip = true;
SimChip = simChip;
}
public void RebuildSimulation()
{
ChipDescription desc = DescriptionCreator.CreateChipDescription(this);
SimChip simChip = Simulator.BuildSimChip(desc, Project.ActiveProject.chipLibrary);
SetSimChip(simChip);
}
public DevPinInstance[] GetInputPins()
{
if (elementsModifiedSinceLastArrayUpdate)
{
elementsModifiedSinceLastArrayUpdate = false;
inputPins_cached = Elements.OfType<DevPinInstance>().Where(p => p.IsInputPin).ToArray();
}
return inputPins_cached;
}
public static (DevChipInstance devChip, bool anyElementFailedToLoad) LoadFromDescriptionTest(ChipDescription description, ChipLibrary library)
{
DevChipInstance instance = new();
instance.LastSavedDescription = description;
// Set any null arrays to empty so don't have to check
description.SubChips ??= Array.Empty<SubChipDescription>();
description.InputPins ??= Array.Empty<PinDescription>();
description.OutputPins ??= Array.Empty<PinDescription>();
description.Wires ??= Array.Empty<WireDescription>();
bool anyElementFailedToLoad = false;
// Load subchips
foreach (SubChipDescription subChipDescription in description.SubChips)
{
if (library.TryGetChipDescription(subChipDescription.Name, out ChipDescription fullDescriptionOfSubchip))
{
SubChipInstance subChip = new(fullDescriptionOfSubchip, subChipDescription);
instance.AddNewSubChip(subChip, true);
}
else anyElementFailedToLoad = true;
}
// Load dev pins
for (int i = 0; i < description.InputPins.Length; i++)
{
PinDescription pinDescription = description.InputPins[i];
instance.AddNewDevPin(new DevPinInstance(pinDescription, true), true);
}
for (int i = 0; i < description.OutputPins.Length; i++)
{
PinDescription pinDescription = description.OutputPins[i];
instance.AddNewDevPin(new DevPinInstance(pinDescription, false), true);
}
// ---- Load wires ----
// Wires can fail to load if associated pin was deleted from subchip. This means that wire indices stored in the save data might not line up with our loaded wires list.
// So, keep track here of the wires with correct indices (with failed entries just being left as null)
WireInstance[] loadedWiresWithOriginalIndices = new WireInstance[description.Wires.Length];
for (int i = 0; i < description.Wires.Length; i++)
{
WireDescription wireDescription = description.Wires[i];
(WireInstance loadedWire, bool failed) = TryLoadWireFromDescription(wireDescription, i, instance, loadedWiresWithOriginalIndices);
if (!failed) instance.AddWire(loadedWire, true);
loadedWiresWithOriginalIndices[i] = loadedWire;
anyElementFailedToLoad |= failed;
}
instance.RegenerateParentChipNamesHash();
return (instance, anyElementFailedToLoad);
}
public static (WireInstance loadedWire, bool failed) TryLoadWireFromDescription(WireDescription wireDescription, int wireIndex, DevChipInstance instance, IList<WireInstance> allWires)
{
bool failedToLoad = false;
WireInstance loadedWire = null;
WireInstance connectedWire = wireDescription.ConnectedWireIndex >= 0 ? allWires[wireDescription.ConnectedWireIndex] : null;
instance.TryFindPin(wireDescription.SourcePinAddress, out PinInstance sourcePin);
instance.TryFindPin(wireDescription.TargetPinAddress, out PinInstance targetPin);
if (sourcePin != null && targetPin != null)
{
WireConnectionType connectionType = wireDescription.ConnectionType;
if (connectionType is WireConnectionType.ToWireSource or WireConnectionType.ToWireTarget)
{
WireInstance wireConnectTarget = connectedWire;
bool wireConnectTargetFailedToLoad = wireConnectTarget == null;
if (!wireConnectTargetFailedToLoad)
{
// If wire connection target did load, double check that it connects to the same pin that this wire is expecting
// (this should always be the case, but a bug in a previous version could cause save files to contain bad connection data)
bool addressMismatch = false;
addressMismatch |= connectionType is WireConnectionType.ToWireSource && !PinAddress.Equals(wireConnectTarget.SourcePin.Address, wireDescription.SourcePinAddress);
addressMismatch |= connectionType is WireConnectionType.ToWireTarget && !PinAddress.Equals(wireConnectTarget.TargetPin_BusCorrected.Address, wireDescription.TargetPinAddress);
wireConnectTargetFailedToLoad = addressMismatch;
}
// If wire is connected to another wire, but the other wire failed to load, then fallback to pin connection type
// (Load failure could be due to a pin could being deleted from a subchip, or the whole subchip being deleted from the library for example)
if (wireConnectTargetFailedToLoad)
{
failedToLoad = true;
connectionType = WireConnectionType.ToPins;
}
}
WireInstance.ConnectionInfo sourceConnection = new()
{
pin = sourcePin,
connectedWire = connectionType == WireConnectionType.ToWireSource ? connectedWire : null,
wireConnectionSegmentIndex = wireDescription.ConnectedWireSegmentIndex
};
WireInstance.ConnectionInfo targetConnection = new()
{
pin = targetPin,
connectedWire = connectionType == WireConnectionType.ToWireTarget ? connectedWire : null,
wireConnectionSegmentIndex = wireDescription.ConnectedWireSegmentIndex
};
loadedWire = new WireInstance(sourceConnection, targetConnection, wireDescription.Points, wireIndex);
}
else
{
failedToLoad = true;
}
return (loadedWire, failedToLoad);
}
// Check if subchip can be added
// The chip may not contain a copy of itself (either directly, or inside some other chip)
public bool CanAddSubchip(string subchipName)
{
// Check if the chip we want to add is the chip itself
if (ChipDescription.NameMatch(ChipName, subchipName)) return false;
// Check if the chip we want to add contains this chip
return !AllParentChipNames.Contains(subchipName);
}
public void DeleteSubchipsByName(string removeName)
{
List<SubChipInstance> subchipsToDelete = new();
foreach (IMoveable element in Elements)
{
if (element is SubChipInstance subchip)
{
if (subchip.Description.NameMatch(removeName))
{
subchipsToDelete.Add(subchip);
}
}
}
foreach (SubChipInstance subchip in subchipsToDelete)
{
DeleteSubChip(subchip);
}
}
public void NotifySaved(ChipDescription savedDescription)
{
LastSavedDescription = savedDescription;
RegenerateParentChipNamesHash();
Simulator.combinationalChipCaches.Remove(savedDescription.Name);
Simulator.chipsKnowToNotBeCombinational.Remove(savedDescription.Name);
}
public void AddNewSubChip(SubChipInstance subChip, bool isLoading)
{
AddElement(subChip);
if (!isLoading)
{
Simulator.AddSubChip(SimChip, subChip.Description, Project.ActiveProject.chipLibrary, subChip.ID, subChip.InternalData);
}
}
public void AddNewDevPin(DevPinInstance pin, bool isLoadingFromFile)
{
AddElement(pin);
if (!isLoadingFromFile)
{
Simulator.AddPin(SimChip, pin.ID, pin.IsInputPin, pin.BitCount);
}
}
public void AddWire(WireInstance wire, bool isLoading, int insertIndex = -1)
{
bool insert = insertIndex != -1;
if (insert) Wires.Insert(insertIndex, wire);
else Wires.Add(wire);
if (!isLoading)
{
Simulator.AddConnection(SimChip, wire.SourcePin.Address, wire.TargetPin.Address);
}
}
void AddElement(IMoveable element)
{
Elements.Add(element);
elementsModifiedSinceLastArrayUpdate = true;
}
void RemoveElement(IMoveable element)
{
elementsModifiedSinceLastArrayUpdate = true;
bool success = Elements.Remove(element);
Debug.Assert(success, "Trying to delete element that was already deleted?");
}
public void DeleteDevPin(DevPinInstance devPin)
{
DeleteWiresAttachedToPin(devPin.Pin);
RemoveElement(devPin);
Simulator.RemovePin(SimChip, devPin.ID);
}
public void DeleteWire(WireInstance wireToDelete)
{
bool success = Wires.Remove(wireToDelete);
if (!success) return; // Wire already deleted
// Remove from simulation
if (hasSimChip)
{
Simulator.RemoveConnection(SimChip, wireToDelete.SourcePin.Address, wireToDelete.TargetPin.Address);
}
// If deleting bus line, automatically delete all other connecting wires
if (wireToDelete.IsBusWire)
{
SubChipInstance busSource = (SubChipInstance)wireToDelete.SourcePin.parent;
DeleteWiresAttachedToPin(busSource.InputPins[0]);
DeleteWiresAttachedToPin(busSource.OutputPins[0]);
}
// Otherwise connecting wires should connect directly to the pin where the deleted wire used to connect
else
{
foreach (WireInstance other in Wires)
{
if (other.ConnectedWire == wireToDelete)
{
other.RemoveConnectionDependency();
}
}
}
}
void DeleteWiresAttachedToPin(PinInstance pin)
{
for (int i = Wires.Count - 1; i >= 0; i--)
{
WireInstance wire = Wires[i];
// Check if wire is connected to the deleted pin
if (PinAddress.Equals(wire.SourcePin.Address, pin.Address) || PinAddress.Equals(wire.TargetPin.Address, pin.Address))
{
DeleteWire(wire);
}
}
}
public bool DeleteWiresAttachedToPinOfSubChip(int pinID)
{
bool anyDeleted = false;
for (int i = Wires.Count - 1; i >= 0; i--)
{
WireInstance wire = Wires[i];
bool sourceMatch = wire.SourcePin.parent is SubChipInstance && wire.SourcePin.Address.PinID == pinID;
bool targetMatch = wire.TargetPin.parent is SubChipInstance && wire.TargetPin.Address.PinID == pinID;
if (sourceMatch || targetMatch)
{
DeleteWire(wire);
anyDeleted = true;
}
}
return anyDeleted;
}
public void GetWiresAttachedToElement(int elementID, HashSet<WireInstance> set)
{
foreach (WireInstance wire in Wires)
{
bool sourceMatch = wire.SourcePin.Address.PinOwnerID == elementID;
bool targetMatch = wire.TargetPin.Address.PinOwnerID == elementID;
if (sourceMatch || targetMatch)
{
set.Add(wire);
}
}
}
public void DeleteWiresAttachedToElement(int elementID)
{
for (int i = Wires.Count - 1; i >= 0; i--)
{
WireInstance wire = Wires[i];
bool sourceMatch = wire.SourcePin.Address.PinOwnerID == elementID;
bool targetMatch = wire.TargetPin.Address.PinOwnerID == elementID;
if (sourceMatch || targetMatch)
{
DeleteWire(wire);
}
}
}
public void DeleteSubChip(SubChipInstance subChip)
{
DeleteWiresAttachedToElement(subChip.ID);
RemoveElement(subChip);
if (hasSimChip) Simulator.RemoveSubChip(SimChip, subChip.ID);
}
// Delete subchip with given id (if it exists)
public bool TryDeleteSubChipByID(int id)
{
for (int i = 0; i < Elements.Count; i++)
{
if (Elements[i] is SubChipInstance subchip && subchip.ID == id)
{
DeleteSubChip(subchip);
return true;
}
}
return false;
}
// Delete devpin with given id (if it exists)
public bool TryDeleteDevPinByID(int id)
{
for (int i = 0; i < Elements.Count; i++)
{
if (Elements[i] is DevPinInstance devPin && devPin.ID == id)
{
DeleteDevPin(devPin);
return true;
}
}
return false;
}
public bool TryGetSubChipByID(int id, out SubChipInstance subchip)
{
foreach (IMoveable element in Elements)
{
if (element.ID == id)
{
subchip = (SubChipInstance)element;
return true;
}
}
subchip = null;
return false;
}
// Update the currently viewed chip from the state of the corresponding simChip.
// Optionally don't set input pins since player controls these (at least when editing a chip, rather than viewing it)
public void UpdateStateFromSim(SimChip simChip, bool updateInputPins)
{
try
{
foreach (IMoveable element in Elements)
{
if (element is DevPinInstance devPin)
{
if (devPin.IsInputPin && !updateInputPins) continue;
SimPin simPin = simChip.GetSimPinFromAddress(devPin.Pin.Address);
devPin.Pin.State = simPin.State;
if (devPin.IsInputPin || simPin.latestSourceID == -1) continue;
// Output pins get colour from whichever pin they last received a signal
PinInstance colSource = TryFindPinFromSimPinSource(simChip, simPin);
devPin.Pin.Colour = colSource.Colour;
}
// -- Subchip --
else if (element is SubChipInstance subChip)
{
// Update the state of each output pin on the subchip to match the state of corresponding pin in the simulation
foreach (PinInstance subChipOutputPin in subChip.OutputPins)
{
SimPin simPin = simChip.GetSimPinFromAddress(subChipOutputPin.Address);
subChipOutputPin.State = simPin.State;
// If is bus, copy colour from the input source
if (ChipTypeHelper.IsBusOriginType(subChip.ChipType))
{
SimPin simInputPin = simChip.GetSimPinFromAddress(subChip.InputPins[0].Address);
if (simInputPin.latestSourceID == -1) continue;
PinInstance colSource = TryFindPinFromSimPinSource(simChip, simInputPin);
subChipOutputPin.Colour = colSource.Colour;
}
}
}
}
}
catch (Exception e)
{
// Updating from sim thread so it's possible for some stuff to be out of sync if player is actively editing -- just ignore
if (Application.isEditor)
{
Debug.Log("Ignoring exception when updating display from sim state: " + e.Message + "\nStack Trace: " + e.StackTrace);
}
}
}
PinInstance TryFindPinFromSimPinSource(SimChip simChip, SimPin simPin)
{
PinAddress srcAddress;
// Is dev pin, so here the SimPin's ID refers to the devpin
if (simPin.latestSourceParentChipID == simChip.ID) srcAddress = new PinAddress(simPin.latestSourceID, 0);
else srcAddress = new PinAddress(simPin.latestSourceParentChipID, simPin.latestSourceID); // subchip pin
if (TryFindPin(srcAddress, out PinInstance colSource)) return colSource;
throw new Exception($"Failed to find colour source: pinID: {srcAddress.PinID} pinOwnerID: {srcAddress.PinOwnerID}");
}
public bool TryFindPin(PinAddress address, out PinInstance pinInstance) => TryFindPin(Elements, address, out pinInstance);
public static bool TryFindPin(List<IMoveable> elements, PinAddress address, out PinInstance pinInstance)
{
foreach (IMoveable element in elements)
{
if (element.ID == address.PinOwnerID)
{
if (element is SubChipInstance subchip)
{
foreach (PinInstance pin in subchip.AllPins)
{
if (PinAddress.Equals(pin.Address, address))
{
pinInstance = pin;
return true;
}
}
}
else if (element is DevPinInstance devPin)
{
if (PinAddress.Equals(devPin.Pin.Address, address))
{
pinInstance = devPin.Pin;
return true;
}
}
break;
}
}
pinInstance = null;
return false;
}
public void NotifyConnectedWiresPointsInserted(WireInstance wire, int insertIndex, float insertPointT, int numPoints)
{
foreach (WireInstance other in Wires)
{
if (other.ConnectedWire == wire)
{
other.NotifyParentWirePointsInserted(insertIndex, insertPointT, numPoints);
}
}
}
public IEnumerable<SubChipInstance> GetSubchips() => Elements.OfType<SubChipInstance>();
public IEnumerable<DevPinInstance> GetOutputPins()
{
return Elements.OfType<DevPinInstance>().Where(p => !p.IsInputPin);
}
void RegenerateParentChipNamesHash()
{
AllParentChipNames.Clear();
GetAllParentChipNames(LastSavedDescription.Name, Project.ActiveProject.chipLibrary, AllParentChipNames);
}
// Recursively get the names of all the chips which contain this chip (either directly, or inside of some other subchip)
// (and add to the hashset)
void GetAllParentChipNames(string name, ChipLibrary library, HashSet<string> hashset)
{
RecursivelyAddParents(name);
void RecursivelyAddParents(string name)
{
ChipDescription[] directParents = library.GetDirectParentChips(name);
foreach (ChipDescription parent in directParents)
{
if (hashset.Add(parent.Name))
{
RecursivelyAddParents(parent.Name);
}
}
}
}
}
}