Enable Activate & Deactive events from EVA.
Enable Activate & Deactive events from EVA.

// QuantumStrutsContinued © 2014 toadicus // QuantumStrutsContinued © 2014 toadicus
// //
// This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. To view a // This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. To view a
// copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ // copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/
// //
// Continued from QuantumStrut, © 2013 BoJaN. Used with permission. // Continued from QuantumStrut, © 2013 BoJaN. Used with permission.
   
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
   
//using System.Threading.Tasks;  
using UnityEngine; using UnityEngine;
   
namespace QuantumStrut namespace QuantumStrut
{ {
class CoreStrut class CoreStrut
{ {
public bool isDestroyed = false; public bool isDestroyed = false;
Material _material = null; Material _material = null;
   
public Material Material public Material Material
{ {
set set
{ {
_material = value; _material = value;
if (Material != null) if (Material != null)
lr.material = Material; lr.material = Material;
} }
get get
{ {
return _material; return _material;
} }
} }
   
Color _startColor = Color.white; Color _startColor = Color.white;
   
public Color StartColor public Color StartColor
{ {
set set
{ {
_startColor = value; _startColor = value;
lr.SetColors(StartColor, EndColor); lr.SetColors(StartColor, EndColor);
} }
get get
{ {
return _startColor; return _startColor;
} }
} }
   
Color _endColor = Color.white; Color _endColor = Color.white;
   
public Color EndColor public Color EndColor
{ {
set set
{ {
_endColor = value; _endColor = value;
lr.SetColors(StartColor, EndColor); lr.SetColors(StartColor, EndColor);
} }
get get
{ {
return _endColor; return _endColor;
} }
} }
   
float _startSize = 0; float _startSize = 0;
   
public float StartSize public float StartSize
{ {
set set
{ {
_startSize = value; _startSize = value;
lr.SetWidth(StartSize, EndSize); lr.SetWidth(StartSize, EndSize);
} }
get get
{ {
return _startSize; return _startSize;
} }
} }
   
float _endSize = 0; float _endSize = 0;
   
public float EndSize public float EndSize
{ {
set set
{ {
_endSize = value; _endSize = value;
lr.SetWidth(StartSize, EndSize); lr.SetWidth(StartSize, EndSize);
} }
get get
{ {
return _endSize; return _endSize;
} }
} }
   
ConfigurableJoint joint; ConfigurableJoint joint;
public bool Active = true; public bool Active = true;
public bool Selected = false; public bool Selected = false;
public Part parent = null; public Part parent = null;
public Vector3 parentOffset = Vector3.zero; public Vector3 parentOffset = Vector3.zero;
public Part target = null; public Part target = null;
public Vector3 targetOffset = Vector3.zero; public Vector3 targetOffset = Vector3.zero;
GameObject LineObj; GameObject LineObj;
LineRenderer lr = null; LineRenderer lr = null;
   
public void print(object body, params object[] args) public void print(object body, params object[] args)
{ {
string final = body.ToString(); string final = body.ToString();
for (int I = 0; I < args.Length; I++) for (int I = 0; I < args.Length; I++)
{ {
final = final.Replace("{" + I + "}", args[I].ToString()); final = final.Replace("{" + I + "}", args[I].ToString());
} }
MonoBehaviour.print("[AutoStrut] " + final); MonoBehaviour.print("[AutoStrut] " + final);
} }
   
void DrawLine(Vector3 origin, Vector3 end) void DrawLine(Vector3 origin, Vector3 end)
{ {
if (Util.isValid(lr)) if (Util.isValid(lr))
{ {
lr.SetPosition(0, origin); lr.SetPosition(0, origin);
lr.SetPosition(1, end); lr.SetPosition(1, end);
} }
} }
   
void createJoint() void createJoint()
{ {
if (!Util.isValid(joint)) if (!Util.isValid(joint))
{ {
joint = parent.gameObject.AddComponent<ConfigurableJoint>(); joint = parent.gameObject.AddComponent<ConfigurableJoint>();
joint.connectedBody = target.rigidbody; joint.connectedBody = target.rigidbody;
   
joint.anchor = new Vector3( joint.anchor = new Vector3(
0, 0,
0, 0,
Vector3.Distance( Vector3.Distance(
parent.transform.TransformPoint(parentOffset), parent.transform.TransformPoint(parentOffset),
target.transform.TransformPoint(targetOffset) target.transform.TransformPoint(targetOffset)
) / 2 ) / 2
); );
joint.axis = new Vector3(0, 0, 1); joint.axis = new Vector3(0, 0, 1);
joint.xMotion = ConfigurableJointMotion.Locked; joint.xMotion = ConfigurableJointMotion.Locked;
joint.yMotion = ConfigurableJointMotion.Locked; joint.yMotion = ConfigurableJointMotion.Locked;
joint.zMotion = ConfigurableJointMotion.Locked; joint.zMotion = ConfigurableJointMotion.Locked;
joint.angularXMotion = ConfigurableJointMotion.Locked; joint.angularXMotion = ConfigurableJointMotion.Locked;
joint.angularYMotion = ConfigurableJointMotion.Locked; joint.angularYMotion = ConfigurableJointMotion.Locked;
joint.angularZMotion = ConfigurableJointMotion.Locked; joint.angularZMotion = ConfigurableJointMotion.Locked;
} }
} }
   
void deleteJoint() void deleteJoint()
{ {
if (Util.isValid(joint)) if (Util.isValid(joint))
GameObject.DestroyImmediate(joint); GameObject.DestroyImmediate(joint);
} }
   
public CoreStrut(Part parent, Vector3 parentOffset, Part target, Vector3 targetOffset) public CoreStrut(Part parent, Vector3 parentOffset, Part target, Vector3 targetOffset)
{ {
this.parent = parent; this.parent = parent;
this.parentOffset = parentOffset; this.parentOffset = parentOffset;
this.target = target; this.target = target;
this.targetOffset = targetOffset; this.targetOffset = targetOffset;
   
createJoint(); createJoint();
   
LineObj = new GameObject(); LineObj = new GameObject();
LineObj.name = "quantumstrut"; LineObj.name = "quantumstrut";
   
lr = LineObj.AddComponent<LineRenderer>(); lr = LineObj.AddComponent<LineRenderer>();
lr.useWorldSpace = true; lr.useWorldSpace = true;
   
Material = QuantumStrut.LaserMaterial; Material = QuantumStrut.LaserMaterial;
StartColor = Color.white; StartColor = Color.white;
EndColor = Color.white; EndColor = Color.white;
StartSize = 0.03f; StartSize = 0.03f;
EndSize = 0.0075f; EndSize = 0.0075f;
   
lr.SetVertexCount(2); lr.SetVertexCount(2);
lr.SetPosition(0, Vector3.zero); lr.SetPosition(0, Vector3.zero);
lr.SetPosition(1, Vector3.zero); lr.SetPosition(1, Vector3.zero);
} }
   
public void Update() public void Update()
{ {
if (Util.isValid(parent) && Util.isValid(target) && Util.isValid(parent.vessel) && parent.vessel.parts.Contains(target)) if (Util.isValid(parent) && Util.isValid(target) && Util.isValid(parent.vessel) && parent.vessel.parts.Contains(target))
{ {
if (Active) if (Active)
{ {
createJoint(); createJoint();
Vector3 start = parent.transform.TransformPoint(parentOffset); Vector3 start = parent.transform.TransformPoint(parentOffset);
Vector3 end = target.transform.TransformPoint(targetOffset); Vector3 end = target.transform.TransformPoint(targetOffset);
if (Selected) if (Selected)
lr.SetColors(Color.blue, Color.blue); lr.SetColors(Color.blue, Color.blue);
else else
lr.SetColors(StartColor, EndColor); lr.SetColors(StartColor, EndColor);
DrawLine(start, end); DrawLine(start, end);
} }
else else
{ {
deleteJoint(); deleteJoint();
DrawLine(Vector3.zero, Vector3.zero); DrawLine(Vector3.zero, Vector3.zero);
} }
} }
else else
{ {
DrawLine(Vector3.zero, Vector3.zero); DrawLine(Vector3.zero, Vector3.zero);
Destroy(); Destroy();
} }
} }
   
public void Destroy() public void Destroy()
{ {
DrawLine(Vector3.zero, Vector3.zero); DrawLine(Vector3.zero, Vector3.zero);
if (Util.isValid(joint)) if (Util.isValid(joint))
GameObject.DestroyImmediate(joint); GameObject.DestroyImmediate(joint);
   
if (Util.isValid(lr)) if (Util.isValid(lr))
GameObject.DestroyImmediate(lr); GameObject.DestroyImmediate(lr);
   
if (Util.isValid(LineObj)) if (Util.isValid(LineObj))
GameObject.DestroyImmediate(LineObj); GameObject.DestroyImmediate(LineObj);
   
joint = null; joint = null;
LineObj = null; LineObj = null;
lr = null; lr = null;
   
parent = null; parent = null;
target = null; target = null;
targetOffset = Vector3.zero; targetOffset = Vector3.zero;
isDestroyed = true; isDestroyed = true;
} }
} }
} }
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
   
