Removed some unused methods for 0.90.0 compatibility.
[QuantumStrutsContinued.git] /
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
// QuantumStrutsContinued
//
// QuantumStrutCore.cs
// 
// Continued from QuantumStruts by BoJaN.  Used by permission.
//
// ModuleManager patches © 2014 K3|Chris.  Used by permission.
//
// Copyright © 2014, toadicus
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation and/or other
//    materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

using KSP;
using KSP.IO;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using UnityEngine;

namespace QuantumStrut
{
	class QuantumStrutCore : PartModule
	{
		GameObject lineObj = null;
		LineRenderer lr = null;
		ConfigNode nodeToLoad = null;
		bool Placing = false;
		bool Deleting = false;
		List<CoreStrut> struts = new List<CoreStrut>();
		Part startPart = null;
		Vector3 startOffset = Vector3.zero;
		Part endPart = null;
		Vector3 endOffset = Vector3.zero;
		public Material material = null;
		public Color startColor = Color.white;
		public Color endColor = Color.white;

		#region Fields

		[KSPField(isPersistant = true)]
		public bool IsEnabled = true;
		[KSPField(isPersistant = false)]
		public float PowerConsumption = 0;
		[KSPField(isPersistant = false)]
		public int MaxStruts = 8;
		[KSPField(isPersistant = false)]
		public string Material = "Particles/Additive";
		[KSPField(isPersistant = false)]
		public Vector3 StartColor = Vector3.zero;
		[KSPField(isPersistant = false)]
		public Vector3 EndColor = Vector3.zero;
		[KSPField(isPersistant = false)]
		public float StartSize = 0.03f;
		[KSPField(isPersistant = false)]
		public float EndSize = 0.0075f;

		#endregion

		#region Actions

		[KSPAction("Toggle")]
		public void ToggleCore(KSPActionParam param)
		{
			IsEnabled = !IsEnabled;
		}

		[KSPAction("Activate")]
		public void ActivateCore(KSPActionParam param)
		{
			IsEnabled = true;
		}

		[KSPAction("Deactivate")]
		public void DeactivateCore(KSPActionParam param)
		{
			IsEnabled = false;
		}

		#endregion

		#region Events

		[KSPEvent(
			guiActive = true,
			guiName = "Place Strut",
			active = false,
			externalToEVAOnly = true,
			guiActiveUnfocused = true,
			unfocusedRange = 5
		)]
		public void BeginPlace()
		{
			startPart = null;
			startOffset = Vector3.zero;
			endPart = null;
			endOffset = Vector3.zero;
			Placing = true;
		}

		[KSPEvent(
			guiActive = true,
			guiName = "Remove Strut",
			active = false,
			externalToEVAOnly = true,
			guiActiveUnfocused = true,
			unfocusedRange = 2500
		)]
		public void BeginDelete()
		{
			Deleting = true;
		}

		[KSPEvent(guiActive = true, guiName = "Activate", active = true)]
		public void ActivateCore()
		{
			IsEnabled = true;
		}

		[KSPEvent(guiActive = true, guiName = "Deactivate", active = false)]
		public void DeactivateCore()
		{
			IsEnabled = false;
		}

		#endregion

		public Vector3 StringToVector3(string str)
		{
			string[] vals = str.Split(',');
			float x = (float)Convert.ToDecimal(vals[0]);
			float y = (float)Convert.ToDecimal(vals[1]);
			float z = (float)Convert.ToDecimal(vals[2]);
			return new Vector3(x, y, z);
		}

		public Color Vector3toColor(Vector3 vec)
		{
			return new Color(vec.x / 255, vec.y / 255, vec.z / 255);
		}

		Part partFromGameObject(GameObject ob)
		{
			GameObject o = ob;

			while (o)
			{
				Part p = Part.FromGO(o);
				if (p && p != null)
				{
					return p;
				}

				if (o.transform.parent)
					o = o.transform.parent.gameObject;
				else
					return null;
			}
			return null;
		}

		Part partFromRaycast(RaycastHit hit)
		{
			return partFromGameObject(hit.collider.gameObject);
		}

		bool isValid(UnityEngine.Object obj)
		{
			return (obj && obj != null);
		}

