-
Notifications
You must be signed in to change notification settings - Fork 13
/
ModelMultiParticlePersistFX.cs
1020 lines (839 loc) · 40 KB
/
ModelMultiParticlePersistFX.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
/*
* Author: Sébastien GAGGINI AKA Sarbian, France
* License: Attribution 4.0 International (CC BY 4.0): http://creativecommons.org/licenses/by/4.0/
*
* Thanks to Nothke for all the feature ideas, testing and feedback
*
*/
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
[EffectDefinition("MODEL_MULTI_PARTICLE_PERSIST")]
public class ModelMultiParticlePersistFX : EffectBehaviour
{
#region Persistent fields
[Persistent]
public string modelName = string.Empty;
[Persistent]
public string transformName = string.Empty;
[Persistent]
public string shaderFileName = string.Empty;
[Persistent]
public string renderMode = "Billboard";
[Persistent]
public bool collide = false;
[Persistent]
public float collideRatio = 0.0f;
[Persistent]
public Vector3 localRotation = Vector3.zero;
[Persistent]
public Vector3 localPosition = Vector3.zero;
[Persistent]
public float fixedScale = 1;
[Persistent]
public float sizeClamp = 50;
// Initial density of the particle seen as sphere of radius size of perfect
// gas. We then assume (only true for ideally expanded exhaust) that the
// expansion is isobaric (by mixing with the atmosphere) in order to compute
// the density afterwards. Units (SI): kg / m^3.
[Persistent]
public double initialDensity = .6;
// Whether to apply Archimedes' force, gravity and other things to the
// particle.
[Persistent]
public bool physical = false;
// How much the particles stick to objects they collide with.
[Persistent]
public double stickiness = 0.5;
[Persistent]
public double dragCoefficient = 0.1;
/// <summary>
/// Whether to nudge particles in order to alleviate the dotted smoke effect.
/// Set this to true (default) when using 'Simulate World Space' in Unity,
/// false otherwise.
/// </summary>
//[Persistent]
public bool fixedEmissions = true;
// The initial velocity of the particles will be offset by a random amount
// lying in a disk perpendicular to the mean initial velocity whose radius
// is randomOffsetMaxRadius. This is similar to Unity's 'Random Velocity'
// Setting, except it will sample the offset from a (normal) disk rather
// than from a cube. Units (SI): m/s.
// TODO Sarbian : have the init auto fill this one
[Persistent]
public float randomInitalVelocityOffsetMaxRadius = 0.0f;
#endregion Persistent fields
public MultiInputCurve emission = new MultiInputCurve("emission");
public MultiInputCurve energy = new MultiInputCurve("energy");
public MultiInputCurve speed = new MultiInputCurve("speed");
public MultiInputCurve grow = new MultiInputCurve("grow", true);
public MultiInputCurve scale = new MultiInputCurve("scale");
public MultiInputCurve size = new MultiInputCurve("size");
public MultiInputCurve offset = new MultiInputCurve("offset", true);
// Logarithmic growth applied to to the particle.
// The size at time t after emission will be approximately
// (Log(logarithmicGrowth * t + 1) + 1) * initialSize, assuming grow = 0.
public MultiInputCurve logGrow = new MultiInputCurve("logGrow", true);
private float logarithmicGrow;
// Those 2 curve are related to the angle and distance to cam
public FXCurve angle = new FXCurve("angle", 1f);
public FXCurve distance = new FXCurve("distance", 1f);
private List<PersistentKSPParticleEmitter> persistentEmitters;
// The time between Update()s (in seconds).
private float variableDeltaTime;
private Shader shader;
public static int activeParticles = 0;
public static int particleDecimate = 0;
public static uint particleCounter = 0;
// Particles Emitter with more than decimateFloor particles will have
// some particles culled if there is more than maximumActiveParticles active
public static int decimateFloor = 30;
public static int maximumActiveParticles = 8000; // The engine won't spawn more than 10k anyway
public bool showUI = true;
private readonly List<ModelMultiParticlePersistFX> list = new List<ModelMultiParticlePersistFX>();
public bool overRideInputs = false;
public readonly float[] inputs = new float[MultiInputCurve.inputsCount];
public List<ModelMultiParticlePersistFX> Instances
{
get
{
return list;
}
}
//public ModelMultiParticlePersistFX()
//{
// list.Add(this);
// winID++;
//}
private void OnDestroy()
{
if (persistentEmitters != null)
{
for (int i = 0; i < persistentEmitters.Count; i++)
{
persistentEmitters[i].Detach(0);
}
}
list.Remove(this);
}
public override void OnEvent()
{
if (persistentEmitters == null)
{
return;
}
UpdateEmitters(1);
for (int i = 0; i < persistentEmitters.Count; i++)
{
persistentEmitters[i].pe.Emit();
}
}
public override void OnEvent(float power)
{
if (persistentEmitters == null)
{
return;
}
if (power > 0f)
{
UpdateEmitters(power);
for (int i = 0; i < persistentEmitters.Count; i++)
{
persistentEmitters[i].fixedEmit = true;
persistentEmitters[i].pe.emit = false;
}
}
else
{
for (int j = 0; j < persistentEmitters.Count; j++)
{
persistentEmitters[j].fixedEmit = false;
persistentEmitters[j].pe.emit = false;
}
}
}
private bool addedLaunchPadCollider = false;
public static uint physicsPass = 4;
public static uint activePhysicsPass = 0;
public void FixedUpdate()
{
if (persistentEmitters == null)
{
return;
}
UpdateParticlesCount();
RaycastHit hit = new RaycastHit();
GameObject pad = GameObject.Find("ksp_pad_launchPad");
//RaycastHit vHit = new RaycastHit();
//Ray vRay = Camera.main.ScreenPointToRay(Input.mousePosition);
//if(Physics.Raycast(vRay, out vHit))
//{
// RaycastHit vHit2 = new RaycastHit();
// if (Physics.Raycast(vHit.point + vHit.normal * 10, -vHit.normal, out vHit2))
// Debug.Log(vHit2.collider.name);
//}
// "Default", "TransparentFX", "Local Scenery", "Ignore Raycast"
int mask = (1 << LayerMask.NameToLayer("Default")) | (1 << LayerMask.NameToLayer("Local Scenery"));
for (int i = 0; i < persistentEmitters.Count; i++)
{
// Emit particles on fixedUpdate rather than Update so that we know which particles
// were just created and should be nudged, should not be collided, etc.
if (persistentEmitters[i].fixedEmit)
{
// Number of particles to emit:
double averageEmittedParticles = UnityEngine.Random.Range(
persistentEmitters[i].pe.minEmission,
persistentEmitters[i].pe.maxEmission) * TimeWarp.fixedDeltaTime;
int emittedParticles = (int)Math.Floor(averageEmittedParticles)
+ (UnityEngine.Random.value
< averageEmittedParticles - Math.Floor(averageEmittedParticles)
? 1
: 0);
for (int k = 0; k < emittedParticles; ++k)
{
persistentEmitters[i].pe.EmitParticle();
}
}
// This line (and the one that does the oposite at the end) is actally the slowest part of the whole function
Particle[] particles = persistentEmitters[i].pe.pe.particles;
double averageSize = 0.5 * (persistentEmitters[i].pe.minSize + persistentEmitters[i].pe.maxSize);
for (int j = 0; j < particles.Length; j++)
{
// Check if we need to cull the number of particles
if (particleDecimate != 0 && particles.Length > decimateFloor)
{
particleCounter++;
if ((particleDecimate > 0 && (particleCounter % particleDecimate) == 0)
|| (particleDecimate < 0 && (particleCounter % particleDecimate) != 0))
{
particles[j].energy = 0; // energy set to 0 remove the particle, as per Unity doc
}
}
if (particles[j].energy > 0)
{
Vector3d pPos = persistentEmitters[i].pe.useWorldSpace
? particles[j].position
: persistentEmitters[i].pe.transform.TransformPoint(particles[j].position);
Vector3d pVel = (persistentEmitters[i].pe.useWorldSpace
? particles[j].velocity
: persistentEmitters[i].pe.transform.TransformDirection(particles[j].velocity))
+ Krakensbane.GetFrameVelocity();
// try-finally block to ensure we set the particle velocities correctly in the end.
try
{
// Fixed update is not the best place to update the size but the particles array copy is slow so doing each frame would be worse
// No need to waste time doing a division if the result is 0.
if (logarithmicGrow != 0.0)
{
// Euler integration of the derivative of Log(logarithmicGrowth * t + 1) + 1.
// This might look weird.
particles[j].size +=
(float)
(((TimeWarp.fixedDeltaTime * logarithmicGrow)
/ (1 + (particles[j].startEnergy - particles[j].energy) * logarithmicGrow))
* averageSize);
}
particles[j].size = Mathf.Min(particles[j].size, sizeClamp);
if (particles[j].energy == particles[j].startEnergy)
{
if (fixedEmissions)
{
// Uniformly scatter newly emitted particles along the emitter's trajectory in order to remove the dotted smoke effect.
// use variableDeltaTime since the particle are emited on Update anyway.
pPos -= (hostPart.rb.velocity + Krakensbane.GetFrameVelocity())
* UnityEngine.Random.value * variableDeltaTime;
}
if (randomInitalVelocityOffsetMaxRadius != 0.0)
{
Vector2 diskPoint = UnityEngine.Random.insideUnitCircle
* randomInitalVelocityOffsetMaxRadius;
Vector3d offset;
if (pVel.x == 0.0 && pVel.y == 0.0)
{
offset = new Vector3d(diskPoint.x, diskPoint.y, 0.0);
}
else
{
// Convoluted calculations to save some operations (especially divisions).
// Not that it really matters, but this achieves 2 divisions and 1 square root.
double x = pVel.x;
double y = pVel.y;
double z = pVel.z;
double xSquared = x * x;
double ySquared = y * y;
double xySquareNorm = xSquared + ySquared;
double inverseXYSquareNorm = 1 / xySquareNorm;
double inverseNorm = 1 / Math.Sqrt(xySquareNorm + z * z);
double zOverNorm = z * inverseNorm;
// TODO(robin): find an identifier for that...
double mixedTerm = x * y * (zOverNorm - 1);
offset =
new Vector3d(
((ySquared + xSquared * zOverNorm) * diskPoint.x + mixedTerm * diskPoint.y)
* inverseXYSquareNorm,
((xSquared + ySquared * zOverNorm) * diskPoint.y + mixedTerm * diskPoint.x)
* inverseXYSquareNorm,
-(x * diskPoint.x + y * diskPoint.y) * inverseNorm);
}
pVel += offset;
}
}
if (physical && (j % physicsPass == activePhysicsPass))
{
// There must be a way to keep the actual initial volume,
// but I'm lazy.
pVel = ParticlePhysics(particles[j].size, averageSize, pPos, pVel);
}
if (collide && particles[j].energy != particles[j].startEnergy
// Do not collide newly created particles (they collide with the emitter and things look bad).
&& (j % physicsPass == activePhysicsPass))
{
pVel = ParticleCollision(pPos, pVel, hit, mask);
}
}
finally
{
particles[j].velocity = (persistentEmitters[i].pe.useWorldSpace
? (Vector3)pVel
: persistentEmitters[i].pe.transform.InverseTransformDirection(
pVel)) - Krakensbane.GetFrameVelocity();
particles[j].position = persistentEmitters[i].pe.useWorldSpace
? (Vector3)pPos
: persistentEmitters[i].pe.transform.InverseTransformPoint(pPos);
}
}
}
activePhysicsPass = ++activePhysicsPass % physicsPass;
persistentEmitters[i].pe.pe.particles = particles;
activeParticles += persistentEmitters[i].pe.pe.particleCount;
}
}
private Vector3 ParticlePhysics(double radius, double initialRadius, Vector3d pPos, Vector3d pVel)
{
// N.B.: multiplications rather than Pow, Pow is slow,
// multiplication by .5 rather than division by 2 (same
// reason).
CelestialBody mainBody = FlightGlobals.currentMainBody;
double estimatedInitialVolume = 0.75 * Math.PI * initialRadius * initialRadius * initialRadius;
double currentVolume = 0.75 * Math.PI * radius * radius * radius;
double volumeChange = currentVolume - estimatedInitialVolume;
double atmosphericDensity = FlightGlobals.getAtmDensity(FlightGlobals.getStaticPressure(pPos, mainBody));
double density = (estimatedInitialVolume * initialDensity + volumeChange * atmosphericDensity) / currentVolume;
double mass = density * currentVolume;
// Weight and buoyancy.
Vector3d mainBodyDist = mainBody.position - pPos;
Vector3d geeForce = mainBodyDist.normalized * (mainBody.gMagnitudeAtCenter / mainBodyDist.sqrMagnitude);
Vector3d acceleration = (1 - (atmosphericDensity / density)) * geeForce;
// Drag. TODO(robin): simplify.
acceleration += -0.5 * atmosphericDensity * pVel * pVel.magnitude * dragCoefficient * Math.PI * radius * radius
/ mass;
// Euler is good enough for graphics.
return pVel + acceleration * TimeWarp.fixedDeltaTime * (float)physicsPass;
}
private Vector3 ParticleCollision(Vector3d pPos, Vector3d pVel, RaycastHit hit, int mask)
{
if (Physics.Raycast(
pPos,
pVel,
out hit,
(float)pVel.magnitude * TimeWarp.fixedDeltaTime * (float)physicsPass,
mask))
{
//// collidersName[hit.collider.name] = true;
if (hit.collider.name != LaunchPadGrateColliderName)
{
Vector3 unitTangent = (hit.normal.x == 0 && hit.normal.y == 0)
? new Vector3(1, 0, 0)
: Vector3.Exclude(hit.normal, new Vector3(0, 0, 1)).normalized;
Vector3 hVel = Vector3.Exclude(hit.normal, pVel);
Vector3 reflectedNormalVelocity = hVel - pVel;
float residualFlow = reflectedNormalVelocity.magnitude * (1 - collideRatio);
// An attempt at a better velocity change; the blob collides with some
// restitution coefficient collideRatio << 1 and we add a random tangential term
// for outflowing particles---randomness handwaved in through fluid dynamics:
float randomAngle = UnityEngine.Random.value * 360.0f;
Vector3d outflow = Quaternion.AngleAxis(randomAngle, hit.normal) * unitTangent * residualFlow;
pVel = hVel + collideRatio * reflectedNormalVelocity + outflow * (1 - stickiness);
}
else
{
// Don't collide with the launch pad grid and add colliders under it
if (!addedLaunchPadCollider)
{
AddLaunchPadColliders(hit);
}
}
}
return pVel;
}
// The whole pad object is named "ksp_pad_launchPad"
private const string LaunchPadGrateColliderName = "Launch Pad Grate";
private const string LaunchPadColliderName = "LaunchPadColliderSmokeScreen";
private void AddLaunchPadColliders(RaycastHit hit)
{
// the Grate Collider size is (37.70, 20.22, 3.47). Way larger that the actual grate
// The current collider do not cover all this area. More are needed
Transform parentTransform = hit.collider.gameObject.transform;
////print("AddLaunchPadColliders col name = " + hit.collider.gameObject.name);
////print("AddLaunchPadColliders parent col name = " + hit.collider.gameObject.transform.parent.gameObject.name);
// Are the collider already here ?
if (parentTransform.FindChild(LaunchPadColliderName))
{
addedLaunchPadCollider = true;
return;
}
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.name = LaunchPadColliderName;
cube.renderer.material.color = Color.green;
cube.transform.parent = parentTransform;
cube.transform.localPosition = new Vector3(8.5f, 0, 2.3f);
cube.transform.localRotation = parentTransform.localRotation;
cube.transform.localScale = new Vector3(0.1f, 7, 16);
cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.name = LaunchPadColliderName;
cube.renderer.material.color = Color.green;
cube.transform.parent = parentTransform;
cube.transform.localPosition = new Vector3(7, 10.5f, 2.3f);
cube.transform.localRotation = parentTransform.localRotation * Quaternion.Euler(0, 60, 0);
cube.transform.localScale = new Vector3(7f, 7, 0.1f);
cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.name = LaunchPadColliderName;
cube.renderer.material.color = Color.green;
cube.transform.parent = parentTransform;
cube.transform.localPosition = new Vector3(7, -10.5f, 2.3f);
cube.transform.localRotation = parentTransform.localRotation * Quaternion.Euler(0, -60, 0);
cube.transform.localScale = new Vector3(7f, 7, 0.1f);
cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.name = LaunchPadColliderName;
cube.renderer.material.color = Color.green;
cube.transform.parent = parentTransform;
cube.transform.localPosition = new Vector3(-8.5f, 0, 2.3f);
cube.transform.localRotation = parentTransform.localRotation;
cube.transform.localScale = new Vector3(0.1f, 7, 16);
cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.name = LaunchPadColliderName;
cube.renderer.material.color = Color.green;
cube.transform.parent = parentTransform;
cube.transform.localPosition = new Vector3(-7, 10.5f, 2.3f);
cube.transform.localRotation = parentTransform.localRotation * Quaternion.Euler(0, -60, 0);
cube.transform.localScale = new Vector3(7f, 7, 0.1f);
cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.name = LaunchPadColliderName;
cube.renderer.material.color = Color.green;
cube.transform.parent = parentTransform;
cube.transform.localPosition = new Vector3(-7, -10.5f, 2.3f);
cube.transform.localRotation = parentTransform.localRotation * Quaternion.Euler(0, 60, 0);
cube.transform.localScale = new Vector3(7f, 7, 0.1f);
addedLaunchPadCollider = true;
}
private static float lastTime = 0;
private static void UpdateParticlesCount()
{
if (lastTime < Time.fixedTime)
{
if (activeParticles > maximumActiveParticles)
{
int toRemove = activeParticles - maximumActiveParticles;
if (toRemove < maximumActiveParticles)
{
particleDecimate = activeParticles / (toRemove + 1); // positive we remove each n
}
else
{
particleDecimate = -activeParticles / maximumActiveParticles; // negative we keep each n
}
}
else
{
particleDecimate = 0;
}
activeParticles = 0;
lastTime = Time.fixedTime;
}
}
private void UpdateInputs(float power)
{
if (overRideInputs)
return;
float atmDensity = 1;
float surfaceVelMach = 1;
float partTemp = 1;
float externalTemp = 1;
if (hostPart != null)
{
partTemp = hostPart.temperature;
if (hostPart.vessel != null)
{
Vessel vessel = hostPart.vessel;
atmDensity = (float)vessel.atmDensity;
externalTemp = vessel.flightIntegrator.getExternalTemperature();
// FAR use a nice config file to get the atmo info for each body.
// For now I'll just use Air for all.
const double magicNumeberFromFAR = 1.4 * 8.3145 * 1000 / 28.96;
double speedOfSound = Math.Sqrt((externalTemp + 273.15) * magicNumeberFromFAR);
surfaceVelMach = (float)(vessel.srf_velocity.magnitude / speedOfSound);
}
else
{
// TODO atmDensity & mach when not attached to a vessel
atmDensity =
(float)
FlightGlobals.getAtmDensity(
FlightGlobals.getStaticPressure(hostPart.transform.position, FlightGlobals.currentMainBody));
}
}
inputs[(int)MultiInputCurve.Inputs.power] = power;
inputs[(int)MultiInputCurve.Inputs.density] = atmDensity;
inputs[(int)MultiInputCurve.Inputs.mach] = surfaceVelMach;
inputs[(int)MultiInputCurve.Inputs.parttemp] = partTemp;
inputs[(int)MultiInputCurve.Inputs.externaltemp] = externalTemp;
}
public void UpdateEmitters(float power)
{
UpdateInputs(power);
for (int i = 0; i < persistentEmitters.Count; i++)
{
PersistentKSPParticleEmitter pkpe = persistentEmitters[i];
float sizePower = size.Value(inputs);
pkpe.pe.minSize = Mathf.Min(pkpe.minSizeBase * sizePower, sizeClamp);
pkpe.pe.maxSize = Mathf.Min(pkpe.maxSizeBase * sizePower, sizeClamp);
float emissionPower = emission.Value(inputs);
pkpe.pe.minEmission = Mathf.FloorToInt(pkpe.minEmissionBase * emissionPower);
pkpe.pe.maxEmission = Mathf.FloorToInt(pkpe.maxEmissionBase * emissionPower);
float energyPower = energy.Value(inputs);
pkpe.pe.minEnergy = pkpe.minEnergyBase * energyPower;
pkpe.pe.maxEnergy = pkpe.maxEnergyBase * energyPower;
float localVelocityPower = speed.Value(inputs);
pkpe.pe.localVelocity = pkpe.localVelocityBase * localVelocityPower;
pkpe.pe.sizeGrow = grow.Value(inputs);
float currentScale = scale.Value(inputs);
pkpe.pe.shape1D = pkpe.scale1DBase * currentScale;
pkpe.pe.shape2D = pkpe.scale2DBase * currentScale;
pkpe.pe.shape3D = pkpe.scale3DBase * currentScale;
logarithmicGrow = logGrow.Value(inputs);
pkpe.go.transform.localPosition = Vector3d.forward * offset.Value(inputs);
////print(atmDensity.ToString("F2") + " " + offset.Value(power).ToString("F2") + " " + offsetFromDensity.Value(atmDensity).ToString("F2") + " " + offsetFromMach.Value(surfaceVelMach).ToString("F2"));
}
}
public void Update()
{
variableDeltaTime = Time.deltaTime; // used for the fixedemission particles distribution
if (persistentEmitters == null)
{
return;
}
for (int i = 0; i < persistentEmitters.Count; i++)
{
// using Camera.main will mess up anything multi cam but using current require adding a OnWillRenderObject() to the ksp particle emitter GameObject (? not tested)
float currentAngle = Vector3.Angle(
-Camera.main.transform.forward,
persistentEmitters[i].go.transform.forward);
float currentDist = (Camera.main.transform.position - persistentEmitters[i].go.transform.position).magnitude;
persistentEmitters[i].pe.maxParticleSize = persistentEmitters[i].maxSizeBase * angle.Value(currentAngle)
* distance.Value(currentDist);
persistentEmitters[i].pe.pr.maxParticleSize = persistentEmitters[i].pe.maxParticleSize;
}
}
public override void OnInitialize()
{
print("OnInitialize");
// The shader loading require proper testing
// Unity doc says that "Creating materials this way supports only simple shaders (fixed function ones).
// If you need a surface shader, or vertex/pixel shaders, you'll need to create shader asset in the editor and use that."
// But importing the same shader that the one used in the editor seems to work
string filename = KSPUtil.ApplicationRootPath + "GameData/" + shaderFileName;
if (shaderFileName != string.Empty && System.IO.File.Exists(filename))
{
try
{
System.IO.TextReader shaderFile = new System.IO.StreamReader(filename);
string shaderText = shaderFile.ReadToEnd();
shader = new Material(shaderText).shader;
}
catch (Exception e)
{
print("unable to load shader " + shaderFileName + " : " + e.ToString());
}
}
List<Transform> transforms = new List<Transform>(hostPart.FindModelTransforms(transformName));
if (transforms.Count == 0)
{
print("Cannot find transform " + transformName);
return;
}
GameObject model = GameDatabase.Instance.GetModel(modelName);
if (model == null)
{
print("Cannot find model " + modelName);
return;
}
model.SetActive(true);
KSPParticleEmitter templateKspParticleEmitter = model.GetComponentInChildren<KSPParticleEmitter>();
if (templateKspParticleEmitter == null)
{
print("Cannot find particle emitter on " + modelName);
UnityEngine.Object.Destroy(model);
return;
}
if (shader != null)
{
templateKspParticleEmitter.material.shader = shader;
}
fixedEmissions = templateKspParticleEmitter.useWorldSpace;
if (persistentEmitters == null)
{
persistentEmitters = new List<PersistentKSPParticleEmitter>();
}
for (int i = 0; i < transforms.Count; i++)
{
GameObject emitterGameObject = UnityEngine.Object.Instantiate(model) as GameObject;
KSPParticleEmitter childKSPParticleEmitter = emitterGameObject.GetComponentInChildren<KSPParticleEmitter>();
if (childKSPParticleEmitter != null)
{
PersistentKSPParticleEmitter pkpe = new PersistentKSPParticleEmitter(
emitterGameObject,
childKSPParticleEmitter,
templateKspParticleEmitter);
childKSPParticleEmitter.shape1D *= fixedScale;
childKSPParticleEmitter.shape2D *= fixedScale;
childKSPParticleEmitter.shape3D *= fixedScale;
templateKspParticleEmitter.shape1D *= fixedScale;
templateKspParticleEmitter.shape2D *= fixedScale;
templateKspParticleEmitter.shape3D *= fixedScale;
try
{
childKSPParticleEmitter.particleRenderMode =
(ParticleRenderMode)Enum.Parse(typeof(ParticleRenderMode), renderMode);
}
catch (ArgumentException)
{
print("ModelMultiParticleFXExt: " + renderMode + " is not a valid ParticleRenderMode");
}
persistentEmitters.Add(pkpe);
emitterGameObject.transform.SetParent(transforms[i]);
emitterGameObject.transform.localPosition = localPosition;
emitterGameObject.transform.localRotation = Quaternion.Euler(localRotation);
}
}
UnityEngine.Object.Destroy(templateKspParticleEmitter);
}
public override void OnLoad(ConfigNode node)
{
print("OnLoad");
ConfigNode.LoadObjectFromConfig(this, node);
print("OnLoad2");
emission.Load(node);
energy.Load(node);
speed.Load(node);
grow.Load(node);
scale.Load(node);
size.Load(node);
offset.Load(node);
logGrow.Load(node);
angle.Load("angle", node);
distance.Load("distance", node);
}
public override void OnSave(ConfigNode node)
{
print("OnSave");
ConfigNode.CreateConfigFromObject(this, node);
emission.Save(node);
energy.Save(node);
speed.Save(node);
grow.Save(node);
scale.Save(node);
size.Save(node);
offset.Save(node);
logGrow.Save(node);
angle.Save(node);
distance.Save(node);
}
private static void print(String s)
{
MonoBehaviour.print("[ModelMultiParticlePersistFX] " + s);
}
// TODO : move the whole UI stuff to a dedicated class - this is getting to big
private Rect winPos = new Rect(300, 100, 400, 100);
private const int baseWinID = 512100;
private int winID = baseWinID;
private string nodeText = "";
private bool nodeEdit = false;
private Vector2 scrollPosition = new Vector2();
private void OnGUI()
{
if (!HighLogic.LoadedSceneIsFlight)
{
return;
}
if (showUI)
{
winPos = GUILayout.Window(winID, winPos, windowGUI, "ModelMultiParticlePersistFX", GUILayout.MinWidth(300));
}
}
private void windowGUI(int ID)
{
GUILayout.BeginVertical();
collide = GUILayout.Toggle(collide, "collide");
physical = GUILayout.Toggle(physical, "physical");
GUILayout.Space(10);
GUILayout.BeginHorizontal();
GUILayout.Label("maximumActiveParticles", GUILayout.ExpandWidth(true));
int.TryParse(
GUILayout.TextField(maximumActiveParticles.ToString(), GUILayout.ExpandWidth(true), GUILayout.Width(100)),
out maximumActiveParticles);
GUILayout.EndHorizontal();
GUILayout.Label("activeParticles : " + activeParticles);
GUILayout.Label("particleDecimate : " + particleDecimate);
GUILayout.Label("particleCounter : " + particleCounter);
GUILayout.Space(10);
overRideInputs = GUILayout.Toggle(overRideInputs, "Manual Inputs");
if (!overRideInputs)
{
GUILayout.Label("Power : " + inputs[(int)MultiInputCurve.Inputs.power].ToString("F2"));
GUILayout.Label("Atmo Density : " + inputs[(int)MultiInputCurve.Inputs.density].ToString("F2"));
GUILayout.Label("Mach Speed : " + inputs[(int)MultiInputCurve.Inputs.mach].ToString("F2"));
GUILayout.Label("Part Temperature : " + inputs[(int)MultiInputCurve.Inputs.parttemp].ToString("F2"));
GUILayout.Label("External Temperature : " + inputs[(int)MultiInputCurve.Inputs.externaltemp].ToString("F2"));
}
else
{
GUIInput((int)MultiInputCurve.Inputs.power,"Power");
GUIInput((int)MultiInputCurve.Inputs.density,"Atmo Density");
GUIInput((int)MultiInputCurve.Inputs.mach, "Mach Speed");
GUIInput((int)MultiInputCurve.Inputs.parttemp, "Part Temperature");
GUIInput((int)MultiInputCurve.Inputs.externaltemp, "External Temperature");
}
GUILayout.Space(10);
nodeEdit = GUILayout.Toggle(nodeEdit, "Open Config Editor");
if (nodeEdit)
{
GUILayout.BeginHorizontal();
if (GUILayout.Button("Import"))
{
ConfigNode node = new ConfigNode();
this.OnSave(node);
nodeText = WriteRootNode(node);
}
//if (GUILayout.Button("Apply"))
//{
// string[] text = nodeText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
// ConfigNode node = ConfigNode.RecurseFormat(ConfigNode.PreFormatConfig(text));
// this.OnLoad(node);
//}
GUILayout.EndHorizontal();
scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.ExpandWidth(true), GUILayout.Height(200));
nodeText = GUILayout.TextArea(nodeText, GUILayout.ExpandWidth(true), GUILayout.Height(200));
GUILayout.EndScrollView();
}
GUILayout.EndVertical();
GUI.DragWindow();
}
private readonly bool[] boxInput = new bool[MultiInputCurve.inputsCount];
private void GUIInput(int id, string text)
{
GUILayout.Label(text);
GUILayout.BeginHorizontal();
boxInput[id] = GUILayout.Toggle(boxInput[id],"");
if (boxInput[id])
{
float.TryParse(
GUILayout.TextField(inputs[id].ToString("F2"), GUILayout.ExpandWidth(true), GUILayout.Width(100)),
out inputs[id]);
}
else
{
inputs[id] = GUILayout.HorizontalSlider(inputs[id], minInput(id), maxInput(id));
}
GUILayout.EndHorizontal();
}
private float minInput(int id)
{
float min = emission.minKey[id];
min = Mathf.Min(min, energy.minKey[id]);
min = Mathf.Min(min, speed.minKey[id]);
min = Mathf.Min(min, grow.minKey[id]);
min = Mathf.Min(min, scale.minKey[id]);
min = Mathf.Min(min, size.minKey[id]);
min = Mathf.Min(min, offset.minKey[id]);
min = Mathf.Min(min, logGrow.minKey[id]);
return min;
}
private float maxInput(int id)
{
float max = emission.maxKey[id];
max = Mathf.Min(max, energy.maxKey[id]);
max = Mathf.Min(max, speed.maxKey[id]);
max = Mathf.Min(max, grow.maxKey[id]);
max = Mathf.Min(max, scale.maxKey[id]);
max = Mathf.Min(max, size.maxKey[id]);
max = Mathf.Min(max, offset.maxKey[id]);
max = Mathf.Min(max, logGrow.maxKey[id]);
return max;
}
// TODO : move those to an utility class
//private static string WriteRootNode(ConfigNode node)
//{
// string result = "";
// print("node.values.Count " + node.values.Count + " node.nodes.Count " + node.nodes.Count);
// for (int i = 0; i < node.values.Count; i++)
// {
// ConfigNode.Value item = node.values[i];
// result += string.Concat(item.name, " = ", item.@value);
// }
// for (int j = 0; j < node.nodes.Count; j++)
// {
// string.Concat(result, WriteNodeString(node.nodes[j], string.Empty));
// }
// return result;
//}
//private static string WriteNodeString(ConfigNode node, string indent)
//{
// string result = "";
// result += string.Concat(indent, node.name);
// result += string.Concat(indent, "{");
// string str = string.Concat(indent, "\t");
// for (int i = 0; i < node.values.Count; i++)
// {
// ConfigNode.Value item = node.values[i];
// result += string.Concat(str, item.name, " = ", item.@value);
// }
// for (int j = 0; j < node.nodes.Count; j++)
// {
// result += WriteNodeString(node, str);
// }
// result += string.Concat(indent, "}");
// return result;
//}
private static string WriteRootNode(ConfigNode node)
{
StringBuilder builder = new StringBuilder();
print("node.values.Count " + node.values.Count + " node.nodes.Count " + node.nodes.Count);
for (int i = 0; i < node.values.Count; i++)
{
ConfigNode.Value item = node.values[i];
builder.AppendLine(string.Concat(item.name, " = ", item.value));
}
for (int j = 0; j < node.nodes.Count; j++)
{
WriteNodeString(node.nodes[j], ref builder, string.Empty);
}
return builder.ToString();
}