// General Information about an assembly is controlled through the following  
// set of attributes. Change these attribute values to modify the information  
// associated with an assembly.  
[assembly: AssemblyTitle("AutoStrut")]  
[assembly: AssemblyDescription("")]  
[assembly: AssemblyConfiguration("")]  
[assembly: AssemblyCompany("")]  
[assembly: AssemblyProduct("AutoStrut")]  
[assembly: AssemblyCopyright("Copyright © 2012")]  
[assembly: AssemblyTrademark("")]  
[assembly: AssemblyCulture("")]  
   
// Setting ComVisible to false makes the types in this assembly not visible  
// to COM components. If you need to access a type in this assembly from  
// COM, set the ComVisible attribute to true on that type.  
[assembly: ComVisible(false)]  
   
// The following GUID is for the ID of the typelib if this project is exposed to COM  
[assembly: Guid("57e209db-4b94-46b4-be0e-bd6e830d4eb5")]  
   
// Version information for an assembly consists of the following four values:  
//  
// Major Version  
// Minor Version  
// Build Number  
// Revision  
//  
// You can specify all the values or you can default the Build and Revision Numbers  
// by using the '*' as shown below:  
// [assembly: AssemblyVersion("1.0.*")]  
[assembly: AssemblyVersion("1.0.0.0")]  
[assembly: AssemblyFileVersion("1.0.0.0")]  
   
  // General Information about an assembly is controlled through the following
  // set of attributes. Change these attribute values to modify the information
  // associated with an assembly.
  [assembly: AssemblyTitle("QuantumStrutsContinued")]
  [assembly: AssemblyDescription("")]
  [assembly: AssemblyConfiguration("")]
  [assembly: AssemblyCompany("")]
  [assembly: AssemblyProduct("QuantumStrutsContinued")]
  [assembly: AssemblyCopyright("Copyright © 2014 toadicus")]
  [assembly: AssemblyTrademark("")]
  [assembly: AssemblyCulture("")]
   
  // Setting ComVisible to false makes the types in this assembly not visible
  // to COM components. If you need to access a type in this assembly from
  // COM, set the ComVisible attribute to true on that type.
  [assembly: ComVisible(false)]
   
  // The following GUID is for the ID of the typelib if this project is exposed to COM
  [assembly: Guid("57e209db-4b94-46b4-be0e-bd6e830d4eb5")]
   
  // Version information for an assembly consists of the following four values:
  //
  // Major Version
  // Minor Version
  // Build Number
  // Revision
  //
  // You can specify all the values or you can default the Build and Revision Numbers
  // by using the '*' as shown below:
  // [assembly: AssemblyVersion("1.0.*")]
  [assembly: AssemblyVersion("1.0.0.0")]
  [assembly: AssemblyFileVersion("1.0.0.0")]
   
// QuantumStrutsContinued © 2014 toadicus // QuantumStrutsContinued © 2014 toadicus
// //
// This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. To view a // This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. To view a
// copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ // copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/
// //
// Continued from QuantumStrut, © 2013 BoJaN. Used with permission. // Continued from QuantumStrut, © 2013 BoJaN. Used with permission.
   
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
   
//using System.Threading.Tasks;  
using UnityEngine; using UnityEngine;
   