		void InitLaser()
		{
			if (!isValid(lr))
			{
				lineObj = new GameObject();

				lr = lineObj.AddComponent<LineRenderer>();
				lr.useWorldSpace = true;

				lr.material = new Material(Shader.Find("Particles/Additive"));
				lr.SetColors(Color.white, Color.white);
				lr.SetWidth(0.03f, 0.03f);

				lr.SetVertexCount(2);
				lr.SetPosition(0, Vector3.zero);
				lr.SetPosition(1, Vector3.zero);
				lr.castShadows = false;
				lr.receiveShadows = true;
			}
		}

		void DestroyLaser()
		{
			if (isValid(lr))
				LineRenderer.DestroyImmediate(lr);
			if (isValid(lineObj))
				GameObject.DestroyImmediate(lineObj);
		}

		float GetEnergy()
		{
			double energy = 0;
			foreach (Part p in part.vessel.parts)
			{
				foreach (PartResource r in p.Resources)
				{
					if (r.resourceName == "ElectricCharge")
						energy += r.amount;
				}
			}
			return (float)energy;
		}

		void AddStrut(Part a, Vector3 aO, Part b, Vector3 bO)
		{
			CoreStrut s = new CoreStrut(a, aO, b, bO);
			s.Material = material;
			s.StartColor = startColor;
			s.EndColor = endColor;
			s.StartSize = StartSize;
			s.EndSize = EndSize;
			struts.Add(s);
		}

		public override string GetInfo()
		{
			return "Max Struts: " + MaxStruts + "\nRequires:\n- ElectricCharge (" + PowerConsumption + "/s.)\n\n Energy cost is per-strut.";
		}

		public override void OnStart(PartModule.StartState state)
		{
			try
			{
				material = new Material(Shader.Find(Material.Trim()));
			}
			catch
			{
				material = null;
			}

			startColor = Vector3toColor(StartColor);
			endColor = Vector3toColor(EndColor);
			base.OnStart(state);
		}

		public override void OnSave(ConfigNode node)
		{
			foreach (CoreStrut strut in struts)
			{
				if (!strut.isDestroyed)
				{
					ConfigNode n = node.AddNode("QuantumStrut");
					n.AddValue("parent", part.vessel.parts.IndexOf(strut.parent));
					n.AddValue(
						"parentOffset",
						strut.parentOffset.x + "," + strut.parentOffset.y + "," + strut.parentOffset.z
					);
					n.AddValue("target", part.vessel.parts.IndexOf(strut.target));
					n.AddValue(
						"targetOffset",
						strut.targetOffset.x + "," + strut.targetOffset.y + "," + strut.targetOffset.z
					);
				}
			}

			base.OnSave(node);
		}

		public override void OnLoad(ConfigNode node)
		{
			if (nodeToLoad == null)
				nodeToLoad = node;

			base.OnLoad(node);
		}

		void printObj(object obj)
		{
			using (KSP.IO.TextWriter writer = TextWriter.CreateForType<string>("obj.cs"))
			{
				string str = printProperties(obj, TypeDescriptor.GetProperties(obj), 0);
				writer.Write(str);
				print(str);
			}
		}

		string printProperties(object obj, PropertyDescriptorCollection collection, int I)
		{
			if (I > 2)
				return "";

			string prefix = "";
			string str = "";
			for (int T = 0; T < I; T++)
			{
				prefix += "    ";
			}

			str += "\n" + prefix + "#region";
			foreach (PropertyDescriptor d in collection)
			{
				str += "\n" + prefix + d.Name + " = " + d.GetValue(obj);
				str += printProperties(obj, d.GetChildProperties(obj), I + 1);
			}
			str += "\n" + prefix + "#endregion";
			return str;
		}

