-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathMenu.cs
More file actions
573 lines (480 loc) · 21.9 KB
/
Copy pathMenu.cs
File metadata and controls
573 lines (480 loc) · 21.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
563
564
565
566
567
568
569
570
571
572
573
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using TMPro;
namespace C2M2
{
using Utils;
using NeuronalDynamics.Simulation;
using NeuronalDynamics.Interaction;
using NeuronalDynamics.Interaction.UI;
/// <summary>
/// Provides Save and Load functionality for cells
/// </summary>
public class Menu : MonoBehaviour
{
private const int MAX_SAVE_FILES = 9; // max # of files that can be created and saved to
private DateTime date = DateTime.Today;
private int file_index; // keep track of how many files are saved already
private String filename; // filename to save to
private String[] files = null; // list of files saved
private bool filelist_visible = false; // if true the children of File object under SaveLoad are active
GameManager gm = null; // current instance of GameManager
private CellData data = null; // data for each cell
private SynapseManager synM = null;
private SynapseData synD = null;
private NDSimulationLoader loader = null; // current loader used
private string path; // save/load file path
// this is for restoring the gradient saved
public int gradientIndex = 0;
public bool loading = false;
public bool finishedLoading = false;
// camera transform
[System.Serializable]
public struct CamTransform
{
public Vector3 camPos;
public Vector3 camRot;
public Vector3 xyz; //x, y, z values from MovementController.cs
public CamTransform(Vector3 pos, Vector3 rot, Vector3 abc)
{
camPos = pos;
camRot = rot;
xyz = abc;
}
}
// current time step
[System.Serializable]
public struct CurrentTimeStep // have to create a struct because of Json
{
public int currentTimeStep;
public CurrentTimeStep(int time)
{
currentTimeStep = time;
}
}
// Graph manager
private NDGraphManager graphM = null;
void Awake()
{
path = Application.dataPath + "/";
if (!Directory.Exists(path + "Save")) Directory.CreateDirectory(path + "Save");
path += "Save/";
gm = GameManager.instance;
if (File.Exists(path + "/settings.txt"))
file_index = int.Parse(File.ReadAllLines(path + "/settings.txt")[0]);
else file_index = 0;
}
private void OnDestroy()
{
File.WriteAllText(path + "/settings.txt", file_index.ToString()); // save current file index to settings.txt
}
/// <summary>
/// Save the current scene.
/// </summary>
public void Save()
{
if (gm.activeSims.Count > 0)
{
// hide save button
SaveButtonVisible(false);
// reset file_index
if (file_index == MAX_SAVE_FILES)
file_index = 0;
// filename format: index_date-time.dat
filename = file_index + "_" + date.Date.ToString("M-d-yyyy") + "-" + DateTime.Now.ToString("HH-mm-ss") + ".dat";
// delete and replace file with the same index
String[] files = Directory.GetFiles(path, file_index + "_*");
foreach (String f in files)
File.Delete(f);
file_index++;
StreamWriter sw = File.AppendText(path + filename);
int limit = gm.activeSims.Count - 1;
// save camera position and rotation (for desktop only!)
MovementController cam = FindObjectOfType<MovementController>();
if (cam != null && cam.transform.parent.gameObject.activeSelf)
{
CamTransform c = new CamTransform(cam.transform.position, cam.transform.eulerAngles, cam.getXYZ());
string saveCam = JsonUtility.ToJson(c); // convert to Json
sw.Write(saveCam + ";");
}
SparseSolverTestv1 s = (SparseSolverTestv1)gm.activeSims[0];
// save current time step
CurrentTimeStep t = new CurrentTimeStep(s.currentTimeStep);
string sCurrT = JsonUtility.ToJson(t);
sw.Write(sCurrT + ";");
// get current gradient
ChangeGradient grad = FindObjectOfType<ChangeGradient>();
int gIndex = grad.GetActiveGradient();
// save cells
for (int i = 0; i <= limit; i++)
{
SparseSolverTestv1 sim = (SparseSolverTestv1)gm.activeSims[i];
graphM = sim.graphManager;
// fill in the variables to be saved
data = new CellData();
data.U = sim.Get1DValues(); // voltage at every node
data.Upre = sim.getUpre(); // Upre vector
// Gating Variable Vectors
var curr = sim.getCurrentStates();
var prev = sim.getPreviousStates();
var gatingVariableList = new List<CellData.GatingVariableData>();
foreach (var kvp in curr)
{
gatingVariableList.Add(new CellData.GatingVariableData {
name = kvp.Key,
current = kvp.Value,
previous = prev[kvp.Key], // lookup by the same key
});
}
data.gates = gatingVariableList.ToArray();
// Save active ion channels
var channelList = new List<CellData.ChannelData>();
foreach (var channel in sim.ionChannels) {
bool active = sim.activeIonChannels.Contains(channel);
channelList.Add(new CellData.ChannelData{
name = channel.Name,
isActive = active
});
}
data.channels = channelList.ToArray();
data.simID = sim.simID;
data.pos = sim.transform.position;
data.rotation = sim.transform.rotation;
data.scale = sim.transform.localScale;
data.vrnFileName = sim.vrnFileName;
data.gradientIndex = gIndex;
data.refinementLevel = sim.RefinementLevel;
data.timeStep = sim.timeStep;
data.endTime = sim.endTime;
// save clamps
if (sim.clampManager.clamps.Count > 0)
{
data.clamps = new CellData.ClampData[sim.clampManager.clamps.Count];
for (int j = 0; j < data.clamps.Length; j++)
{
data.clamps[j].vertex1D = sim.clampManager.clamps[j].FocusVert;
data.clamps[j].live = sim.clampManager.clamps[j].ClampLive;
data.clamps[j].power = sim.clampManager.clamps[j].ClampPower;
}
}
// save graphs
if (graphM.graphs.Count > 0)
{
data.graphs = new CellData.Graph[graphM.graphs.Count];
for (int j = 0; j < data.graphs.Length; j++)
{
data.graphs[j].vertex = graphM.graphs[j].FocusVert;
data.graphs[j].positions = new Vector3[graphM.graphs[j].ndlinegraph.positions.Count];
for (int k = 0; k < graphM.graphs[j].ndlinegraph.positions.Count; k++)
data.graphs[j].positions[k] = graphM.graphs[j].ndlinegraph.positions[k];
}
}
string json = JsonUtility.ToJson(data); // convert to Json
sw.Write(json);
if (i != limit)
sw.Write(';'); // add delimiter unless it's the last object
}
// write synapses list to file (Json doesn't work with List)
synM = gm.simulationManager.synapseManager;
sw.Write(';');
synD = new SynapseData();
if (synM.synapses.Count > 0)
{
// the list of synapses in SynapseManager is of the form List(Synapse, Synpase)
// so the array needs Count * 2 elements to store all of them
synD.syns = new SynapseData.SynData[synM.synapses.Count*2];
for (int j = 0; j < synM.synapses.Count; j++)
{
synD.syns[j * 2].synVert = synM.synapses[j].Item1.FocusVert;
synD.syns[j * 2].simID = synM.synapses[j].Item1.simulation.simID;
synD.syns[j * 2].model = synM.synapses[j].Item1.currentModel.Value;
synD.syns[(j * 2) + 1].synVert = synM.synapses[j].Item2.FocusVert;
synD.syns[(j * 2) + 1].simID = synM.synapses[j].Item2.simulation.simID;
synD.syns[(j * 2) + 1].model = synM.synapses[j].Item2.currentModel.Value;
}
}
string jSon = JsonUtility.ToJson(synD);
sw.Write(jSon);
sw.Close();
StartCoroutine(ShowSaveButton()); // hide save button for 1.5 seconds
}
}
/// <summary>
/// Show save button if it is possible.
/// </summary>
IEnumerator ShowSaveButton()
{
yield return new WaitForSeconds(1.5f);
if (!filelist_visible && !gm.cellPreviewer.activeInHierarchy)
SaveButtonVisible(true);
}
/// <summary>
/// Load a file. Return true if successful.
/// </summary>
public bool Load(String f)
{
ClearScene();
loader = gm.cellPreviewer.GetComponentInChildren<NDSimulationLoader>();
if (loader != null)
{
loading = true; // this is for ChangeGradient
gm.Loading = true;
string[] json;
try
{
json = File.ReadAllText(path + f + ".dat").Split(';');
}
catch (FileNotFoundException e)
{
Debug.Log(e.Message);
loading = false;
gm.Loading = false;
finishedLoading = true;
return false;
}
int i = 0; // index for json string
// load camera position and rotation (for desktop only!)
MovementController cam = FindObjectOfType<MovementController>();
if (cam != null && cam.transform.parent.gameObject.activeSelf)
{
CamTransform c = JsonUtility.FromJson<CamTransform>(json[i]);
cam.transform.position = c.camPos;
cam.transform.eulerAngles = c.camRot;
cam.setXYZ(c.xyz);
}
++i;
CurrentTimeStep t = JsonUtility.FromJson<CurrentTimeStep>(json[i++]);
int limit = json.Length - 2; // account for the synapses array at the end of the file
int ID = 0; // this will be the current ID when placing a new cell after loading
for (; i <= limit; i++)
{
// retrieve saved data
data = JsonUtility.FromJson<CellData>(json[i]);
loader.vrnFileName = data.vrnFileName;
loader.refinementLevel = data.refinementLevel;
loader.timestepSize = data.timeStep;
loader.endTime = data.endTime;
// restore vectors
gm.U = data.U;
gm.Upre = data.Upre;
// Build Gating Variables and Ion Channels
var currStates = new Dictionary<string,double[]>();
var prevStates = new Dictionary<string,double[]>();
foreach(var g in data.gates) {
currStates[g.name] = g.current;
prevStates[g.name] = g.previous;
}
gm.currentStates = currStates;
gm.previousStates = prevStates;
GameObject go;
try
{
go = loader.Load(new RaycastHit()); // load the cell
}
catch (FileNotFoundException e)
{
go = FindObjectOfType<SparseSolverTestv1>().gameObject;
gm.activeSims.RemoveAt(gm.activeSims.Count-1);
Destroy(go);
Debug.Log(e.Message);
loading = false;
gm.Loading = false;
finishedLoading = true;
return false;
}
SparseSolverTestv1 sim = go.GetComponent<SparseSolverTestv1>();
// 1) initialize ion channels (so sim.ionChannels is populated)
sim.InitializeIonChannel();
// 2) clear active channels then enable/disable each one according to what was saved
sim.activeIonChannels.Clear();
// Load Ion Channels
foreach (var cd in data.channels) {
// find the matching IonChannel object
var match = sim.ionChannels.FirstOrDefault(ch => ch.Name == cd.name);
if (match != null && cd.isActive) sim.activeIonChannels.Add(match);
}
// restore cell ID
sim.simID = data.simID;
ID = sim.simID;
go.transform.position = data.pos;
go.transform.rotation = data.rotation;
go.transform.localScale = data.scale;
// get clamp manager
NeuronClampManager clampMng = sim.clampManager;
// set current time step
sim.currentTimeStep = t.currentTimeStep;
// recreate clamps
if (data.clamps.Length > 0)
{
for (int j = 0; j < data.clamps.Length; j++)
{
NeuronClamp clamp;
clamp = Instantiate(clampMng.clampPrefab, go.transform).GetComponentInChildren<NeuronClamp>();
clamp.AttachToSimulation(sim, data.clamps[j].vertex1D);
clamp.ClampPower = data.clamps[j].power;
if (data.clamps[j].live) clamp.ActivateClamp();
}
}
// recreate graphs
if (data.graphs.Length > 0)
{
graphM = sim.graphManager;
GameObject graphPrefab = Resources.Load("Prefabs" + Path.DirectorySeparatorChar + "NeuronalDynamics" + Path.DirectorySeparatorChar + "NDLineGraph") as GameObject;
for (int j = 0; j < data.graphs.Length; j++)
{
var graphObj = Instantiate(graphPrefab);
NDLineGraph g = graphObj.GetComponent<NDLineGraph>();
g.ndgraph.FocusVert = data.graphs[j].vertex;
g.ndgraph.simulation = sim;
graphM.graphs.Add(g.ndgraph);
foreach (Vector3 v in data.graphs[j].positions)
{
g.positions.Add(v);
}
}
}
// each cell has the same gradient so assign gradientIndex only once
// the gradient is applied once loading is finished; check ChangeGradient.cs
if (i == limit)
gradientIndex = data.gradientIndex;
}
// recreate synapses
synD = JsonUtility.FromJson<SynapseData>(json[i]);
synM = gm.simulationManager.synapseManager;
for (int j = 0; j < synD.syns.Length; j++)
{
Synapse syn;
NDSimulation ndsim = null;
foreach (NDSimulation sim in gm.activeSims)
{
if (sim.simID == synD.syns[j].simID)
{
ndsim = sim;
break;
}
}
syn = Instantiate(GameManager.instance.synapseManagerPrefab.GetComponent<SynapseManager>().synapsePrefab, ndsim.transform).GetComponentInChildren<Synapse>();
syn.AttachToSimulation(ndsim, synD.syns[j].synVert);
// syn.SwitchModel(synD.syns[j].model);
}
finishedLoading = true; // this is for ChangeGradient
gm.Loading = false;
GameManager.simID = ID;
// set paused
gm.simulationManager.Paused = true;
}
else
{
Debug.LogError("Loader is null!");
return false;
}
return true;
}
/// <summary>
/// Clear the scene in order to load a file.
/// </summary>
public void ClearScene()
{
GameObject controlPanel = GameObject.FindGameObjectWithTag("ControlPanel");
if (controlPanel != null)
{
NDBoardController c = controlPanel.GetComponent<NDBoardController>();
c.CloseAllSimulations();
DestroyImmediate(c.gameObject);
DestroyImmediate(controlPanel);
}
}
/// <summary>
/// Loads the selected (clicked) file.
/// </summary>
public void LoadThisFile(RaycastHit hit)
{
GameObject g = hit.collider.gameObject.transform.GetChild(1).gameObject;
TextMeshProUGUI text = g.GetComponent<TextMeshProUGUI>();
Transform t = hit.collider.transform.parent.parent;
for (int i = 0; i < t.childCount; i++)
t.GetChild(i).gameObject.SetActive(false);
if (!Load(text.text))
CloseFileList();
LoadButtonVisible(true);
CloseButtonVisible(false);
}
/// <summary>
/// Lists the filename objects.
/// </summary>
public void ListSavedFiles()
{
files = Directory.GetFiles(path, "*.dat");
if (files.Length > 0)
{
GameObject controlPanel = GameObject.FindGameObjectWithTag("ControlPanel");
if (controlPanel != null)
{
NDBoardController c = controlPanel.GetComponent<NDBoardController>();
c.MinimizeBoard(true);
}
if (gm.cellPreviewer != null) gm.cellPreviewer.SetActive(false);
SaveButtonVisible(false);
LoadButtonVisible(false);
CloseButtonVisible(true);
Transform g = gameObject.transform.GetChild(3);
for (int i = 0; i < files.Length; i++)
{
g.GetChild(i).gameObject.SetActive(true);
TextMeshProUGUI t = g.GetChild(i).GetChild(0).GetChild(1).GetComponent<TextMeshProUGUI>();
t.text = Path.GetFileNameWithoutExtension(files[i]);
}
filelist_visible = true;
}
}
/// <summary>
/// Close filename objects.
/// </summary>
public void CloseFileList()
{
if (filelist_visible)
{
CloseButtonVisible(false);
Transform g = gameObject.transform.GetChild(3);
for (int i = 0; i < files.Length; i++)
g.GetChild(i).gameObject.SetActive(false);
filelist_visible = false;
LoadButtonVisible(true);
// if controlPanel is active unminimize it, otherwise show the cell previewer
GameObject controlPanel = GameObject.FindGameObjectWithTag("ControlPanel");
if (controlPanel != null)
{
NDBoardController c = controlPanel.GetComponent<NDBoardController>();
c.MinimizeBoard(false);
SaveButtonVisible(true);
}
else
{
gm.cellPreviewer.SetActive(true);
}
}
}
/*
* Show/hide buttons.
*/
public void SaveButtonVisible(bool visible)
{
GameObject save = gameObject.transform.GetChild(0).gameObject;
save.SetActive(visible);
}
public void LoadButtonVisible(bool visible)
{
GameObject load = gameObject.transform.GetChild(1).gameObject;
load.SetActive(visible);
}
public void CloseButtonVisible(bool visible)
{
GameObject close = gameObject.transform.GetChild(2).gameObject;
close.SetActive(visible);
}
}
}