-
-
Notifications
You must be signed in to change notification settings - Fork 588
Expand file tree
/
Copy pathMicrobeStage.cs
More file actions
2103 lines (1662 loc) · 75.2 KB
/
MicrobeStage.cs
File metadata and controls
2103 lines (1662 loc) · 75.2 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Arch.Buffer;
using Arch.Core;
using Arch.Core.Extensions;
using Components;
using Godot;
using SharedBase.Archive;
/// <summary>
/// Main class for managing the microbe stage
/// </summary>
[SceneLoadedClass("res://src/microbe_stage/MicrobeStage.tscn")]
public sealed partial class MicrobeStage : CreatureStageBase<Entity, MicrobeWorldSimulation>, IMicrobeSpawnEnvironment,
IArchivable
{
public const int SERIALIZATION_VERSION = 1;
private readonly Dictionary<MicrobeSpecies, ResolvedMicrobeTolerances> resolvedTolerancesCache = new();
private OrganelleDefinition cytoplasm = null!;
// This is no longer saved with child properties as it gets really complicated trying to load data into this from
// a save
private PatchManager patchManager = null!;
private Patch? tempPatchManagerCurrentPatch;
private float tempPatchManagerBrightness;
#pragma warning disable CA2213
[Export]
private Node3D heatViewOverlay = null!;
[Export]
private FluidCurrentDisplay fluidCurrentDisplay = null!;
[Export]
private MovementModeSelectionPopup movementModeSelectionPopup = null!;
private MicrobeTutorialGUI tutorialGUI = null!;
private PackedScene guidanceLineScene = null!;
[Export]
private GuidanceLine guidanceLine = null!;
#pragma warning restore CA2213
private Vector3? guidancePosition;
/// <summary>
/// Used to track chemoreception lines. If TargetMicrobe is null, the target is static.
/// </summary>
private List<(GuidanceLine Line, Entity TargetEntity)> chemoreceptionLines = new();
/// <summary>
/// Used to control how often compound position info is sent to the tutorial
/// </summary>
private double elapsedSinceEntityPositionCheck = Constants.TUTORIAL_ENTITY_POSITION_UPDATE_INTERVAL + 1;
private bool wonOnce;
private double movementModeShowTimer;
private bool playerInColony;
/// <summary>
/// Used to mark the first time the player turns off tutorials in the game
/// </summary>
private bool tutorialCanceledOnce;
/// <summary>
/// Used to detect when the welcome tutorial is over and some state should be checked.
/// For example, having already played certain tutorials requires restoring the compounds panel to open.
/// </summary>
private bool waitingForWelcomeTutorialToEnd;
private bool environmentPanelAutomaticallyOpened;
/// <summary>
/// Used to give increasing numbers to player offspring to know which is the latest
/// </summary>
private int playerOffspringTotalCount;
private float maxLightLevel;
private float templateMaxLightLevel;
private float previousLightLevel;
private bool appliedPlayerGodMode;
private bool appliedUnlimitGrowthSpeed;
private bool loadSaveAdviceTriggered;
private bool loadSaveAdviseSuppressed;
private string? foundPreviousEditorSave;
/// <summary>
/// Used to ferry data between the patch change logic and handling the player cell splitting (as I couldn't
/// figure out another way to fit this into the code architecture -hhyyrylainen)
/// </summary>
private bool switchedPatchInEditorForCompounds;
public CompoundCloudSystem Clouds { get; private set; } = null!;
/// <summary>
/// The main camera. This needs to be after anything with AssignOnlyChildItemsOnDeserialize due to load order
/// </summary>
public MicrobeCamera Camera { get; private set; } = null!;
public MicrobeHUD HUD { get; private set; } = null!;
public MicrobeInspectInfo HoverInfo { get; private set; } = null!;
public TutorialState TutorialState =>
CurrentGame?.TutorialState ?? throw new InvalidOperationException("Game not started yet");
public override bool HasPlayer => Player != Entity.Null && Player.IsAlive();
public override bool HasAlivePlayer => HasPlayer && IsPlayerAlive();
public IDaylightInfo DaylightInfo => GameWorld.LightCycle;
public WorldGenerationSettings WorldSettings => GameWorld.WorldSettings;
public BiomeConditions CurrentBiome => GameWorld.Map.CurrentPatch?.Biome ??
throw new InvalidOperationException("no current patch set");
// TODO: these two can now be made differently probably with the new save archive format
/// <summary>
/// Makes saving information related to the patch manager work. This checks the patch manager against null to
/// make saves made in the editor after loading a save made in the editor work.
/// </summary>
public Patch? SavedPatchManagerPatch
{
get => patchManager == null! ? tempPatchManagerCurrentPatch : patchManager.ReadPreviousPatchForSave();
set => tempPatchManagerCurrentPatch = value;
}
public float SavedPatchManagerBrightness
{
get => patchManager == null! ? tempPatchManagerBrightness : patchManager.ReadBrightnessForSave();
set => tempPatchManagerBrightness = value;
}
public ushort CurrentArchiveVersion => SERIALIZATION_VERSION;
public ArchiveObjectType ArchiveObjectType => (ArchiveObjectType)ThriveArchiveObjectType.MicrobeStage;
public override MainGameState GameState => MainGameState.MicrobeStage;
protected override ICreatureStageHUD BaseHUD => HUD;
private LocalizedString CurrentPatchName =>
GameWorld.Map.CurrentPatch?.Name ?? throw new InvalidOperationException("no current patch");
public static void WriteToArchive(ISArchiveWriter writer, ArchiveObjectType type, object obj)
{
if (type != (ArchiveObjectType)ThriveArchiveObjectType.MicrobeStage)
throw new NotSupportedException();
writer.WriteObject((MicrobeStage)obj);
}
public static MicrobeStage ReadFromArchive(ISArchiveReader reader, ushort version, int referenceId)
{
if (version is > SERIALIZATION_VERSION or <= 0)
throw new InvalidArchiveVersionException(version, SERIALIZATION_VERSION);
var scene = GD.Load<PackedScene>("res://src/microbe_stage/MicrobeStage.tscn");
var instance = scene.Instantiate<MicrobeStage>();
reader.ReportObjectConstructorDone(instance, referenceId);
instance.ResolveNodeReferences();
// Base version is different from this version
instance.ReadBasePropertiesFromArchive(reader, reader.ReadUInt16());
instance.wonOnce = reader.ReadBool();
instance.movementModeShowTimer = reader.ReadDouble();
instance.playerInColony = reader.ReadBool();
instance.tutorialCanceledOnce = reader.ReadBool();
instance.environmentPanelAutomaticallyOpened = reader.ReadBool();
instance.playerOffspringTotalCount = reader.ReadInt32();
instance.appliedPlayerGodMode = reader.ReadBool();
instance.loadSaveAdviseSuppressed = reader.ReadBool();
reader.ReadObjectProperties(instance.Clouds);
reader.ReadObjectProperties(instance.Camera);
reader.ReadObjectProperties(instance.HUD);
instance.SavedPatchManagerPatch = reader.ReadObjectOrNull<Patch>();
instance.SavedPatchManagerBrightness = reader.ReadFloat();
return instance;
}
public void WriteToArchive(ISArchiveWriter writer)
{
writer.Write(SERIALIZATION_VERSION_CREATURE);
WriteBasePropertiesToArchive(writer);
writer.Write(wonOnce);
writer.Write(movementModeShowTimer);
writer.Write(playerInColony);
writer.Write(tutorialCanceledOnce);
writer.Write(environmentPanelAutomaticallyOpened);
writer.Write(playerOffspringTotalCount);
writer.Write(appliedPlayerGodMode);
writer.Write(loadSaveAdviseSuppressed);
writer.WriteObjectProperties(Clouds);
writer.WriteObjectProperties(Camera);
writer.WriteObjectProperties(HUD);
writer.WriteObjectOrNull(SavedPatchManagerPatch);
writer.Write(SavedPatchManagerBrightness);
}
/// <summary>
/// This method gets called the first time the stage scene is put into an active scene tree.
/// So returning from the editor doesn't cause this to re-run.
/// </summary>
public override void _Ready()
{
base._Ready();
// Set a null player until we are initialised
if (Player == default(Entity))
Player = Entity.Null;
// Start a new game if started directly from MicrobeStage.tscn
CurrentGame ??= GameProperties.StartNewMicrobeGame(new WorldGenerationSettings());
ResolveNodeReferences();
guidanceLineScene = GD.Load<PackedScene>("res://src/engine/GuidanceLine.tscn");
var simulationParameters = SimulationParameters.Instance;
cytoplasm = simulationParameters.GetOrganelleType("cytoplasm");
tutorialGUI.Visible = true;
HUD.Init(this);
HoverInfo.Init(Clouds, Camera);
// Do stage setup to spawn things and set up all parts of the stage
SetupStage();
fluidCurrentDisplay.Init(WorldSimulation, Camera);
}
public override void ResolveNodeReferences()
{
if (NodeReferencesResolved)
return;
base.ResolveNodeReferences();
HUD = GetNode<MicrobeHUD>("MicrobeHUD");
tutorialGUI = GetNode<MicrobeTutorialGUI>("TutorialGUI");
HoverInfo = GetNode<MicrobeInspectInfo>("PlayerHoverInfo");
Camera = world.GetNode<MicrobeCamera>("PrimaryCamera");
Clouds = world.GetNode<CompoundCloudSystem>("CompoundClouds");
}
public override void _EnterTree()
{
base._EnterTree();
CheatManager.OnSpawnEnemyCheatUsed += OnSpawnEnemyCheatUsed;
CheatManager.OnPlayerDuplicationCheatUsed += OnDuplicatePlayerCheatUsed;
CheatManager.OnDespawnAllEntitiesCheatUsed += OnDespawnAllEntitiesCheatUsed;
// Re-register these callbacks in case it is necessary
// The primary registration for this is in OnGameStarted
if (CurrentGame != null && HUD != null!)
{
TutorialState.GlucoseCollecting.OnOpened += SetupPlayerForGlucoseCollecting;
TutorialState.DayNightTutorial.OnOpened += HUD.CloseProcessPanel;
}
}
public override void _ExitTree()
{
base._ExitTree();
CheatManager.OnSpawnEnemyCheatUsed -= OnSpawnEnemyCheatUsed;
CheatManager.OnPlayerDuplicationCheatUsed -= OnDuplicatePlayerCheatUsed;
CheatManager.OnDespawnAllEntitiesCheatUsed -= OnDespawnAllEntitiesCheatUsed;
DebugOverlays.Instance.OnWorldDisabled(WorldSimulation);
if (CurrentGame != null)
{
TutorialState.GlucoseCollecting.OnOpened -= SetupPlayerForGlucoseCollecting;
TutorialState.DayNightTutorial.OnOpened -= HUD.CloseProcessPanel;
}
}
public override void _Process(double delta)
{
base._Process(delta);
if (StageLoadingState != LoadState.NotLoading)
return;
WorldPosition playerPosition = default;
if (HasPlayer)
{
try
{
// Intentional copy here to simplify the later block that also wants to use the player position
playerPosition = Player.Get<WorldPosition>();
WorldSimulation.ReportPlayerPosition(playerPosition.Position);
DebugOverlays.Instance.ReportPositionCoordinates(playerPosition.Position);
}
catch (Exception e)
{
GD.PrintErr("Can't read player position: " + e);
}
HandleMovementModePrompt(delta);
}
bool playerAlive = HasAlivePlayer;
if (WorldSimulation.ProcessAll((float)delta))
{
// If game logic didn't run, the debug labels don't need to update
DebugOverlays.Instance.UpdateActiveEntities(WorldSimulation);
}
if (gameOver || playerExtinctInCurrentPatch)
return;
if (playerAlive != HasAlivePlayer)
{
// Player just became dead
GD.Print("Detected player is no longer alive after last simulation update");
OnPlayerDied(Player);
playerAlive = false;
}
if (HasPlayer)
{
DebugOverlays.Instance.ReportLookingAtCoordinates(Camera.CursorWorldPos);
DebugOverlays.Instance.ReportHeatValue(WorldSimulation.SampleTemperatureAt(Camera.CursorWorldPos));
TutorialState.SendEvent(TutorialEventType.MicrobePlayerOrientation,
new RotationEventArgs(playerPosition.Rotation, playerPosition.Rotation.GetEuler()), this);
TutorialState.SendEvent(TutorialEventType.MicrobePlayerCompounds,
new CompoundBagEventArgs(Player.Get<CompoundStorage>().Compounds), this);
TutorialState.SendEvent(TutorialEventType.MicrobePlayerTotalCollected,
new CompoundEventArgs(Player.Get<CompoundAbsorber>().TotalAbsorbedCompounds ??
throw new Exception("Player is missing absorbed compounds")), this);
// TODO: if we start getting a ton of tutorial stuff reported each frame we should only report stuff when
// relevant, for example only when in a colony or just leaving a colony should the player colony
// info be sent
if (Player.Has<MicrobeColony>())
{
TutorialState.SendEvent(TutorialEventType.MicrobePlayerColony,
new MicrobeColonyEventArgs(true, Player.Get<MicrobeColony>().ColonyMembers.Length,
Player.Has<MulticellularSpeciesMember>()), this);
if (playerAlive && GameWorld.PlayerSpecies is MulticellularSpecies)
{
MakeEditorForFreebuildAvailable();
}
if (!playerInColony)
{
playerInColony = true;
AchievementEvents.ReportPlayerInCellColony();
}
}
else if (playerAlive)
{
MakeEditorForFreebuildAvailable();
playerInColony = false;
}
if (Player.Has<CompoundStorage>())
{
var storage = Player.Get<CompoundStorage>();
var compounds = storage.Compounds;
HUD.UpdateRadiationBar(compounds.GetCompoundAmount(Compound.Radiation),
compounds.GetCapacityForCompound(Compound.Radiation), Constants.RADIATION_WARNING);
}
elapsedSinceEntityPositionCheck += delta;
if (elapsedSinceEntityPositionCheck > Constants.TUTORIAL_ENTITY_POSITION_UPDATE_INTERVAL)
{
elapsedSinceEntityPositionCheck = 0;
if (TutorialState.WantsNearbyCompoundInfo())
{
TutorialState.SendEvent(TutorialEventType.MicrobeCompoundsNearPlayer,
new EntityPositionEventArgs(Clouds.FindCompoundNearPoint(playerPosition.Position,
Compound.Glucose)), this);
}
if (TutorialState.WantsNearbyEngulfableInfo())
{
// Filter to spawned engulfables that can be despawned (this likely just filters out the player
// themselves
ref var engulfer = ref Player.Get<Engulfer>();
var position = engulfer.FindNearestEngulfableSlow(ref Player.Get<CellProperties>(),
ref Player.Get<OrganelleContainer>(), ref Player.Get<WorldPosition>(),
Player.Get<CompoundStorage>().Compounds, Player, Player.Get<SpeciesMember>().ID,
WorldSimulation, skipLikelyTooFastTargets: true);
TutorialState.SendEvent(TutorialEventType.MicrobeChunksNearPlayer,
new EntityPositionEventArgs(position), this);
}
guidancePosition = TutorialState.GetPlayerGuidancePosition();
}
if (guidancePosition != null)
{
guidanceLine.Visible = true;
// To avoid line jitter, always make the line start from the camera's position
var start = Camera.GlobalPosition;
start.Y = 0;
guidanceLine.LineStart = start;
guidanceLine.LineEnd = guidancePosition.Value;
}
else
{
guidanceLine.Visible = false;
}
if (waitingForWelcomeTutorialToEnd)
{
// Check if the welcome tutorial has ended
if (TutorialState.MicrobeStageWelcome.Complete)
{
waitingForWelcomeTutorialToEnd = false;
// Restore panel state if tutorials won't be played
bool showCompounds = TutorialState.GlucoseCollecting.Complete;
bool showEnvironment = TutorialState.DayNightTutorial.Complete;
if (showEnvironment)
HUD.ShowEnvironmentPanel();
if (showCompounds)
HUD.ShowCompoundPanel();
}
}
if (!environmentPanelAutomaticallyOpened)
{
// Open panel automatically if taking radiation
var compounds = Player.Get<CompoundStorage>().Compounds;
if (compounds.GetCompoundAmount(Compound.Radiation) > 0.1f)
{
HUD.ShowEnvironmentPanel();
environmentPanelAutomaticallyOpened = true;
}
}
if (TutorialState.Enabled)
{
if (GameWorld.HasExternalEffectForSpecies(GameWorld.PlayerSpecies, true))
{
TutorialState.SendEvent(TutorialEventType.PlayerSpeciesMemberDied, EventArgs.Empty, this);
}
}
// Apply player god mode
ref var playerHealth = ref Player.Get<Health>();
if (playerHealth.Invulnerable != CheatManager.GodMode)
{
// Only reset invulnerability if set by god mode
if (playerHealth.Invulnerable && appliedPlayerGodMode)
{
playerHealth.Invulnerable = false;
appliedPlayerGodMode = false;
}
else if (!playerHealth.Invulnerable)
{
GD.Print("Enabling microbe god mode");
playerHealth.Invulnerable = true;
appliedPlayerGodMode = true;
}
}
if (appliedUnlimitGrowthSpeed != CheatManager.UnlimitedGrowthSpeed)
{
appliedUnlimitGrowthSpeed = CheatManager.UnlimitedGrowthSpeed;
CurrentGame!.GameWorld.WorldSettings.Difficulty.SetGrowthRateLimitCheatOverride(!CheatManager
.UnlimitedGrowthSpeed);
}
ref var processor = ref Player.Get<BioProcesses>();
if (processor.ProcessStatistics != null && Player.Has<CompoundStorage>())
{
// Send photosynthesis and radiation stats to achievements
SendProductionTypesToAchievements(ref processor);
}
else
{
GD.PrintErr("Player process component is missing speed statistics");
}
}
else
{
guidanceLine.Visible = false;
HUD.UpdateRadiationBar(0, 1, 1);
}
UpdateLinePlayerPosition();
}
public override void OnFinishTransitioning()
{
base.OnFinishTransitioning();
if (GameWorld.PlayerSpecies is not MulticellularSpecies)
{
TutorialState.SendEvent(TutorialEventType.EnteredMicrobeStage,
new AggregateEventArgs(new CallbackEventArgs(() => HUD.ShowPatchName(CurrentPatchName.ToString())),
new GameWorldEventArgs(GameWorld)), this);
}
else
{
TutorialState.SendEvent(TutorialEventType.EnteredMulticellularStage, EventArgs.Empty, this);
}
}
public override void OnFinishLoading(Save save)
{
OnFinishLoading();
}
public override void StartNewGame()
{
CurrentGame = GameProperties.StartNewMicrobeGame(new WorldGenerationSettings());
UpdatePatchSettings(!TutorialState.Enabled);
base.StartNewGame();
}
public override void StartMusic()
{
var biome = CurrentGame!.GameWorld.Map.CurrentPatch!.BiomeTemplate;
Jukebox.Instance.PlayCategory(GameWorld.PlayerSpecies is MulticellularSpecies ?
"MulticellularStage" :
"MicrobeStage", biome.ActiveMusicContexts);
}
[RunOnKeyDown("g_pause")]
public void PauseKeyPressed()
{
// Check nothing else has keyboard focus and pause the game
if (HUD.GetFocusOwner() == null)
{
HUD.PauseButtonPressed(!HUD.Paused);
}
}
[RunOnKeyDown("g_toggle_speed_mode")]
public void ToggleSpeedMode()
{
HUD.ApplySpeedMode(!HUD.GetCurrentSpeedMode());
}
public override void SetSpecialViewMode(ViewMode mode)
{
if (mode == ViewMode.Normal)
{
heatViewOverlay.Visible = false;
}
else if (mode == ViewMode.Heat)
{
heatViewOverlay.Visible = true;
}
else
{
base.SetSpecialViewMode(mode);
}
}
public void RecordPlayerReproduction()
{
GameWorld.StatisticsTracker.PlayerReproductionStatistic.RecordPlayerReproduction(Player,
GameWorld.Map.CurrentPatch!.BiomeTemplate);
}
public ResolvedMicrobeTolerances GetSpeciesTolerances(MicrobeSpecies microbeSpecies)
{
// Use caching to speed up spawning
lock (resolvedTolerancesCache)
{
if (resolvedTolerancesCache.TryGetValue(microbeSpecies, out var cached))
return cached;
var tolerances =
MicrobeEnvironmentalToleranceCalculations.CalculateTolerances(microbeSpecies, CurrentBiome);
cached = MicrobeEnvironmentalToleranceCalculations.ResolveToleranceValues(tolerances);
resolvedTolerancesCache[microbeSpecies] = cached;
return cached;
}
}
/// <summary>
/// Switches to the editor
/// </summary>
public override void MoveToEditor()
{
if (!HasPlayer || Player.Get<Health>().Dead || PlayerIsEngulfed(Player))
{
GD.PrintErr("Player object disappeared, died, or was engulfed while transitioning to the editor");
HUD.OnCancelEditorEntry();
return;
}
if (CurrentGame == null)
throw new InvalidOperationException("Stage has no current game");
// Update endosymbiosis progress now that the player got to the editor
if (Player.Has<TemporaryEndosymbiontInfo>())
{
ref var endosymbiontInfo = ref Player.Get<TemporaryEndosymbiontInfo>();
endosymbiontInfo.UpdateEndosymbiosisProgress(Player.Get<SpeciesMember>().Species);
}
Node sceneInstance;
if (Player.Has<MulticellularSpeciesMember>())
{
// Player is a multicellular species, go to multicellular editor
var scene = SceneManager.Instance.LoadScene(MainGameState.MulticellularEditor);
sceneInstance = scene.Instantiate();
var editor = (MulticellularEditor)sceneInstance;
editor.CurrentGame = CurrentGame;
editor.ReturnToStage = this;
// TODO: severely limit the MP points in awakening stage
}
else
{
// This might not be required anymore but just for extra safety this is here
if (Player.Has<MicrobeColony>())
{
GD.PrintErr("Editor button was enabled and pressed while the player is in a colony");
MovingToEditor = false;
return;
}
var scene = SceneManager.Instance.LoadScene(MainGameState.MicrobeEditor);
sceneInstance = scene.Instantiate();
var editor = (MicrobeEditor)sceneInstance;
editor.CurrentGame = CurrentGame;
editor.ReturnToStage = this;
}
GiveReproductionPopulationBonus();
RecordPlayerReproduction();
PauseMenu.Instance.ReportStageTransition();
// We don't free this here as the editor will return to this scene
if (SceneManager.Instance.SwitchToScene(sceneInstance, true) != this)
{
throw new Exception("failed to keep the current scene root");
}
MovingToEditor = false;
}
/// <summary>
/// Moves to the multicellular editor (the first time)
/// </summary>
public void MoveToMulticellular()
{
if (!HasPlayer || Player.Get<Health>().Dead || !Player.Has<MicrobeColony>() || PlayerIsEngulfed(Player))
{
GD.PrintErr("Player object disappeared or died (or not in a colony) while trying to become multicellular");
HUD.OnCancelEditorEntry();
return;
}
ref var entitySpecies = ref Player.Get<SpeciesMember>();
var previousSpecies = entitySpecies.Species;
previousSpecies.Obsolete = true;
// Log becoming multicellular in the timeline
GameWorld.LogEvent(new LocalizedString("TIMELINE_SPECIES_BECAME_MULTICELLULAR",
previousSpecies.FormattedNameBbCodeUnstyled), true, false, "multicellularTimelineMembraneTouch.png");
GameWorld.Map.CurrentPatch!.LogEvent(
new LocalizedString("TIMELINE_SPECIES_BECAME_MULTICELLULAR", previousSpecies.FormattedNameBbCodeUnstyled),
true, false, "multicellularTimelineMembraneTouch.png");
if (WorldSimulation.Processing)
throw new Exception("This shouldn't be ran while world is in the middle of a simulation");
GD.Print("Disbanding colony and becoming multicellular");
// Move to multicellular always happens when the player is in a colony, so we force disband that here before
// proceeding
MicrobeColonyHelpers.UnbindAllOutsideGameUpdate(Player, WorldSimulation);
if (Player.Has<MicrobeColony>())
throw new Exception("Unbind failed");
GiveReproductionPopulationBonus();
CurrentGame!.EnterPrototypes();
var playerSpeciesMicrobes = GetAllPlayerSpeciesMicrobes();
// Re-apply species here so that the player cell knows it is multicellular after this
// Also apply species here to other members of the player's previous species
// This prevents previous members of the player's colony from immediately being hostile
bool playerHandled = false;
var multicellularSpecies = GameWorld.ChangeSpeciesToMulticellular(previousSpecies);
foreach (var microbe in playerSpeciesMicrobes)
{
// Direct component setting is safe as we verified above we aren't running during a simulation update
microbe.Remove<MicrobeSpeciesMember>();
microbe.Set(new SpeciesMember(multicellularSpecies));
microbe.Add(new MulticellularSpeciesMember(multicellularSpecies,
multicellularSpecies.ModifiableCellTypes[0], 0));
microbe.Add(new MulticellularGrowth(multicellularSpecies));
if (microbe.Has<PlayerMarker>())
playerHandled = true;
}
if (!playerHandled)
throw new Exception("Did not find player to apply multicellular species to");
GameWorld.NotifySpeciesChangedStages();
// Make sure no queued player species can spawn with the old species
WorldSimulation.SpawnSystem.ClearSpawnQueue();
var scene = SceneManager.Instance.LoadScene(MainGameState.MulticellularEditor);
var editor = scene.Instantiate<MulticellularEditor>();
editor.CurrentGame = CurrentGame ?? throw new InvalidOperationException("Stage has no current game");
editor.ReturnToStage = this;
GD.Print("Switching to multicellular editor");
// We don't free this here as the editor will return to this scene
if (SceneManager.Instance.SwitchToScene(editor, true) != this)
{
throw new Exception("failed to keep the current scene root");
}
GameWorld.PlayerSpecies.Endosymbiosis.CancelAllEndosymbiosisTargets();
// TODO: The multicellular stage needs to be able to track statistics and not break organelle unlocks
GameWorld.UnlockProgress.UnlockAll = true;
MovingToEditor = false;
}
/// <summary>
/// Moves to the macroscopic editor (the first time)
/// </summary>
public void MoveToMacroscopic()
{
if (!HasPlayer || Player.Get<Health>().Dead || !Player.Has<MicrobeColony>())
{
GD.PrintErr("Player object disappeared or died (or not in a colony) while trying to become macroscopic");
return;
}
GD.Print("Becoming macroscopic");
// We don't really need to handle the player state or anything like that here as once we go to the late
// multicellular editor, we never return to the microbe stage. So we don't need that much setup as becoming
// multicellular
// We don't really need to disband the colony here
GiveReproductionPopulationBonus();
CurrentGame!.EnterPrototypes();
var modifiedSpecies = GameWorld.ChangeSpeciesToMacroscopic(Player.Get<SpeciesMember>().Species);
// Similar code as in the MetaballBodyEditorComponent to prevent the player automatically getting stuck
// underwater in the awakening stage
if (modifiedSpecies.MacroscopicType == MacroscopicSpeciesType.Awakened)
{
GD.Print("Preventing player from becoming awakened too soon");
modifiedSpecies.KeepPlayerInAwareStage();
}
GameWorld.NotifySpeciesChangedStages();
var scene = SceneManager.Instance.LoadScene(MainGameState.MacroscopicEditor);
var editor = scene.Instantiate<MacroscopicEditor>();
editor.CurrentGame = CurrentGame ?? throw new InvalidOperationException("Stage has no current game");
// We'll start off in a brand-new stage in the macroscopic part
editor.ReturnToStage = null;
GD.Print("Switching to macroscopic editor");
SceneManager.Instance.SwitchToScene(editor, false);
MovingToEditor = false;
}
public override void OnReturnFromEditor()
{
UpdatePatchSettings();
base.OnReturnFromEditor();
ProceduralDataCache.Instance.OnEnterState(MainGameState.MicrobeStage);
// Add a cloud of glucose if difficulty settings call for it
if (GameWorld.WorldSettings.FreeGlucoseCloud)
{
Clouds.AddCloud(Compound.Glucose, 200000.0f,
Player.Get<WorldPosition>().Position + new Vector3(0.0f, 0.0f, -25.0f));
}
// Check win conditions
if (!CurrentGame!.FreeBuild && GameWorld.PlayerSpecies.Generation >= 20 &&
GameWorld.PlayerSpecies.Population >= 300 && !wonOnce)
{
HUD.ToggleWinBox();
wonOnce = true;
}
loadSaveAdviceTriggered = false;
var playerSpecies = Player.Get<SpeciesMember>().Species;
// Update the player environmental properties
ref var bioProcesses = ref Player.Get<BioProcesses>();
// Make sure there's no way this cache has outdated values
ClearResolvedTolerancesCache();
var environmentalEffects = new MicrobeEnvironmentalEffects
{
OsmoregulationMultiplier = 1,
HealthMultiplier = 1,
ProcessSpeedModifier = 1,
};
var workData1 = new List<Hex>();
var workData2 = new List<Hex>();
bool playerHasThermoplast = false;
// Update the player's cell
ref var cellProperties = ref Player.Get<CellProperties>();
bool playerIsMulticellular = Player.Has<MulticellularSpeciesMember>();
if (playerIsMulticellular)
{
ref var earlySpeciesType = ref Player.Get<MulticellularSpeciesMember>();
// TODO: multicellular tolerances
// Allow updating the first cell type to reproduce (reproduction order changed)
earlySpeciesType.MulticellularCellType = earlySpeciesType.Species.ModifiableCells[0].ModifiableCellType;
cellProperties.ReApplyCellTypeProperties(ref environmentalEffects, Player,
earlySpeciesType.MulticellularCellType, earlySpeciesType.Species, WorldSimulation, workData1,
workData2);
}
else
{
ref var species = ref Player.Get<MicrobeSpeciesMember>();
var resolvedTolerances = MicrobeEnvironmentalToleranceCalculations.ResolveToleranceValues(
MicrobeEnvironmentalToleranceCalculations.CalculateTolerances(species.Species, CurrentBiome));
environmentalEffects.ApplyEffects(resolvedTolerances, ref bioProcesses);
cellProperties.ReApplyCellTypeProperties(ref environmentalEffects, Player,
species.Species, species.Species, WorldSimulation,
workData1, workData2);
foreach (var organelle in species.Species.Organelles)
{
if (organelle.Definition.HasHeatCollection)
{
playerHasThermoplast = true;
break;
}
}
}
UpdateZoomLevels(playerIsMulticellular);
Player.Set(environmentalEffects);
var playerCompounds = Player.Get<CompoundStorage>().Compounds;
var playerPosition = Player.Get<WorldPosition>().Position;
// Setup handling for what happens to compounds after reproduction
Dictionary<Compound, float>? topUpToCustom = null;
bool topUp = false;
switch (GameWorld.WorldSettings.Difficulty.ReproductionCompounds)
{
case ReproductionCompoundHandling.SplitWithSister:
// Default handling
break;
case ReproductionCompoundHandling.KeepAsIs:
topUpToCustom = playerCompounds.Compounds.CloneShallow();
break;
case ReproductionCompoundHandling.TopUpWithInitial:
topUp = true;
break;
case ReproductionCompoundHandling.TopUpOnPatchChange:
if (switchedPatchInEditorForCompounds)
{
topUp = true;
}
break;
default:
GD.PrintErr("Unknown handling of reproduction compounds mode: " +
$"{GameWorld.WorldSettings.Difficulty.ReproductionCompounds}");
break;
}
switchedPatchInEditorForCompounds = false;
// Spawn another cell from the player species
// This needs to be done after updating the player so that multicellular organisms are accurately separated
cellProperties.Divide(ref Player.Get<OrganelleContainer>(), Player, playerSpecies, WorldSimulation,
this, WorldSimulation.SpawnSystem, (ref Entity daughter, CommandBuffer commandBuffer) =>
{
// Mark as a player-reproduced entity
commandBuffer.Add(daughter, new PlayerOffspring
{
OffspringOrderNumber = ++playerOffspringTotalCount,
});
// If multicellular, we want that other cell colony to be fully grown to show budding in action
}, MulticellularSpawnState.FullColony);
// This is queued to run on the world after the next update as that's when the duplicate entity will spawn
// The entity is not forced to spawn here immediately to reduce the lag impact that is already caused by
// switching from the editor back to the stage scene
WorldSimulation.Invoke(() =>
{
// We need to find the entity reference of the offspring that was spawned last frame
var doNotDespawn = PlayerOffspringHelpers.FindLatestSpawnedOffspring(WorldSimulation.EntitySystem);
#if DEBUG
if (doNotDespawn.IsAlive() && !doNotDespawn.Has<Spawned>())
{
throw new Exception(
"Spawned player offspring has no spawned component, microbe reproduction method is" +
"working incorrectly");
}
#endif
WorldSimulation.SpawnSystem.EnsureEntityLimitAfterPlayerReproduction(playerPosition, doNotDespawn);
});
// Handle the compound modes
if (topUp)
{
// Top up with the player species definitions of the initial compounds