namespace QuantumStrut namespace QuantumStrut
{ {
public class QuantumStrut : PartModule public class QuantumStrut : PartModule
{ {
public static Material LaserMaterial; public static Material LaserMaterial;
Strut strut = null; Strut strut = null;
GameObject lineObj; GameObject lineObj;
LineRenderer lr; LineRenderer lr;
bool Editor = false; bool Editor = false;
int I = 0; int I = 0;
   
#region Fields #region Fields
   
[KSPField(isPersistant = true)] [KSPField(isPersistant = true)]
public bool IsEnabled = true; public bool IsEnabled = true;
[KSPField(isPersistant = false)] [KSPField(isPersistant = false)]
public float PowerConsumption = 0; public float PowerConsumption = 0;
[KSPField(isPersistant = false)] [KSPField(isPersistant = false)]
public string TransformName = ""; public string TransformName = "";
[KSPField(isPersistant = false)] [KSPField(isPersistant = false)]
public Vector3 Start = new Vector3(0, 0, 0); public Vector3 Start = new Vector3(0, 0, 0);
[KSPField(isPersistant = false)] [KSPField(isPersistant = false)]
public Vector3 Dir = new Vector3(0, 1, 0); public Vector3 Dir = new Vector3(0, 1, 0);
[KSPField(isPersistant = false)] [KSPField(isPersistant = false)]
public string Material = "Particles/Additive"; public string Material = "Particles/Additive";
[KSPField(isPersistant = false)] [KSPField(isPersistant = false)]
public Vector3 StartColor = Vector3.zero; public Vector3 StartColor = Vector3.zero;
[KSPField(isPersistant = false)] [KSPField(isPersistant = false)]
public Vector3 EndColor = Vector3.zero; public Vector3 EndColor = Vector3.zero;
[KSPField(isPersistant = false)] [KSPField(isPersistant = false)]
public float StartSize = 0.03f; public float StartSize = 0.03f;
[KSPField(isPersistant = false)] [KSPField(isPersistant = false)]
public float EndSize = 0.0075f; public float EndSize = 0.0075f;
   
#endregion #endregion
   
#region Actions #region Actions
   
[KSPAction("Toggle")] [KSPAction("Toggle")]
public void ToggleStrut(KSPActionParam param) public void ToggleStrut(KSPActionParam param)
{ {
IsEnabled = !IsEnabled; IsEnabled = !IsEnabled;
CheckHit(); CheckHit();
} }
   
[KSPAction("Activate")] [KSPAction("Activate")]
public void ActivateStrut(KSPActionParam param) public void ActivateStrut(KSPActionParam param)
{ {
IsEnabled = true; IsEnabled = true;
CheckHit(); CheckHit();
} }
   
[KSPAction("Deactivate")] [KSPAction("Deactivate")]
public void DeactivateStrut(KSPActionParam param) public void DeactivateStrut(KSPActionParam param)
{ {
IsEnabled = false; IsEnabled = false;
CheckHit(); CheckHit();
} }
   
#endregion #endregion
   
#region Events #region Events
   
[KSPEvent(guiActive = true, guiName = "Activate", active = true)] [KSPEvent(guiActive = true, guiName = "Activate", active = true, guiActiveUnfocused = true, unfocusedRange = 2f)]
public void ActivateStrut() public void ActivateStrut()
{ {
IsEnabled = true; IsEnabled = true;
CheckHit(); CheckHit();
} }
   
[KSPEvent(guiActive = true, guiName = "Deactivate", active = false)] [KSPEvent(guiActive = true, guiName = "Deactivate", active = false, guiActiveUnfocused = true, unfocusedRange = 2f)]
public void DeactivateStrut() public void DeactivateStrut()
{ {
IsEnabled = false; IsEnabled = false;
CheckHit(); CheckHit();
} }
   
#endregion #endregion
   
public Material material = null; public Material material = null;
public Color startColor = Color.white; public Color startColor = Color.white;
public Color endColor = Color.white; public Color endColor = Color.white;
   
public Color Vector3toColor(Vector3 vec) public Color Vector3toColor(Vector3 vec)
{ {
return new Color(vec.x / 255, vec.y / 255, vec.z / 255); return new Color(vec.x / 255, vec.y / 255, vec.z / 255);
} }
   
Transform getTransform() Transform getTransform()
{ {
if (TransformName == "") if (TransformName == "")
return part.transform; return part.transform;
else else
return part.FindModelTransform(TransformName); return part.FindModelTransform(TransformName);
} }
   
public void print(object body, params object[] args) public void print(object body, params object[] args)
{ {
string final = body.ToString(); string final = body.ToString();
for (int I = 0; I < args.Length; I++) for (int I = 0; I < args.Length; I++)
{ {
final = final.Replace("{" + I + "}", args[I].ToString()); final = final.Replace("{" + I + "}", args[I].ToString());
} }
MonoBehaviour.print("[AutoStrut] " + final); MonoBehaviour.print("[AutoStrut] " + final);
} }
   
public override void OnLoad(ConfigNode node) public override void OnLoad(ConfigNode node)
{ {
base.OnLoad(node); base.OnLoad(node);
} }
   
public override void OnActive() public override void OnActive()
{ {
InitLaser(); InitLaser();
   
base.OnActive(); base.OnActive();
} }
   
public override void OnInactive() public override void OnInactive()
{ {
DestroyLaser(); DestroyLaser();
   
base.OnInactive(); base.OnInactive();
} }
   
public override string GetInfo() public override string GetInfo()
{ {
return "Requires:\n- ElectricCharge (" + PowerConsumption + "/s.)\n\n Costs 5 to create strut."; return "Requires:\n- ElectricCharge (" + PowerConsumption + "/s.)\n\n Costs 5 to create strut.";
} }
   
public override void OnStart(PartModule.StartState state) public override void OnStart(PartModule.StartState state)
{ {
try try
{ {
print("Material: {0}", Material); print("Material: {0}", Material);
material = new Material(Shader.Find(Material.Trim())); material = new Material(Shader.Find(Material.Trim()));
} }
catch catch
{ {
material = null; material = null;
} }
   
startColor = Vector3toColor(StartColor); startColor = Vector3toColor(StartColor);
endColor = Vector3toColor(EndColor); endColor = Vector3toColor(EndColor);
   
if (!Util.isValid(LaserMaterial)) if (!Util.isValid(LaserMaterial))
LaserMaterial = new Material(Shader.Find("Particles/Additive")); LaserMaterial = new Material(Shader.Find("Particles/Additive"));
   
if (state == StartState.Docked) if (state == StartState.Docked)
CheckHit(); CheckHit();
   
if (state == StartState.Editor) if (state == StartState.Editor)
{ {
Editor = true; Editor = true;
RenderingManager.AddToPostDrawQueue(0, DrawBuildOverlay); RenderingManager.AddToPostDrawQueue(0, DrawBuildOverlay);
InitLaser(); InitLaser();
} }
else else
{ {
Editor = false; Editor = false;
RenderingManager.RemoveFromPostDrawQueue(0, DrawBuildOverlay); RenderingManager.RemoveFromPostDrawQueue(0, DrawBuildOverlay);
DestroyLaser(); DestroyLaser();
} }
   
base.OnStart(state); base.OnStart(state);
} }
   
public override void OnFixedUpdate() public override void OnFixedUpdate()
{ {
base.OnFixedUpdate(); base.OnFixedUpdate();
} }
   
public override void OnUpdate() public override void OnUpdate()
{ {
Events["ActivateStrut"].active = !IsEnabled; Events["ActivateStrut"].active = !IsEnabled;
Events["DeactivateStrut"].active = IsEnabled; Events["DeactivateStrut"].active = IsEnabled;
   
if (IsEnabled) if (IsEnabled)
{ {
I = I + 1 % 255; I = I + 1 % 255;
   
if (strut != null && !strut.isDestroyed) if (strut != null && !strut.isDestroyed)
{ {
if (PowerConsumption == 0 || (Util.GetEnergy(part.vessel) > PowerConsumption * TimeWarp.fixedDeltaTime && part.RequestResource( if (PowerConsumption == 0 || (Util.GetEnergy(part.vessel) > PowerConsumption * TimeWarp.fixedDeltaTime && part.RequestResource(
"ElectricCharge", "ElectricCharge",
PowerConsumption * TimeWarp.fixedDeltaTime PowerConsumption * TimeWarp.fixedDeltaTime
) > 0)) ) > 0))
strut.Update(); strut.Update();
else else
strut.Destroy(); strut.Destroy();
} }
else else
{ {
if ((I % 10) == 0) if ((I % 10) == 0)
{ {
CheckHit(); CheckHit();
} }
} }
} }
else else
{ {
if (strut != null) if (strut != null)
{ {
strut.Destroy(); strut.Destroy();
strut = null; strut = null;
} }
} }
   
base.OnUpdate(); base.OnUpdate();
} }
   
void CheckHit() void CheckHit()
{ {
if (!isEnabled) if (!isEnabled)
{ {
strut.Destroy(); strut.Destroy();
strut = null; strut = null;
return; return;
} }
   
if (strut == null || strut.isDestroyed) if (strut == null || strut.isDestroyed)
{ {
Vector3 dir = getTransform().TransformDirection(Dir); Vector3 dir = getTransform().TransformDirection(Dir);
Vector3 start = getTransform().TransformPoint(Start); Vector3 start = getTransform().TransformPoint(Start);
   
UnityEngine.RaycastHit info = new RaycastHit(); UnityEngine.RaycastHit info = new RaycastHit();
bool hit = Physics.Raycast(new UnityEngine.Ray(start + (dir * 0.05f), dir), out info, 10); bool hit = Physics.Raycast(new UnityEngine.Ray(start + (dir * 0.05f), dir), out info, 10);
if (hit) if (hit)
{ {
Part targetPart = Util.partFromRaycast(info); Part targetPart = Util.partFromRaycast(info);
   
if (targetPart && vessel.parts.Contains(targetPart) && Util.GetEnergy(part.vessel) > 5 * TimeWarp.fixedDeltaTime) if (targetPart && vessel.parts.Contains(targetPart) && Util.GetEnergy(part.vessel) > 5 * TimeWarp.fixedDeltaTime)
{ {
strut = new Strut( strut = new Strut(
part, part,
targetPart, targetPart,
targetPart.transform.InverseTransformPoint(info.point), targetPart.transform.InverseTransformPoint(info.point),
getTransform() getTransform()
); );
strut.Material = material; strut.Material = material;
strut.StartColor = startColor; strut.StartColor = startColor;
strut.EndColor = endColor; strut.EndColor = endColor;
strut.StartSize = StartSize; strut.StartSize = StartSize;
strut.EndSize = EndSize; strut.EndSize = EndSize;
} }
} }
} }
} }
   
void InitLaser() void InitLaser()
{ {
if (!Util.isValid(lr)) if (!Util.isValid(lr))
{ {
lineObj = new GameObject(); lineObj = new GameObject();
   
lr = lineObj.AddComponent<LineRenderer>(); lr = lineObj.AddComponent<LineRenderer>();
lr.useWorldSpace = true; lr.useWorldSpace = true;
   
lr.material = material; lr.material = material;
lr.SetColors(startColor, endColor); lr.SetColors(startColor, endColor);
lr.SetWidth(StartSize, EndSize); lr.SetWidth(StartSize, EndSize);
   
lr.SetVertexCount(2); lr.SetVertexCount(2);
lr.SetPosition(0, Vector3.zero); lr.SetPosition(0, Vector3.zero);
lr.SetPosition(1, Vector3.zero); lr.SetPosition(1, Vector3.zero);
lr.castShadows = false; lr.castShadows = false;
lr.receiveShadows = true; lr.receiveShadows = true;
} }
} }
   
void DestroyLaser() void DestroyLaser()
{ {
if (Util.isValid(lr)) if (Util.isValid(lr))
LineRenderer.DestroyImmediate(lr); LineRenderer.DestroyImmediate(lr);
   
if (Util.isValid(lineObj)) if (Util.isValid(lineObj))
GameObject.DestroyImmediate(lineObj); GameObject.DestroyImmediate(lineObj);
} }
   
public void DrawBuildOverlay() public void DrawBuildOverlay()
{ {
if (Util.isValid(part)) if (Util.isValid(part))
{ {
if (!Editor) if (!Editor)
return; return;
   
if (Util.isValid(lr)) if (Util.isValid(lr))
{ {
Vector3 dir = getTransform().TransformDirection(Dir); Vector3 dir = getTransform().TransformDirection(Dir);
Vector3 start = getTransform().TransformPoint(Start); Vector3 start = getTransform().TransformPoint(Start);
   
UnityEngine.RaycastHit info = new RaycastHit(); UnityEngine.RaycastHit info = new RaycastHit();
bool hit = Physics.Raycast(new UnityEngine.Ray(start + (dir * 0.05f), dir), out info, 10); bool hit = Physics.Raycast(new UnityEngine.Ray(start + (dir * 0.05f), dir), out info, 10);
if (hit) if (hit)
{ {
if (Util.isValid(material)) if (Util.isValid(material))
lr.material = material; lr.material = material;
   
lr.SetColors(startColor, endColor); lr.SetColors(startColor, endColor);
lr.SetWidth(StartSize, EndSize); lr.SetWidth(StartSize, EndSize);
   
lr.SetPosition(0, start); lr.SetPosition(0, start);
lr.SetPosition(1, info.point); lr.SetPosition(1, info.point);
} }
else else
{ {
lr.material = LaserMaterial; lr.material = LaserMaterial;
lr.SetColors(Color.red, Color.red); lr.SetColors(Color.red, Color.red);
lr.SetWidth(0.01f, 0.01f); lr.SetWidth(0.01f, 0.01f);
   
lr.SetPosition(0, start); lr.SetPosition(0, start);
lr.SetPosition(1, start + (dir * 10)); lr.SetPosition(1, start + (dir * 10));
} }
} }
} }
else else
{ {
DestroyLaser(); DestroyLaser();
RenderingManager.RemoveFromPostDrawQueue(0, DrawBuildOverlay); RenderingManager.RemoveFromPostDrawQueue(0, DrawBuildOverlay);
} }
} }
} }
} }
// QuantumStrutsContinued © 2014 toadicus // QuantumStrutsContinued © 2014 toadicus
// //
// This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. To view a // This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. To view a
// copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ // copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/
// //
// Continued from QuantumStrut, © 2013 BoJaN. Used with permission. // Continued from QuantumStrut, © 2013 BoJaN. Used with permission.
   
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
//using System.Threading.Tasks;  
using UnityEngine; using UnityEngine;
using KSP.IO; using KSP.IO;
   
   
namespace QuantumStrut namespace QuantumStrut
{ {
class QuantumStrutCore : PartModule class QuantumStrutCore : PartModule
{ {
GameObject lineObj = null; GameObject lineObj = null;
LineRenderer lr = null; LineRenderer lr = null;
ConfigNode nodeToLoad = null; ConfigNode nodeToLoad = null;
  bool Placing = false;
bool Placing = false; bool Deleting = false;
bool Deleting = false; List<CoreStrut> struts = new List<CoreStrut>();
List<CoreStrut> struts = new List<CoreStrut>(); Part startPart = null;
  Vector3 startOffset = Vector3.zero;
Part startPart = null; Part endPart = null;
Vector3 startOffset = Vector3.zero; Vector3 endOffset = Vector3.zero;
Part endPart = null; public Material material = null;
Vector3 endOffset = Vector3.zero; public Color startColor = Color.white;
  public Color endColor = Color.white;
public Material material = null;  
public Color startColor = Color.white; #region Fields
public Color endColor = Color.white;  
  [KSPField(isPersistant = true)]
#region Fields public bool IsEnabled = true;
[KSPField(isPersistant = true)] [KSPField(isPersistant = false)]
public bool IsEnabled = true; public float PowerConsumption = 0;
  [KSPField(isPersistant = false)]
[KSPField(isPersistant = false)] public int MaxStruts = 8;
public float PowerConsumption = 0; [KSPField(isPersistant = false)]
  public string Material = "Particles/Additive";
[KSPField(isPersistant = false)] [KSPField(isPersistant = false)]
public int MaxStruts = 8; public Vector3 StartColor = Vector3.zero;
  [KSPField(isPersistant = false)]
[KSPField(isPersistant = false)] public Vector3 EndColor = Vector3.zero;
public string Material = "Particles/Additive"; [KSPField(isPersistant = false)]
  public float StartSize = 0.03f;
[KSPField(isPersistant = false)] [KSPField(isPersistant = false)]
public Vector3 StartColor = Vector3.zero; public float EndSize = 0.0075f;
   
[KSPField(isPersistant = false)] #endregion
public Vector3 EndColor = Vector3.zero;  
  #region Actions
   
[KSPField(isPersistant = false)] [KSPAction("Toggle")]
public float StartSize = 0.03f; public void ToggleCore(KSPActionParam param)
  {
[KSPField(isPersistant = false)] IsEnabled = !IsEnabled;
public float EndSize = 0.0075f; }
#endregion  
  [KSPAction("Activate")]
#region Actions public void ActivateCore(KSPActionParam param)
[KSPAction("Toggle")] {
public void ToggleCore(KSPActionParam param) IsEnabled = true;
{ }
IsEnabled = !IsEnabled;  
} [KSPAction("Deactivate")]
  public void DeactivateCore(KSPActionParam param)
[KSPAction("Activate")] {
public void ActivateCore(KSPActionParam param) IsEnabled = false;
{ }
IsEnabled = true;  
} #endregion
   
[KSPAction("Deactivate")] #region Events
public void DeactivateCore(KSPActionParam param)  
{ [KSPEvent(
IsEnabled = false; guiActive = true,
} guiName = "Place Strut",
#endregion active = false,
  externalToEVAOnly = true,
#region Events guiActiveUnfocused = true,
[KSPEvent(guiActive = true, guiName = "Place Strut", active = false, externalToEVAOnly=true, guiActiveUnfocused=true, unfocusedRange = 5)] unfocusedRange = 5
public void BeginPlace() )]
{ public void BeginPlace()
startPart = null; {
startOffset = Vector3.zero; startPart = null;
endPart = null; startOffset = Vector3.zero;
endOffset = Vector3.zero; endPart = null;
Placing = true; endOffset = Vector3.zero;
} Placing = true;
  }
[KSPEvent(guiActive = true, guiName = "Remove Strut", active = false, externalToEVAOnly = true, guiActiveUnfocused = true, unfocusedRange = 2500)]  
public void BeginDelete() [KSPEvent(
{ guiActive = true,
Deleting = true; guiName = "Remove Strut",
} active = false,
  externalToEVAOnly = true,
[KSPEvent(guiActive = true, guiName = "Activate", active = true)] guiActiveUnfocused = true,
public void ActivateCore() unfocusedRange = 2500
{ )]
IsEnabled = true; public void BeginDelete()
} {
  Deleting = true;
[KSPEvent(guiActive = true, guiName = "Deactivate", active = false)] }
public void DeactivateCore()  
{ [KSPEvent(guiActive = true, guiName = "Activate", active = true)]
IsEnabled = false; public void ActivateCore()
} {
#endregion IsEnabled = true;
  }
public Vector3 StringToVector3(string str)  
{ [KSPEvent(guiActive = true, guiName = "Deactivate", active = false)]
string[] vals = str.Split(','); public void DeactivateCore()
float x = (float)Convert.ToDecimal(vals[0]); {
float y = (float)Convert.ToDecimal(vals[1]); IsEnabled = false;
float z = (float)Convert.ToDecimal(vals[2]); }
return new Vector3(x, y, z);  
} #endregion
   
public Color Vector3toColor(Vector3 vec) public Vector3 StringToVector3(string str)
{ {
return new Color(vec.x / 255, vec.y / 255, vec.z / 255); string[] vals = str.Split(',');
} float x = (float)Convert.ToDecimal(vals[0]);
  float y = (float)Convert.ToDecimal(vals[1]);
Part partFromGameObject(GameObject ob) float z = (float)Convert.ToDecimal(vals[2]);
{ return new Vector3(x, y, z);
GameObject o = ob; }
   
while (o) public Color Vector3toColor(Vector3 vec)
{ {
Part p = Part.FromGO(o); return new Color(vec.x / 255, vec.y / 255, vec.z / 255);
if (p && p != null) }
{  
return p; Part partFromGameObject(GameObject ob)
} {
  GameObject o = ob;
if (o.transform.parent)  
o = o.transform.parent.gameObject; while (o)
else {
return null; Part p = Part.FromGO(o);
} if (p && p != null)
return null; {
} return p;
  }
Part partFromRaycast(RaycastHit hit)  
{ if (o.transform.parent)
return partFromGameObject(hit.collider.gameObject); o = o.transform.parent.gameObject;
} else
  return null;
Part partFromId(long id) }
{ return null;
Console.WriteLine("Vessel Parts: " + part.vessel.Parts.Count); }
foreach (Part p in part.vessel.Parts)  
{ Part partFromRaycast(RaycastHit hit)
print(p.uid + " ?= " + id + ": " + (p.uid == id)); {
if (p.uid == id) return partFromGameObject(hit.collider.gameObject);
return p; }
}  
return null; Part partFromId(long id)
} {
  Console.WriteLine("Vessel Parts: " + part.vessel.Parts.Count);
bool isValid(UnityEngine.Object obj) foreach (Part p in part.vessel.Parts)
{ {
return (obj && obj != null); print(p.uid + " ?= " + id + ": " + (p.uid == id));
} if (p.uid == id)
  return p;
void InitLaser() }
{ return null;
if (!isValid(lr)) }
{  
lineObj = new GameObject(); bool isValid(UnityEngine.Object obj)
  {
lr = lineObj.AddComponent<LineRenderer>(); return (obj && obj != null);
lr.useWorldSpace = true; }
   
lr.material = new Material(Shader.Find("Particles/Additive")); void InitLaser()
lr.SetColors(Color.white, Color.white); {
lr.SetWidth(0.03f, 0.03f); if (!isValid(lr))
  {
lr.SetVertexCount(2); lineObj = new GameObject();
lr.SetPosition(0, Vector3.zero);  
lr.SetPosition(1, Vector3.zero); lr = lineObj.AddComponent<LineRenderer>();
lr.castShadows = false; lr.useWorldSpace = true;
lr.receiveShadows = true;  
} lr.material = new Material(Shader.Find("Particles/Additive"));
} lr.SetColors(Color.white, Color.white);
  lr.SetWidth(0.03f, 0.03f);
void DestroyLaser()  
{ lr.SetVertexCount(2);
if (isValid(lr)) lr.SetPosition(0, Vector3.zero);
LineRenderer.DestroyImmediate(lr); lr.SetPosition(1, Vector3.zero);
if (isValid(lineObj)) lr.castShadows = false;
GameObject.DestroyImmediate(lineObj); lr.receiveShadows = true;
} }
  }
float GetEnergy()  
{ void DestroyLaser()
double energy = 0; {
foreach (Part p in part.vessel.parts) if (isValid(lr))
{ LineRenderer.DestroyImmediate(lr);
foreach (PartResource r in p.Resources) if (isValid(lineObj))
{ GameObject.DestroyImmediate(lineObj);
if (r.resourceName == "ElectricCharge") }
energy += r.amount;  
} float GetEnergy()
} {
return (float)energy; double energy = 0;
} foreach (Part p in part.vessel.parts)
  {
void AddStrut(Part a, Vector3 aO, Part b, Vector3 bO) foreach (PartResource r in p.Resources)
{ {
CoreStrut s = new CoreStrut(a, aO, b, bO); if (r.resourceName == "ElectricCharge")
s.Material = material; energy += r.amount;
s.StartColor = startColor; }
s.EndColor = endColor; }
s.StartSize = StartSize; return (float)energy;
s.EndSize = EndSize; }
struts.Add(s);  
} void AddStrut(Part a, Vector3 aO, Part b, Vector3 bO)
  {
public override string GetInfo() CoreStrut s = new CoreStrut(a, aO, b, bO);
{ s.Material = material;
return "Max Struts: " + MaxStruts + "\nRequires:\n- ElectricCharge (" + PowerConsumption + "/s.)\n\n Energy cost is per-strut."; s.StartColor = startColor;
} s.EndColor = endColor;
  s.StartSize = StartSize;
public override void OnStart(PartModule.StartState state) s.EndSize = EndSize;
{ struts.Add(s);
try }
{  
material = new Material(Shader.Find(Material.Trim())); public override string GetInfo()
} {
catch return "Max Struts: " + MaxStruts + "\nRequires:\n- ElectricCharge (" + PowerConsumption + "/s.)\n\n Energy cost is per-strut.";
{ }
material = null;  
} public override void OnStart(PartModule.StartState state)
  {
startColor = Vector3toColor(StartColor); try
endColor = Vector3toColor(EndColor); {
base.OnStart(state); material = new Material(Shader.Find(Material.Trim()));
} }
  catch
public override void OnSave(ConfigNode node) {
{ material = null;
foreach (CoreStrut strut in struts) }
{  
if (!strut.isDestroyed) startColor = Vector3toColor(StartColor);
{ endColor = Vector3toColor(EndColor);
ConfigNode n = node.AddNode("QuantumStrut"); base.OnStart(state);
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)); public override void OnSave(ConfigNode node)
n.AddValue("targetOffset", strut.targetOffset.x + "," + strut.targetOffset.y + "," + strut.targetOffset.z); {
} foreach (CoreStrut strut in struts)
} {
  if (!strut.isDestroyed)
base.OnSave(node); {
} ConfigNode n = node.AddNode("QuantumStrut");
  n.AddValue("parent", part.vessel.parts.IndexOf(strut.parent));
public override void OnLoad(ConfigNode node) n.AddValue(
{ "parentOffset",
if (nodeToLoad == null) strut.parentOffset.x + "," + strut.parentOffset.y + "," + strut.parentOffset.z
nodeToLoad = node; );
  n.AddValue("target", part.vessel.parts.IndexOf(strut.target));
base.OnLoad(node); n.AddValue(
} "targetOffset",
  strut.targetOffset.x + "," + strut.targetOffset.y + "," + strut.targetOffset.z
void printObj(object obj) );
{ }
using (KSP.IO.TextWriter writer = TextWriter.CreateForType<string>("obj.cs")) }
{  
string str = printProperties(obj, TypeDescriptor.GetProperties(obj), 0); base.OnSave(node);
writer.Write(str); }
print(str);  
} public override void OnLoad(ConfigNode node)
} {
  if (nodeToLoad == null)
string printProperties(object obj, PropertyDescriptorCollection collection, int I) nodeToLoad = node;
{  
if (I > 2) return ""; base.OnLoad(node);
  }
string prefix = "";  
string str = ""; void printObj(object obj)
for (int T = 0; T < I; T++) {
{ using (KSP.IO.TextWriter writer = TextWriter.CreateForType<string>("obj.cs"))
prefix += " "; {
} string str = printProperties(obj, TypeDescriptor.GetProperties(obj), 0);
  writer.Write(str);
str += "\n" + prefix + "#region"; print(str);
foreach (PropertyDescriptor d in collection) }
{ }
str += "\n" + prefix + d.Name + " = " + d.GetValue(obj);  
str += printProperties(obj, d.GetChildProperties(obj), I+1); string printProperties(object obj, PropertyDescriptorCollection collection, int I)
} {
str += "\n" + prefix + "#endregion"; if (I > 2)
return str; return "";
}  
  string prefix = "";
public override void OnUpdate() string str = "";
{ for (int T = 0; T < I; T++)
bool eva = isValid(Util.Kerbal); {
Events["ActivateCore"].active = !IsEnabled; prefix += " ";
Events["DeactivateCore"].active = IsEnabled; }
Events["BeginPlace"].active = !Placing && !Deleting && struts.Count < MaxStruts && eva;  
Events["BeginDelete"].active = !Deleting && !Placing && struts.Count > 0 && eva; str += "\n" + prefix + "#region";
  foreach (PropertyDescriptor d in collection)
if (nodeToLoad != null) {
{ str += "\n" + prefix + d.Name + " = " + d.GetValue(obj);
foreach (ConfigNode strut in nodeToLoad.GetNodes("QuantumStrut")) str += printProperties(obj, d.GetChildProperties(obj), I + 1);
{ }
Part parent = part.vessel.parts[Convert.ToInt32(strut.GetValue("parent"))]; str += "\n" + prefix + "#endregion";
Vector3 parentOffset = StringToVector3(strut.GetValue("parentOffset")); return str;
Part target = part.vessel.parts[Convert.ToInt32(strut.GetValue("target"))]; }
Vector3 targetOffset = StringToVector3(strut.GetValue("targetOffset"));  
  public override void OnUpdate()
if (isValid(parent) && isValid(target)) {
AddStrut(parent, parentOffset, target, targetOffset); bool eva = isValid(Util.Kerbal);
} Events["ActivateCore"].active = !IsEnabled;
nodeToLoad = null; Events["DeactivateCore"].active = IsEnabled;
} Events["BeginPlace"].active = !Placing && !Deleting && struts.Count < MaxStruts && eva;
  Events["BeginDelete"].active = !Deleting && !Placing && struts.Count > 0 && eva;
if (eva)  
{ if (nodeToLoad != null)
InitLaser(); {
if (Placing) foreach (ConfigNode strut in nodeToLoad.GetNodes("QuantumStrut"))
{ {
RaycastHit info = new RaycastHit(); Part parent = part.vessel.parts[Convert.ToInt32(strut.GetValue("parent"))];
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); Vector3 parentOffset = StringToVector3(strut.GetValue("parentOffset"));
bool hit = Physics.Raycast(ray, out info, Mathf.Infinity); Part target = part.vessel.parts[Convert.ToInt32(strut.GetValue("target"))];
if (isValid(startPart)) Vector3 targetOffset = StringToVector3(strut.GetValue("targetOffset"));
{  
Vector3 pos = startPart.transform.TransformPoint(startOffset); if (isValid(parent) && isValid(target))
ray = new Ray(pos, (info.point - pos).normalized); AddStrut(parent, parentOffset, target, targetOffset);
hit = Physics.Raycast(ray, out info, 10); }
} nodeToLoad = null;
  }
if (Input.GetMouseButtonUp(0))  
{ if (eva)
if (hit) {
{ InitLaser();
if (!isValid(startPart)) if (Placing)
{ {
startPart = partFromRaycast(info); RaycastHit info = new RaycastHit();
if (isValid(startPart)) Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
startOffset = startPart.transform.InverseTransformPoint(info.point); bool hit = Physics.Raycast(ray, out info, Mathf.Infinity);
} if (isValid(startPart))
else if (!isValid(endPart)) {
{ Vector3 pos = startPart.transform.TransformPoint(startOffset);
Part p = partFromRaycast(info); ray = new Ray(pos, (info.point - pos).normalized);
if (isValid(p)) hit = Physics.Raycast(ray, out info, 10);
{ }
if (p != startPart && startPart.vessel.parts.Contains(p))  
{ if (Input.GetMouseButtonUp(0))
endPart = p; {
endOffset = endPart.transform.InverseTransformPoint(info.point); if (hit)
  {
AddStrut(startPart, startOffset, endPart, endOffset); if (!isValid(startPart))
} {
Placing = false; startPart = partFromRaycast(info);
} if (isValid(startPart))
} startOffset = startPart.transform.InverseTransformPoint(info.point);
} }
} else if (!isValid(endPart))
  {
if(isValid(startPart)) Part p = partFromRaycast(info);
{ if (isValid(p))
if (hit) {
{ if (p != startPart && startPart.vessel.parts.Contains(p))
Part p = partFromRaycast(info); {
Color c = Color.red; endPart = p;
  endOffset = endPart.transform.InverseTransformPoint(info.point);
if (isValid(p))  
{ AddStrut(startPart, startOffset, endPart, endOffset);
if (startPart.vessel.parts.Contains(p) && p != startPart) }
c = Color.green; Placing = false;
} }
  }
lr.SetColors(c, c); }
lr.SetPosition(0, startPart.transform.TransformPoint(startOffset)); }
lr.SetPosition(1, info.point);  
} if (isValid(startPart))
else {
{ if (hit)
lr.SetColors(Color.red, Color.red); {
lr.SetPosition(0, startPart.transform.TransformPoint(startOffset)); Part p = partFromRaycast(info);
lr.SetPosition(1, ray.GetPoint(10)); Color c = Color.red;
}  
} if (isValid(p))
} {
else if (startPart.vessel.parts.Contains(p) && p != startPart)
{ c = Color.green;
lr.SetPosition(0, Vector3.zero); }
lr.SetPosition(1, Vector3.zero);  
} lr.SetColors(c, c);
  lr.SetPosition(0, startPart.transform.TransformPoint(startOffset));
if (Deleting) lr.SetPosition(1, info.point);
{ }
RaycastHit info = new RaycastHit(); else
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); {
bool hit = Physics.Raycast(ray, out info, Mathf.Infinity); lr.SetColors(Color.red, Color.red);
  lr.SetPosition(0, startPart.transform.TransformPoint(startOffset));
CoreStrut closest = null; lr.SetPosition(1, ray.GetPoint(10));
float closestDist = Mathf.Infinity; }
foreach (CoreStrut strut in struts) }
{ }
strut.Selected = false; else
if (hit) {
{ lr.SetPosition(0, Vector3.zero);
Vector3 start = strut.parent.transform.TransformPoint(strut.parentOffset); lr.SetPosition(1, Vector3.zero);
float d = Vector3.Distance(start, info.point); }
   
if (d < 0.05 && d < closestDist) if (Deleting)
{ {
closest = strut; RaycastHit info = new RaycastHit();
closestDist = d; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
} bool hit = Physics.Raycast(ray, out info, Mathf.Infinity);
}  
} CoreStrut closest = null;
  float closestDist = Mathf.Infinity;
if(closest != null) foreach (CoreStrut strut in struts)
closest.Selected = true; {
  strut.Selected = false;
if (Input.GetMouseButtonUp(0)) if (hit)
{ {
if (closest != null) Vector3 start = strut.parent.transform.TransformPoint(strut.parentOffset);
{ float d = Vector3.Distance(start, info.point);
closest.Destroy();  
struts.Remove(closest); if (d < 0.05 && d < closestDist)
} {
Deleting = false; closest = strut;
} closestDist = d;
} }
} }
else }
{  
DestroyLaser(); if (closest != null)
} closest.Selected = true;
   
foreach (CoreStrut s in struts.ToArray()) if (Input.GetMouseButtonUp(0))
{ {
if (IsEnabled) if (closest != null)
{ {
if (s.Active) closest.Destroy();
{ struts.Remove(closest);
if (PowerConsumption == 0 || (GetEnergy() > PowerConsumption * TimeWarp.fixedDeltaTime && part.RequestResource("ElectricCharge", PowerConsumption * TimeWarp.fixedDeltaTime) > 0)) }
{ Deleting = false;
s.Active = true; }
} }
else }
{ else
s.Active = false; {
} DestroyLaser();
} }
else  
{ foreach (CoreStrut s in struts.ToArray())
if (GetEnergy() > 5 * TimeWarp.fixedDeltaTime && part.RequestResource("ElectricCharge", 5 * TimeWarp.fixedDeltaTime) > 0) {
{ if (IsEnabled)
s.Active = true; {
} if (s.Active)
} {
} if (PowerConsumption == 0 || (GetEnergy() > PowerConsumption * TimeWarp.fixedDeltaTime && part.RequestResource(
else "ElectricCharge",
{ PowerConsumption * TimeWarp.fixedDeltaTime
s.Active = false; ) > 0))
} {
  s.Active = true;
s.Update(); }
if (s.isDestroyed) else
struts.Remove(s); {
} s.Active = false;
base.OnUpdate(); }
} }
} 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();
  }
  }
} }
   
