-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathtsorcRevampUtils.cs
More file actions
1538 lines (1372 loc) · 63.7 KB
/
tsorcRevampUtils.cs
File metadata and controls
1538 lines (1372 loc) · 63.7 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 Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Newtonsoft.Json;
using ReLogic.Graphics;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using Terraria;
using Terraria.Audio;
using Terraria.Chat;
using Terraria.DataStructures;
using Terraria.ID;
using Terraria.Localization;
using Terraria.ModLoader;
using Terraria.UI;
using tsorcRevamp.NPCs;
using tsorcRevamp.Projectiles;
using tsorcRevamp.Projectiles.VFX;
using tsorcRevamp.Items;
namespace tsorcRevamp
{
//using static tsorcRevamp.SpawnHelper;
public static class SpawnHelper
{
//undergroundJungle, undergroundEvil, and undergroundHoly are deliberately missing. call Cavern && p.zone instead.
public static bool Cavern(Player p)
{ //if youre calling Cavern without a p.zone check, also call NoSpecialBiome
return p.position.Y >= Main.rockLayer && p.position.Y <= Main.rockLayer * 25;
}
public static bool NoSpecialBiome(Player p)
{
return (!p.ZoneJungle && !p.ZoneCorrupt && !p.ZoneCrimson && !p.ZoneHallow && !p.ZoneMeteor && !p.ZoneDungeon);
}
public static bool Sky(Player p)
{ //p.ZoneSkyHeight is more restrictive than this, so use this if an enemy uses it
return p.position.Y < Main.worldSurface * 0.44999998807907104;
}
public static bool Surface(Player p)
{
return !Sky(p) && (p.position.Y < Main.worldSurface); //dont need to check nospecialbiome here since we're already calling Sky
}
public static bool Underground(Player p)
{
return Main.worldSurface > p.position.Y && p.position.Y < Main.rockLayer;
}
public static bool Underworld(Player p)
{
int playerYTile = (int)(p.Bottom.Y + 8f) / 16;
return playerYTile > Main.maxTilesY - 190;
}
}
//using static tsorcRevamp.oSpawnHelper;
public static class oSpawnHelper
{
public static bool oCavern(Player p)
{
return (p.position.Y >= (Main.rockLayer * 17)) && (p.position.Y < (Main.rockLayer * 24));
}
public static bool oCavernByTile(Player p)
{
int playerYTile = (int)(p.Bottom.Y + 8f) / 16;
return playerYTile >= (Main.maxTilesY * 0.4f) && playerYTile < (Main.maxTilesY * 0.6f);
}
public static bool oMagmaCavern(Player p)
{
return (p.position.Y >= (Main.rockLayer * 24)) && (p.position.Y < (Main.rockLayer * 32));
}
public static bool oMagmaCavernByTile(Player p)
{
int playerYTile = (int)(p.Bottom.Y + 8f) / 16;
return playerYTile >= (Main.maxTilesY * 0.6f) && playerYTile < (Main.maxTilesY * 0.8f);
}
public static bool oSky(Player p)
{
return p.position.Y <= Main.rockLayer * 4;
}
public static bool oSkyByTile(Player p)
{
int playerYTile = (int)(p.Bottom.Y + 8f) / 16;
return playerYTile < (Main.maxTilesY * 0.1f);
}
public static bool oSurface(Player p)
{
return !p.ZoneSkyHeight && (p.position.Y <= Main.worldSurface);
}
public static bool oUnderground(Player p)
{
return (p.position.Y >= (Main.rockLayer * 13)) && (p.position.Y < (Main.rockLayer * 17));
}
public static bool oUndergroundByTile(Player p)
{
int playerYTile = (int)(p.Bottom.Y + 8f) / 16;
return playerYTile >= (Main.maxTilesY * 0.3f) && playerYTile < (Main.maxTilesY * 0.4f);
}
public static bool oUnderSurface(Player p)
{
return (p.position.Y > (Main.rockLayer * 8)) && (p.position.Y < (Main.rockLayer * 13));
}
public static bool oUnderSurfaceByTile(Player p)
{
int playerYTile = (int)(p.Bottom.Y + 8f) / 16;
return (playerYTile >= (Main.maxTilesY * 0.2f) && playerYTile < (Main.maxTilesY * 0.3f));
}
public static bool oUnderworld(Player p)
{
return p.position.Y >= (Main.rockLayer * 32);
}
public static bool oUnderworldByHeight(Player p)
{
int playerYTile = (int)(p.Bottom.Y + 8f) / 16;
return (playerYTile >= (Main.maxTilesY * 0.8f));
}
}
public static class VariousConstants
{
public const int CUSTOM_MAP_WORLD_ID = 44874972;
public const string MUSIC_MOD_URL = "https://github.com/timhjersted/tsorcDownload/raw/1.4.4/tsorcMusic.tmod";
public const string MAP_URL = "https://github.com/timhjersted/tsorcDownload/raw/1.4.4/the-story-of-red-cloud.wld";
public const string MAP_REMIX_URL = "https://github.com/timhjersted/tsorcDownload/raw/1.4.4/the-story-of-red-cloud-xelvaa-remix.wld";
public const string CHANGELOG_URL = "https://raw.githubusercontent.com/timhjersted/tsorcDownload/1.4.4/changelog.txt";
}
public static class PriceByRarity
{
//minimal exploration. pre-hardmode ores. likely no items that craft from souls will use this
public static readonly int White_0 = Item.buyPrice(platinum: 0, gold: 0, silver: 40, copper: 0);
//underground chest loots (shoe spikes, CiaB, etc), shadow orb items, floating island
public static readonly int Blue_1 = Item.buyPrice(platinum: 0, gold: 1, silver: 25, copper: 0);
//gold dungeon chest (handgun, cobalt shield, etc), goblin invasion
public static readonly int Green_2 = Item.buyPrice(platinum: 0, gold: 2, silver: 50, copper: 0);
//hell, underground jungle
public static readonly int Orange_3 = Item.buyPrice(platinum: 0, gold: 3, silver: 50, copper: 0);
//early hardmode (hm ores), mimics
public static readonly int LightRed_4 = Item.buyPrice(platinum: 0, gold: 12, silver: 50, copper: 0);
//hallowed tier. post mech, pre plantera. pirates.
public static readonly int Pink_5 = Item.buyPrice(platinum: 0, gold: 18, silver: 50, copper: 0);
//some biome mimic gear, high level tinkerer combinations (ankh charm, mechanical glove). seldom used in vanilla
public static readonly int LightPurple_6 = Item.buyPrice(platinum: 0, gold: 24, silver: 50, copper: 0);
//plantera, golem, chlorophyte
public static readonly int Lime_7 = Item.buyPrice(platinum: 0, gold: 30, silver: 50, copper: 0);
//post-plantera dungeon, martian madness, pumpkin/frost moon
public static readonly int Yellow_8 = Item.buyPrice(platinum: 0, gold: 36, silver: 0, copper: 0);
//lunar fragments, dev armor. seldom used in vanilla
public static readonly int Cyan_9 = Item.buyPrice(platinum: 0, gold: 42, silver: 50, copper: 0);
//luminite, lunar fragment gear, moon lord drops
public static readonly int Red_10 = Item.buyPrice(platinum: 0, gold: 48, silver: 0, copper: 0);
//no vanilla items have purple rarity base. only cyan and red with modifiers can be purple. im guessing on the price.
public static readonly int Purple_11 = Item.buyPrice(platinum: 0, gold: 54, silver: 0, copper: 0);
// Returns whether the value is within the lower and upper bounds, inclusive
public static bool InRange(int x, int lower, int upper)
{
return x >= lower && x <= upper;
}
public static int fromItem(Item item)
{
// Item has a vanilla rarity
if (InRange(item.rare, 0, 11))
{
return fromRarity(item.rare);
}
// These rarities are for post attraides content
if (item.rare == ModContent.RarityType<OrangeRed>() || item.rare == ModContent.RarityType<DarkBlue>())
{
return Red_10;
}
// Used for eternal potions
else if (item.rare == ModContent.RarityType<Pinky>())
{
return Yellow_8;
}
return White_0;
}
public static int fromRarity(int rarity)
{
switch (rarity)
{
case 0:
{
return White_0;
}
case 1:
{
return Blue_1;
}
case 2:
{
return Green_2;
}
case 3:
{
return Orange_3;
}
case 4:
{
return LightRed_4;
}
case 5:
{
return Pink_5;
}
case 6:
{
return LightPurple_6;
}
case 7:
{
return Lime_7;
}
case 8:
{
return Yellow_8;
}
case 9:
{
return Cyan_9;
}
case 10:
{
return Red_10;
}
case 11:
{
return Purple_11;
}
}
return 0;
}
}
public static class UsefulFunctions
{
///<summary>
///Gets the coordinates of the first solid thing a line fired in a certain direction will hit
///Counts both tiles and NPCs as solid
///Returns null if no collision
///This could be a lot faster and more accurate if necessary by simply bifurcating the distance repeatedly until the exact collision point is found
///That probably isn't necessary unless there's something that needs to run this every tick
///</summary>
///<param name="start">The start of the vector</param>
///<param name="direction">The direction it's aiming in</param>
///<param name="maxDistance">How far to search for</param>
///<param name="ignoreFriendly">Ignore town NPCs in collision checks</param>
public static Vector2 GetFirstCollision(Vector2 start, Vector2 direction, float maxDistance = 5000f, bool ignoreFriendly = false, bool ignoreNPCs = false)
{
direction.Normalize();
Vector2 unitVector = direction;
direction *= 10;
Vector2 currentPosition = direction * maxDistance / 10;
for (float distance = 0; distance <= maxDistance / 10f; distance += 0.5f)
{
currentPosition = start + (direction * distance);
if (!Collision.CanHit(start, 1, 1, currentPosition, 1, 1) && !Collision.CanHitLine(start, 1, 1, currentPosition, 1, 1))
{
currentPosition = start + (direction * (distance - 1));
break;
}
}
float closestCollision = maxDistance;
if (!ignoreNPCs)
{
for (int i = 0; i < Main.maxNPCs; i++)
{
if (Main.npc[i] == null || Main.npc[i].active == false)
{
continue;
}
if (ignoreFriendly && Main.npc[i].friendly) { continue; }
else
{
NPC npc = Main.npc[i];
float collision = maxDistance;
//Expand the enemy hitbox slightly to increase consistency
//Vector2 adjustedPosition = npc.position;
//Vector2 adjustedSize = npc.Size;
//adjustedSize *= 1.5f;
//adjustedPosition -= (adjustedSize - npc.Size) / 2;
if (Collision.CheckAABBvLineCollision(npc.position, npc.Size, start, currentPosition, 32, ref collision))
{
if (collision < closestCollision)
{
closestCollision = collision;
}
}
}
}
}
if (closestCollision < (start - currentPosition).Length())
{
currentPosition = start + (unitVector * closestCollision);
}
return currentPosition;
}
///<summary>
///Modifies a float between 0 and 1, and returns a 'softened' value between 0 and one calculated via the easing curve sin(x * pi/2)
///Useful for making smoother looking motion
///</summary>
///<param name="source">A float between 0 and 1</param>
public static float EasingCurve(float source)
{
return (float)Math.Sin(source * MathHelper.PiOver2);
}
///<summary>
///Just so I don't have to keep copying and pasting this
///</summary>
///<param name="center">The center of the flash</param>
public static void DespawnFlash(Vector2 center)
{
Projectile.NewProjectileDirect(new EntitySource_Misc("VFX"), center, Vector2.Zero, ModContent.ProjectileType<ShockwaveEffect>(), 0, 0, Main.myPlayer, 500, 60);
}
///<summary>
///Spawns a piece of gore simply
///Checks dedserv and calculates the randomness, reducing how much we have to type
///</summary>
///<param name="npc">A float between 0 and 1</param>
public static void SimpleGore(NPC npc, string path, float scale = 1, float speed = 6)
{
if (!Main.dedServ)
{
Vector2 vel = Main.rand.NextVector2Circular(speed, speed);
Gore.NewGore(npc.GetSource_Death(), npc.position, vel, npc.ModNPC.Mod.Find<ModGore>(path).Type, scale);
}
}
///<summary>
///Loads a texture, and ensures it stays loaded
///</summary>
///<param name="texture">The texture object</param>
///<param name="path">The path</param>
public static void EnsureLoaded(ref Texture2D texture, string path)
{
if (texture == null || texture.IsDisposed)
{
texture = (Texture2D)ModContent.Request<Texture2D>(path, ReLogic.Content.AssetRequestMode.ImmediateLoad);
}
}
///<summary>
///Returns the closest living player to a point
///</summary>
///<param name="point">The point to compare against</param>
public static Player GetClosestPlayer(Vector2 point)
{
int targetIndex = -1;
float targetDistance = float.MaxValue;
for (int i = 0; i < Main.maxPlayers; i++)
{
if (Main.player[i].active && !Main.player[i].dead)
{
float distance = Main.player[i].DistanceSQ(point);
if (distance < targetDistance)
{
targetIndex = i;
targetDistance = distance;
}
}
}
if (targetIndex >= 0)
{
return Main.player[targetIndex];
}
else
{
return null;
}
}
///<summary>
///Returns the closest living player to a point
///</summary>
///<param name="point">The point to compare against</param>
public static void TeleportEffects(Vector2 oldPosition, Vector2 newPosition, NPC npc, int DustID = DustID.FireworkFountain_Pink)
{
Vector2 diff = newPosition - oldPosition;
float length = diff.Length();
diff.Normalize();
Vector2 offset = Vector2.Zero;
for (int i = 0; i < length; i++)
{
offset += diff;
if (Main.rand.NextBool(2))
{
Vector2 dustPoint = offset;
dustPoint.X += Main.rand.NextFloat(-npc.width / 2, npc.width / 2);
dustPoint.Y += Main.rand.NextFloat(-npc.height / 2, npc.height / 2);
if (Main.rand.NextBool())
{
Dust.NewDustPerfect(oldPosition + dustPoint, 71, diff * 5, 200, default, 0.8f).noGravity = true;
}
else
{
Dust.NewDustPerfect(oldPosition + dustPoint, DustID, diff * 5, 200, default, 0.8f).noGravity = true;
}
}
}
}
///<summary>
///Returns a vector pointing from a source, to a target, with a speed.
///Simplifies basic projectile, enemy dash, etc aiming calculations to a single call.
///If "ballistic" is true it adjusts for gravity. Default is 0.1f, may be stronger or weaker for some projectiles though.
///</summary>
///<param name="source">The start point of the vector</param>
///<param name="target">The end point it is aiming towards</param>
///<param name="speed">The length of the resulting vector</param>
public static Vector2 Aim(Vector2 source, Vector2 target, float speed)
{
Vector2 distance = target - source;
if (distance == Vector2.Zero)
{
return Vector2.Zero;
}
distance.Normalize();
return distance * speed;
}
/// <summary>
/// Add an attack to this NPC. Requires calling SimpleProjectile in their AI for it to actually be executed
/// </summary>
/// <param name="npc">The NPC this is operating on</param>
///<param name="timerCap">How high does the timer have to be for it to shoot</param>
///<param name="projectileType">The ID of the projectile you want to shoot</param>
///<param name="projectileDamage">Damage of the projectile. Multiplied by 2 by default, and then 2 again in expert mode</param>
///<param name="projectileVelocity">Speed of the projectile</param>
///<param name="shootSound">The sound to play when shooting</param>
///<param name="projectileGravity">How much is the projectile's y velocity reduced each tick? Leave blank for default gravity, set to 0 for projectiles with no gravity, set it custom if your projectile has custom gravity</param>
///<param name="ai0">Lets you pass a value to the projectile's ai0</param>
///<param name="ai1">Lets you pass a value to the projectile's ai1</param>
///<param name="overshoot">Lets you make it aim somewhere offset from the player. Useful for making it lob projectiles above their head.</param>
///<param name="telegraphColor">The color of its telegraph flash. Defaults to white.</param>
///<param name="stopBeforeFiring">Should this NPC stop moving before firing?</param>
///<param name="needsLineOfSight">Does this NPC need line of sight to the player to shoot?</param>
///<param name="weight">The weight of this attack. Lower = less likely to occur and vice versa, default is 1</param>
///<param name="condition">The attack will only execute if this condition is true. Takes a lambda experession.</param>
public static void AddAttack(NPC npc, int timerCap, int projectileType, int projectileDamage, float projectileVelocity, SoundStyle? shootSound = null, float projectileGravity = 0.035f, float ai0 = 0, float ai1 = 0, Vector2? overshoot = null, Color? telegraphColor = null, bool stopBeforeFiring = true, bool needsLineOfSight = true, float weight = 1, Func<NPC, bool> condition = null)
{
npc.GetGlobalNPC<tsorcRevampGlobalNPC>().AttackList.Add(new tsorcRevampAIs.ProjectileData(projectileType, timerCap, projectileDamage, projectileVelocity, shootSound, projectileGravity, ai0, ai1, overshoot, telegraphColor, stopBeforeFiring, needsLineOfSight, weight, condition));
}
///<summary>
///Sets the camera of all players to focus on the selected point
///Moves toward it gradually to make it less jarring
///</summary>
///<param name="target">The target point</param>
///<param name="progress">What percent of the way the camera has moved toward the new point</param>
///<param name="lerpRate">The speed at which the camera moves toward it</param>
public static void SetAllCameras(Vector2 target, ref float progress, float lerpRate = 0.07f)
{
for (int i = 0; i < Main.maxPlayers; i++)
{
if (Main.player[i].active && !Main.player[i].dead)
{
Main.player[i].immuneTime = 60;
Main.player[i].immune = true;
tsorcRevampPlayer modPlayer = Main.player[i].GetModPlayer<tsorcRevampPlayer>();
modPlayer.OverrideCamera = true;
modPlayer.newScreenPosition = target;
modPlayer.progress = progress;
}
}
if (progress < 1)
{
progress += lerpRate;
}
else
{
progress = 1;
}
}
///<summary>
///Returns a vector pointing from a source, to a target, with a speed.
///Simplifies basic projectile, enemy dash, etc aiming calculations to a single call.
///If "ballistic" is true it adjusts for gravity. Default is 0.1f, may be stronger or weaker for some projectiles though.
///</summary>
///<param name="identity">The identity of the projectile</param>
///<param name="owner">The owner of the projectile</param>
public static int GetLocalWhoAmIFromIdentity(int identity, int owner)
{
for (int i = 0; i < Main.maxProjectiles; i++)
{
if (Main.projectile[i].identity == identity && Main.projectile[i].owner == owner && Main.projectile[i].active)
{
return i;
}
}
return -1;
}
public static int DecodeID(float encodedIdentity)
{
int encodedInt = (int)encodedIdentity;
int owner = encodedInt / 1000;
int identity = encodedInt % 1000;
return GetLocalWhoAmIFromIdentity(identity, owner);
}
public static float EncodeID(Projectile proj)
{
return EncodeID(proj.identity, proj.owner);
}
public static float EncodeID(int identity, int owner)
{
return (1000 * owner) + identity;
}
/*
public static float CreateUniqueIdentifier()
{
float newIdentifier = Main.rand.NextFloat(float.MinValue, float.MaxValue);
bool failed = false;
do
{
for (int i = 0; i < Main.maxProjectiles; i++)
{
if (Main.projectile[i].GetGlobalProjectile<tsorcGlobalProjectile>().UniqueIdentifier == newIdentifier)
{
newIdentifier = Main.rand.NextFloat(float.MinValue, float.MaxValue);
failed = true;
break;
}
}
} while (failed);
return newIdentifier;
}
public static int GetProjectileIndexFromIdentifier(float identifier)
{
for (int i = 0; i < Main.maxProjectiles; i++)
{
if (Main.projectile[i].GetGlobalProjectile<tsorcGlobalProjectile>().UniqueIdentifier == identifier)
{
return i;
}
}
return -1;
}*/
///<summary>
///Converts a Color to a floating point number
///Useful for passing one into places that require a float, such as a projectile ai array
///It must be unconverted before it can be used
///</summary>
///<param name="color">The color to be converted</param>
public static float ColorToFloat(Color color)
{
return BitConverter.UInt32BitsToSingle(color.PackedValue);
}
///<summary>
///Converts a Color to a floating point number
///Useful for passing one into places that require a float, such as a projectile ai array
///It must be unconverted before it can be used
///</summary>
///<param name="color">The color to be converted</param>
public static Color ColorFromFloat(float color)
{
Color outColor = new();
outColor.PackedValue = BitConverter.SingleToUInt32Bits(color);
return outColor;
}
///<summary>
///Returns a vector that indicates a true ballistic trajectory from a source to a target
///</summary>
///<param name="source">The start point of the vector</param>
///<param name="target">The end point it is aiming towards</param>
///<param name="speed">The initial speed of the projectile</param>
///<param name="gravity">How much does the projectile's Y velocity increase every tick? Default is fairly close for aiStyle 1 projectiles, but for true accuracy set it yourself in the projectile AI instead of using an aiStyle</param>
///<param name="highAngle">There are two solutions to this equation. This makes it return the higher arcing one. Does not work at *all* for projectiles with vanilla aiStyles</param>
///<param name="fallback">If this is set to true it will fall back to GenerateTargetingVector if it's mathematically impossible to hit its target. If not it will return Vector2.Zero so you can handle it yourself</param>
public static Vector2 BallisticTrajectory(Vector2 source, Vector2 target, float speed, float gravity = 0.035f, bool highAngle = false, bool fallback = true)
{
//This is where the fun begins
Vector2 diff = target - source;
diff.Y *= -1;
double calculation = (gravity * diff.X * diff.X) + (2 * speed * speed * diff.Y);
calculation *= gravity;
calculation = Math.Pow(speed, 4) - calculation;
calculation = Math.Sqrt(calculation);
double angle;
if (highAngle)
{
angle = Math.Atan(((speed * speed) + calculation) / (gravity * diff.X));
}
else
{
angle = Math.Atan(((speed * speed) - calculation) / (gravity * diff.X));
}
if (Double.IsNaN(angle))
{
if (fallback)
{
return Aim(source, target, speed);
}
else
{
return Vector2.Zero;
}
}
Vector2 velocity = new Vector2();
velocity.X = speed * (float)Math.Cos(angle);
velocity.Y = -speed * (float)Math.Sin(angle);
if (diff.X < 0)
{
velocity *= -1;
}
return velocity;
}
///<summary>
///Draws a projectile fully lit. Goes in PreDraw(), simply return false after calling it.
///</summary>
///<param name="spriteBatch">The currently open SpriteBatch</param>
///<param name="projectile">The projectile to be drawn</param>
///<param name="texture">An empty static Texture2D variable that this function can use to cache the projectile's texture.</param>
public static void DrawSimpleLitProjectile(Projectile projectile, ref Texture2D texture)
{
SpriteEffects spriteEffects = SpriteEffects.None;
if (projectile.spriteDirection == -1)
{
spriteEffects = SpriteEffects.FlipHorizontally;
}
if (texture == null || texture.IsDisposed)
{
texture = (Texture2D)ModContent.Request<Texture2D>(projectile.ModProjectile.Texture);
}
int frameHeight = texture.Height / Main.projFrames[projectile.type];
int startY = frameHeight * projectile.frame;
Rectangle sourceRectangle = new Rectangle(0, startY, texture.Width, frameHeight);
Vector2 origin = sourceRectangle.Size() / 2f;
Main.EntitySpriteDraw(texture,
projectile.Center - Main.screenPosition + new Vector2(0f, projectile.gfxOffY),
sourceRectangle, Color.White, projectile.rotation, origin, projectile.scale, spriteEffects, 0);
}
internal static Color RandomColor()
{
return new Color(Main.rand.Next(256), Main.rand.Next(256), Main.rand.Next(256));
}
///<summary>
///Spawns a ring of dust around a point
///</summary>
///<param name="center">Center of the dust ring</param>
///<param name="radius">Radius of the ring</param>
///<param name="dustID">ID of the dust to spawn</param>
///<param name="dustCount">How many to spawn per tick</param>
///<param name="dustSpeed">How fast dust should rotate</param>
public static void DustRing(Vector2 center, float radius, int dustID, int dustCount = 5, float dustSpeed = 2)
{
for (int j = 0; j < dustCount; j++)
{
Vector2 dir = Main.rand.NextVector2CircularEdge(radius, radius);
Vector2 dustPos = center + dir;
Vector2 dustVel = new Vector2(dustSpeed, 0).RotatedBy(dir.ToRotation() + MathHelper.Pi / 2);
Dust.NewDustPerfect(dustPos, dustID, dustVel, 200).noGravity = true;
}
}
///<summary>
///Checks if a point is within an ellipse
///</summary>
///<param name="point">Point to be checked</param>
///<param name="center">Centerpoint of the ellipse</param>
///<param name="width">How wide is the ellipse</param>
///<param name="height">How tall is the ellipse</param>
public static bool IsPointWithinEllipse(Vector2 point, Vector2 center, float width, float height)
{
float xTerm = ((point.X - center.X) * (point.X - center.X)) / (width * width);
float yTerm = ((point.Y - center.Y) * (point.Y - center.Y)) / (height * height);
if (xTerm + yTerm < 1)
{
return true;
}
else
{
return false;
}
}
///<summary>
///This syncs a few extra stats that the default SyncNPC does not
///</summary>
///<param name="npc">The NPC to be synced</param>
public static void SyncNPCExtraStats(NPC npc)
{
NetMessage.SendData(MessageID.SyncNPC, -1, -1, null, npc.whoAmI);
//TODO: Sync maxLife, defense, damage, value
ModPacket npcExtrasPacket = ModContent.GetInstance<tsorcRevamp>().GetPacket();
npcExtrasPacket.Write(tsorcPacketID.SyncNPCExtras);
npcExtrasPacket.Write(npc.whoAmI);
npcExtrasPacket.Write(npc.lifeMax);
npcExtrasPacket.Write(npc.defense);
npcExtrasPacket.Write(npc.damage);
npcExtrasPacket.Write(npc.value);
npcExtrasPacket.Send();
}
///<summary>
///Broadcasts a message from the server to all players. Safe to use in either multiplayer or singleplayer contexts, where it simply defaults to a NewText() instead.
///It does nothing when run on a multiplayer client, as that would make it spam a new copy of the message for every client that runs it. Use NewText() for client-only code like items!
///</summary>
///<param name="text">String containing the text</param>
public static void BroadcastText(string text)
{
BroadcastText(text, Color.Yellow);
}
public static void BroadcastText(string text, int r, int g, int b)
{
BroadcastText(text, new Color(r, g, b));
}
///<summary>
///Now in technicolor!
///</summary>
///<param name="text">String containing the text</param>
///<param name="color">Color of the text</param>
public static void BroadcastText(string text, Color color)
{
if (Main.netMode == NetmodeID.Server)
{
ChatHelper.BroadcastChatMessage(NetworkText.FromLiteral(text), color);
}
if (Main.netMode == NetmodeID.SinglePlayer)
{
Main.NewText(text, color);
}
}
///<summary>
///Gets the first npc of a given type. Basically NPC.AnyNPC, except it actually returns what it finds.
///Uses nullable ints, aka "int?". Will return null if it can't find one.
///</summary>
///<param name="type">Type of NPC to look for</param>
public static int? GetFirstNPC(int type)
{
for (int i = 0; i < Main.maxNPCs; i++)
{
if (Main.npc[i].active && Main.npc[i].type == type)
{
return i;
}
}
return null;
}
///<summary>
///Gets the closest Enemy NPC to a given point. Returns that NPC's whoami.
///Uses nullable ints, will return null if it can't find one (like in the rare but possible situation where there *are* no NPCs). You've been warned!
///</summary>
///<param name="point">The point it's comparing to</param>
public static int? GetClosestEnemyNPC(Vector2 point)
{
int? closestNPC = null;
float distance = float.MaxValue;
for (int i = 0; i < Main.maxNPCs; i++)
{
if (Main.npc[i].active && !Main.npc[i].friendly && !Main.npc[i].dontTakeDamage && !NPCID.Sets.CountsAsCritter[Main.npc[i].type] && Main.npc[i].lifeMax > 1)
{
float newDistance = Vector2.DistanceSquared(point, Main.npc[i].Center);
if (newDistance < distance)
{
distance = newDistance;
closestNPC = i;
}
}
}
return closestNPC;
}
///<summary>
///Gets the closest projectile of a given type to a given point. Returns that projectile's whoami.
///Uses nullable ints, will return null if it can't find one. You've been warned!
///</summary>
///<param name="point">The point it's comparing to</param>
///<param name="type">The type of the projectile to search for</param>
public static int? GetClosestProjectile(Vector2 point, int type)
{
int? closestProj = null;
float distance = float.MaxValue;
for (int i = 0; i < Main.maxNPCs; i++)
{
if (Main.projectile[i].active)
{
float newDistance = Vector2.DistanceSquared(point, Main.projectile[i].Center);
if (newDistance < distance && Main.projectile[i].type == type)
{
distance = newDistance;
closestProj = i;
}
}
}
return closestProj;
}
///<summary>
///Gets the closest projectile of a given type to a given point. Returns that projectile's whoami.
///Uses nullable ints, will return null if it can't find one. You've been warned!
///Contains a check to ensure the projectile is owned by the correct player.
///</summary>
///<param name="point">The point it's comparing to</param>
///<param name="type">The type of the projectile to search for</param>
public static int? GetClosestPlayerProjectile(Vector2 point, int type, in int playerID)
{
int? closestProj = null;
float distance = float.MaxValue;
for (int i = 0; i < Main.maxNPCs; i++)
{
if (Main.projectile[i].active)
{
float newDistance = Vector2.DistanceSquared(point, Main.projectile[i].Center);
if (newDistance < distance && playerID == Main.projectile[i].owner && Main.projectile[i].type == type)
{
distance = newDistance;
closestProj = i;
return closestProj;
}
}
}
return closestProj;
}
///<summary>
///Does this tile exist, and if so is it solid?
///Yes, this requires all of this to learn the answer safely. Nothing can be easy here.
///Also returns false if the tile is null, or if the coordinates you gave it are out of range of the tile array.
///</summary>
///<param name="tilePos">The coordinates of the tile</param>
public static bool IsTileReallySolid(Vector2 tilePos)
{
if (Main.tile.Width > tilePos.X && Main.tile.Height > tilePos.Y)
{
Tile thisTile = Main.tile[(int)tilePos.X, (int)tilePos.Y];
//null = tile is not instantiated at all (yes, that is possible) | active = tile is not air | inActive = actuated | Main.tileSolid = is it solid
if (thisTile != null && thisTile.HasTile && !thisTile.IsActuated && Main.tileSolid[thisTile.TileType] && !TileID.Sets.Platforms[thisTile.TileType])
{
return true;
}
}
return false;
}
///<summary>
///Shifts a color back and forth by a certain percent over time
///Useful for making things seem shimmery or less flat
///</summary>
///<param name="originalColor">The original color to be shifted</param>
///<param name="timeFactor">Increment this to control how fast it shifts</param>
///<param name="percent">The intensity of the shift</param>
public static Color ShiftColor(Color originalColor, float timeFactor, float percent = 0.03f)
{
Vector3 hslColor = Main.rgbToHsl(originalColor);
hslColor.X += percent * (float)Math.Cos(timeFactor / 25f);
return Main.hslToRgb(hslColor);
}
///<summary>
///Accelerates an entity toward a target in a smooth way
///Returns a Vector2 with length 'acceleration' that points in the optimal direction to accelerate the NPC toward the target
///If the target is moving, then it accounts for that
///(No, unfortunately the optimal direction is not actually a straight line most of the time)
///Accelerates until the NPC is moving fast enough that the acceleration can *just* slow it down in time, then does so
///Do not ask me how long this took 💀
///</summary>
///<param name="actor">The entity moving</param>
///<param name="target">The target point it is aiming for</param>
///<param name="acceleration">The rate at which it can accelerate</param>
///<param name="topSpeed">The max speed of the entity</param>
///<param name="targetVelocity">The velocity of its target, defaults to 0</param>
///<param name="bufferZone">Should it smoothly slow down on approach?</param>
public static void SmoothHoming(Entity actor, Vector2 target, float acceleration, float topSpeed, Vector2? targetVelocity = null, bool bufferZone = true, float bufferStrength = 0.1f)
{
//If the target has a velocity then factor it in
Vector2 velTarget = Vector2.Zero;
if (targetVelocity != null)
{
velTarget = targetVelocity.Value;
}
//Get the difference between the center of both entities
Vector2 posDifference = target - actor.Center;
//Get the distance between them
float distance = posDifference.Length();
//Get the difference of velocities
//This shifts the reference frame of the calculations, from here on out we are looking at the problem as if Entity 1 was still and Entity 2 had the velocity of both entities combined
//The formulas below calculate where it will be in the future and then the entity is accelerated toward that point on an intercept trajectory
Vector2 vTarget = velTarget - actor.velocity;
//Normalize posDifference to get the direction of it, ignoring the length
posDifference.Normalize();
//Use a dot product to get the length of the velocity vector in the direction of the target.
//This tells us how fast the actor is moving toward the target already
float velocity = Vector2.Dot(-vTarget, posDifference);
//Use the current velocity plus acceleration to calculate how long it will take to arrive using the formula for acceleration
float eta = (-velocity / acceleration) + (float)Math.Sqrt((velocity * velocity / (acceleration * acceleration)) + 2 * distance / acceleration);
//Use the velocity plus arrival time plus current target location to calculate the location the target will be at in the future
Vector2 impactPos = target + vTarget * eta;
//Generate a vector with length 'acceleration' pointing at that future location
Vector2 fixedAcceleration = Aim(actor.Center, impactPos, acceleration);
//If distance or acceleration is 0 it will have nans, this deals with that
if (fixedAcceleration.HasNaNs())
{
fixedAcceleration = Vector2.Zero;
}
//Update its acceleration
actor.velocity += fixedAcceleration;