		public override void OnUpdate()
		{
			bool eva = isValid(Util.Kerbal);
			Events["ActivateCore"].active = !IsEnabled;
			Events["DeactivateCore"].active = IsEnabled;
			Events["BeginPlace"].active = !Placing && !Deleting && struts.Count < MaxStruts && eva;
			Events["BeginDelete"].active = !Deleting && !Placing && struts.Count > 0 && eva;

			if (nodeToLoad != null)
			{
				foreach (ConfigNode strut in nodeToLoad.GetNodes("QuantumStrut"))
				{
					Part parent = part.vessel.parts[Convert.ToInt32(strut.GetValue("parent"))];
					Vector3 parentOffset = StringToVector3(strut.GetValue("parentOffset"));
					Part target = part.vessel.parts[Convert.ToInt32(strut.GetValue("target"))];
					Vector3 targetOffset = StringToVector3(strut.GetValue("targetOffset"));

					if (isValid(parent) && isValid(target))
						AddStrut(parent, parentOffset, target, targetOffset);
				}
				nodeToLoad = null;
			}

			if (eva)
			{
				InitLaser();
				if (Placing)
				{
					RaycastHit info = new RaycastHit();
					Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
					bool hit = Physics.Raycast(ray, out info, Mathf.Infinity);
					if (isValid(startPart))
					{
						Vector3 pos = startPart.transform.TransformPoint(startOffset);
						ray = new Ray(pos, (info.point - pos).normalized);
						hit = Physics.Raycast(ray, out info, 10);
					}

					if (Input.GetMouseButtonUp(0))
					{
						if (hit)
						{
							if (!isValid(startPart))
							{
								startPart = partFromRaycast(info);
								if (isValid(startPart))
									startOffset = startPart.transform.InverseTransformPoint(info.point);
							}
							else if (!isValid(endPart))
							{
								Part p = partFromRaycast(info);
								if (isValid(p))
								{
									if (p != startPart && startPart.vessel.parts.Contains(p))
									{
										endPart = p;
										endOffset = endPart.transform.InverseTransformPoint(info.point);

										AddStrut(startPart, startOffset, endPart, endOffset);
									}
									Placing = false;
								}
							}
						}
					}

					if (isValid(startPart))
					{
						if (hit)
						{
							Part p = partFromRaycast(info);
							Color c = Color.red;

							if (isValid(p))
							{
								if (startPart.vessel.parts.Contains(p) && p != startPart)
									c = Color.green;
							}

							lr.SetColors(c, c);
							lr.SetPosition(0, startPart.transform.TransformPoint(startOffset));
							lr.SetPosition(1, info.point);
						}
						else
						{
							lr.SetColors(Color.red, Color.red);
							lr.SetPosition(0, startPart.transform.TransformPoint(startOffset));
							lr.SetPosition(1, ray.GetPoint(10));
						}
					}
				}
				else
				{
					lr.SetPosition(0, Vector3.zero);
					lr.SetPosition(1, Vector3.zero);
				}

				if (Deleting)
				{
					RaycastHit info = new RaycastHit();
					Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
					bool hit = Physics.Raycast(ray, out info, Mathf.Infinity);

					CoreStrut closest = null;
					float closestDist = Mathf.Infinity;
					foreach (CoreStrut strut in struts)
					{
						strut.Selected = false;
						if (hit)
						{
							Vector3 start = strut.parent.transform.TransformPoint(strut.parentOffset);
							float d = Vector3.Distance(start, info.point);

							if (d < 0.05 && d < closestDist)
							{
								closest = strut;
								closestDist = d;
							}
						}
					}

					if (closest != null)
						closest.Selected = true;

					if (Input.GetMouseButtonUp(0))
					{
						if (closest != null)
						{
							closest.Destroy();
							struts.Remove(closest);
						}
						Deleting = false;
					}
				}
			}
			else
			{
				DestroyLaser();
			}

			foreach (CoreStrut s in struts.ToArray())
			{
				if (IsEnabled)
				{
					if (s.Active)
					{
						if (PowerConsumption == 0 || (GetEnergy() > PowerConsumption * TimeWarp.fixedDeltaTime && part.RequestResource(
							                      "ElectricCharge",
							                      PowerConsumption * TimeWarp.fixedDeltaTime
						                      ) > 0))
						{
							s.Active = true;
						}
						else
						{
							s.Active = false;
						}
					}
					else
					{
						if (GetEnergy() > 5 * TimeWarp.fixedDeltaTime && part.RequestResource(
							                      "ElectricCharge",
							                      5 * TimeWarp.fixedDeltaTime
						                      ) > 0)
						{
							s.Active = true;
						}
					}
				}
				else
				{
					s.Active = false;
				}

				s.Update();
				if (s.isDestroyed)
					struts.Remove(s);
			}
			base.OnUpdate();
		}
	}
}