forked from 1wsx10/VectorThrust2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
VectorThrust.cs
1648 lines (1304 loc) · 53.3 KB
/
VectorThrust.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ALWAYS CHECK FOR UPDATES
// to update, simply load it from the workshop tab again (no need to actually go to the workshop page)
// weather or not dampeners are on when you start the script
public bool dampeners = true;
// weather or not thrusters are on when you start the script
public bool jetpack = false;
// weather or not cruise mode is on when you start the script
public bool cruise = false;
// make cruise mode act more like an airplane
public bool cruisePlane = false;
// this is used to identify blocks as belonging to this programmable block.
// pass the '%applyTags' argument, and the program will spread its tag across all blocks it controls.
// the program then won't touch any blocks that don't have the tag. unless you pass the '%removeTags' argument.
// if you add or remove a tag manually, pass the '%reset' argument to force a re-check
// if you make this tag unique to this ship, it won't interfere with your other vector thrust ships
public const string myName = "VT";
// normal: |VT|
public const string activeSurround = "|";
// standby: .VT.
public const string standbySurround = ".";
// put this in custom data of a cockpit to instruct the script to use a display in that cockpit
// it has to be on a line of its own, and have an integer after the ':'
// the integer must be 0 <= integer <= total # of displays in the cockpit
// eg:
// %Vector:0
// this would make the script use the 1st display. the 1st display is #0, 2nd #1 etc..
// if you have trouble, look in the bottom right of the PB terminal, it will print errors there
public const string textSurfaceKeyword = "%Vector:";
// standby stops all calculations and safely turns off all nacelles, good if you want to stop flying
// but dont want to turn the craft off.
public const bool startInStandby = true;
// change this is you don't want the script to start in standby... please only use this if you have permission from the server owner
// set to -1 for the fastest speed in the game (changes with mods)
public float maxRotorRPM = 60f;
public const float defaultAccel = 1f;//this is the default target acceleration you see on the display
// if you want to change the default, change this
// note, values higher than 1 will mean your nacelles will face the ground when you want to go
// down rather than just lower thrust
// '1g' is acceleration caused by current gravity (not nessicarily 9.81m/s) although
// if current gravity is less than 0.1m/s it will ignore this setting and be 9.81m/s anyway
public const float accelBase = 1.5f;//accel = defaultAccel * g * base^exponent
// your +, - and 0 keys increment, decrement and reset the exponent respectively
// this means increasing the base will increase the amount your + and - change target acceleration
// multiplier for dampeners, higher is stronger dampeners
public const float dampenersModifier = 0.1f;
// default acceleration in situations with 0 (or low) gravity
public const float zeroGAcceleration = 9.81f;
// if gravity becomes less than this, zeroGAcceleration will kick in
public const float gravCutoff = 0.1f * zeroGAcceleration;
// determines when the thrusters will cut out in space.
public const float lowThrustCutOff = 0.1f;
// determines when the thrusters will turn back on. this should always be greater than cutoff
public const float lowThrustCutOn = 1.0f;
// true: only main cockpit can be used even if there is no one in the main cockpit
// false: any cockpits can be used, but if there is someone in the main cockpit, it will only obey the main cockpit
// no main cockpit: any cockpits can be used
public const bool onlyMainCockpit = true;
// Choose wether you want the script to update once every frame or once every 10 frames
// should be 1 of:
// UpdateFrequency.Update1
// UpdateFrequency.Update10
public const UpdateFrequency update_frequency = UpdateFrequency.Update1;
public const string LCDName = "%VectorLCD";
// arguments, you can change these to change what text you run the programmable block with
public const string standbytogArg = "%standby";
public const string standbyonArg = "%standbyenter";
public const string standbyoffArg = "%standbyexit";
public const string dampenersArg = "%dampeners";
public const string cruiseArg = "%cruise";
public const string jetpackArg = "%jetpack";
public const string raiseAccelArg = "%raiseAccel";
public const string lowerAccelArg = "%lowerAccel";
public const string resetAccelArg = "%resetAccel";
public const string resetArg = "%reset";//this one re-runs the initial setup... you probably want to use %resetAccel
public const string applyTagsArg = "%applyTags";
public const string removeTagsArg = "%removeTags";
public string[] allArgs = {
standbytogArg,
standbyonArg,
standbyoffArg,
dampenersArg,
cruiseArg,
jetpackArg,
raiseAccelArg,
lowerAccelArg,
resetAccelArg,
resetArg,
applyTagsArg,
removeTagsArg
};
// control module gamepad bindings
// type "/cm showinputs" into chat
// press the desired button
// put that text EXACTLY as it is in the quotes for the control you want
public const string jetpackButton = "c.thrusts";
public const string dampenersButton = "c.damping";
public const string cruiseButton = "c.cubesizemode";
public const string lowerAccel = "c.switchleft";
public const string raiseAccel = "c.switchright";
public const string resetAccel = "pipe";
// boost settings (this only works with control module)
// you can use this to set target acceleration values that you can quickly jump to by holding down the specified button
// there are defaults here:
// c.sprint (shift) 3g
// ctrl 0.3g
public const bool useBoosts = true;
public KeyValuePair<string,float>[] boosts = {
new KeyValuePair<string,float>("c.sprint", 3f),
new KeyValuePair<string,float>("ctrl", 0.3f)
};
// DEPRECATED: use the tags instead
// only use blocks that have 'show in terminal' set to true
public bool ignoreHiddenBlocks = false;
// this can't be const, because it causes unreachable code warning, which now can't be disabled
// V 180 degrees
// V 0 degrees V 360 degrees
// |-----\ /------
// desired power|----------------------------------------- value of 0.1
// | \ /
// | \ /
// | \ /
// no power |-----------------------------------------
//
//
// |-----\ /------stuff above desired power gets set to desired power
// | \ /
// | \ /
// desired power|----------------------------------------- value of 0.8
// | \ /
// no power |-----------------------------------------
// the above pictures are for 'thrustModifierAbove', the same principle applies for 'thrustModifierBelow', except it goes below the 0 line, instead of above the max power line.
// the clipping value 'thrustModifier' defines how far the thruster can be away from the desired direction of thrust, and have the power still at desired power, otherwise it will be less
// these values can only be between 0 and 1
// another way to look at it is:
// set above to 1, its at 100% of desired power far from the direction of thrust
// set below to 1, its at 000% of desired power far from the opposite direction of thrust
// set above to 0, its at 100% of desired power only when it is exactly in the direction of thrust
// set below to 0, its at 000% of desired power only when it is exactly in the opposite direction of thrust
public const double thrustModifierAboveSpace = 0.01;
public const double thrustModifierBelowSpace = 0.9;
public const double thrustModifierAboveGrav = 0.1;
public const double thrustModifierBelowGrav = 0.1;
// use control module... this can always be true
public bool controlModule = true;
public Program() {
Echo("Just Compiled");
programCounter = 0;
gotNacellesCount = 0;
updateNacellesCount = 0;
Runtime.UpdateFrequency = UpdateFrequency.Once;
this.greedy = !hasTag(Me);
if(Me.CustomData.Equals("")) {
Me.CustomData = textSurfaceKeyword + 0;
}
}
public void Save() {}
//at 60 fps this will last for 9000+ hrs before going negative
public long programCounter;
public long gotNacellesCount;
public long updateNacellesCount;
string lastArg = "";
// THE Issue: Any thruster(s) on a rotor when thrusting apply a torque that turns the thruster to face the center of gravity of the ship.
// The more thrust, the stronger this force, and it can exceed the maximum torque that can be set on the rotor, at which point the nacelle
// can no longer be controlled at all (before that, the nacelle might already see some adverse affects, turning slower/faster than intended).
// The further away a thruster is from the center of mass (ignoring the axis of rotation of the rotor), the stronger the effect.
// That is why building aligned with the center of mass helps, but since cargo affects the center of mass, this doesn't work well for cargo haulers.
public void Main(string argument, UpdateType runType) {
if(argument.Length != 0) {
lastArg = argument;
}
// Only accept arguments on certain update types
UpdateType valid_argument_updates = UpdateType.None;
valid_argument_updates |= UpdateType.Terminal;
valid_argument_updates |= UpdateType.Trigger;
valid_argument_updates |= UpdateType.Script;
if((runType & valid_argument_updates) == UpdateType.None) {
argument = "";
}
if(!doStartup(argument, runType)) {
return;
}
MatrixD shipWorldMatrix = mainController != null ? mainController.WorldMatrix : usableControllers[0].WorldMatrix;
MatrixD worldShipMatrix = MatrixD.Invert(shipWorldMatrix);
// Get a vector indicating where we want to go, in world space.
// For each key held a vector length 1 is added in the respective direction, analog controllers are analog and might have a bigger value.
Vector3D desiredVec = getMovementInput(argument);
Vector3D shipVel;
float shipPhysicalMass;
float worldGravAccMag;
Vector3D requiredThrustVec;
doPhysics(desiredVec, out shipVel, out shipPhysicalMass, out worldGravAccMag, out requiredThrustVec);
// ========== DISTRIBUTE THE FORCE EVENLY BETWEEN NACELLES ==========
// hysteresis
if(requiredThrustVec.Length() > lowThrustCutOn * gravCutoff * shipPhysicalMass) {//TODO: this causes problems if there are many small nacelles
thrustOn = true;
}
if(requiredThrustVec.Length() < lowThrustCutOff * gravCutoff * shipPhysicalMass) {
thrustOn = false;
}
//Echo($"thrustOn: {thrustOn} \n{Math.Round(requiredThrustVec.Length()/(gravCutoff*shipPhysicalMass), 2)}\n{Math.Round(requiredThrustVec.Length()/(gravCutoff*shipPhysicalMass*0.01), 2)}");
// maybe lerp this in the future
if(!thrustOn) {// Zero G
//Echo("\nnot much thrust");
Vector3D zero_G_accel = (shipWorldMatrix.Down + shipWorldMatrix.Backward) * zeroGAcceleration / 1.414f;
if(dampeners) {
requiredThrustVec = zero_G_accel * shipPhysicalMass + requiredThrustVec;
} else {
requiredThrustVec = (requiredThrustVec - shipVel) + zero_G_accel;
}
}
// update thrusters on/off and re-check nacelles direction
// When we switch to/from fake zero-G grav I guess, which is usually near where atmospheric thrusters stop working?
bool gravChanged = Math.Abs(lastGrav - worldGravAccMag) > 0.05f;
lastGrav = worldGravAccMag;
bool reGroupNacelles = false;
foreach(Nacelle n in nacelles) {
// we want to update if the thrusters are not valid, or atmosphere has changed
if(!n.validateThrusters(jetpack) || gravChanged) {
n.detectThrustDirection();
reGroupNacelles = true;
}
// These are set by doPhysics
n.thrustModifierAbove = thrustModifierAbove;
n.thrustModifierBelow = thrustModifierBelow;
// This needs to be done all the time, because atmospheric thrusters vary with atmosphere density, which changes with height.
n.calcMaxEffectiveThrust();
}
// We expect any rotor to be aligned with one of the ships primary axes.
// Otherwise solving becomes far harder (and it's hard enough already!).
// So stick rotors on rotors or hinges, and you get what you deserve.
// We might want to do this more often if we want to support nacelles with mixed thruster types in different directions.
if(reGroupNacelles || (nacelleGroups.Count == 0 && nacelles.Count != 0)) {
// Create/reset the groups
foreach (Base6Directions.Axis axis in Enum.GetValues(typeof(Base6Directions.Axis))) {
nacelleGroups[axis] = new List<Nacelle>();
}
// Group nacelles among the 3 primary axes.
foreach(Nacelle nacelle in nacelles) {
Vector3D rotorUpInShipSpace = Vector3D.TransformNormal(nacelle.rotor.WorldMatrix.Up, worldShipMatrix);
Base6Directions.Axis axis = Base6Directions.GetAxis(Base6Directions.GetDirection(rotorUpInShipSpace));
nacelleGroups[axis].Add(nacelle);
}
}
// The main solver, note that 'regular' thrusters are controlled by the game itself,
// and their thrust has already been subtracted from the required thrust vector.
// So first the game tries to achieve wanted dampening + acceleration with the regular thrusters.
// And then we do the same, but on top of the solution the game has already set.
// Note that the game does not seem to dampen against thrusters set to a value,
// which is good since it won't fight us, but it also won't compensate any mistakes we make.
// Also note that if the game misses (counter) thrust in one direction, it will not throttle down other
// directions to prevent drifting that way. This is also good, since we can then provide the needed counter thrust.
// Get the group sizes for scaling, because of phantom torque we want force spread evenly over each nacelle(rotor).
float forwardBackwardSize = nacelleGroups[Base6Directions.Axis.ForwardBackward].Count;
float leftRightSize = nacelleGroups[Base6Directions.Axis.LeftRight].Count;
float upDownSize = nacelleGroups[Base6Directions.Axis.UpDown].Count;
// The ? : here are to prevent division by zero if two groups are empty.
float xScaleUp = upDownSize == 0 ? 0 : upDownSize / (upDownSize + forwardBackwardSize);
float yScaleRight = leftRightSize == 0 ? 0 : leftRightSize / (leftRightSize + forwardBackwardSize);
float zScaleRight = leftRightSize == 0 ? 0 : leftRightSize / (leftRightSize + upDownSize);
Vector3D reqThrustShipSpace = Vector3D.TransformNormal(requiredThrustVec, worldShipMatrix);
// Apply first nacelle settings to rest in each group, split between the nacelles in the group based on available thrust.
foreach(Base6Directions.Axis axis in nacelleGroups.Keys) {
// write($"-- Group: {axis}");
List<Nacelle> group = nacelleGroups[axis];
if(group.Count == 0) {
continue;
}
Vector3D groupThrustVec;
if(axis == Base6Directions.Axis.ForwardBackward) {
groupThrustVec = new Vector3D(reqThrustShipSpace.X * (1.0 - xScaleUp), reqThrustShipSpace.Y * (1.0 - yScaleRight), 0);
} else if( axis == Base6Directions.Axis.LeftRight) {
groupThrustVec = new Vector3D(0, reqThrustShipSpace.Y * yScaleRight, reqThrustShipSpace.Z * zScaleRight);
} else {
groupThrustVec = new Vector3D(reqThrustShipSpace.X * xScaleUp, 0, reqThrustShipSpace.Z * (1.0 - zScaleRight));
}
Vector3D reqFull = Vector3D.TransformNormal(groupThrustVec, shipWorldMatrix);
float groupMaxEffectiveThrust = group.Sum(n => n.maxEffectiveThrust);
foreach(Nacelle n in group) {
n.requiredThrustVec = (n.maxEffectiveThrust / groupMaxEffectiveThrust) * reqFull;
n.go(jetpack);
// n.diag();
}
}
write($"Last cmd: {lastArg}");
write($"Target Accel: {getAccelerationMul():N2}g");
write($"Thrusters: {jetpack}");
write($"Dampeners: {dampeners}");
write($"Cruise: {cruise}");
write($"Active Nacelles: {nacelles.Count}");//TODO: make activeNacelles account for the number of nacelles that are actually active (activeThrusters.Count > 0)
// write("Got Nacelles: " + gotNacellesCount);
// write("Update Nacelles: " + updateNacellesCount);
// ========== END OF MAIN ==========
// echo the errors with surface provider
Echo(surfaceProviderErrorStr);
}
string surfaceProviderErrorStr = "";
int accelExponent = 0;
bool jetpackIsPressed = false;
bool dampenersIsPressed = false;
bool cruiseIsPressed = false;
bool plusIsPressed = false;
bool minusIsPressed = false;
bool globalAppend = false;
IMyShipController mainController = null;
List<IMyShipController> allControllers = new List<IMyShipController>();
List<IMyShipController> usableControllers = new List<IMyShipController>();
List<Nacelle> nacelles = new List<Nacelle>();
Dictionary<Base6Directions.Axis, List<Nacelle>> nacelleGroups = new Dictionary<Base6Directions.Axis, List<Nacelle>>();
List<IMyThrust> normalThrusters = new List<IMyThrust>();
List<IMyTextPanel> allScreens = new List<IMyTextPanel>();
List<IMyTextPanel> usableScreens = new List<IMyTextPanel>();
HashSet<IMyTextSurface> surfaces = new HashSet<IMyTextSurface>();
float oldMass = 0;
int rotorCount = 0;
int rotorTopCount = 0;
int thrusterCount = 0;
bool standby = startInStandby;
double thrustModifierAbove = 0.1;// how close the rotor has to be to target position before the thruster gets to full power
double thrustModifierBelow = 0.1;// how close the rotor has to be to opposite of target position before the thruster gets to 0 power
bool justCompiled = true;
bool goToStandby = false;
bool comeFromStandby = false;
const string tag = activeSurround + myName + activeSurround;
const string offtag = standbySurround + myName + standbySurround;
bool applyTags = false;
bool removeTags = false;
bool greedy = true;
float lastGrav = -1;
public bool thrustOn = false;
Dictionary<string, object> CMinputs = null;
bool doStartup(string argument, UpdateType runType) {
globalAppend = false;
programCounter++;
Echo($"Last Runtime {Runtime.LastRunTimeMs:N2}ms #{programCounter}");
write($"{"|\\-/"[(int)programCounter/10%4]} {Runtime.LastRunTimeMs:N0}ms");
Echo($"Greedy: {greedy}");
bool anyArg = Array.Exists(allArgs, arg => isArg(argument, arg));
if(isArg(argument, standbyonArg) ||
(isArg(argument, standbytogArg) && !standby) ||
goToStandby) {
enterStandby();
return false;
} else if(isArg(argument, standbyoffArg) ||
((anyArg || runType == UpdateType.Terminal) && standby) ||
comeFromStandby) {
exitStandby();
} else {
Echo("Normal Running");
}
if(justCompiled || allControllers.Count == 0 || isArg(argument, resetArg)) {
Echo("Initialising..");
getNacelles(true);
List<IMyShipController> conts = new List<IMyShipController>();
GridTerminalSystem.GetBlocksOfType<IMyShipController>(conts);
if(!getControllers(conts)) {
Echo("Init failed.");
return false;
}
Echo("Init success.");
}
//tags and getting blocks
applyTags = isArg(argument, applyTagsArg);
removeTags = !applyTags && isArg(argument, removeTagsArg);
// switch on: removeTags
// switch off: applyTags
greedy = (!applyTags && greedy) || removeTags;
if(applyTags) {
addTag(Me);
} else if(removeTags) {
removeTag(Me);
}
// this automatically calls getNacelles() as needed, and passes in previous GridTerminalSystem data
if(!checkNacelles()) {
Echo("Setup failed, stopping.");
return false;
}
applyTags = false;
removeTags = false;
if(justCompiled) {
justCompiled = false;
Runtime.UpdateFrequency = UpdateFrequency.Once;
if(Storage == "" || !startInStandby) {
Storage = "Don't Start Automatically";
// run normally
comeFromStandby = true;
return false;
} else {
// go into standby mode
goToStandby = true;
return false;
}
}
if(standby) {
Echo("Standing By");
write("Standing By");
return false;
}
return true;
}
void doPhysics(Vector3D desiredVec, out Vector3D shipVel, out float shipPhysicalMass, out float worldGravAccMag, out Vector3D requiredThrustVec) {
// Get gravity in world space, gravity is measured as acceleration in m/s^2.
Vector3D worldGravAcc = usableControllers[0].GetNaturalGravity();
// Get velocity, which is measured in m/s, just like you see in the hud.
shipVel = usableControllers[0].GetShipVelocities().LinearVelocity;
// Setup mass
MyShipMass myShipMass = usableControllers[0].CalculateShipMass();
shipPhysicalMass = myShipMass.PhysicalMass;
if(myShipMass.BaseMass < 0.001f) {
Echo("Can't fly a Station");
shipPhysicalMass = 0.001f;
}
// Get the magintude of the gravity vector, use a fake value if we're not in a gravity well.
worldGravAccMag = (float)worldGravAcc.Length();
if(worldGravAccMag < gravCutoff) {
worldGravAccMag = zeroGAcceleration;
thrustModifierAbove = thrustModifierAboveSpace;
thrustModifierBelow = thrustModifierBelowSpace;
} else {
thrustModifierAbove = thrustModifierAboveGrav;
thrustModifierBelow = thrustModifierBelowGrav;
}
Vector3D shipWeightForce = shipPhysicalMass * worldGravAcc;
if(dampeners) {
Vector3D dampVec = Vector3D.Zero;
// I think this prevents dampening in the direction we actually want to go.
if(desiredVec != Vector3D.Zero) {
// Cancel movement opposite to desired movement direction
if(desiredVec.dot(shipVel) < 0) {
// If you want to go opposite to velocity
dampVec += shipVel.project(desiredVec.normalized());
}
// Cancel sideways movement
dampVec += shipVel.reject(desiredVec.normalized());
} else {
dampVec += shipVel;
}
if(cruise) {
foreach(IMyShipController cont in usableControllers) {
if(onlyMain() && cont != mainController) continue;
if(!cont.IsUnderControl) continue;
if(dampVec.dot(cont.WorldMatrix.Forward) > 0 || cruisePlane) { // only front, or front+back if cruisePlane is activated
dampVec -= dampVec.project(cont.WorldMatrix.Forward);
}
if(cruisePlane) {
// Remove the ship forward/backward component of the force our weight excerts, so that we don't compensate it.
// This results in us moving forward with nose down, and backwards with nose up.
shipWeightForce -= shipWeightForce.project(cont.WorldMatrix.Forward);
}
}
}
desiredVec -= dampVec * dampenersModifier;
}
desiredVec *= shipPhysicalMass * worldGravAccMag * getAccelerationMul();
// point thrust in opposite direction, add weight. this is force, not acceleration
requiredThrustVec = -desiredVec + shipWeightForce;
// Remove thrust done by normal thrusters, note that thrust points to Forward, so adding Backward has the same effect as subtracting.
foreach(IMyThrust normalThruster in normalThrusters) {
requiredThrustVec += normalThruster.WorldMatrix.Backward * normalThruster.CurrentThrust;
}
Echo($"Required Force: {requiredThrustVec.Length():N0}N");
}
// Pretty print the given normal after conversion by the given matrix.
public static String formatNormal(ref Vector3D normal, ref MatrixD matrix) {
Vector3D transformed;
Vector3D.TransformNormal(ref normal, ref matrix, out transformed);
return formatVec(ref transformed);
}
// Pretty print the given vector.
public static String formatVec(ref Vector3D vec) {
return $"X:{vec.X,11:N2} Y:{vec.Y,11:N2} Z:{vec.Z,11:N2}";
}
bool isArg(string argument, string toCheck) {
return argument.ToLower().Contains(toCheck.ToLower());
}
void enterStandby() {
standby = true;
goToStandby = false;
//set status of blocks
foreach(Nacelle n in nacelles) {
n.rotor.Enabled = false;
standbyTag(n.rotor);
foreach(Thruster t in n.thrusters) {
t.theBlock.Enabled = false;
standbyTag(t.theBlock);
}
}
foreach(IMyTextPanel screen in usableScreens) {
standbyTag(screen);
}
foreach(IMyShipController cont in usableControllers) {
standbyTag(cont);
}
standbyTag(Me);
Runtime.UpdateFrequency = UpdateFrequency.None;
Echo("Standing By");
write("Standing By");
}
void exitStandby() {
standby = false;
comeFromStandby = false;
//set status of blocks
foreach(Nacelle n in nacelles) {
n.rotor.Enabled = true;
activeTag(n.rotor);
foreach(Thruster t in n.thrusters) {
if(t.IsOn) {
t.theBlock.Enabled = true;
}
activeTag(t.theBlock);
}
}
foreach(IMyTextPanel screen in usableScreens) {
activeTag(screen);
}
foreach(IMyShipController cont in usableControllers) {
activeTag(cont);
}
activeTag(Me);
Runtime.UpdateFrequency = update_frequency;
Echo("Resuming from standby");
}
bool hasTag(IMyTerminalBlock block) {
return block.CustomName.Contains(tag) || block.CustomName.Contains(offtag);
}
void addTag(IMyTerminalBlock block) {
string name = block.CustomName;
if(name.Contains(tag)) {
// there is already a tag, just set it to current status
if(standby) {
block.CustomName = name.Replace(tag, offtag);
}
} else if(name.Contains(offtag)) {
// there is already a tag, just set it to current status
if(!standby) {
block.CustomName = name.Replace(offtag, tag);
}
} else {
// no tag found, add tag to start of string
if(standby) {
block.CustomName = offtag + " " + name;
} else {
block.CustomName = tag + " " + name;
}
}
}
void removeTag(IMyTerminalBlock block) {
block.CustomName = block.CustomName.Replace(tag, "").Trim();
block.CustomName = block.CustomName.Replace(offtag, "").Trim();
}
void standbyTag(IMyTerminalBlock block) {
block.CustomName = block.CustomName.Replace(tag, offtag);
}
void activeTag(IMyTerminalBlock block) {
block.CustomName = block.CustomName.Replace(offtag, tag);
}
// true: only main cockpit can be used even if there is no one in the main cockpit
// false: any cockpits can be used, but if there is someone in the main cockpit, it will only obey the main cockpit
// no main cockpit: any cockpits can be used
bool onlyMain() {
return mainController != null && (mainController.IsUnderControl || onlyMainCockpit);
}
void getScreens() {
getScreens(allScreens);
}
void getScreens(List<IMyTextPanel> newScreens) {
allScreens = newScreens;
usableScreens.Clear();
foreach(IMyTextPanel screen in allScreens) {
if(removeTags) {
removeTag(screen);
}
bool actGreedy = greedy || applyTags || removeTags;
if ( (!actGreedy && !hasTag(screen)) ||
(!screen.IsWorking) ||
(!hasTag(screen) && !screen.CustomName.ToLower().Contains(LCDName.ToLower())) ) {
surfaces.Remove(screen);
continue;
}
if(applyTags) {
addTag(screen);
}
usableScreens.Add(screen);
surfaces.Add(screen);
}
}
public void write(string str) {
if(this.surfaces.Count > 0) {
str += "\n";
foreach(IMyTextSurface surface in this.surfaces) {
surface.WriteText(str, globalAppend);
surface.ContentType = ContentType.TEXT_AND_IMAGE;
}
} else if(!globalAppend) {
Echo("No text surfaces available");
}
globalAppend = true;
}
float getAccelerationMul() {
// Look through boosts, applies acceleration of first one found. If none found or boosts not enabled, go for normal accel
int boostIndex = useBoosts && this.controlModule ? Array.FindIndex(this.boosts, boost => CMinputs.ContainsKey(boost.Key)) : -1;
float accel = boostIndex != -1 ? this.boosts[boostIndex].Value : (float)Math.Pow(accelBase, accelExponent);
return accel * defaultAccel;
}
Vector3D getMovementInput(string arg) {
if(controlModule) {
// setup control module
Dictionary<string, object> inputs = new Dictionary<string, object>();
try {
CMinputs = Me.GetValue<Dictionary<string, object>>("ControlModule.Inputs");
Me.SetValue<string>("ControlModule.AddInput", "all");
Me.SetValue<bool>("ControlModule.RunOnInput", true);
Me.SetValue<int>("ControlModule.InputState", 1);
Me.SetValue<float>("ControlModule.RepeatDelay", 0.016f);
} catch(Exception e) {
controlModule = false;
}
}
if(controlModule) {
// non-movement controls
if(CMinputs.ContainsKey(dampenersButton) && !dampenersIsPressed) {//inertia dampener key
dampeners = !dampeners;//toggle
dampenersIsPressed = true;
}
if(!CMinputs.ContainsKey(dampenersButton)) {
dampenersIsPressed = false;
}
if(CMinputs.ContainsKey(cruiseButton) && !cruiseIsPressed) {//cruise key
cruise = !cruise;//toggle
cruiseIsPressed = true;
}
if(!CMinputs.ContainsKey(cruiseButton)) {
cruiseIsPressed = false;
}
if(CMinputs.ContainsKey(jetpackButton) && !jetpackIsPressed) {//jetpack key
jetpack = !jetpack;//toggle
jetpackIsPressed = true;
}
if(!CMinputs.ContainsKey(jetpackButton)) {
jetpackIsPressed = false;
}
if(CMinputs.ContainsKey(raiseAccel) && !plusIsPressed) {//throttle up
accelExponent++;
plusIsPressed = true;
}
if(!CMinputs.ContainsKey(raiseAccel)) { //increase target acceleration
plusIsPressed = false;
}
if(CMinputs.ContainsKey(lowerAccel) && !minusIsPressed) {//throttle down
accelExponent--;
minusIsPressed = true;
}
if(!CMinputs.ContainsKey(lowerAccel)) { //lower target acceleration
minusIsPressed = false;
}
if(CMinputs.ContainsKey(resetAccel)) { //default target acceleration
accelExponent = 0;
}
}
bool changeDampeners = false;
if(isArg(arg, dampenersArg)) {
dampeners = !dampeners;
changeDampeners = true;
}
if(isArg(arg, cruiseArg)) {
cruise = !cruise;
}
if(isArg(arg, jetpackArg)) {
jetpack = !jetpack;
}
if(isArg(arg, raiseAccelArg)) {
accelExponent++;
}
if(isArg(arg, lowerAccelArg)) {
accelExponent--;
}
if(isArg(arg, resetAccelArg)) {
accelExponent = 0;
}
// dampeners (if there are any normal thrusters, the dampeners control works)
if(normalThrusters.Count != 0) {
if(onlyMain()) {
if(changeDampeners) {
mainController.DampenersOverride = dampeners;
} else {
dampeners = mainController.DampenersOverride;
}
} else {
if(changeDampeners) {
// make all conform
foreach(IMyShipController cont in usableControllers) {
cont.DampenersOverride = dampeners;
}
} else {
// check if any are different to us
bool any_different = false;
foreach(IMyShipController cont in usableControllers) {
if(cont.DampenersOverride != dampeners) {
any_different = true;
dampeners = cont.DampenersOverride;
break;
}
}
if(any_different) {
// update all others to new value too
foreach(IMyShipController cont in usableControllers) {
cont.DampenersOverride = dampeners;
}
}
}
}
}
// Movement controls
Vector3D moveVec;
if(onlyMain()) {
moveVec = mainController.getWorldMoveIndicator();
} else {
moveVec = Vector3D.Zero;
foreach(IMyShipController cont in usableControllers) {
if(cont.IsUnderControl) {
moveVec += cont.getWorldMoveIndicator();
}
}
}
return moveVec;
}
void removeSurface(IMyTextSurface surface) {
if(surfaces.Contains(surface)) {
//need to check this, because otherwise it will reset panels
//we aren't controlling
surfaces.Remove(surface);
surface.ContentType = ContentType.NONE;
surface.WriteText("", false);
}
}
bool removeSurfaceProvider(IMyTerminalBlock block) {
if(!(block is IMyTextSurfaceProvider)) return false;
IMyTextSurfaceProvider provider = (IMyTextSurfaceProvider)block;
for(int i = 0; i < provider.SurfaceCount; i++) {
if(surfaces.Contains(provider.GetSurface(i))) {
removeSurface(provider.GetSurface(i));
}
}
return true;
}
bool addSurfaceProvider(IMyTerminalBlock block) {
if(!(block is IMyTextSurfaceProvider)) return false;
IMyTextSurfaceProvider provider = (IMyTextSurfaceProvider)block;
bool retval = true;
if(block.CustomData.Length == 0) {
return false;
}
bool [] to_add = new bool[provider.SurfaceCount];
for(int i = 0; i < to_add.Length; i++) {
to_add[i] = false;
}
int begin_search = 0;
while(begin_search >= 0) {
string data = block.CustomData;
int start = data.IndexOf(textSurfaceKeyword, begin_search);
if(start < 0) {
// true if it found at least 1
retval = begin_search != 0;
break;
}
int end = data.IndexOf("\n", start);
begin_search = end;
string display = "";
if(end < 0) {
display = data.Substring(start + textSurfaceKeyword.Length);