file:a/Strut.cs -> file:b/Strut.cs
// QuantumStrutsContinued © 2014 toadicus // QuantumStrutsContinued © 2014 toadicus
// //
// This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. To view a // This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. To view a
// copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ // copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/
// //
// Continued from QuantumStrut, © 2013 BoJaN. Used with permission. // Continued from QuantumStrut, © 2013 BoJaN. Used with permission.
   
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
   
//using System.Threading.Tasks;  
using UnityEngine; using UnityEngine;
   
namespace QuantumStrut namespace QuantumStrut
{ {
class Strut class Strut
{ {
public bool isDestroyed = false; public bool isDestroyed = false;
Material _material = null; Material _material = null;
   
public Material Material public Material Material
{ {
set set
{ {
_material = value; _material = value;
if (Material != null) if (Material != null)
lr.material = Material; lr.material = Material;
} }
get get
{ {
return _material; return _material;
} }
} }
   
Color _startColor = Color.white; Color _startColor = Color.white;
   
public Color StartColor public Color StartColor
{ {
set set
{ {
_startColor = value; _startColor = value;
lr.SetColors(StartColor, EndColor); lr.SetColors(StartColor, EndColor);
} }
get get
{ {
return _startColor; return _startColor;
} }
} }
   
Color _endColor = Color.white; Color _endColor = Color.white;
   
public Color EndColor public Color EndColor
{ {
set set
{ {
_endColor = value; _endColor = value;
lr.SetColors(StartColor, EndColor); lr.SetColors(StartColor, EndColor);
} }
get get
{ {
return _endColor; return _endColor;
} }
} }
   
float _startSize = 0; float _startSize = 0;
   
public float StartSize public float StartSize
{ {
set set
{ {
_startSize = value; _startSize = value;
lr.SetWidth(StartSize, EndSize); lr.SetWidth(StartSize, EndSize);
} }
get get
{ {
return _startSize; return _startSize;
} }
} }
   
float _endSize = 0; float _endSize = 0;
   
public float EndSize public float EndSize
{ {
set set
{ {
_endSize = value; _endSize = value;
lr.SetWidth(StartSize, EndSize); lr.SetWidth(StartSize, EndSize);
} }
get get
{ {
return _endSize; return _endSize;
} }
} }
   
ConfigurableJoint joint; ConfigurableJoint joint;
Transform parentTransform = null; Transform parentTransform = null;
Part parent = null; Part parent = null;
Part target = null; Part target = null;
Vector3 targetOffset = Vector3.zero; Vector3 targetOffset = Vector3.zero;
GameObject LineObj = null; GameObject LineObj = null;
LineRenderer lr = null; LineRenderer lr = null;
   
public void print(object body, params object[] args) public void print(object body, params object[] args)
{ {
string final = body.ToString(); string final = body.ToString();
for (int I = 0; I < args.Length; I++) for (int I = 0; I < args.Length; I++)
{ {
final = final.Replace("{" + I + "}", args[I].ToString()); final = final.Replace("{" + I + "}", args[I].ToString());
} }
MonoBehaviour.print("[AutoStrut] " + final); MonoBehaviour.print("[AutoStrut] " + final);
} }
   
void DrawLine(Vector3 origin, Vector3 end) void DrawLine(Vector3 origin, Vector3 end)
{ {
if (Util.isValid(lr)) if (Util.isValid(lr))
{ {
lr.SetPosition(0, origin); lr.SetPosition(0, origin);
lr.SetPosition(1, end); lr.SetPosition(1, end);
} }
} }
   
public Strut(Part parent, Part target, Vector3 targetOffset, Transform parentTransform) public Strut(Part parent, Part target, Vector3 targetOffset, Transform parentTransform)
{ {
this.parent = parent; this.parent = parent;
this.target = target; this.target = target;
this.targetOffset = targetOffset; this.targetOffset = targetOffset;
this.parentTransform = parentTransform; this.parentTransform = parentTransform;
   
if (parent.vessel.parts.Contains(target)) if (parent.vessel.parts.Contains(target))
{ {
joint = parent.parent.gameObject.AddComponent<ConfigurableJoint>(); joint = parent.parent.gameObject.AddComponent<ConfigurableJoint>();
joint.connectedBody = target.rigidbody; joint.connectedBody = target.rigidbody;
   
joint.anchor = new Vector3( joint.anchor = new Vector3(
0, 0,
0, 0,
Vector3.Distance( Vector3.Distance(
parentTransform.position, parentTransform.position,
target.transform.TransformPoint(targetOffset) target.transform.TransformPoint(targetOffset)
) / 2 ) / 2
); );
joint.axis = new Vector3(0, 0, 1); joint.axis = new Vector3(0, 0, 1);
joint.xMotion = ConfigurableJointMotion.Locked; joint.xMotion = ConfigurableJointMotion.Locked;
joint.yMotion = ConfigurableJointMotion.Locked; joint.yMotion = ConfigurableJointMotion.Locked;
joint.zMotion = ConfigurableJointMotion.Locked; joint.zMotion = ConfigurableJointMotion.Locked;
joint.angularXMotion = ConfigurableJointMotion.Locked; joint.angularXMotion = ConfigurableJointMotion.Locked;
joint.angularYMotion = ConfigurableJointMotion.Locked; joint.angularYMotion = ConfigurableJointMotion.Locked;
joint.angularZMotion = ConfigurableJointMotion.Locked; joint.angularZMotion = ConfigurableJointMotion.Locked;
   
LineObj = new GameObject(); LineObj = new GameObject();
LineObj.name = "quantumstrut"; LineObj.name = "quantumstrut";
   
lr = LineObj.AddComponent<LineRenderer>(); lr = LineObj.AddComponent<LineRenderer>();
lr.useWorldSpace = true; lr.useWorldSpace = true;
   
Material = QuantumStrut.LaserMaterial; Material = QuantumStrut.LaserMaterial;
StartColor = Color.white; StartColor = Color.white;
EndColor = Color.white; EndColor = Color.white;
StartSize = 0.03f; StartSize = 0.03f;
EndSize = 0.0075f; EndSize = 0.0075f;
   
lr.SetVertexCount(2); lr.SetVertexCount(2);
lr.SetPosition(0, Vector3.zero); lr.SetPosition(0, Vector3.zero);
lr.SetPosition(1, Vector3.zero); lr.SetPosition(1, Vector3.zero);
} }
else else
{ {
Destroy(); Destroy();
} }
} }
   
public void Update() public void Update()
{ {
if (Util.isValid(parent) && Util.isValid(target) && Util.isValid(parent.vessel) && parent.vessel.parts.Contains(target)) if (Util.isValid(parent) && Util.isValid(target) && Util.isValid(parent.vessel) && parent.vessel.parts.Contains(target))
{ {
Vector3 start = parentTransform.position; Vector3 start = parentTransform.position;
Vector3 end = target.transform.TransformPoint(targetOffset); Vector3 end = target.transform.TransformPoint(targetOffset);
DrawLine(start, end); DrawLine(start, end);
} }
else else
{ {
DrawLine(Vector3.zero, Vector3.zero); DrawLine(Vector3.zero, Vector3.zero);
Destroy(); Destroy();
} }
} }
   
public void Destroy() public void Destroy()
{ {
DrawLine(Vector3.zero, Vector3.zero); DrawLine(Vector3.zero, Vector3.zero);
if (Util.isValid(joint)) if (Util.isValid(joint))
GameObject.DestroyImmediate(joint); GameObject.DestroyImmediate(joint);
   
if (Util.isValid(lr)) if (Util.isValid(lr))
GameObject.DestroyImmediate(lr); GameObject.DestroyImmediate(lr);
   
if (Util.isValid(LineObj)) if (Util.isValid(LineObj))
GameObject.DestroyImmediate(LineObj); GameObject.DestroyImmediate(LineObj);
   
joint = null; joint = null;
LineObj = null; LineObj = null;
lr = null; lr = null;
   
parentTransform = null; parentTransform = null;
parent = null; parent = null;
target = null; target = null;
targetOffset = Vector3.zero; targetOffset = Vector3.zero;
isDestroyed = true; isDestroyed = true;
} }
} }
} }
file:a/Util.cs -> file:b/Util.cs
// QuantumStrutsContinued © 2014 toadicus // QuantumStrutsContinued © 2014 toadicus
// //
// This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. To view a // This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. To view a
// copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/ // copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/
// //
// Continued from QuantumStrut, © 2013 BoJaN. Used with permission. // Continued from QuantumStrut, © 2013 BoJaN. Used with permission.
   
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
//using System.Threading.Tasks;  
using KSP.IO; using KSP.IO;
using UnityEngine; using UnityEngine;
   
