forked from Biotronic/TweakScale
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScale.cs
675 lines (590 loc) · 24 KB
/
Scale.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
using KSPAPIExtensions;
using System;
using System.Linq;
using TweakScale.Annotations;
using UnityEngine;
namespace TweakScale
{
/// <summary>
/// Converts from Gaius' GoodspeedTweakScale to updated TweakScale.
/// </summary>
public class GoodspeedTweakScale : TweakScale
{
private bool _updated;
protected override void Setup()
{
base.Setup();
if (_updated)
return;
tweakName = (int)tweakScale;
tweakScale = ScaleFactors[tweakName];
_updated = true;
}
}
public class TweakScale : PartModule, IPartCostModifier
{
/// <summary>
/// The selected scale. Different from currentScale only for destination single update, where currentScale is set to match this.
/// </summary>
[KSPField(isPersistant = true, guiActiveEditor = true, guiName = "Scale", guiFormat = "S4", guiUnits = "m")]
[UI_FloatEdit(scene = UI_Scene.Editor, minValue = 0.625f, maxValue = 5, incrementLarge = 1.25f, incrementSmall = 0.125f, incrementSlide = 0.001f)]
// ReSharper disable once InconsistentNaming
public float tweakScale = 1;
/// <summary>
/// Index into scale values array.
/// </summary>
[KSPField(isPersistant = false, guiActiveEditor = true, guiName = "Scale")]
[UI_ChooseOption(scene = UI_Scene.Editor)]
// ReSharper disable once InconsistentNaming
public int tweakName = 0;
/// <summary>
/// The scale to which the part currently is scaled.
/// </summary>
[KSPField(isPersistant = true)]
// ReSharper disable once InconsistentNaming
public float currentScale = -1;
/// <summary>
/// The default scale, i.e. the number by which to divide tweakScale and currentScale to get the relative size difference from when the part is used without TweakScale.
/// </summary>
[KSPField(isPersistant = true)]
// ReSharper disable once InconsistentNaming
public float defaultScale = -1;
/// <summary>
/// Whether the part should be freely scalable or limited to destination list of allowed values.
/// </summary>
[KSPField(isPersistant = true)]
// ReSharper disable once InconsistentNaming
public bool isFreeScale = false;
/// <summary>
/// The version of TweakScale last used to change this part. Intended for use in the case of non-backward-compatible changes.
/// </summary>
[KSPField(isPersistant = true)]
// ReSharper disable once InconsistentNaming
public string version;
/// <summary>
/// The scale exponentValue array. If isFreeScale is false, the part may only be one of these scales.
/// </summary>
protected float[] ScaleFactors = { 0.625f, 1.25f, 2.5f, 3.75f, 5f };
/// <summary>
/// The node scale array. If node scales are defined the nodes will be resized to these values.
///</summary>
protected int[] ScaleNodes = { };
/// <summary>
/// The unmodified prefab part. From this, default values are found.
/// </summary>
private Part _prefabPart;
/// <summary>
/// Like currentScale above, this is the current scale vector. If TweakScale supports non-uniform scaling in the future (e.g. changing only the length of destination booster), savedScale may represent such destination scaling, while currentScale won't.
/// </summary>
private Vector3 _savedScale;
/// <summary>
/// The exponentValue by which the part is scaled by default. When destination part uses MODEL { scale = ... }, this will be different from (1,1,1).
/// </summary>
[KSPField(isPersistant = true)]
// ReSharper disable once InconsistentNaming
public Vector3 defaultTransformScale = new Vector3(0f, 0f, 0f);
//[KSPField(isPersistant = true)]
private bool _firstUpdateWithParent = true;
private bool _setupRun;
private bool _invalidCfg;
/// <summary>
/// Updaters for different PartModules.
/// </summary>
private IRescalable[] _updaters = new IRescalable[0];
private enum Tristate
{
True,
False,
Unset
}
/// <summary>
/// Whether this instance of TweakScale is the first. If not, log an error and make sure the TweakScale modules don't harmfully interact.
/// </summary>
private Tristate _duplicate = Tristate.Unset;
/// <summary>
/// The ScaleType for this part.
/// </summary>
public ScaleType ScaleType { get; private set; }
/// <summary>
/// Cost of unscaled, empty part.
/// </summary>
[KSPField(isPersistant = true)]
public float DryCost;
private Hotkeyable _chainingEnabled;
private Hotkeyable _autoscaleEnabled;
/// <summary>
/// The ConfigNode that belongs to the part this modules affects.
/// </summary>
private ConfigNode PartNode
{
get
{
return GameDatabase.Instance.GetConfigs("PART").Single(c => c.name.Replace('_', '.') == part.partInfo.name)
.config;
}
}
/// <summary>
/// The ConfigNode that belongs to this module.
/// </summary>
public ConfigNode ModuleNode
{
get
{
return PartNode.GetNodes("MODULE").FirstOrDefault(n => n.GetValue("name") == moduleName);
}
}
/// <summary>
/// The current scaling factor.
/// </summary>
public ScalingFactor ScalingFactor
{
get
{
return new ScalingFactor(tweakScale / defaultScale, tweakScale / currentScale, isFreeScale ? -1 : tweakName);
}
}
/// <summary>
/// The smallest scale the part can be.
/// </summary>
private float MinSize
{
get
{
if (!isFreeScale)
return ScaleFactors.Min();
var range = (UI_FloatEdit)Fields["tweakScale"].uiControlEditor;
return range.minValue;
}
}
/// <summary>
/// The largest scale the part can be.
/// </summary>
internal float MaxSize
{
get
{
if (!isFreeScale)
return ScaleFactors.Max();
var range = (UI_FloatEdit)Fields["tweakScale"].uiControlEditor;
return range.maxValue;
}
}
/// <summary>
/// Loads settings from <paramref name="scaleType"/>.
/// </summary>
/// <param name="scaleType">The settings to use.</param>
private void SetupFromConfig(ScaleType scaleType)
{
isFreeScale = scaleType.IsFreeScale;
defaultScale = scaleType.DefaultScale;
Fields["tweakScale"].guiActiveEditor = false;
Fields["tweakName"].guiActiveEditor = false;
if (isFreeScale)
{
Fields["tweakScale"].guiActiveEditor = true;
var range = (UI_FloatEdit)Fields["tweakScale"].uiControlEditor;
range.minValue = scaleType.MinValue;
range.maxValue = scaleType.MaxValue;
range.incrementLarge = (float)Math.Round(range.maxValue / 8, 3);
range.incrementSmall = (float)Math.Round(range.incrementLarge / 2, 3);
range.incrementSlide = (float)Math.Round(range.incrementSmall / 25, 3);
Fields["tweakScale"].guiUnits = scaleType.Suffix;
}
else
{
Fields["tweakName"].guiActiveEditor = scaleType.ScaleFactors.Length > 1;
var options = (UI_ChooseOption)Fields["tweakName"].uiControlEditor;
if (ScaleFactors.Length <= 0)
return;
ScaleFactors = scaleType.ScaleFactors;
ScaleNodes = scaleType.ScaleNodes;
options.options = scaleType.ScaleNames;
}
}
/// <summary>
/// Sets up values from ScaleType, creates updaters, and sets up initial values.
/// </summary>
protected virtual void Setup()
{
if (part.partInfo == null)
{
return;
}
if (_setupRun)
{
return;
}
_prefabPart = PartLoader.getPartInfoByName(part.partInfo.name).partPrefab;
_updaters = TweakScaleUpdater.CreateUpdaters(part).ToArray();
SetupFromConfig(ScaleType = new ScaleType(ModuleNode));
var doUpdate = currentScale < 0f;
if (doUpdate)
{
tweakScale = currentScale = defaultScale;
DryCost = (float)(part.partInfo.cost - _prefabPart.Resources.Cast<PartResource>().Aggregate(0.0, (a, b) => a + b.maxAmount * b.info.unitCost));
if (DryCost < 0)
{
DryCost = 0;
}
}
if (!isFreeScale && ScaleFactors.Length != 0)
{
tweakName = Tools.ClosestIndex(tweakScale, ScaleFactors);
tweakScale = ScaleFactors[tweakName];
}
if (!doUpdate)
{
UpdateByWidth(false, true);
foreach (var updater in _updaters)
{
updater.OnRescale(ScalingFactor);
}
}
_setupRun = true;
}
public override void OnStart(StartState state)
{
base.OnStart(state);
if (part.parent != null)
{
_firstUpdateWithParent = false;
}
Setup();
if (HighLogic.LoadedSceneIsEditor)
{
_autoscaleEnabled = HotkeyManager.Instance.AddHotkey("Autoscale", new[] {KeyCode.LeftShift},
new[] {KeyCode.LeftControl, KeyCode.L}, true);
_chainingEnabled = HotkeyManager.Instance.AddHotkey("Scale chaining", new[] {KeyCode.LeftShift},
new[] {KeyCode.LeftControl, KeyCode.K}, true);
}
}
public override void OnLoad(ConfigNode node)
{
base.OnLoad(node);
Setup();
}
public override void OnSave(ConfigNode node)
{
version = GetType().Assembly.GetName().Version.ToString();
base.OnSave(node);
}
/// <summary>
/// Moves <paramref name="node"/> to reflect the new scale. If <paramref name="movePart"/> is true, also moves attached parts.
/// </summary>
/// <param name="node">The node to move.</param>
/// <param name="baseNode">The same node, as found on the prefab part.</param>
/// <param name="movePart">Whether or not to move attached parts.</param>
/// <param name="absolute">Whether to use absolute or relative scaling.</param>
private void MoveNode(AttachNode node, AttachNode baseNode, bool movePart, bool absolute)
{
if (baseNode == null)
{
baseNode = node;
absolute = false;
}
var oldPosition = node.position;
if (absolute)
node.position = baseNode.position * ScalingFactor.absolute.linear;
else
node.position = node.position * ScalingFactor.relative.linear;
var deltaPos = node.position - oldPosition;
if (movePart && node.attachedPart != null)
{
if (node.attachedPart == part.parent)
{
part.transform.Translate(-deltaPos, part.transform);
}
else
{
var offset = node.attachedPart.attPos*(ScalingFactor.relative.linear - 1);
node.attachedPart.transform.Translate(deltaPos + offset, part.transform);
node.attachedPart.attPos *= ScalingFactor.relative.linear;
}
}
RescaleNode(node, baseNode);
}
/// <summary>
/// Change the size of <paramref name="node"/> to reflect the new size of the part it's attached to.
/// </summary>
/// <param name="node">The node to resize.</param>
/// <param name="baseNode">The same node, as found on the prefab part.</param>
private void RescaleNode(AttachNode node, AttachNode baseNode)
{
if (isFreeScale)
{
float tmpBaseNodeSize = baseNode.size;
if (tmpBaseNodeSize == 0)
{
tmpBaseNodeSize = 0.5f;
}
node.size = (int)(tmpBaseNodeSize * tweakScale / defaultScale +0.49);
}
else
{
if (ScaleNodes.Length > 0)
{
node.size = baseNode.size + (1 * ScaleNodes[tweakName]);
}
else
{
node.size = (int)(baseNode.size + (Tools.ClosestIndex(tweakScale, ScaleType.AllScaleFactors) - Tools.ClosestIndex(defaultScale, ScaleType.AllScaleFactors)) / (float)ScaleType.AllScaleFactors.Length * 5);
}
}
if (node.size < 0)
{
node.size = 0;
}
}
/// <summary>
/// Updates properties that change linearly with scale.
/// </summary>
/// <param name="moveParts">Whether or not to move attached parts.</param>
/// <param name="absolute">Whether to use absolute or relative scaling.</param>
private void UpdateByWidth(bool moveParts, bool absolute)
{
if (defaultTransformScale.x == 0.0f)
{
defaultTransformScale = part.transform.GetChild(0).localScale;
}
_savedScale = part.transform.GetChild(0).localScale = ScalingFactor.absolute.linear * defaultTransformScale;
part.transform.GetChild(0).hasChanged = true;
part.transform.hasChanged = true;
foreach (var node in part.attachNodes)
{
var nodesWithSameId = part.attachNodes
.Where(a => a.id == node.id)
.ToArray();
var idIdx = Array.FindIndex(nodesWithSameId, a => a == node);
var baseNodesWithSameId = _prefabPart.attachNodes
.Where(a => a.id == node.id)
.ToArray();
if (idIdx < baseNodesWithSameId.Length)
{
var baseNode = baseNodesWithSameId[idIdx];
MoveNode(node, baseNode, moveParts, absolute);
}
else
{
Tools.LogWf("Error scaling part. Node {0} does not have counterpart in base part.", node.id);
}
}
if (part.srfAttachNode != null)
{
MoveNode(part.srfAttachNode, _prefabPart.srfAttachNode, moveParts, absolute);
}
if (moveParts)
{
foreach (var child in part.children)
{
if (child.srfAttachNode == null || child.srfAttachNode.attachedPart != part)
continue;
var attachedPosition = child.transform.localPosition + child.transform.localRotation * child.srfAttachNode.position;
var targetPosition = attachedPosition * ScalingFactor.relative.linear;
child.transform.Translate(targetPosition - attachedPosition, part.transform);
}
}
}
/// <summary>
/// Whether the part holds any resources (fuel, electricity, etc).
/// </summary>
private bool HasResources
{
get
{
return part.Resources.Count > 0;
}
}
/// <summary>
/// Marks the right-click window as dirty (i.e. tells it to update).
/// </summary>
private void UpdateWindow() // redraw the right-click window with the updated stats
{
if (isFreeScale || !HasResources)
return;
foreach (var win in FindObjectsOfType<UIPartActionWindow>().Where(win => win.part == part))
{
// This causes the slider to be non-responsive - i.e. after you click once, you must click again, not drag the slider.
win.displayDirty = true;
}
}
/// <summary>
/// Find the Attachnode that fastens <paramref name="a"/> to <paramref name="b"/> and vice versa.
/// </summary>
/// <param name="a">The source part (often the parent)</param>
/// <param name="b">The target part (often the child)</param>
/// <returns>The AttachNodes between the two parts.</returns>
private static Tuple<AttachNode, AttachNode>? NodesBetween(Part a, Part b)
{
var nodeA = a.findAttachNodeByPart(b);
var nodeB = b.findAttachNodeByPart(a);
if (nodeA == null || nodeB == null)
return null;
return Tuple.Create(nodeA, nodeB);
}
/// <summary>
/// Calculate the correct scale to use for scaling a part relative to another.
/// </summary>
/// <param name="a">Source part, from which we get the desired scale.</param>
/// <param name="b">Target part, which will potentially be scaled.</param>
/// <returns>The difference in scale between the (scaled) attachment nodes connecting <paramref name="a"/> and <paramref name="b"/>, or null if somethinng went wrong.</returns>
private static float? GetRelativeScaling(TweakScale a, TweakScale b)
{
if (a == null || b == null)
return null;
var nodes = NodesBetween(a.part, b.part);
if (!nodes.HasValue)
return null;
var nodeA = nodes.Value.Item1;
var nodeB = nodes.Value.Item2;
var aIdx = a._prefabPart.attachNodes.FindIndex( t => t.id == nodeA.id);
var bIdx = b._prefabPart.attachNodes.FindIndex( t => t.id == nodeB.id);
if (aIdx < 0 || bIdx < 0
|| aIdx >= a._prefabPart.attachNodes.Count
|| aIdx >= a._prefabPart.attachNodes.Count)
return null;
var sizeA = (float)a._prefabPart.attachNodes[aIdx].size;
var sizeB = (float)b._prefabPart.attachNodes[bIdx].size;
if (sizeA == 0)
sizeA = 0.5f;
if (sizeB == 0)
sizeB = 0.5f;
return (sizeA * a.tweakScale/a.defaultScale)/(sizeB * b.tweakScale/b.defaultScale);
}
/// <summary>
/// Automatically scale part to match other part, if applicable.
/// </summary>
/// <param name="a">Source part, from which we get the desired scale.</param>
/// <param name="b">Target part, which will potentially be scaled.</param>
private static void AutoScale(TweakScale a, TweakScale b)
{
if (a == null || b == null)
return;
var factor = GetRelativeScaling(a,b);
if (!factor.HasValue)
return;
b.tweakScale = b.tweakScale * factor.Value;
if (b.ScaleFactors.Length > 0)
{
b.tweakName = Tools.ClosestIndex(b.tweakScale, b.ScaleFactors);
}
b.OnTweakScaleChanged();
}
/// <summary>
/// Scale children with the part.
/// </summary>
private void ChainScale()
{
foreach (var child in part.children)
{
var ts = child.GetComponent<TweakScale>();
// var factor = GetRelativeScaling(this, ts);
// if (!factor.HasValue)
// continue;
// no idea what this condition does
// but it will not work with the changed GetRelativeScaling method
// if (factor.Value*currentScale == ts.tweakScale)
// {
AutoScale(this, ts);
// }
}
}
/// <summary>
/// Scale has changed!
/// </summary>
private void OnTweakScaleChanged()
{
if (!isFreeScale)
{
tweakScale = ScaleFactors[tweakName];
}
if (_chainingEnabled)
{
ChainScale();
}
UpdateByWidth(true, false);
UpdateWindow();
foreach (var updater in _updaters)
{
updater.OnRescale(ScalingFactor);
}
currentScale = tweakScale;
}
/// <summary>
/// Checks if there is more than one TweakScale instance on this part.
/// </summary>
/// <returns>True if duplicates exist, false otherwise.</returns>
private bool CheckForDuplicateTweakScale()
{
if (_duplicate == Tristate.False)
return false;
if (_duplicate == Tristate.True)
return true;
if (this != part.GetComponent<TweakScale>())
{
Tools.LogWf("Duplicate TweakScale module on part [{0}] {1}", part.partInfo.name, part.partInfo.title);
Fields["tweakScale"].guiActiveEditor = false;
Fields["tweakName"].guiActiveEditor = false;
_duplicate = Tristate.True;
return true;
}
_duplicate = Tristate.False;
return false;
}
/// <summary>
/// Checks if the config for this TweakScale instance is valid. If not, logs it and returns false.
/// </summary>
/// <returns>True if the config is invalid, false otherwise.</returns>
private bool CheckForInvalidCfg()
{
if (ScaleFactors.Length != 0)
return false;
if (_invalidCfg)
return true;
_invalidCfg = true;
Tools.LogWf("{0}({1}) has no valid scale factors. This is probably caused by an invalid TweakScale configuration for the part.", part.name, part.partInfo.title);
return true;
}
[UsedImplicitly]
void Update()
{
if (CheckForDuplicateTweakScale() || CheckForInvalidCfg())
{
return;
}
if (_firstUpdateWithParent && part.HasParent())
{
if (_autoscaleEnabled)
{
AutoScale(part.parent.GetComponent<TweakScale>(), this);
}
_firstUpdateWithParent = false;
}
if (HighLogic.LoadedSceneIsEditor && currentScale >= 0f)
{
var changed = currentScale != (isFreeScale ? tweakScale : ScaleFactors[tweakName]);
if (changed) // user has changed the scale tweakable
{
// If the user has changed the scale of the part before attaching it, we want to keep that scale.
_firstUpdateWithParent = false;
OnTweakScaleChanged();
}
else if (part.transform.GetChild(0).localScale != _savedScale) // editor frequently nukes our OnStart resize some time later
{
UpdateByWidth(false, true);
}
}
foreach (var upd in _updaters.OfType<IUpdateable>())
{
upd.OnUpdate();
}
}
public float GetModuleCost(float defaultCost)
{
if (!_setupRun)
{
Setup();
}
return (float)(DryCost - part.partInfo.cost + part.Resources.Cast<PartResource>().Aggregate(0.0, (a, b) => a + b.maxAmount * b.info.unitCost));
}
}
}