-
-
Notifications
You must be signed in to change notification settings - Fork 589
Expand file tree
/
Copy pathSimulationCache.cs
More file actions
1269 lines (1049 loc) · 53.3 KB
/
SimulationCache.cs
File metadata and controls
1269 lines (1049 loc) · 53.3 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
// Tradeoff between safety and faster score lookups
#define USE_HASHED_SCORE_KEYS
// Some extra debug stuff that should be disabled in most cases
// #define VERIFY_PROCESS_SPEED_CACHE_RETURNS
namespace AutoEvo;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Godot;
using Systems;
/// <summary>
/// Caches some information in auto-evo runs to speed them up
/// </summary>
/// <remarks>
/// <para>
/// Some information will get outdated when data that the auto-evo relies on changes. If in the future
/// caching is moved to a higher level in the auto-evo, that needs to be considered.
/// </para>
/// </remarks>
public class SimulationCache
{
private readonly CompoundDefinition oxytoxy = SimulationParameters.GetCompound(Compound.Oxytoxy);
private readonly CompoundDefinition mucilage = SimulationParameters.GetCompound(Compound.Mucilage);
private readonly WorldGenerationSettings worldSettings;
#if USE_HASHED_SCORE_KEYS
private readonly Dictionary<ulong, float> cachedPressureScores = new();
private readonly Dictionary<ulong, EnergyBalanceInfoSimple> cachedSimpleEnergyBalances = [];
#else
private readonly Dictionary<(Species, SelectionPressure, Patch), float> cachedPressureScores = new();
private readonly Dictionary<(MicrobeSpecies, IBiomeConditions), EnergyBalanceInfoSimple>
cachedSimpleEnergyBalances = [];
#endif
private readonly Dictionary<MicrobeSpecies, float> cachedBaseSpeeds = new();
private readonly Dictionary<MicrobeSpecies, float> cachedBaseHexSizes = new();
private readonly Dictionary<(MicrobeSpecies, MicrobeSpecies, IBiomeConditions), float> predationScores = new();
private readonly Dictionary<ulong, ProcessSpeedInformation> cachedProcessSpeeds = new();
private readonly Dictionary<MicrobeSpecies, PredationToolsRawScores>
cachedPredationToolsRawScores = new();
private readonly Dictionary<MicrobeSpecies, List<TweakedProcess>> cachedProcessLists = new();
private readonly Dictionary<(MicrobeSpecies, BiomeConditions), bool> cachedUsesVaryingCompounds = new();
private readonly Dictionary<OrganelleDefinition, int> workMemory1 = new();
public SimulationCache(WorldGenerationSettings worldSettings)
{
this.worldSettings = worldSettings;
}
public float GetPressureScore(SelectionPressure pressure, Patch patch, Species species)
{
#if USE_HASHED_SCORE_KEYS
// TODO: even better would be if pressure scores had unique IDs and we could use the species ID +
// some modification marker as the hash input here
var key = (ulong)(uint)pressure.GetHashCode() << 32 | (uint)species.GetHashCode();
// Use a big prime to shuffle the hash to hopefully avoid collisions
key *= 11265003396083139817;
key += (ulong)patch.ID;
key *= 13900709095051265681;
#else
var key = (species, pressure, patch);
#endif
ref var score = ref CollectionsMarshal.GetValueRefOrNullRef(cachedPressureScores, key);
if (!Unsafe.IsNullRef(ref score))
{
return score;
}
var cached = pressure.Score(species, patch, this);
cachedPressureScores.Add(key, cached);
return cached;
}
public EnergyBalanceInfoSimple GetEnergyBalanceForSpecies(MicrobeSpecies species,
BiomeConditions biomeConditions)
{
// TODO: this gets called an absolute ton with the new auto-evo so a more efficient caching method (to allow
// different species but with same organelles to be able to use the same cache value) would be nice here
#if USE_HASHED_SCORE_KEYS
var key = (ulong)(uint)biomeConditions.GetHashCode() << 32 | (uint)species.GetHashCode();
#else
var key = (species, biomeConditions);
#endif
ref var balance = ref CollectionsMarshal.GetValueRefOrNullRef(cachedSimpleEnergyBalances, key);
if (!Unsafe.IsNullRef(ref balance))
{
return balance;
}
var maximumMovementDirection = MicrobeInternalCalculations.MaximumSpeedDirection(species.Organelles);
// TODO: check if caching instances of these objects would be better than always recreating
var cached = new EnergyBalanceInfoSimple();
// Assume here that the species specialization factor may not be up to date, so recalculate here
var specialization = MicrobeInternalCalculations.CalculateSpecializationBonus(species.Organelles, workMemory1);
// Auto-evo uses the average values of compound during the course of a simulated day
ProcessSystem.ComputeEnergyBalanceSimple(species.Organelles, biomeConditions,
GetEnvironmentalTolerances(species, biomeConditions), specialization, species.MembraneType,
maximumMovementDirection, true, species.PlayerSpecies, worldSettings, CompoundAmountType.Average, this,
cached);
cachedSimpleEnergyBalances.Add(key, cached);
return cached;
}
// TODO: Both of these seem like something that could easily be stored on the species with OnEdited
// And also *not* caching them at all is much slower (so if not cached in species, they must be cached here)
public float GetSpeedForSpecies(MicrobeSpecies species)
{
ref var speed = ref CollectionsMarshal.GetValueRefOrNullRef(cachedBaseSpeeds, species);
if (!Unsafe.IsNullRef(ref speed))
{
return speed;
}
var cached = MicrobeInternalCalculations.CalculateSpeed(species.Organelles.Organelles, species.MembraneType,
species.MembraneRigidity, species.IsBacteria, true);
cachedBaseSpeeds.Add(species, cached);
return cached;
}
public float GetBaseHexSizeForSpecies(MicrobeSpecies species)
{
ref var size = ref CollectionsMarshal.GetValueRefOrNullRef(cachedBaseHexSizes, species);
if (!Unsafe.IsNullRef(ref size))
{
return size;
}
var cached = species.BaseHexSize;
cachedBaseHexSizes.Add(species, cached);
return cached;
}
public float GetRotationSpeedForSpecies(MicrobeSpecies species)
{
// TODO: this might be useful to cache though this is just used from a single place (though targeted
// prey species by multiple predators might benefit ever so slightly, but it seems kind of unlikely).
// A more useful thing would be to cache this directly in the species when calculating other movement cached
// properties.
return MicrobeInternalCalculations.CalculateRotationSpeed(species.Organelles.Organelles);
}
public float GetCompoundConversionScoreForSpecies(CompoundDefinition fromCompound, CompoundDefinition toCompound,
MicrobeSpecies species)
{
// This method is faster when not using caching
// With cache: 3 925 ms for 1,470 million calls
// Without caching: 2 284 ms for 1,291 million calls
var compoundIn = 0.0f;
var compoundOut = 0.0f;
var activeProcessList = GetActiveProcessList(species);
// For maximum efficiency, as this is called an absolute ton, the following approach is used
foreach (var process in activeProcessList)
{
if (process.Process.Inputs.TryGetValue(fromCompound, out var inputAmount))
{
if (process.Process.Outputs.TryGetValue(toCompound, out var outputAmount))
{
// We don't multiply by speed here as it is about pure efficiency
compoundIn += inputAmount;
compoundOut += outputAmount;
}
}
}
float cached;
if (compoundIn <= 0)
{
cached = 0;
}
else
{
cached = compoundOut / compoundIn;
}
return cached;
}
public float GetCompoundGeneratedFrom(CompoundDefinition fromCompound, CompoundDefinition toCompound,
MicrobeSpecies species, BiomeConditions biomeConditions)
{
// This method is faster when not using caching
// With cache: 2 408 ms for 776 344 calls
// Without caching: 1 257 ms for 680 411 calls
var cached = 0.0f;
var activeProcessList = GetActiveProcessList(species);
var tolerances = GetEnvironmentalTolerances(species, biomeConditions);
foreach (var process in activeProcessList)
{
if (process.Process.Inputs.ContainsKey(fromCompound))
{
if (process.Process.Outputs.TryGetValue(toCompound, out var outputAmount))
{
var processSpeed =
GetProcessMaximumSpeed(process, tolerances.ProcessSpeedModifier, biomeConditions)
.CurrentSpeed;
cached += outputAmount * processSpeed;
}
}
}
return cached;
}
/// <summary>
/// Calculates a maximum speed for a process that can happen given the environmental. Environmental compounds
/// are always used at the average amount in auto-evo.
/// </summary>
/// <param name="process">The process to calculate the speed for</param>
/// <param name="speedModifier">
/// Process speed modifier from <see cref="ResolvedMicrobeTolerances.ProcessSpeedModifier"/>
/// </param>
/// <param name="biomeConditions">The biome conditions to use</param>
/// <returns>The speed information for the process</returns>
/// <remarks>
/// <para>
/// This is important to cache as it is called very many times, but the speed modifier slightly reduces
/// the cache usefulness.
/// </para>
/// </remarks>
public ProcessSpeedInformation GetProcessMaximumSpeed(TweakedProcess process, float speedModifier,
IBiomeConditions biomeConditions)
{
// For caching resolve some data already to have better cache hits
var effectiveMultiplier = process.Rate * speedModifier;
// 16 low bits of the key (as process amounts are limited, we save bits on them)
ulong key = process.Process.ProcessId;
// These slightly overlap, but hopefully this doesn't lead to collisions (the most significant effect would be
// just a process or two running at the wrong speed)
// The overlap is 16 bits of the upper end of the float
key |= (ulong)(uint)BitConverter.SingleToInt32Bits(effectiveMultiplier) << 16;
key ^= (ulong)(uint)biomeConditions.GetHashCode() << 32;
// Shuffle key bits with a prime number (we could do a double shuffle above, but processes are needed so much
// that we do not want the extra work)
key *= 9853659385249210933;
ref var speed = ref CollectionsMarshal.GetValueRefOrNullRef(cachedProcessSpeeds, key);
if (!Unsafe.IsNullRef(ref speed))
{
#if VERIFY_PROCESS_SPEED_CACHE_RETURNS
if (speed.Process != process.Process)
throw new Exception("Cached process speed does not match requested process");
#endif
return speed;
}
// TODO: cache process speed information objects?
var cached = ProcessSystem.CalculateProcessMaximumSpeed(process, speedModifier, biomeConditions,
CompoundAmountType.Average, true);
cachedProcessSpeeds.Add(key, cached);
return cached;
}
public float GetPredationScore(Species predatorSpecies, Species preySpecies, BiomeConditions biomeConditions)
{
if (predatorSpecies is not MicrobeSpecies predator)
return 0;
if (preySpecies is not MicrobeSpecies prey)
return 0;
// No cannibalism
if (predator == prey)
{
return 0.0f;
}
var key = (microbeSpecies: predator, prey, biomeConditions);
ref var score = ref CollectionsMarshal.GetValueRefOrNullRef(predationScores, key);
if (!Unsafe.IsNullRef(ref score))
{
return score;
}
var cached = 0.0f;
// First values necessary to check whether predation is possible at all
var predatorToolScores = GetPredationToolsRawScores(predator);
var pilusScore = predatorToolScores.PilusScore;
var injectisomeScore = predatorToolScores.InjectisomeScore;
var oxytoxyScore = predatorToolScores.OxytoxyScore;
var cytotoxinScore = predatorToolScores.CytotoxinScore;
var channelInhibitorScore = predatorToolScores.ChannelInhibitorScore;
var canEngulf = predator.CanEngulf;
// Don't bother with the rest if the predator cannot predate
var engulfOnly = false;
if (pilusScore == 0 &&
injectisomeScore == 0 &&
oxytoxyScore == 0 &&
cytotoxinScore == 0 &&
channelInhibitorScore == 0)
{
if (canEngulf)
{
engulfOnly = true;
}
else
{
predationScores.Add(key, cached);
return cached;
}
}
var predatorHexSize = GetBaseHexSizeForSpecies(predator);
var preyHexSize = GetBaseHexSizeForSpecies(prey);
var enzymesScore = GetEnzymesScore(predator, prey.MembraneType.DissolverEnzyme);
var canDigestPrey = predatorHexSize / preyHexSize > Constants.ENGULF_SIZE_RATIO_REQ && canEngulf &&
enzymesScore > 0.0f;
if (engulfOnly && !canDigestPrey)
{
cached = 0;
predationScores.Add(key, cached);
return cached;
}
// Constants
var sprintMultiplier = Constants.SPRINTING_FORCE_MULTIPLIER;
var sprintingStrain = Constants.SPRINTING_STRAIN_INCREASE_PER_SECOND / 5;
var strainPerHex = Constants.SPRINTING_STRAIN_INCREASE_PER_HEX / 5;
var sizeAffectedProjectileMissFactor = Constants.AUTO_EVO_SIZE_AFFECTED_PROJECTILE_MISS_FACTOR;
var toxicityHitModifier = Constants.AUTO_EVO_TOXICITY_HIT_MODIFIER;
var oxytoxyDebuffPerOrganelle = Constants.OXYTOXY_DAMAGE_DEBUFF_PER_ORGANELLE;
var oxytoxyDebuffMax = Constants.OXYTOXY_DAMAGE_DEBUFF_MAX;
var oxygenInhibitorBuffPerOrganelle = Constants.OXYGEN_INHIBITOR_DAMAGE_BUFF_PER_ORGANELLE;
var oxygenInhibitorBuffMax = Constants.OXYGEN_INHIBITOR_DAMAGE_BUFF_MAX;
var oxytoxyDamage = Constants.OXYTOXY_DAMAGE;
var channelInhibitorATPDebuff = Constants.CHANNEL_INHIBITOR_ATP_DEBUFF;
var signallingBonus = Constants.AUTO_EVO_SIGNALLING_BONUS;
// We want prey defensive measures to only reduce predation score, not eliminate it.
// (Predation Score is reduced to 0 anyway if the "prey" has a higher predation score to the predator)
var defenseScoreModifier = Constants.AUTO_EVO_PREDATION_DEFENSE_SCORE_MODIFIER;
// TODO: If these two methods were combined it might result in better performance with needing just
// one dictionary lookup
var predatorSpeed = GetSpeedForSpecies(predator);
var predatorRotationSpeed = GetRotationSpeedForSpecies(predator);
var predatorEnergyBalance = GetEnergyBalanceForSpecies(predator, biomeConditions);
var predatorOsmoregulationCost = predatorEnergyBalance.Osmoregulation;
var preySpeed = GetSpeedForSpecies(prey);
var preyRotationSpeed = GetRotationSpeedForSpecies(prey);
var slowedPreySpeed = preySpeed;
var preyIndividualCost = MichePopulation.CalculateMicrobeIndividualCost(prey, biomeConditions, this);
var preyEnergyBalance = GetEnergyBalanceForSpecies(prey, biomeConditions);
var preyOsmoregulationCost = preyEnergyBalance.Osmoregulation;
// uses an HP estimate without taking into account environmental tolerance effect
var predatorHP = predator.MembraneType.Hitpoints + predator.MembraneRigidity *
Constants.MEMBRANE_RIGIDITY_HITPOINTS_MODIFIER;
var preyHP = prey.MembraneType.Hitpoints + prey.MembraneRigidity *
Constants.MEMBRANE_RIGIDITY_HITPOINTS_MODIFIER;
var preyToolScores = GetPredationToolsRawScores(prey);
var toxicity = predatorToolScores.AverageToxicity;
var macrolideScore = predatorToolScores.MacrolideScore;
var oxygenMetabolismInhibitorScore = predatorToolScores.OxygenMetabolismInhibitorScore;
var predatorSlimeJetScore = predatorToolScores.SlimeJetScore;
var pullingCiliaModifier = predatorToolScores.PullingCiliaModifier;
var strongPullingCiliaModifier = pullingCiliaModifier * pullingCiliaModifier;
var predatorToxinResistance = predator.MembraneType.ToxinResistance;
var predatorPhysicalResistance = predator.MembraneType.PhysicalResistance;
var preySlimeJetScore = preyToolScores.SlimeJetScore;
var preyMucocystsScore = preyToolScores.MucocystsScore;
var preyPilusScore = preyToolScores.PilusScore;
var preyInjectisomeScore = preyToolScores.InjectisomeScore;
var preyToxicity = preyToolScores.AverageToxicity;
var preyOxytoxyScore = preyToolScores.OxytoxyScore;
var preyCytotoxinScore = preyToolScores.CytotoxinScore;
var preyMacrolideScore = preyToolScores.MacrolideScore;
var preyChannelInhibitorScore = preyToolScores.ChannelInhibitorScore;
var preyOxygenMetabolismInhibitorScore = preyToolScores.OxygenMetabolismInhibitorScore;
var defensivePilusScore = preyToolScores.DefensivePilusScore;
var defensiveInjectisomeScore = preyToolScores.DefensiveInjectisomeScore;
var preyToxinResistance = prey.MembraneType.ToxinResistance;
// Not an ideal solution, but accounts for the fact that the oxytoxy and cyanide processes require oxygen to run
biomeConditions.Compounds.TryGetValue(Compound.Oxygen, out BiomeCompoundProperties oxygen);
if (oxygen.Ambient == 0)
{
oxytoxyScore = 0;
preyOxytoxyScore = 0;
oxygenMetabolismInhibitorScore = 0;
preyOxygenMetabolismInhibitorScore = 0;
}
var aggressionScore = predator.Behaviour.Aggression / Constants.MAX_SPECIES_AGGRESSION;
var activityScore = predator.Behaviour.Activity / Constants.MAX_SPECIES_ACTIVITY;
var preyFearScore = prey.Behaviour.Fear / Constants.MAX_SPECIES_FEAR;
var preyAggressionScore = prey.Behaviour.Aggression / Constants.MAX_SPECIES_AGGRESSION;
var preyOpportunismScore = prey.Behaviour.Opportunism / Constants.MAX_SPECIES_OPPORTUNISM;
// prey's effectiveness at running away depends on how quickly they choose to run away
preySpeed *= preyFearScore;
// Sprinting calculations
var predatorSprintSpeed = predatorSpeed * sprintMultiplier;
var predatorSprintConsumption = sprintingStrain + predatorHexSize * strainPerHex;
var predatorSprintTime = MathF.Max(predatorEnergyBalance.FinalBalance / predatorSprintConsumption, 0.0f);
var preySprintSpeed = preySpeed * sprintMultiplier;
var preySprintConsumption = sprintingStrain + preyHexSize * strainPerHex;
var preySprintTime = MathF.Max(preyEnergyBalance.FinalBalance / preySprintConsumption, 0.0f);
// Give damage resistance if you have a nucleus (50 % general damage resistance)
if (!predator.IsBacteria)
predatorHP *= 2;
if (!prey.IsBacteria)
preyHP *= 2;
// This makes rotation "speed" not matter until the editor shows ~300,
// which is where it also becomes noticeable in-game.
// The mechanical microbe rotation speed value is reverse to intuitive: higher value means slower turning.
// (The editor reverses this to make it intuitive to the player)
var predatorRotationModifier = float.Min(1.0f, 1.5f - predatorRotationSpeed * 1.45f);
var preyRotationModifier = float.Min(1.0f, 1.5f - preyRotationSpeed * 1.45f);
// Simple estimation of slime jet propulsion.
var predatorSlimeSpeed = predatorSpeed + predatorSlimeJetScore / (predatorHexSize * 11);
var preySlimeSpeed = preySpeed + preySlimeJetScore / (preyHexSize * 11);
var hasChemoreceptor = false;
var hasSignallingAgent = false;
var preyHasSignallingAgent = false;
var predatorOxygenUsingOrganellesCount = 0;
var preyOxygenUsingOrganellesCount = 0;
var organelles = predator.Organelles.Organelles;
int count = organelles.Count;
for (int i = 0; i < count; ++i)
{
var organelle = organelles[i];
if (organelle.Definition.HasChemoreceptorComponent && organelle.GetActiveTargetSpecies() == prey)
hasChemoreceptor = true;
if (organelle.Definition.HasSignalingFeature)
hasSignallingAgent = true;
if (organelles[i].Definition.IsOxygenMetabolism)
++predatorOxygenUsingOrganellesCount;
}
var preyOrganelles = prey.Organelles.Organelles;
int preyOrganellesCount = preyOrganelles.Count;
for (int i = 0; i < preyOrganellesCount; ++i)
{
var organelle = preyOrganelles[i];
if (organelle.Definition.HasSignalingFeature)
preyHasSignallingAgent = true;
if (preyOrganelles[i].Definition.IsOxygenMetabolism)
++preyOxygenUsingOrganellesCount;
}
// Calculating "hit chance" modifier from prey size and predator toxicity
var sizeHitFactor = sizeAffectedProjectileMissFactor / float.Sqrt(preyHexSize);
var toxicityHitFactor = toxicity / toxicityHitModifier;
var hitProportion = 1 - sizeHitFactor - toxicityHitFactor;
// Calculating prey energy production altered by channel inhbitor
var preyInhibitedPreyEnergyProduction = preyEnergyBalance.TotalProduction;
if (channelInhibitorScore > 0)
{
preyInhibitedPreyEnergyProduction *= 1 - channelInhibitorATPDebuff *
MicrobeEmissionSystem.ToxinAmountMultiplierFromToxicity(toxicity, ToxinType.ChannelInhibitor);
// If inhibited energy production affects movement,
// add (part of) the inhibitor score to macrolide score
if (preyInhibitedPreyEnergyProduction < preyEnergyBalance.TotalConsumption)
{
var channelInhibitorSlowFactor = Math.Min(
Math.Max(preyInhibitedPreyEnergyProduction - preyOsmoregulationCost, 0) /
preyEnergyBalance.TotalMovement, 1);
macrolideScore += channelInhibitorScore * channelInhibitorSlowFactor;
slowedPreySpeed *= 1 - channelInhibitorSlowFactor;
}
}
// Calculating predator energy production altered by channel inhbitor
var predatorInhibitedPreyEnergyProduction = predatorEnergyBalance.TotalProduction;
if (preyChannelInhibitorScore > 0)
{
predatorInhibitedPreyEnergyProduction *= 1 - channelInhibitorATPDebuff *
MicrobeEmissionSystem.ToxinAmountMultiplierFromToxicity(preyToxicity, ToxinType.ChannelInhibitor);
}
// Calculating how much prey is slowed down by macrolide, and how frequently they are succesfully slowed down
var slowedProportion = 0.0f;
if (macrolideScore > 0)
{
slowedPreySpeed *= 1 - Constants.MACROLIDE_BASE_MOVEMENT_DEBUFF *
MicrobeEmissionSystem.ToxinAmountMultiplierFromToxicity(toxicity, ToxinType.Macrolide);
slowedProportion = 1.0f - MathF.Exp(-Constants.AUTO_EVO_TOXIN_AFFECTED_PROPORTION_SCALING *
macrolideScore * hitProportion);
}
// Catch scores grossly accounts for how many preys you catch in melee in a run;
var catchScore = 0.0f;
var accidentalCatchScore = 0.0f;
// Only calculate catch score if one can actually engulf (and digest) or use pili
var engulfmentScore = 0.0f;
if (canDigestPrey || pilusScore > 0.0f || injectisomeScore > 0.0f)
{
// First, you may hunt individual preys, but only if you are fast enough...
if (predatorSpeed > preySpeed)
{
// You catch more preys if you are fast, and if they are slow.
// This incentivizes engulfment strategies in these cases.
// Sigmoidal calculation to avoid divisions by zero
catchScore += (predatorSpeed + 0.001f) / (preySpeed + 0.0001f) * (1 - slowedProportion);
}
// If you can slow the target, some proportion of prey are easier to catch
if (predatorSpeed > slowedPreySpeed)
{
catchScore += (predatorSpeed + 0.001f) / (slowedPreySpeed + 0.0001f) * slowedProportion;
}
// Sprinting can help catch prey.
if (predatorSprintSpeed > preySpeed)
{
catchScore += (predatorSprintSpeed + 0.001f) / (preySpeed + 0.0001f) * (1 - slowedProportion) *
predatorSprintTime;
}
if (predatorSprintSpeed > slowedPreySpeed)
{
catchScore += (predatorSprintSpeed + 0.001f) / (slowedPreySpeed + 0.0001f) * slowedProportion *
predatorSprintTime;
}
// Sprinting can also help prey escape.
if (preySprintSpeed > predatorSpeed)
{
catchScore -= (preySprintSpeed + 0.001f) / (predatorSpeed + 0.0001f) * preySprintTime;
}
// If you have Slime Jets, this can help you catch targets.
if (predatorSlimeSpeed > preySpeed)
{
catchScore += (predatorSlimeSpeed + 0.001f) / (preySpeed + 0.0001f) * (1 - slowedProportion);
}
if (predatorSlimeSpeed > slowedPreySpeed)
{
catchScore += (predatorSlimeSpeed + 0.001f) / (slowedPreySpeed + 0.0001f) * slowedProportion;
}
// Having Slime Jets can also help prey escape.
if (preySlimeSpeed > predatorSpeed)
{
catchScore += (preySlimeSpeed + 0.001f) / (predatorSpeed + 0.0001f);
}
// prevent potential negative catchScore.
catchScore = MathF.Max(catchScore, 0);
// But prey may escape if they move away before you can turn to chase them
catchScore *= predatorRotationModifier;
// Pulling Cilia help with catching
catchScore *= pullingCiliaModifier;
// If you have a chemoreceptor, active hunting types are more effective
if (hasChemoreceptor)
{
catchScore *= Constants.AUTO_EVO_CHEMORECEPTOR_PREDATION_BASE_MODIFIER;
// Uses crude estimate of population density assuming same energy capture
catchScore *= 1 + Constants.AUTO_EVO_CHEMORECEPTOR_PREDATION_VARIABLE_MODIFIER
* float.Sqrt(preyIndividualCost);
}
// Active hunting is more effective for active species
catchScore *= activityScore;
// ... but you may also catch them by luck (e.g. when they run into you),
// Prey that can't turn away fast enough are more likely to get caught.
accidentalCatchScore = Constants.AUTO_EVO_ENGULF_LUCKY_CATCH_PROBABILITY *
strongPullingCiliaModifier * preyRotationModifier;
}
// targets that resist physical damage are of course less vulnerable to it
pilusScore /= preyHP * prey.MembraneType.PhysicalResistance;
preyPilusScore /= predatorHP * predatorPhysicalResistance;
defensivePilusScore /= predatorHP * predatorPhysicalResistance;
// But targets that resist toxin damage are less vulnerable to the injectisome
injectisomeScore /= preyHP * preyToxinResistance;
preyInjectisomeScore /= predatorHP * predatorToxinResistance;
defensiveInjectisomeScore /= predatorHP * predatorToxinResistance;
// Combine pili for further calculations
pilusScore += injectisomeScore;
preyPilusScore += preyInjectisomeScore;
defensivePilusScore += defensiveInjectisomeScore;
// defensive pili need to be turned directly away from the predator to work
defensivePilusScore *= preyRotationModifier * preyFearScore;
// Calling for allies helps with combat.
if (hasSignallingAgent)
pilusScore *= signallingBonus;
if (preyHasSignallingAgent)
preyPilusScore *= signallingBonus;
// Use catch score for Pili
pilusScore -= defensivePilusScore;
if (pilusScore < 0)
pilusScore = 0;
pilusScore *= catchScore + accidentalCatchScore;
// Prey can use offensive pili for defense in these encounters, but only if they have the right behaviour
preyPilusScore *= (catchScore + accidentalCatchScore) * preyRotationModifier * defenseScoreModifier *
preyAggressionScore * (1 - preyFearScore);
if (canDigestPrey)
{
// total prey toxin amount for anti-engulfment purposes
// Toxin content is higher if the toxin are not being shot for offense
var totalPreyToxinContent = preyOxytoxyScore + preyCytotoxinScore + preyMacrolideScore +
preyChannelInhibitorScore + preyOxygenMetabolismInhibitorScore;
totalPreyToxinContent *= (1 - preyAggressionScore) + preyAggressionScore;
if (predatorHexSize > preyHexSize)
{
totalPreyToxinContent *= 1 - preyOpportunismScore * preyAggressionScore * (1 - preyFearScore);
}
else
{
totalPreyToxinContent *= 1 - preyAggressionScore * (1 - preyFearScore);
}
totalPreyToxinContent *= Constants.AUTO_EVO_TOXIN_ENGULFMENT_DEFENSE_MODIFIER;
totalPreyToxinContent /= predatorHP;
// Final engulfment score calculation
// Engulfing prey by luck is especially easy if you are huge.
// This is also used to incentivize size in microbe species.
engulfmentScore = (catchScore + accidentalCatchScore * predatorHexSize) *
(Constants.AUTO_EVO_ENGULF_PREDATION_SCORE - defensivePilusScore - totalPreyToxinContent);
if (engulfmentScore < 0)
engulfmentScore = 0;
engulfmentScore *= enzymesScore;
}
// Damaging toxin section
oxytoxyScore *= 1 - Math.Min(preyOxygenUsingOrganellesCount * oxytoxyDebuffPerOrganelle, oxytoxyDebuffMax);
oxygenMetabolismInhibitorScore *= 1 + Math.Min(preyOxygenUsingOrganellesCount * oxygenInhibitorBuffPerOrganelle,
oxygenInhibitorBuffMax);
var damagingToxinScore = oxytoxyScore + cytotoxinScore + oxygenMetabolismInhibitorScore;
preyOxytoxyScore *= 1 - Math.Min(predatorOxygenUsingOrganellesCount * oxytoxyDebuffPerOrganelle,
oxytoxyDebuffMax);
preyOxygenMetabolismInhibitorScore *= 1 + Math.Min(
predatorOxygenUsingOrganellesCount * oxygenInhibitorBuffPerOrganelle, oxygenInhibitorBuffMax);
var preyDamagingToxinScore = preyOxytoxyScore + preyCytotoxinScore + preyOxygenMetabolismInhibitorScore;
// If toxin-inhibited energy production is lower than osmoregulation cost, channel inhibitor is a damaging toxin
if (preyInhibitedPreyEnergyProduction < preyOsmoregulationCost)
damagingToxinScore += channelInhibitorScore;
if (predatorInhibitedPreyEnergyProduction < predatorOsmoregulationCost)
damagingToxinScore += channelInhibitorScore;
if (damagingToxinScore > 0)
{
// Applying projectile hit chance to damaging toxins
damagingToxinScore *= hitProportion;
// Predators are less likely to use toxin against larger prey, unless they are opportunistic
if (preyHexSize > predatorHexSize)
{
damagingToxinScore *= predator.Behaviour.Opportunism / Constants.MAX_SPECIES_OPPORTUNISM;
}
// If you can store enough to kill the prey, producing more isn't as important
var storageToKillRatio = predator.StorageCapacities.Nominal * oxytoxyDamage /
(preyHP * preyToxinResistance);
if (storageToKillRatio > 1)
{
damagingToxinScore = MathF.Pow(damagingToxinScore, 0.8f);
}
else
{
damagingToxinScore = MathF.Pow(damagingToxinScore, storageToKillRatio * 0.8f);
}
// Targets that resist toxin are of course less vulnerable to being damaged with it
damagingToxinScore /= preyHP * preyToxinResistance;
// Toxins also require facing and tracking the target
damagingToxinScore *= predatorRotationModifier;
// Calling for allies helps with combat.
if (hasSignallingAgent)
damagingToxinScore *= signallingBonus;
// If you have a chemoreceptor, active hunting types are more effective
if (hasChemoreceptor)
{
damagingToxinScore *= Constants.AUTO_EVO_CHEMORECEPTOR_PREDATION_BASE_MODIFIER;
damagingToxinScore *= 1 + Constants.AUTO_EVO_CHEMORECEPTOR_PREDATION_VARIABLE_MODIFIER
* float.Sqrt(preyIndividualCost);
}
// Active hunting is more effective for active species
damagingToxinScore *= activityScore;
}
if (preyDamagingToxinScore > 0)
{
// Calculating "hit chance" modifier from predator size and prey toxicity
var predatorSizeHitFactor = sizeAffectedProjectileMissFactor / float.Sqrt(predatorHexSize);
var preyToxicityHitFactor = preyToxicity / toxicityHitModifier;
var preyHitProportion = 1 - predatorSizeHitFactor - preyToxicityHitFactor;
// Applying projectile hit chance to damaging toxins
preyDamagingToxinScore *= preyHitProportion;
// Prey are less likely to use toxin against larger predators, unless they are opportunistic
if (predatorHexSize > preyHexSize)
{
damagingToxinScore *= predator.Behaviour.Opportunism / Constants.MAX_SPECIES_OPPORTUNISM;
}
// If you can store enough to kill the predator, producing more isn't as important
var preyStorageToKillRatio = prey.StorageCapacities.Nominal * oxytoxyDamage /
(predatorHP * predatorToxinResistance);
if (preyStorageToKillRatio > 1)
{
preyDamagingToxinScore = MathF.Pow(preyDamagingToxinScore, 0.8f);
}
else
{
preyDamagingToxinScore = MathF.Pow(preyDamagingToxinScore, preyStorageToKillRatio * 0.8f);
}
// Targets that resist toxin are of course less vulnerable to being damaged with it
preyDamagingToxinScore /= predatorHP * predatorToxinResistance;
// Toxins also require facing and tracking the target
preyDamagingToxinScore *= preyRotationModifier;
// Calling for allies helps with combat.
if (preyHasSignallingAgent)
preyDamagingToxinScore *= signallingBonus;
// Prey can use toxins for defense, but only if they have the right behaviour
preyDamagingToxinScore *= preyRotationModifier * defenseScoreModifier *
preyAggressionScore * (1 - preyFearScore);
}
var scoreMultiplier = 1.0f;
if (!canEngulf)
{
// If you can't engulf, you just get energy from the chunks leaking.
scoreMultiplier *= Constants.AUTO_EVO_CHUNK_LEAK_MULTIPLIER;
}
// predators that have slime jets themselves ignore the immobilising effect of prey slimejets
preySlimeJetScore = MathF.Sqrt(preySlimeJetScore);
if (predatorSlimeJetScore > 0)
preySlimeJetScore = 0;
cached = scoreMultiplier * aggressionScore *
(pilusScore + engulfmentScore + damagingToxinScore) - (preySlimeJetScore + preyMucocystsScore +
preyPilusScore + preyDamagingToxinScore);
if (cached < 0)
cached = 0;
predationScores.Add(key, cached);
return cached;
}
public bool GetUsesVaryingCompoundsForSpecies(MicrobeSpecies species, BiomeConditions biomeConditions)
{
// Disabling this cache makes this ever so slightly slower
var key = (species, biomeConditions);
ref var usesVarying = ref CollectionsMarshal.GetValueRefOrNullRef(cachedUsesVaryingCompounds, key);
if (!Unsafe.IsNullRef(ref usesVarying))
{
return usesVarying;
}
var cached = MicrobeInternalCalculations.UsesDayVaryingCompounds(species.Organelles, biomeConditions, null);
cachedUsesVaryingCompounds.Add(key, cached);
return cached;
}
public float GetChemoreceptorCloudScore(MicrobeSpecies species, CompoundDefinition compound,
BiomeConditions biomeConditions)
{
// This method is faster when not using caching
// With cache: 2 192 ms for 1,245 million calls
// Without caching: 762 ms for 1,096 million calls
var cached = 0.0f;
var hasChemoreceptor = false;
foreach (var organelle in species.Organelles.Organelles)
{
var organelleTargetCompound = organelle.GetActiveTargetCompound();
if (organelleTargetCompound == Compound.Invalid)
continue;
if (organelleTargetCompound == compound.ID)
hasChemoreceptor = true;
}
if (hasChemoreceptor)
{
if (biomeConditions.AverageCompounds.TryGetValue(compound.ID, out var compoundData) &&
compoundData.Density > 0)
{
cached = Constants.AUTO_EVO_CHEMORECEPTOR_BASE_SCORE
+ Constants.AUTO_EVO_CHEMORECEPTOR_VARIABLE_CLOUD_SCORE
/ (compoundData.Density * compoundData.Amount);
}
}
return cached;
}
public float GetChemoreceptorChunkScore(MicrobeSpecies species, ChunkConfiguration chunk,
CompoundDefinition compound)
{
// This method is faster when not using caching
// With cache: 3 977 ms for 2,005 million calls
// Without caching: 916 ms for 1,285 million calls
// Need to have chemoreceptor to be able to "smell" chunks
var cached = 0.0f;
var hasChemoreceptor = false;
foreach (var organelle in species.Organelles.Organelles)
{
var organelleTargetCompound = organelle.GetActiveTargetCompound();
if (organelleTargetCompound == Compound.Invalid)
continue;
if (organelleTargetCompound == compound.ID)
hasChemoreceptor = true;
}
// If the chunk doesn't spawn, it doesn't give any of its compound
if (hasChemoreceptor && chunk.Density > 0)
{
// We use null suppression here
// as this method is only meant to be called on chunks that are known to contain the given compound
if (!chunk.Compounds!.TryGetValue(compound.ID, out var compoundAmount))
throw new ArgumentException("Chunk does not contain compound");
cached = Constants.AUTO_EVO_CHEMORECEPTOR_BASE_SCORE
+ Constants.AUTO_EVO_CHEMORECEPTOR_VARIABLE_CHUNK_SCORE
/ (chunk.Density * MathF.Pow(compoundAmount.Amount, Constants.AUTO_EVO_CHUNK_AMOUNT_NERF));
}
return cached;
}
public bool MatchesSettings(WorldGenerationSettings checkAgainst)
{
return worldSettings.Equals(checkAgainst);
}
/// <summary>
/// Clears all data in this cache. Can be used to re-use a cache object *but should not be called* while anything
/// might still be using this cache currently!
/// </summary>
public void Clear()
{
cachedPressureScores.Clear();
cachedSimpleEnergyBalances.Clear();
cachedBaseSpeeds.Clear();
cachedBaseHexSizes.Clear();
predationScores.Clear();
cachedProcessSpeeds.Clear();
cachedPredationToolsRawScores.Clear();
cachedUsesVaryingCompounds.Clear();
cachedProcessLists.Clear();
}
public List<TweakedProcess> GetActiveProcessList(MicrobeSpecies microbeSpecies)
{
if (cachedProcessLists.TryGetValue(microbeSpecies, out var cached))
{
return cached;
}
// TODO: a buffer of process lists (to make small list allocations rarer) (as cached is null here if not found)
ProcessSystem.ComputeActiveProcessList(microbeSpecies.Organelles, ref cached);
cachedProcessLists.Add(microbeSpecies, cached);
return cached;
}
public PredationToolsRawScores GetPredationToolsRawScores(MicrobeSpecies microbeSpecies)
{
// Seems like this takes twice the amount of time from the predation score calculation if this is not cached,
// so this should definitely use caching.
ref var score = ref CollectionsMarshal.GetValueRefOrNullRef(cachedPredationToolsRawScores, microbeSpecies);
if (!Unsafe.IsNullRef(ref score))
{
return score;
}
var averageToxicity = 0.0f;
var totalToxicity = 0.0f;
var totalToxinScore = 0.0f;
var everyToxinScore = 0.0f;
var oxytoxyScore = 0.0f;
var cytotoxinScore = 0.0f;
var macrolideScore = 0.0f;
var channelInhibitorScore = 0.0f;
var oxygenMetabolismInhibitorScore = 0.0f;
var pilusScore = Constants.AUTO_EVO_PILUS_PREDATION_SCORE;
var injectisomeScore = Constants.AUTO_EVO_PILUS_PREDATION_SCORE;
var defensivePilusScore = Constants.AUTO_EVO_PILUS_DEFENSE_SCORE;
var defensiveInjectisomeScore = Constants.AUTO_EVO_PILUS_DEFENSE_SCORE;
var slimeJetScore = Constants.AUTO_EVO_SLIME_JET_SCORE;
var mucocystsScore = Constants.AUTO_EVO_MUCOCYST_SCORE;
var pullingCiliaModifier = 1.0f;
var organelles = microbeSpecies.Organelles.Organelles;
var organelleCount = organelles.Count;
var totalToxinOrganellesCount = 0;
var totalToxinTypesCount = 0;
var pilusCount = 0.0f;
var injectisomeCount = 0.0f;
var defensivePilusCount = 0.0f;
var defensiveInjectisomeCount = 0.0f;
var slimeJetsCount = 0;
var mucocystsCount = 0;
var pullingCiliasCount = 0;
var slimeJetsMultiplier = 1.0f;
var hasOxytoxy = false;
var hasCytotoxin = false;
var hasMacrolide = false;
var hasChannelInhibitor = false;
var hasOxygenMetabolismInhibitor = false;
for (int i = 0; i < organelleCount; ++i)
{
var organelle = organelles[i];
var organelleDefinition = organelle.Definition;
if (organelleDefinition.HasPilusComponent)
{
// Make sure that pili are positioned at the front of the cell for offensive action,
// and the back of the cell for defensive action