namespace QuantumStrut namespace QuantumStrut
{ {
public static class Util public static class Util
{ {
static System.Random r = new System.Random(); static System.Random r = new System.Random();
   
public static float Random(float min, float max) public static float Random(float min, float max)
{ {
return (float)((r.NextDouble() * (max - min)) + min); return (float)((r.NextDouble() * (max - min)) + min);
} }
   
public static float Random() public static float Random()
{ {
return (float)r.NextDouble(); return (float)r.NextDouble();
} }
   
public static Part getTank(Part parent) public static Part getTank(Part parent)
{ {
if (parent.Resources.Count != 0) if (parent.Resources.Count != 0)
return parent; return parent;
   
if (isValid(parent.parent) && parent.fuelCrossFeed) if (isValid(parent.parent) && parent.fuelCrossFeed)
return getTank(parent.parent); return getTank(parent.parent);
   
return null; return null;
} }
   
public static Vessel Kerbal public static Vessel Kerbal
{ {
get get
{ {
if (isValid(FlightGlobals.fetch.activeVessel) && FlightGlobals.fetch.activeVessel.isEVA) if (isValid(FlightGlobals.fetch.activeVessel) && FlightGlobals.fetch.activeVessel.isEVA)
return FlightGlobals.fetch.activeVessel; return FlightGlobals.fetch.activeVessel;
return null; return null;
} }
} }
   
public static bool isValid(UnityEngine.Object obj) public static bool isValid(UnityEngine.Object obj)
{ {
return (obj && obj != null); return (obj && obj != null);
} }
   
public static void printObj(object obj) public static void printObj(object obj)
{ {
using (KSP.IO.TextWriter writer = TextWriter.CreateForType<string>("obj.cs")) using (KSP.IO.TextWriter writer = TextWriter.CreateForType<string>("obj.cs"))
{ {
string str = printProperties(obj, TypeDescriptor.GetProperties(obj), 0); string str = printProperties(obj, TypeDescriptor.GetProperties(obj), 0);
writer.Write(str); writer.Write(str);
MonoBehaviour.print(str); MonoBehaviour.print(str);
} }
} }
   
static string printProperties(object obj, PropertyDescriptorCollection collection, int I) static string printProperties(object obj, PropertyDescriptorCollection collection, int I)
{ {
if (I > 2) return ""; if (I > 2)
  return "";
   
string prefix = ""; string prefix = "";
string str = ""; string str = "";
for (int T = 0; T < I; T++) for (int T = 0; T < I; T++)
{ {
prefix += " "; prefix += " ";
} }
   
foreach (PropertyDescriptor d in collection) foreach (PropertyDescriptor d in collection)
{ {
str += "\n" + prefix + d.Name + " = " + d.GetValue(obj); str += "\n" + prefix + d.Name + " = " + d.GetValue(obj);
} }
return str; return str;
} }
   
public static Part partFromGameObject(GameObject ob) public static Part partFromGameObject(GameObject ob)
{ {
GameObject o = ob; GameObject o = ob;
   
while (o) while (o)
{ {
Part p = Part.FromGO(o); Part p = Part.FromGO(o);
if (p && p != null) if (p && p != null)
{ {
return p; return p;
} }
   
if (o.transform.parent) if (o.transform.parent)
o = o.transform.parent.gameObject; o = o.transform.parent.gameObject;
else else
return null; return null;
} }
return null; return null;
} }
   
public static Part partFromRaycast(RaycastHit hit) public static Part partFromRaycast(RaycastHit hit)
{ {
return partFromGameObject(hit.collider.gameObject); return partFromGameObject(hit.collider.gameObject);
} }
   
public static Part partFromId(Vessel vessel, long id) public static Part partFromId(Vessel vessel, long id)
{ {
Console.WriteLine("Vessel Parts: " + vessel.Parts.Count); Console.WriteLine("Vessel Parts: " + vessel.Parts.Count);
foreach (Part p in vessel.Parts) foreach (Part p in vessel.Parts)
{ {
MonoBehaviour.print(p.uid + " ?= " + id + ": " + (p.uid == id)); MonoBehaviour.print(p.uid + " ?= " + id + ": " + (p.uid == id));
if (p.uid == id) if (p.uid == id)
return p; return p;
} }
return null; return null;
} }
   
public static float GetEnergy(Vessel vessel) public static float GetEnergy(Vessel vessel)
{ {
double energy = 0; double energy = 0;
foreach (Part p in vessel.parts) foreach (Part p in vessel.parts)
{ {
foreach (PartResource r in p.Resources) foreach (PartResource r in p.Resources)
{ {
if (r.resourceName == "ElectricCharge") if (r.resourceName == "ElectricCharge")
energy += r.amount; energy += r.amount;
} }
} }
return (float)energy; return (float)energy;
} }
} }
} }