-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAnimations.cs
2061 lines (1806 loc) · 89.7 KB
/
Animations.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//reference System.dll
//reference System.Core.dll
//reference System.Xml.dll
// Thanks goes out to D_Flat for suggesting the way to write the command, in a way I think is absolutely perfect
using MCGalaxy.Events.LevelEvents;
using MCGalaxy.Maths;
using MCGalaxy.Tasks;
using MCGalaxy.Events.PlayerEvents;
using System;
using System.Collections.Generic;
using System.IO;
using BlockID = System.UInt16;
using MCGalaxy.Network;
using System.Linq;
using System.Xml.Serialization;
using MCGalaxy.Blocks;
namespace MCGalaxy
{
/***********************
* ANIMATION DATA TYPES *
************************/
// Contains all the animation blocks for a given map, as well as the task schedulers (they aren't in animation handler because they tick at a per-level rate)
public sealed class MapAnimation
{
public BufferedBlockSender buffer;
static readonly ushort DEFAULT_SPEED = 100;
public bool bRunning;
public bool bEditingLock; // Stops all updates writing/deleting to/from the block list
public ushort _currentTick;
public List<AnimBlock> _blocks;
public ushort _numLoops;
public ushort _speed;
public bool bKiller;
private SchedulerTask _task;
private readonly Level _level;
private Scheduler instance;
private readonly object activateLock = new object();
private readonly object deactivateLock = new object();
public MapAnimation(bool running, ushort currentTick, ushort numLoops, Level level, ushort speed, bool killer)
{
bRunning = running; bEditingLock = true; _currentTick = currentTick; _numLoops = numLoops; _blocks = new List<AnimBlock>(); _level = level; _speed = speed; bKiller = killer;
}
public void Activate()
{
lock (activateLock)
{
if (instance != null) return;
instance = new Scheduler(String.Format("AnimationsScheduler+{0}", _level.name));
}
buffer = new BufferedBlockSender(_level);
_task = instance.QueueRepeat(AnimationHandler.Update, _level, TimeSpan.FromMilliseconds(DEFAULT_SPEED));
}
public void Deactivate()
{
lock (deactivateLock)
{
if (instance != null)
{
instance.Cancel(_task);
}
}
buffer = new BufferedBlockSender();
_blocks = new List<AnimBlock>();
}
public void SetSpeed(ushort speed)
{
_speed = speed;
_task.Delay = TimeSpan.FromMilliseconds(speed);
}
}
// An animated block at a specific coordinate. Contains animation loops
public sealed class AnimBlock
{
public AnimBlock(ushort x, ushort y, ushort z, BlockID block)
{
this._x = x; this._y = y; this._z = z; this._currentBlock = block; this._loopList = new SortedList<ushort, AnimLoop>();
}
public ushort _x;
public ushort _y;
public ushort _z;
public BlockID _currentBlock; // Currently visible block
public SortedList<ushort, AnimLoop> _loopList; // List sorted by index
}
// A single animation loop
public sealed class AnimLoop
{
public AnimLoop(ushort interval, ushort duration, short startTick, ushort endTick, BlockID block)
{
this._interval = interval; this._duration = duration; this._startTick = startTick; this._endTick = endTick; this._block = block;
}
public ushort _interval; // The period of the loop
public ushort _duration; // The length of time we keep seeing the loop
public short _startTick; // Animation offset
public ushort _endTick; // Animation end
public BlockID _block;
}
/**********
* PLUGIN *
**********/
public class AnimationsPlugin : Plugin
{
public override string creator { get { return "Opapinguin"; } }
public override string MCGalaxy_Version { get { return "1.9.4.0"; } }
public override string name { get { return "Animations"; } }
public override void Load(bool startup)
{
CreateAnimsDir();
StartAnimations();
OnLevelLoadedEvent.Register(HandleLevelLoaded, Priority.Normal);
OnLevelUnloadEvent.Register(HandleLevelUnload, Priority.Normal);
OnLevelSaveEvent.Register(HandleLevelSave, Priority.Normal);
OnLevelRenamedEvent.Register(HandleLevelRenamed, Priority.Normal);
OnLevelCopiedEvent.Register(HandleLevelCopied, Priority.Normal);
OnLevelDeletedEvent.Register(HandleLevelDeleted, Priority.Normal);
OnPlayerClickEvent.Register(HandlePlayerClick, Priority.Normal);
OnJoinedLevelEvent.Register(HandleJoinedLevel, Priority.Normal);
InitializeAnimDict();
AnimationHandler.Activate();
Command.Register(new CmdAnimation());
}
public override void Unload(bool shutdown)
{
OnLevelLoadedEvent.Unregister(HandleLevelLoaded);
OnLevelUnloadEvent.Unregister(HandleLevelUnload);
OnLevelSaveEvent.Unregister(HandleLevelSave);
OnLevelRenamedEvent.Unregister(HandleLevelRenamed);
OnLevelCopiedEvent.Unregister(HandleLevelCopied);
OnLevelDeletedEvent.Unregister(HandleLevelDeleted);
OnPlayerClickEvent.Unregister(HandlePlayerClick);
OnJoinedLevelEvent.Unregister(HandleJoinedLevel);
AnimationHandler.Deactivate();
Command.Unregister(Command2.Find("Animation"));
}
// Creates the animation directory
private void CreateAnimsDir()
{
if (!Directory.Exists("Animations"))
{
try
{
Directory.CreateDirectory("Animations");
}
catch (Exception e)
{
Logger.Log(LogType.Error, "Failed to create Animations folder");
Logger.Log(LogType.Error, e.StackTrace);
}
}
if (!Directory.Exists("AnimationsBackup"))
{
try
{
Directory.CreateDirectory("AnimationsBackup");
}
catch (Exception e)
{
Logger.Log(LogType.Error, "Failed to create AnimationsBackup folder");
Logger.Log(LogType.Error, e.StackTrace);
}
}
}
/******************
* EVENT HANDLERS *
******************/
private void InitializeAnimDict()
{
foreach (Level level in LevelInfo.Loaded.Items)
{
if (File.Exists(String.Format("Animations/{0}+animation.txt", level.name)))
{
ReadAnimation(level);
ReadConfig(level);
}
}
}
private void HandleLevelDeleted(string level)
{
ConditionalDeleteAnimationFile(level);
ConditionalDeleteAnimationConfigFile(level);
}
private void HandleLevelCopied(string srcMap, string dstMap)
{
RenameAnimation(srcMap, dstMap);
RenameAnimationConfig(srcMap, dstMap);
}
private void HandleLevelRenamed(string srcMap, string dstMap)
{
RenameAnimation(srcMap, dstMap);
RenameAnimationConfig(srcMap, dstMap);
}
private void HandleLevelSave(Level level, ref bool cancel)
{
SaveAnimation(level);
SaveConfig(level);
}
private void HandleLevelLoaded(Level level)
{
ReadAnimation(level);
ReadConfig(level);
}
private void HandleLevelUnload(Level level, ref bool cancel)
{
SaveAnimation(level);
SaveConfig(level);
AnimationHandler.RemoveFromActiveLevels(level);
}
private void HandlePlayerClick(Player p, MouseButton button, MouseAction action, ushort yaw, ushort pitch, byte entity, ushort x, ushort y, ushort z, TargetBlockFace face)
{
AnimationHandler.SendCurrentFrameBlock(p, x, y, z);
}
private void HandleJoinedLevel(Player p, Level prevLevel, Level level, ref bool announce)
{
AnimationHandler.SendCurrentFrame(p, level);
}
/******************************
* FILE AND ANIMATION HANDLING *
*******************************/
// Starts all animations for maps that have them
private void StartAnimations()
{
foreach (Level level in LevelInfo.Loaded.Items)
{
ReadAnimation(level);
ReadConfig(level);
}
}
// Read the animation file for a level if it exists, then sends it to the level's MapAnimation (creates it if it does not exist)
public static void ReadAnimation(Level level)
{
// File is ordered as <x> <y> <z> <index> <interval> <duration> <start> <end> <blockID>
List<String> animFile;
try
{
if (File.Exists(String.Format("Animations/{0}+animation.txt", level.name)))
{
string[] logFile = File.ReadAllLines(String.Format("Animations/{0}+animation.txt", level.name));
animFile = new List<string>(logFile);
}
else
{
return;
}
}
catch (Exception e)
{
Logger.Log(LogType.Error, String.Format("Could not read Animations/{0}+animation.txt", level.name));
Logger.Log(LogType.Error, e.StackTrace);
return;
}
AnimationHandler.ConditionalAddMapAnimation(level);
AnimationHandler.dictActiveLevels[level.name].bEditingLock = true;
// Write into the MapAnimation for the level
foreach (String line in animFile)
{
string[] l = line.Split(' ');
try
{
AnimationHandler.AddLoop(level, Convert.ToUInt16(l[0]), Convert.ToUInt16(l[1]), Convert.ToUInt16(l[2]), Convert.ToUInt16(l[3]), Convert.ToUInt16(l[4]), Convert.ToUInt16(l[5]), Convert.ToInt16(l[6]), Convert.ToUInt16(l[7]), Convert.ToUInt16(l[8]));
}
catch (Exception e)
{
Logger.Log(LogType.Error, String.Format("Could not read line \" {0} \" from Animations/{1}+animation.txt", line, level.name));
Logger.Log(LogType.Error, e.StackTrace);
return;
}
}
AnimationHandler.dictActiveLevels[level.name].bEditingLock = false;
}
// Read properties file for animations
public static void ReadConfig(Level level)
{
if (!File.Exists(String.Format("Animations/{0}+animationProps.xml", level.name))) { return; }
if (!AnimationHandler.HasAnims(level)) { return; }
AnimConfig config;
XmlSerializer reader = new XmlSerializer(typeof(AnimConfig));
using (var sww = new StreamReader(String.Format("Animations/{0}+animationProps.xml", level.name)))
{
config = (AnimConfig)reader.Deserialize(sww);
}
AnimationHandler.dictActiveLevels[level.name].bKiller = config.Killer;
AnimationHandler.dictActiveLevels[level.name].SetSpeed(config.Speed);
}
// Save properties file for animations as an XML file
public static void SaveConfig(Level level)
{
if (!AnimationHandler.HasAnims(level)) { return; }
MapAnimation mapAnimation = AnimationHandler.dictActiveLevels[level.name];
var config = new AnimConfig
{
Killer = mapAnimation.bKiller,
Speed = mapAnimation._speed
};
XmlSerializer writer = new XmlSerializer(typeof(AnimConfig));
using (var sw = new StreamWriter(String.Format("Animations/{0}+animationProps.xml", level.name)))
{
writer.Serialize(sw, config);
string xml = sw.ToString();
}
}
// Renames one [level]+animation.txt to another
private void RenameAnimation(string srcMap, string dstMap)
{
try
{
if (File.Exists(String.Format("Animations/{0}+animation.txt", srcMap)))
{
File.Move(String.Format("Animations/{0}+animation.txt", srcMap),
String.Format("Animations/{0}+animation.txt", dstMap));
}
else
{
return;
}
}
catch (Exception e)
{
Logger.Log(LogType.Error, String.Format("Could not copy Animations/{0}+animation.txt" +
" into Animations/{1}+animation.txt", srcMap, dstMap));
Logger.Log(LogType.Error, e.StackTrace);
return;
}
}
// Renames one [level]+animationProps.xml to another
private void RenameAnimationConfig(string srcMap, string dstMap)
{
try
{
if (File.Exists(String.Format("Animations/{0}+animationProps.xml", srcMap)))
{
File.Move(String.Format("Animations/{0}+animationProps.xml", srcMap),
String.Format("Animations/{0}+animationProps.xml", dstMap));
}
else
{
return;
}
}
catch (Exception e)
{
Logger.Log(LogType.Error, String.Format("Could not copy Animations/{0}+animationProps.xml" +
" into Animations/{1}+animationProps.xml", srcMap, dstMap));
Logger.Log(LogType.Error, e.StackTrace);
return;
}
}
// Write the animation thus far to [level]+animation.txt in ./Animations
public static void SaveAnimation(Level level)
{
if (!LevelInfo.Loaded.Contains(level))
{
return;
}
if (!AnimationHandler.HasAnims(level))
{
return;
}
MapAnimation mapAnim = AnimationHandler.dictActiveLevels[level.name];
if (mapAnim._numLoops == 0)
{
return;
}
List<string> lines = new List<string>();
foreach (AnimBlock animBlock in mapAnim._blocks)
{
foreach (var kvp in animBlock._loopList)
{
// File is ordered as <x> <y> <z> <index> <interval> <duration> <start> <end> <blockID>
lines.Add(String.Format("{0} {1} {2} {3} {4} {5} {6} {7} {8}", animBlock._x, animBlock._y, animBlock._z, kvp.Key, kvp.Value._interval, kvp.Value._duration, kvp.Value._startTick, kvp.Value._endTick, kvp.Value._block));
}
}
File.WriteAllLines(String.Format("Animations/{0}+animation.txt", level.name), lines.ToArray());
}
// Write the animation thus far to [level]+animation.txt in ./AnimationsBackup TODO: Repetition of code, but not sure of an abstract is necessary here
public static void SaveAnimationBackup(Level level)
{
if (!LevelInfo.Loaded.Contains(level))
{
return;
}
if (!AnimationHandler.HasAnims(level))
{
return;
}
MapAnimation mapAnim = AnimationHandler.dictActiveLevels[level.name];
if (mapAnim._numLoops == 0)
{
return;
}
List<string> lines = new List<string>();
foreach (AnimBlock animBlock in mapAnim._blocks)
{
foreach (var kvp in animBlock._loopList)
{
// File is ordered as <x> <y> <z> <index> <interval> <duration> <start> <end> <blockID>
lines.Add(String.Format("{0} {1} {2} {3} {4} {5} {6} {7} {8}", animBlock._x, animBlock._y, animBlock._z, kvp.Key, kvp.Value._interval, kvp.Value._duration, kvp.Value._startTick, kvp.Value._endTick, kvp.Value._block));
}
}
File.WriteAllLines(String.Format("AnimationsBackup/{0}+animation.txt", level.name), lines.ToArray());
}
// Deletes the animation file [level]+animation.txt in ./Animations if it exists
public static void ConditionalDeleteAnimationFile(string level)
{
if (AnimationExists(level))
{
try
{
File.Delete(String.Format("Animations/{0}+animation.txt", level));
}
catch (Exception e)
{
Logger.Log(LogType.Error, String.Format("Failed to delete file \"Animations/{0}+animation.txt\"", level));
Logger.Log(LogType.Error, e.StackTrace);
}
}
}
// Deletes the animation config file [level]+animationProps.xml in ./Animations if it exists
public static void ConditionalDeleteAnimationConfigFile(string level)
{
if (AnimationExists(level))
{
try
{
File.Delete(String.Format("Animations/{0}+animationProps.xml", level));
}
catch (Exception e)
{
Logger.Log(LogType.Error, String.Format("Failed to delete file \"Animations/{0}+animationProps.xml\"", level));
Logger.Log(LogType.Error, e.StackTrace);
}
}
}
// Checks if [level]+animations.txt exists in ./Animations
public static bool AnimationExists(string level)
{
return File.Exists(String.Format("Animations/{0}+animation.txt", level));
}
}
/**********
* CONFIG *
**********/
public sealed class AnimConfig
{
public ushort Speed { get; set; }
public bool Killer { get; set; }
}
/*********************
* ANIMATION HANDLER *
*********************/
// Handles animation scheduling across maps as well as adding loops to/removing loops from animations in these maps
// Note that we need to keep maps in this static class, because maps are not passed around by reference but rather many instances
// Are made for each player, so that using the ExtrasCollection for each map will not be viable
public static class AnimationHandler
{
public static Dictionary<string, MapAnimation> dictActiveLevels = new Dictionary<string, MapAnimation>(); // Levels with map animations
internal static void Activate()
{
foreach (var kvp in dictActiveLevels)
{
kvp.Value.Activate();
}
}
internal static void Deactivate()
{
foreach (var kvp in dictActiveLevels)
{
kvp.Value.Deactivate();
}
dictActiveLevels.Clear();
}
// Keeps track of which (loaded) maps have animations i.e. which maps to handle
internal static bool HasAnims(Level level)
{
return dictActiveLevels.ContainsKey(level.name);
}
// Sets the map animation for a level
internal static void SetAnims(Level level, MapAnimation mapAnim)
{
dictActiveLevels[level.name] = mapAnim;
dictActiveLevels[level.name].Activate();
}
// Removes a level from the active levels
internal static void RemoveFromActiveLevels(Level level)
{
if (HasAnims(level))
{
dictActiveLevels[level.name].Deactivate();
dictActiveLevels.Remove(level.name);
}
}
// Sends current animation frame globally, for everyone on the level
internal static void SendCurrentFrame(Level level)
{
foreach (Player pl in level.players)
{
SendCurrentFrame(pl, level);
}
}
// Sends current animation frame. Useful when marking or breaking a block, or on level join event
internal static void SendCurrentFrame(Player p, Level level)
{
BufferedBlockSender sender = new BufferedBlockSender(p);
MapAnimation mapAnimation;
if (HasAnims(level))
{
mapAnimation = dictActiveLevels[level.name];
}
else
{
return;
}
foreach (AnimBlock aBlock in mapAnimation._blocks)
{
BlockID CurrentBlock = GetCurrentBlock(aBlock._loopList, mapAnimation._currentTick);
if (CurrentBlock == BlockID.MaxValue)
{
CurrentBlock = level.GetBlock(aBlock._x, aBlock._y, aBlock._z);
}
sender.Add(level.PosToInt(aBlock._x, aBlock._y, aBlock._z), CurrentBlock);
}
if (sender.count > 0)
{
sender.Flush();
}
}
// Sends current frame block identity for a specific block
internal static void SendCurrentFrameBlock(Player p, ushort x, ushort y, ushort z)
{
MapAnimation mapAnimation;
if (HasAnims(p.level))
{
mapAnimation = dictActiveLevels[p.level.name];
}
else
{
return;
}
foreach (AnimBlock aBlock in mapAnimation._blocks)
{
if (aBlock._x == x && aBlock._y == y && aBlock._z == z)
{
BlockID CurrentBlock = GetCurrentBlock(aBlock._loopList, mapAnimation._currentTick);
if (CurrentBlock != BlockID.MaxValue)
{
p.SendBlockchange(aBlock._x, aBlock._y, aBlock._z, CurrentBlock);
}
else
{
p.RevertBlock(aBlock._x, aBlock._y, aBlock._z);
}
return;
}
}
}
// Handles animation on a single map
internal static void Update(SchedulerTask task)
{
Level currentLevel = (Level)task.State;
MapAnimation mapAnimation = dictActiveLevels[currentLevel.name];
if (mapAnimation.bRunning && !mapAnimation.bEditingLock)
{
foreach (AnimBlock animBlock in mapAnimation._blocks)
{
BlockID prevBlock = animBlock._currentBlock; // Previous frame's block
BlockID currentBlock = GetCurrentBlock(animBlock._loopList, mapAnimation._currentTick); // Current frame's block
// Special value saying that the loop is off. Revert to usual block
if (currentBlock == UInt16.MaxValue)
{
currentBlock = currentLevel.GetBlock(animBlock._x, animBlock._y, animBlock._z);
}
if (currentBlock == prevBlock) // Don't have to send block changes if the block doesn't change
{
continue;
}
int index = currentLevel.PosToInt((ushort)animBlock._x, (ushort)animBlock._y, (ushort)animBlock._z);
mapAnimation.buffer.Add(index, currentBlock);
animBlock._currentBlock = currentBlock;
}
// Handle remaining blocks
if (mapAnimation.buffer.count != 0)
{
mapAnimation.buffer.Flush();
}
// Handle death
if (mapAnimation.bKiller)
{
foreach (Player pl in currentLevel.players)
{
Walkthrough(pl, pl.ModelBB.OffsetPosition(pl.Pos), mapAnimation._currentTick, mapAnimation);
}
}
mapAnimation._currentTick += 1;
if (mapAnimation._currentTick == ushort.MaxValue)
{
mapAnimation._currentTick = 0;
}
}
}
// Handles walkthrough, checks if player dies
internal static void Walkthrough(Player p, AABB bb, ushort tick, MapAnimation mapAnim)
{
Vec3S32 min = bb.BlockMin, max = bb.BlockMax;
bool hitWalkthrough = false;
for (int y = min.Y; y <= max.Y; y++)
for (int z = min.Z; z <= max.Z; z++)
for (int x = min.X; x <= max.X; x++)
{
ushort xP = (ushort)x, yP = (ushort)y, zP = (ushort)z;
BlockID block = AnimationHandler.GetCurrentBlock(mapAnim, xP, yP, zP, tick);
if (block == System.UInt16.MaxValue) continue;
AABB blockBB = Block.BlockAABB(block, p.level).Offset(x * 32, y * 32, z * 32);
if (!AABB.Intersects(ref bb, ref blockBB)) continue;
// We can activate only one walkthrough block per movement
if (!hitWalkthrough)
{
HandleWalkthrough handler = p.level.WalkthroughHandlers[block];
if (handler != null && handler(p, block, xP, yP, zP))
{
hitWalkthrough = true;
}
}
// Some blocks will cause death of players
if (!p.level.Props[block].KillerBlock) continue;
if (block == Block.Train && p.trainInvincible) continue;
if (p.level.Config.KillerBlocks) p.HandleDeath(block);
}
}
// Gets the currently visible block at a specific location
private static BlockID GetCurrentBlock(MapAnimation mapAnim, ushort x, ushort y, ushort z, ushort tick)
{
foreach (AnimBlock animBlock in mapAnim._blocks)
{
if (animBlock._x == x && animBlock._y == y && animBlock._z == z)
{
return GetCurrentBlock(animBlock._loopList, tick);
}
}
// Return this if nothing is there
return System.UInt16.MaxValue;
}
// Gets the currently visible block given the tick across an array of loops. Returns 65535 if no block is visible at that frame
private static BlockID GetCurrentBlock(SortedList<ushort, AnimLoop> loops, ushort tick)
{
BlockID loopActiveBlock;
foreach (var kvp in loops) // kvp = (index, AnimLoop). Note that this loops from lowest to highest index automatically
{
loopActiveBlock = CurrentBlock(kvp.Value, tick); // The block visible during the current loop
if (loopActiveBlock != System.UInt16.MaxValue)
{
return loopActiveBlock;
}
}
return System.UInt16.MaxValue;
}
// Gets the currently visible block for a single loop. Returns 65535 if the loop is "off" in a frame
private static BlockID CurrentBlock(AnimLoop loop, ushort tick)
{
if (tick < loop._startTick)
{
return System.UInt16.MaxValue;
}
if (tick > loop._endTick)
{
if (((loop._endTick - loop._startTick) % loop._interval) < loop._duration) // If the block is active during the loop
{
return loop._block;
}
return System.UInt16.MaxValue;
}
if (((tick - loop._startTick) % loop._interval) < loop._duration) // If the block is active during the loop
{
return loop._block;
}
return System.UInt16.MaxValue;
}
// Initializes a map animation if it does not already exist. Adds it to the active levels
internal static void ConditionalAddMapAnimation(Level level)
{
if (!HasAnims(level))
{
MapAnimation mapAnimation = new MapAnimation(true, 0, 0, level, 100, false)
{
_blocks = new List<AnimBlock>()
};
SetAnims(level, mapAnimation);
}
}
// Remove a map animation if it exists. Removes it from the active levels
private static void ConditionalRemoveMapAnimation(Level level)
{
if (HasAnims(level))
{
RemoveFromActiveLevels(level);
}
}
// Places a loop in a level. If "all" is set to true, replaces all loops for a block
internal static void Place(Level level, ushort x, ushort y, ushort z, ushort idx, ushort interval, ushort duration, short startTick, ushort endTick, BlockID block, bool all, bool append)
{
ConditionalAddMapAnimation(level);
MapAnimation mapAnimation = AnimationHandler.dictActiveLevels[level.name];
mapAnimation.bEditingLock = true;
if (mapAnimation._numLoops == ushort.MaxValue)
{
mapAnimation.bEditingLock = false;
return;
}
foreach (AnimBlock animB in mapAnimation._blocks)
{
if (animB._x == x && animB._y == y && animB._z == z)
{
AnimLoop loop = new AnimLoop(interval, duration, startTick, endTick, block);
if (all) // If replacing
{
mapAnimation._numLoops -= (ushort)animB._loopList.Count;
animB._loopList.Clear();
}
else if (!all && append) // If appending
{
idx = (ushort)(animB._loopList.Keys.Max() + 1);
}
else if (!all && !append) // If prepending
{
if (animB._loopList.Keys.Min() == 1)
{
// Push everything forward by 1
foreach (ushort k in animB._loopList.Keys.Reverse())
{
AnimLoop copy = new AnimLoop(animB._loopList[k]._interval, animB._loopList[k]._duration,
animB._loopList[k]._startTick, animB._loopList[k]._endTick, animB._loopList[k]._block);
animB._loopList[(ushort)(k + 1)] = copy;
animB._loopList.Remove(k);
}
animB._loopList.Remove(1);
}
idx = (ushort)(animB._loopList.Keys.Min() - 1);
}
// Replace loop if it already exists with the given index. Otherwise overwrite it
if (animB._loopList.Keys.Contains(idx))
{
animB._loopList[idx] = loop;
}
else
{
animB._loopList.Add(idx, loop);
mapAnimation._numLoops += 1;
}
mapAnimation.bEditingLock = false;
return;
}
}
// If we're here, it means we're not overwriting a block but creating a new one
AnimBlock animBlock = new AnimBlock(x, y, z, block);
animBlock._loopList.Add(1, new AnimLoop(interval, duration, startTick, endTick, block));
mapAnimation._blocks.Add(animBlock);
mapAnimation._numLoops += 1;
mapAnimation.bEditingLock = false;
}
// Deletes a loop in a level. If all is true, deletes all loops for a block
internal static void Delete(Level level, ushort x, ushort y, ushort z, ushort idx, bool all, bool deleteBlock)
{
if (!AnimationHandler.HasAnims(level)) return;
MapAnimation mapAnimation = AnimationHandler.dictActiveLevels[level.name];
mapAnimation.bEditingLock = true;
// Looks like a massive loop but takes no more than O(number of animation blocks) operations
foreach (AnimBlock animBlock in mapAnimation._blocks)
{
if (!(animBlock._x == x && animBlock._y == y && animBlock._z == z)) { continue; }
if (all) // Remove all loops at the location
{
mapAnimation._numLoops -= (ushort)animBlock._loopList.Count;
if (mapAnimation._numLoops <= 0)
{
ConditionalRemoveMapAnimation(level);
}
mapAnimation._blocks.Remove(animBlock);
mapAnimation.bEditingLock = false;
break;
}
else
{
foreach (var kvp in animBlock._loopList) // Find the loop with the specified index and remove only that
{
if ((kvp.Key == idx && deleteBlock == false) || (kvp.Value._block == idx && deleteBlock == true)) // Deletes by block if deleteBlock is true, else by index
{
animBlock._loopList.Remove(kvp.Key);
if (animBlock._loopList.Count == 0)
{
mapAnimation._blocks.Remove(animBlock);
}
mapAnimation._numLoops -= 1;
if (mapAnimation._numLoops <= 0)
{
ConditionalRemoveMapAnimation(level);
}
break;
}
}
break;
}
}
mapAnimation.bEditingLock = false;
}
// Adds a loop in a level. Creates animation block for this loop if it does not exist already. If loop index already exists, overwrites it
internal static void AddLoop(Level level, ushort x, ushort y, ushort z, ushort index, ushort interval, ushort duration, short start, ushort end, BlockID block)
{
ConditionalAddMapAnimation(level);
MapAnimation mapAnimation = dictActiveLevels[level.name];
AnimLoop loop = new AnimLoop(interval, duration, start, end, block);
// Add loop to an existing animation block if it exists
foreach (AnimBlock aBlock in mapAnimation._blocks)
{
if (aBlock._x == x && aBlock._y == y && aBlock._z == z)
{
if (aBlock._loopList.ContainsKey(index))
{
aBlock._loopList[index] = new AnimLoop(interval, duration, start, end, block);
return;
}
else
{
aBlock._loopList.Add(index, loop);
mapAnimation._numLoops += 1;
return;
}
}
}
// Create the animation block then add the loop
AnimBlock animBlock = new AnimBlock(x, y, z, block);
animBlock._loopList.Add(index, loop);
mapAnimation._blocks.Add(animBlock);
mapAnimation._numLoops += 1;
}
}
public sealed class CmdAnimation : Command2
{
public override string name { get { return "Animation"; } }
public override string shortcut { get { return "anim"; } }
public override string type { get { return CommandTypes.Other; } }
public override LevelPermission defaultRank { get { return LevelPermission.Guest; } }
public override void Use(Player p, string message)
{
if (!p.level.BuildAccess.CheckAllowed(p))
{
p.Message("You do not have permissions to use animations on this level.");
return;
}
string[] args = message.ToLower().SplitSpaces();
AnimationArgs animArgs = new AnimationArgs();
/******************
* COMMAND PARSER *
******************/
/* EXTRAS FLAGS */
bool bCuboid = false; bool bAll = true; bool bAppend = false; // Default behavior
List<string> zSynms = new List<string> { "z", "cuboid" }; // Cuboid synonynms
List<string> appSynms = new List<string> { "a", "append" }; // Append/prepend synonyms
List<string> prepSynms = new List<string> { "p", "prepend" }; // Append/prepend synonyms
foreach (string arg in args)
{
if (zSynms.Contains(arg))