-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpServerSystem.cs
More file actions
1335 lines (1320 loc) · 54 KB
/
Copy pathHttpServerSystem.cs
File metadata and controls
1335 lines (1320 loc) · 54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Text;
using System.Threading;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.ModLoader;
namespace TerraBlind
{
public class ControlInput
{
public bool Left, Right, Up, Down, Jump, UseItem, UseTile;
public int SelectedSlot = -1;
public int SmartCursor = -1;
public long Tick;
public float Mx = float.NaN;
public float My = float.NaN;
}
public class HttpServerSystem : ModSystem
{
public static volatile Snapshot LatestSnapshot;
public static volatile ControlInput PendingControl;
private static readonly ConcurrentQueue<(int src, int dst)> _swapQueue = new();
private static readonly ConcurrentQueue<(int tx, int ty)> _interactQueue = new();
private static volatile bool _lootAllRequested;
private static volatile bool _quickHealRequested;
private const string Prefix = "http://127.0.0.1:17878/";
private HttpListener _listener;
private Thread _thread;
private volatile bool _running;
private bool _announced;
public override void PostUpdateEverything()
{
if (!_announced && _running)
{
if (Main.netMode == 2) { _announced = true; return; }
if (Main.LocalPlayer == null || !Main.LocalPlayer.active) return;
Main.NewText("[TerraBlind] HTTP server listening on " + Prefix, Color.LightGreen);
_announced = true;
}
if (Main.LocalPlayer == null || !Main.LocalPlayer.active) return;
while (_swapQueue.TryDequeue(out var swap))
{
int src = swap.src, dst = swap.dst;
if (src < 0 || src > 57 || dst < 0 || dst > 57 || src == dst) continue;
var inv = Main.LocalPlayer.inventory;
(inv[src], inv[dst]) = (inv[dst], inv[src]);
}
while (_interactQueue.TryDequeue(out var tile))
{
if (Main.LocalPlayer.chest != -1) continue;
int idx = Chest.FindChest(tile.tx, tile.ty);
if (idx == -1) continue;
if (Chest.UsingChest(idx) != -1) continue;
Main.LocalPlayer.chest = idx;
Main.LocalPlayer.chestX = tile.tx;
Main.LocalPlayer.chestY = tile.ty;
Main.playerInventory = true;
Terraria.Audio.SoundEngine.PlaySound(Terraria.ID.SoundID.MenuOpen);
}
if (_lootAllRequested)
{
_lootAllRequested = false;
if (Main.LocalPlayer.chest != -1)
Terraria.UI.ChestUI.LootAll();
}
if (_quickHealRequested)
{
_quickHealRequested = false;
Main.LocalPlayer.QuickHeal();
}
}
public override void Load()
{
LatestSnapshot = null;
try
{
_listener = new HttpListener();
_listener.Prefixes.Add(Prefix);
_listener.Start();
_running = true;
_thread = new Thread(Loop) { IsBackground = true, Name = "TerraBlindHttp" };
_thread.Start();
Mod.Logger.Info("TerraBlind HTTP server listening on " + Prefix);
}
catch (Exception e)
{
Mod.Logger.Error("TerraBlind failed to start HTTP server: " + e);
}
}
public override void Unload()
{
_running = false;
_announced = false;
try { _listener?.Stop(); } catch { }
try { _listener?.Close(); } catch { }
_listener = null;
try { _thread?.Join(500); } catch { }
_thread = null;
LatestSnapshot = null;
}
private static System.Collections.Generic.HashSet<(int, int)> ParseExcludedGoals(string rb)
{
var result = new System.Collections.Generic.HashSet<(int, int)>();
var pairs = System.Text.RegularExpressions.Regex.Matches(rb, "\\[(-?\\d+),(-?\\d+)\\]");
bool inExcluded = false;
int excludedIdx = rb.IndexOf("\"excluded_goals\"");
if (excludedIdx < 0) return result;
foreach (System.Text.RegularExpressions.Match p in pairs)
{
if (p.Index > excludedIdx)
result.Add((int.Parse(p.Groups[1].Value), int.Parse(p.Groups[2].Value)));
}
return result;
}
private void Loop()
{
while (_running && _listener != null)
{
HttpListenerContext ctx;
try
{
ctx = _listener.GetContext();
}
catch
{
break;
}
try
{
Handle(ctx);
}
catch (Exception e)
{
try
{
ctx.Response.StatusCode = 500;
ctx.Response.Close();
}
catch { }
Mod.Logger.Warn("TerraBlind request error: " + e.Message);
}
}
}
private void Handle(HttpListenerContext ctx)
{
string path = ctx.Request.Url.AbsolutePath;
string body;
int status = 200;
if (path == "/state")
{
body = StateSerializer.ToJson(LatestSnapshot);
}
else if (path == "/digtable")
{
DigTableSystem.Pending = true; // Dump runs on the main thread (PostUpdateEverything) to read tiles safely
body = "{\"ok\":true}";
}
else if (path == "/cursor")
{
var p = Main.LocalPlayer;
if (p != null && p.active)
{
float mx = (Main.mouseX + Main.screenPosition.X - p.position.X - p.width / 2f) / 16f;
float my = (Main.mouseY + Main.screenPosition.Y - p.position.Y - p.height / 2f) / 16f;
int tx = (int)((Main.mouseX + Main.screenPosition.X) / 16f);
int ty = (int)((Main.mouseY + Main.screenPosition.Y) / 16f);
body = $"{{\"mx\":{mx:F3},\"my\":{my:F3},\"tile_x\":{tx},\"tile_y\":{ty}}}";
}
else body = "{\"error\":\"no_player\"}";
}
else if (path == "/swap")
{
var qs = ctx.Request.QueryString;
if (int.TryParse(qs["src"], out int src) && int.TryParse(qs["dst"], out int dst))
{
_swapQueue.Enqueue((src, dst));
body = "{\"ok\":true,\"src\":" + src + ",\"dst\":" + dst + "}";
}
else
{
body = "{\"error\":\"bad_params\",\"usage\":\"GET /swap?src=15&dst=0\"}";
status = 400;
}
}
else if (path == "/fight")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var rb = reqBody.Replace(" ", "");
if (rb.Contains("\"active\":false"))
FightCoordinator.Stop();
else
{
var distm = System.Text.RegularExpressions.Regex.Match(rb, "\"max_dist\":([0-9.]+)");
float maxDist = distm.Success ? float.Parse(distm.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture) : 20f;
FightCoordinator.Start(maxDist);
}
body = "{\"ok\":true}";
}
else if (path == "/loot_all")
{
_lootAllRequested = true;
body = "{\"ok\":true}";
}
else if (path == "/quick_heal")
{
_quickHealRequested = true;
body = "{\"ok\":true}";
}
else if (path == "/control")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var ci = new ControlInput();
ci.SelectedSlot = -1;
var rb = reqBody.Replace(" ", "");
if (rb.Contains("\"left\":true")) ci.Left = true;
if (rb.Contains("\"right\":true")) ci.Right = true;
if (rb.Contains("\"up\":true")) ci.Up = true;
if (rb.Contains("\"down\":true")) ci.Down = true;
if (rb.Contains("\"jump\":true")) ci.Jump = true;
if (rb.Contains("\"jump_place\":true")) { StateSnapshotPlayer.JumpPlaceEnabled = true; }
if (rb.Contains("\"use_item\":true")) ci.UseItem = true;
if (rb.Contains("\"use_tile\":true")) ci.UseTile = true;
var slotMatch = System.Text.RegularExpressions.Regex.Match(rb, "\"selected_slot\"\\s*:\\s*(\\d+)");
if (slotMatch.Success) ci.SelectedSlot = int.Parse(slotMatch.Groups[1].Value);
var mxm = System.Text.RegularExpressions.Regex.Match(rb, "\"mx\":(-?[0-9.]+)");
var mym = System.Text.RegularExpressions.Regex.Match(rb, "\"my\":(-?[0-9.]+)");
if (mxm.Success) ci.Mx = float.Parse(mxm.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture);
if (mym.Success) ci.My = float.Parse(mym.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture);
var scm2 = System.Text.RegularExpressions.Regex.Match(rb, "\"sc\":(\\d+)");
if (scm2.Success) ci.SmartCursor = int.Parse(scm2.Groups[1].Value);
ci.Tick = (long)Main.GameUpdateCount;
PendingControl = ci;
body = "{\"ok\":true}";
}
else if (path == "/interact")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var rb = reqBody.Replace(" ", "");
var txMatch = System.Text.RegularExpressions.Regex.Match(rb, "\"tile_x\"\\s*:\\s*(-?\\d+)");
var tyMatch = System.Text.RegularExpressions.Regex.Match(rb, "\"tile_y\"\\s*:\\s*(-?\\d+)");
if (txMatch.Success && tyMatch.Success)
{
int tx = int.Parse(txMatch.Groups[1].Value);
int ty = int.Parse(tyMatch.Groups[1].Value);
_interactQueue.Enqueue((tx, ty));
body = "{\"ok\":true,\"tile_x\":" + tx + ",\"tile_y\":" + ty + "}";
}
else
{
body = "{\"error\":\"bad_params\",\"usage\":\"POST /interact {\\\"tile_x\\\":N,\\\"tile_y\\\":N}\"}";
status = 400;
}
}
else if (path == "/place")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var rb = reqBody.Replace(" ", "");
var dxMatch = System.Text.RegularExpressions.Regex.Match(rb, "\"dx\"\\s*:\\s*(-?\\d+)");
var dyMatch = System.Text.RegularExpressions.Regex.Match(rb, "\"dy\"\\s*:\\s*(-?\\d+)");
var slotMatch = System.Text.RegularExpressions.Regex.Match(rb, "\"slot\"\\s*:\\s*(\\d+)");
var durMatch = System.Text.RegularExpressions.Regex.Match(rb, "\"duration_frames\"\\s*:\\s*(\\d+)");
if (dxMatch.Success && dyMatch.Success && slotMatch.Success && durMatch.Success)
{
PlaceCoordinator.Start(new PlaceRequest
{
Dx = int.Parse(dxMatch.Groups[1].Value),
Dy = int.Parse(dyMatch.Groups[1].Value),
Slot = int.Parse(slotMatch.Groups[1].Value),
RemainingFrames = int.Parse(durMatch.Groups[1].Value),
});
body = "{\"ok\":true}";
}
else
{
body = "{\"error\":\"bad_params\",\"usage\":\"POST /place {dx,dy,slot,duration_frames,smart_cursor?}\"}";
status = 400;
}
}
else if (path == "/place_stop")
{
PlaceCoordinator.Stop();
body = "{\"ok\":true}";
}
else if (path == "/mine")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var rb = reqBody.Replace(" ", "");
var dirM = System.Text.RegularExpressions.Regex.Match(rb, "\"dir\"\\s*:\\s*\"(left|right|up|down)\"");
var txM = System.Text.RegularExpressions.Regex.Match(rb, "\"target_wx\"\\s*:\\s*(-?\\d+)");
var tyM = System.Text.RegularExpressions.Regex.Match(rb, "\"target_wy\"\\s*:\\s*(-?\\d+)");
if (dirM.Success && txM.Success && tyM.Success)
{
var dir = dirM.Groups[1].Value switch {
"left" => MineDir.Left, "right" => MineDir.Right,
"up" => MineDir.Up, _ => MineDir.Down };
var mp = Main.LocalPlayer;
MineCoordinator.Start(new MineRequest {
Dir = dir,
StartWx = (int)(mp.Center.X / 16f),
StartWy = (int)((mp.position.Y + mp.height) / 16f) - 1,
TargetWx = int.Parse(txM.Groups[1].Value),
TargetWy = int.Parse(tyM.Groups[1].Value),
});
body = "{\"ok\":true}";
}
else
{
body = "{\"error\":\"bad_params\",\"usage\":\"POST /mine {\\\"dir\\\":\\\"down\\\",\\\"target_wx\\\":N,\\\"target_wy\\\":N}\"}";
status = 400;
}
}
else if (path == "/mine_stop")
{
MineCoordinator.Stop();
body = "{\"ok\":true}";
}
else if (path == "/item_use")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var rb = reqBody.Replace(" ", "");
var wxM = System.Text.RegularExpressions.Regex.Match(rb, "\"target_wx\"\\s*:\\s*(-?\\d+)");
var wyM = System.Text.RegularExpressions.Regex.Match(rb, "\"target_wy\"\\s*:\\s*(-?\\d+)");
if (wxM.Success && wyM.Success)
{
var slotM = System.Text.RegularExpressions.Regex.Match(rb, "\"slot\"\\s*:\\s*(-?\\d+)");
var durM = System.Text.RegularExpressions.Regex.Match(rb, "\"duration_ticks\"\\s*:\\s*(\\d+)");
ItemUseCoordinator.Start(new ItemUseRequest {
TargetWx = int.Parse(wxM.Groups[1].Value),
TargetWy = int.Parse(wyM.Groups[1].Value),
Slot = slotM.Success ? int.Parse(slotM.Groups[1].Value) : -1,
DurationTicks = durM.Success ? int.Parse(durM.Groups[1].Value) : 0,
});
body = "{\"ok\":true}";
}
else
{
body = "{\"error\":\"bad_params\",\"usage\":\"POST /item_use {\\\"target_wx\\\":N,\\\"target_wy\\\":N,\\\"slot\\\":N,\\\"duration_ticks\\\":N}\"}";
status = 400;
}
}
else if (path == "/item_use_stop")
{
ItemUseCoordinator.Stop();
body = "{\"ok\":true}";
}
else if (path == "/walk_to_edge")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var rb = reqBody.Replace(" ", "");
var dirMatch = System.Text.RegularExpressions.Regex.Match(rb, "\"direction\"\\s*:\\s*\"([^\"]+)\"");
var extraMatch = System.Text.RegularExpressions.Regex.Match(rb, "\"extra_tiles\"\\s*:\\s*([0-9.]+)");
bool dirRight = !dirMatch.Success || dirMatch.Groups[1].Value != "left";
float extraTiles = extraMatch.Success ? float.Parse(extraMatch.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture) : 2f;
WalkCoordinator.Start(dirRight, extraTiles);
body = "{\"ok\":true}";
}
else if (path == "/walk_to_edge_stop")
{
WalkCoordinator.Stop();
body = "{\"ok\":true}";
}
else if (path == "/jump")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var rb = reqBody.Replace(" ", "");
var dirMatch = System.Text.RegularExpressions.Regex.Match(rb, "\"direction\"\\s*:\\s*\"([^\"]+)\"");
var lxMatch = System.Text.RegularExpressions.Regex.Match(rb, "\"launch_x\"\\s*:\\s*(-?[0-9.]+)");
var txMatch = System.Text.RegularExpressions.Regex.Match(rb, "\"target_x\"\\s*:\\s*(-?[0-9.]+)");
bool dirRight = !dirMatch.Success || dirMatch.Groups[1].Value != "left";
float launchX = lxMatch.Success ? float.Parse(lxMatch.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture) : 0f;
float targetX = txMatch.Success ? float.Parse(txMatch.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture) : launchX;
JumpCoordinator.Start(dirRight, launchX, targetX);
body = "{\"ok\":true}";
}
else if (path == "/jump_stop")
{
JumpCoordinator.Stop();
body = "{\"ok\":true}";
}
else if (path == "/jump_done")
{
body = !JumpCoordinator.IsActive ? "{\"done\":true}" : "{\"done\":false}";
}
else if (path == "/jump_envelope")
{
var p = Main.LocalPlayer;
if (p == null || !p.active)
{
body = "{\"error\":\"no_player\"}";
status = 503;
}
else
{
float js = Player.jumpSpeed;
float grav = p.gravity > 0f ? p.gravity : 0.4f;
int jh = Player.jumpHeight;
float vx = Math.Max(p.maxRunSpeed, p.accRunSpeed);
float maxFall = p.maxFallSpeed;
int tileSize = 16;
float holdSpeed = js - grav;
float phase1Ticks = jh + 1;
float phase2Ticks = holdSpeed / grav;
float peakT = phase1Ticks + phase2Ticks;
float peakRisePx = holdSpeed * phase1Ticks + holdSpeed * phase2Ticks - 0.5f * grav * phase2Ticks * phase2Ticks;
int maxCols = 32;
var sb2 = new StringBuilder();
sb2.Append("{\"envelope\":[");
for (int col = 0; col < maxCols; col++)
{
if (col > 0) sb2.Append(',');
float t = col * tileSize / Math.Max(vx, 0.01f);
float risePx;
if (t <= phase1Ticks)
risePx = holdSpeed * t;
else if (t <= peakT)
{
float dt = t - phase1Ticks;
risePx = holdSpeed * phase1Ticks + holdSpeed * dt - 0.5f * grav * dt * dt;
}
else
{
float dt = t - peakT;
risePx = peakRisePx - 0.5f * grav * dt * dt;
}
int dy = (int)(-risePx / tileSize);
sb2.Append(dy);
}
sb2.Append("],");
sb2.Append("\"vx\":").Append(vx.ToString("0.###", System.Globalization.CultureInfo.InvariantCulture)).Append(',');
sb2.Append("\"jump_speed\":").Append(js.ToString("0.###", System.Globalization.CultureInfo.InvariantCulture)).Append(',');
sb2.Append("\"jump_height\":").Append(jh).Append(',');
sb2.Append("\"gravity\":").Append(grav.ToString("0.###", System.Globalization.CultureInfo.InvariantCulture));
sb2.Append('}');
body = sb2.ToString();
}
}
else if (path == "/skill")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var rb = reqBody.Replace(" ", "");
var nameMatch = System.Text.RegularExpressions.Regex.Match(rb, "\"name\"\\s*:\\s*\"([^\"]+)\"");
var dirMatch = System.Text.RegularExpressions.Regex.Match(rb, "\"direction\"\\s*:\\s*\"([^\"]+)\"");
if (nameMatch.Success)
{
string skillName = nameMatch.Groups[1].Value;
bool dirRight = !dirMatch.Success || dirMatch.Groups[1].Value != "left";
if (skillName == "pillar_jump")
{
var riseMatch = System.Text.RegularExpressions.Regex.Match(rb, "\"rise_tiles\"\\s*:\\s*(\\d+)");
int riseTiles = riseMatch.Success ? int.Parse(riseMatch.Groups[1].Value) : 8;
SkillExecutor.StartPillarJump(dirRight, riseTiles);
body = "{\"ok\":true,\"skill\":\"pillar_jump\",\"rise_tiles\":" + riseTiles + "}";
}
else if (skillName == "dig_down")
{
SkillExecutor.StartDigDown();
body = "{\"ok\":true,\"skill\":\"dig_down\"}";
}
else if (skillName == "dig_left")
{
SkillExecutor.StartDigLeft();
body = "{\"ok\":true,\"skill\":\"dig_left\"}";
}
else if (skillName == "dig_right")
{
SkillExecutor.StartDigRight();
body = "{\"ok\":true,\"skill\":\"dig_right\"}";
}
else if (skillName == "dig_up")
{
SkillExecutor.StartDigUp();
body = "{\"ok\":true,\"skill\":\"dig_up\"}";
}
else if (skillName == "stop")
{
SkillExecutor.Stop();
body = "{\"ok\":true,\"skill\":\"stop\"}";
}
else
{
body = "{\"error\":\"unknown_skill\",\"name\":\"" + skillName + "\"}";
status = 400;
}
}
else
{
body = "{\"error\":\"bad_params\"}";
status = 400;
}
}
else if (path == "/replay")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var frames = new System.Collections.Generic.List<ReplayFrame>();
var frameMatches = System.Text.RegularExpressions.Regex.Matches(reqBody, "\\{[^}]*\\}");
foreach (System.Text.RegularExpressions.Match m in frameMatches)
{
var rb = m.Value.Replace(" ", "");
var mxm = System.Text.RegularExpressions.Regex.Match(rb, "\"mx\":(-?[0-9.]+)");
var mym = System.Text.RegularExpressions.Regex.Match(rb, "\"my\":(-?[0-9.]+)");
var slotm = System.Text.RegularExpressions.Regex.Match(rb, "\"slot\":(\\d+)");
var scm = System.Text.RegularExpressions.Regex.Match(rb, "\"sc\":([01])");
var reprm = System.Text.RegularExpressions.Regex.Match(rb, "\"repeat\":(\\d+)");
int repeat = reprm.Success ? int.Parse(reprm.Groups[1].Value) : 1;
var frame = new ReplayFrame
{
Left = rb.Contains("\"left\":true"),
Right = rb.Contains("\"right\":true"),
Up = rb.Contains("\"up\":true"),
Down = rb.Contains("\"down\":true"),
Jump = rb.Contains("\"jump\":true"),
UseItem = rb.Contains("\"use_item\":true"),
Grapple = rb.Contains("\"grapple\":true"),
UseAlt = rb.Contains("\"use_alt\":true"),
UseTile = rb.Contains("\"use_tile\":true"),
Mount = rb.Contains("\"mount\":true"),
SelectedSlot = slotm.Success ? int.Parse(slotm.Groups[1].Value) : -1,
SmartCursor = scm.Success ? int.Parse(scm.Groups[1].Value) : -1,
Mx = mxm.Success ? float.Parse(mxm.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture) : 0f,
My = mym.Success ? float.Parse(mym.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture) : 0f,
};
for (int r = 0; r < repeat; r++) frames.Add(frame);
}
ReplaySystem.Load(frames);
body = "{\"ok\":true,\"frames\":" + frames.Count + "}";
}
else if (path == "/replay_stop")
{
ReplaySystem.Stop();
body = "{\"ok\":true}";
}
else if (path == "/record_start")
{
RecordSystem.Start();
body = "{\"ok\":true}";
}
else if (path == "/record_stop")
{
string recorded = RecordSystem.Stop();
body = recorded;
}
else if (path == "/test_action")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var rb = reqBody.Replace(" ", "");
var nm = System.Text.RegularExpressions.Regex.Match(reqBody, "\"name\"\\s*:\\s*\"([^\"]+)\"");
var dm = System.Text.RegularExpressions.Regex.Match(rb, "\"dir\":(-?\\d+)");
string aName = nm.Success ? nm.Groups[1].Value : "";
int aDir = dm.Success ? int.Parse(dm.Groups[1].Value) : 0;
StateSpacePlanner.RequestTestAction(aName, aDir);
body = $"{{\"ok\":true,\"name\":\"{aName}\",\"dir\":{aDir}}}";
}
else if (path == "/craft")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var rb = reqBody.Replace(" ", "");
var idMatch = System.Text.RegularExpressions.Regex.Match(rb, "\"item_id\":(\\d+)");
var nameMatch = System.Text.RegularExpressions.Regex.Match(reqBody, "\"item_name\"\\s*:\\s*\"([^\"]+)\"");
var amtMatch = System.Text.RegularExpressions.Regex.Match(rb, "\"amount\":(\\d+)");
int amount = amtMatch.Success ? int.Parse(amtMatch.Groups[1].Value) : 1;
int targetId = -1;
if (idMatch.Success)
targetId = int.Parse(idMatch.Groups[1].Value);
else if (nameMatch.Success)
{
string targetName = nameMatch.Groups[1].Value.ToLowerInvariant();
for (int ri = 0; ri < Main.numAvailableRecipes; ri++)
{
var r = Main.recipe[Main.availableRecipe[ri]];
if ((r.createItem.Name ?? "").ToLowerInvariant() == targetName)
{
targetId = r.createItem.type;
break;
}
}
}
if (targetId < 0)
{
var sb2 = new System.Text.StringBuilder();
sb2.Append("{\"error\":\"item_not_found\",\"name_matched\":").Append(nameMatch.Success.ToString().ToLower());
sb2.Append(",\"available_count\":").Append(Main.numAvailableRecipes);
sb2.Append(",\"raw_name\":\"").Append(nameMatch.Success ? nameMatch.Groups[1].Value : "").Append("\"");
sb2.Append(",\"available_names\":[");
for (int ri = 0; ri < Main.numAvailableRecipes; ri++)
{
if (ri > 0) sb2.Append(',');
sb2.Append('"').Append(Main.recipe[Main.availableRecipe[ri]].createItem.Name ?? "").Append('"');
}
sb2.Append("]}");
body = sb2.ToString();
status = 400;
}
else
{
int crafted = CraftCoordinator.Craft(targetId, amount);
if (crafted > 0)
body = "{\"ok\":true,\"crafted\":" + crafted + "}";
else
body = "{\"error\":\"not_available\",\"item_id\":" + targetId + "}";
}
}
else if (path == "/nav")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var rb = reqBody.Replace(" ", "");
var gxM = System.Text.RegularExpressions.Regex.Match(rb, "\"gx\":(-?\\d+)");
var gyM = System.Text.RegularExpressions.Regex.Match(rb, "\"gy\":(-?\\d+)");
if (!gxM.Success || !gyM.Success)
{
body = "{\"ok\":false,\"reason\":\"bad_request\"}";
status = 400;
}
else
{
int gxN = int.Parse(gxM.Groups[1].Value);
int gyN = int.Parse(gyM.Groups[1].Value);
// route single-point nav through the NEW StateSpacePlanner (physics-faithful) instead of the
// legacy NavCoordinator. Execute plans + dispatches; ExecFailCode tells us if planning failed.
var ssr = StateSpacePlanner.Execute(gxN, gyN);
if (ssr.Found)
body = "{\"ok\":true,\"goal\":[" + gxN + "," + gyN + "]}";
else
{
string code = string.IsNullOrEmpty(StateSpacePlanner.ExecFailCode) ? "unreachable" : StateSpacePlanner.ExecFailCode;
body = "{\"ok\":false,\"reason\":\"" + code + "\"}";
status = 400;
}
}
}
else if (path == "/nav_unlimited")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var rb = reqBody.Replace(" ", "");
var gxM = System.Text.RegularExpressions.Regex.Match(rb, "\"gx\":(-?\\d+)");
var gyM = System.Text.RegularExpressions.Regex.Match(rb, "\"gy\":(-?\\d+)");
if (!gxM.Success || !gyM.Success)
{
body = "{\"ok\":false,\"reason\":\"bad_request\"}";
status = 400;
}
else
{
int gxN = int.Parse(gxM.Groups[1].Value);
int gyN = int.Parse(gyM.Groups[1].Value);
NavCoordinator.StartTo(gxN, gyN);
body = "{\"ok\":true,\"goal\":[" + gxN + "," + gyN + "],\"unlimited\":true}";
}
}
else if (path == "/nav_start")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var rb = reqBody.Replace(" ", "");
var signMatch = System.Text.RegularExpressions.Regex.Match(rb, "\"sign\"\\s*:\\s*(-?1)");
int navSign = signMatch.Success ? int.Parse(signMatch.Groups[1].Value) : 1;
// direction explore now runs on the NEW StateSpacePlanner via ExploreCoordinator (was NavCoordinator).
ExploreCoordinator.Start(navSign);
body = "{\"ok\":true}";
}
else if (path == "/nav_set_path")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var signMatch = System.Text.RegularExpressions.Regex.Match(reqBody.Replace(" ", ""), "\"sign\"\\s*:\\s*(-?1)");
int navSign = signMatch.Success ? int.Parse(signMatch.Groups[1].Value) : 1;
var nodes = NavCoordinator.ParsePathPublic(reqBody);
if (nodes != null && nodes.Count > 0)
{
NavCoordinator.SetPath(navSign, nodes);
body = $"{{\"ok\":true,\"nodes\":{nodes.Count}}}";
}
else
{
body = "{\"ok\":false,\"error\":\"no nodes parsed\"}";
}
}
else if (path == "/nav_stop")
{
ExploreCoordinator.Stop(); // direction explore (new); also stops the SSP leg it dispatched
NavCoordinator.Stop(); // legacy, in case anything still drives it
StateSpacePlanner.StopExec();
body = "{\"ok\":true}";
}
else if (path == "/sim_jump")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var rb = reqBody.Replace(" ", "");
float simPx = float.Parse(System.Text.RegularExpressions.Regex.Match(rb, "\"px\":(-?[\\d.]+)").Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture);
float simPy = float.Parse(System.Text.RegularExpressions.Regex.Match(rb, "\"py\":(-?[\\d.]+)").Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture);
float simVx = float.Parse(System.Text.RegularExpressions.Regex.Match(rb, "\"vx\":(-?[\\d.]+)").Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture);
int simHold = int.Parse(System.Text.RegularExpressions.Regex.Match(rb, "\"hold\":(\\d+)").Groups[1].Value);
int simSign = System.Text.RegularExpressions.Regex.Match(rb, "\"sign\":(-?1)").Success ? int.Parse(System.Text.RegularExpressions.Regex.Match(rb, "\"sign\":(-?1)").Groups[1].Value) : 1;
var simVyMatch = System.Text.RegularExpressions.Regex.Match(rb, "\"vy\":(-?[\\d.]+)");
float simVy = simVyMatch.Success ? float.Parse(simVyMatch.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture) : 0f;
var simGroundedMatch = System.Text.RegularExpressions.Regex.Match(rb, "\"grounded\":(true|false)");
bool simGrounded = !simGroundedMatch.Success || simGroundedMatch.Groups[1].Value == "true";
var simStart = new PhysicsSimulator.State { Px = simPx, Py = simPy, Vx = simVx, Vy = simVy, Grounded = simGrounded, JumpFramesLeft = simHold };
var simResult = PhysicsSimulator.SimulateJump(simStart, simSign, simHold);
var sb2 = new System.Text.StringBuilder();
sb2.Append("{\"landed\":").Append(simResult.Landed ? "true" : "false");
sb2.Append(",\"cx\":").Append(simResult.Cx).Append(",\"cy\":").Append(simResult.Cy);
sb2.Append(",\"end_px\":").Append(simResult.EndState.Px.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture));
sb2.Append(",\"end_py\":").Append(simResult.EndState.Py.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture));
sb2.Append(",\"end_vx\":").Append(simResult.EndState.Vx.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture));
sb2.Append(",\"end_vy\":").Append(simResult.EndState.Vy.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture));
sb2.Append(",\"end_grounded\":").Append(simResult.EndState.Grounded ? "true" : "false");
sb2.Append(",\"min_py\":").Append(simResult.MinPy.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture));
sb2.Append(",\"frames\":[");
var s2 = simStart;
for (int fi = 0; fi < simResult.Frames.Count; fi++)
{
if (fi > 0) sb2.Append(',');
var inp = simResult.Frames[fi];
var ns = PhysicsSimulator.Step(s2, inp);
int fcx = (int)((ns.Px + PhysicsSimulator.PlayerW / 2f) / 16);
int fcy = (int)((ns.Py + PhysicsSimulator.PlayerH) / 16);
sb2.Append($"{{\"f\":{fi},\"px\":{ns.Px.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture)},\"py\":{ns.Py.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture)},\"vx\":{ns.Vx.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture)},\"vy\":{ns.Vy.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture)},\"cx\":{fcx},\"cy\":{fcy},\"g\":{(ns.Grounded ? 1 : 0)}}}");
s2 = ns;
}
sb2.Append("]}");
body = sb2.ToString();
}
else if (path == "/start_seg_nav")
{
string reqBodySN;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBodySN = sr.ReadToEnd();
var rbSN = reqBodySN.Replace(" ", "");
int gxSN = int.Parse(System.Text.RegularExpressions.Regex.Match(rbSN, "\"gx\":(-?\\d+)").Groups[1].Value);
int gySN = int.Parse(System.Text.RegularExpressions.Regex.Match(rbSN, "\"gy\":(-?\\d+)").Groups[1].Value);
SegmentedNavCoordinator.StartTo(gxSN, gySN);
body = "{\"ok\":true}";
}
else if (path == "/stop_seg_nav")
{
SegmentedNavCoordinator.Stop();
body = "{\"ok\":true}";
}
else if (path == "/debug_segment_plan")
{
string reqBodyS;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBodyS = sr.ReadToEnd();
var rbS = reqBodyS.Replace(" ", "");
int gxS = int.Parse(System.Text.RegularExpressions.Regex.Match(rbS, "\"gx\":(-?\\d+)").Groups[1].Value);
int gyS = int.Parse(System.Text.RegularExpressions.Regex.Match(rbS, "\"gy\":(-?\\d+)").Groups[1].Value);
var mR = System.Text.RegularExpressions.Regex.Match(rbS, "\"radius\":(\\d+)");
int radiusS = mR.Success ? int.Parse(mR.Groups[1].Value) : 25;
body = PathPlanner.PlanToWindowed(gxS, gyS, radiusS);
var segNodes = NavCoordinator.ParsePathPublic(body);
PathVisSystem.SetPlanPath(segNodes, PathPlanner.GetEnvelopeCache());
}
else if (path == "/ss_plan")
{
string rbBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
rbBody = sr.ReadToEnd();
var rb2 = rbBody.Replace(" ", "");
int gx2 = int.Parse(System.Text.RegularExpressions.Regex.Match(rb2, "\"gx\":(-?\\d+)").Groups[1].Value);
int gy2 = int.Parse(System.Text.RegularExpressions.Regex.Match(rb2, "\"gy\":(-?\\d+)").Groups[1].Value);
var ssr = StateSpacePlanner.Plan(gx2, gy2);
StateSpacePlanner.Visualize(ssr, gx2, gy2);
var sb2 = new System.Text.StringBuilder();
sb2.Append("{\"found\":").Append(ssr.Found ? "true" : "false");
sb2.Append(",\"expansions\":").Append(ssr.Expansions);
sb2.Append(",\"millis\":").Append(ssr.Millis.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture));
sb2.Append(",\"path_len\":").Append(ssr.Path.Count);
sb2.Append(",\"best_dx\":").Append(ssr.BestDx.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture));
sb2.Append(",\"best_dy\":").Append(ssr.BestDy.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture));
sb2.Append(",\"path\":[");
for (int i = 0; i < ssr.Path.Count; i++)
{
if (i > 0) sb2.Append(',');
sb2.Append('[').Append((int)ssr.Path[i].px).Append(',').Append((int)ssr.Path[i].py).Append(']');
}
sb2.Append("]}");
body = sb2.ToString();
}
else if (path == "/debug_waypoints")
{
string reqBodyW;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBodyW = sr.ReadToEnd();
var rbW = reqBodyW.Replace(" ", "");
int gxW = int.Parse(System.Text.RegularExpressions.Regex.Match(rbW, "\"gx\":(-?\\d+)").Groups[1].Value);
int gyW = int.Parse(System.Text.RegularExpressions.Regex.Match(rbW, "\"gy\":(-?\\d+)").Groups[1].Value);
var pw = Main.LocalPlayer;
if (pw == null) { body = "{\"error\":\"no_player\"}"; }
else
{
int sxW = (int)((pw.position.X + pw.width / 2f) / 16f);
int syW = (int)((pw.position.Y + pw.height) / 16f);
var wps = WaypointPlanner.Generate(sxW, syW, gxW, gyW);
var tilesW = new System.Collections.Generic.List<(int, int, Microsoft.Xna.Framework.Color)>();
foreach (var (wxW, wyW) in wps)
tilesW.Add((wxW, wyW, new Microsoft.Xna.Framework.Color(255, 100, 255, 220)));
PathVisSystem.SetTiles(tilesW, ttlFrames: 600);
var sbW = new System.Text.StringBuilder();
sbW.Append("{\"start\":[").Append(sxW).Append(',').Append(syW).Append("],\"waypoints\":[");
for (int i = 0; i < wps.Count; i++)
{
if (i > 0) sbW.Append(',');
sbW.Append('[').Append(wps[i].wx).Append(',').Append(wps[i].wy).Append(']');
}
sbW.Append("]}");
body = sbW.ToString();
}
}
else if (path == "/exec_jump_to")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var rb = reqBody.Replace(" ", "");
int ejTargetCx = int.Parse(System.Text.RegularExpressions.Regex.Match(rb, "\"target_cx\":(-?\\d+)").Groups[1].Value);
int ejSign2 = System.Text.RegularExpressions.Regex.Match(rb, "\"sign\":(-?1)").Success ? int.Parse(System.Text.RegularExpressions.Regex.Match(rb, "\"sign\":(-?1)").Groups[1].Value) : 1;
body = JumpExecutor.FindAndExecute(ejTargetCx, ejSign2);
}
else if (path == "/exec_jump")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var rb = reqBody.Replace(" ", "");
int ejHold = int.Parse(System.Text.RegularExpressions.Regex.Match(rb, "\"hold\":(\\d+)").Groups[1].Value);
int ejSign = System.Text.RegularExpressions.Regex.Match(rb, "\"sign\":(-?1)").Success ? int.Parse(System.Text.RegularExpressions.Regex.Match(rb, "\"sign\":(-?1)").Groups[1].Value) : 1;
var ejMsM = System.Text.RegularExpressions.Regex.Match(rb, "\"move_start\":(\\d+)");
var ejMfM = System.Text.RegularExpressions.Regex.Match(rb, "\"move_frames\":(\\d+)");
int ejMoveStart = ejMsM.Success ? int.Parse(ejMsM.Groups[1].Value) : 0;
int ejMoveFrames = ejMfM.Success ? int.Parse(ejMfM.Groups[1].Value) : ejHold;
JumpExecutor.Start(ejHold, ejSign, ejMoveStart, ejMoveFrames);
body = "{\"ok\":true}";
}
else if (path == "/exec_jump_result")
{
body = JumpExecutor.GetResult();
}
else if (path == "/test_plat_up")
{
var pp = Main.LocalPlayer;
if (pp == null) { body = "{\"error\":\"no_player\"}"; }
else
{
int slot = NavCoordinator.FindPlatformSlot(pp);
if (slot < 0) { body = "{\"error\":\"no_platform_item\"}"; }
else
{
var frames = PlatformExecutor.BuildPlatUpFrames(pp, slot);
ReplaySystem.Load(frames);
body = $"{{\"ok\":true,\"slot\":{slot},\"total_frames\":{frames.Count}}}";
}
}
}
else if (path == "/test_plat_up_n")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var rb = reqBody.Replace(" ", "");
var nM = System.Text.RegularExpressions.Regex.Match(rb, "\"n\":(\\d+)");
int n = nM.Success ? int.Parse(nM.Groups[1].Value) : 2;
var pp = Main.LocalPlayer;
if (pp == null) { body = "{\"error\":\"no_player\"}"; }
else
{
int slot = NavCoordinator.FindPlatformSlot(pp);
if (slot < 0) { body = "{\"error\":\"no_platform_item\"}"; }
else
{
var seg = PlatformExecutor.BuildPlatUpFrames(pp, slot);
var all = new System.Collections.Generic.List<ReplayFrame>();
for (int i = 0; i < n; i++) all.AddRange(seg);
ReplaySystem.Load(all);
body = $"{{\"ok\":true,\"slot\":{slot},\"n\":{n},\"total_frames\":{all.Count}}}";
}
}
}
else if (path == "/test_plat_jump")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var rb = reqBody.Replace(" ", "");
var signM = System.Text.RegularExpressions.Regex.Match(rb, "\"sign\":(-?1)");
int sign = signM.Success ? int.Parse(signM.Groups[1].Value) : 1;
var pp = Main.LocalPlayer;
if (pp == null) { body = "{\"error\":\"no_player\"}"; }
else
{
int slot = NavCoordinator.FindPlatformSlot(pp);
if (slot < 0) { body = "{\"error\":\"no_platform_item\"}"; }
else
{
var frames = PlatformExecutor.BuildPlatJumpFrames(pp, slot, sign, out int placeTx, out int placeTy, out int landFrame);
ReplaySystem.Load(frames);
body = $"{{\"ok\":true,\"slot\":{slot},\"land_frame\":{landFrame},\"place_tx\":{placeTx},\"place_ty\":{placeTy},\"total_frames\":{frames.Count}}}";
}
}
}
else if (path == "/test_plat_jump_n")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var rb = reqBody.Replace(" ", "");
var nM = System.Text.RegularExpressions.Regex.Match(rb, "\"n\":(\\d+)");
var signM2 = System.Text.RegularExpressions.Regex.Match(rb, "\"sign\":(-?1)");
int n = nM.Success ? int.Parse(nM.Groups[1].Value) : 2;
int sign2 = signM2.Success ? int.Parse(signM2.Groups[1].Value) : 1;
body = PlatJumpExecutor.StartN(n, sign2);
}
else if (path == "/mark_placeable")
{
var p3 = Main.LocalPlayer;
if (p3 == null) { body = "{\"error\":\"no_player\"}"; }
else
{
int pcx = (int)((p3.position.X + p3.width / 2f) / 16f);
int pcy = (int)((p3.position.Y + p3.height) / 16f);
var tiles = new System.Collections.Generic.List<(int, int, Microsoft.Xna.Framework.Color)>();
for (int dx = -3; dx <= 3; dx++)
for (int dy = -3; dy <= 3; dy++)
{
int tx = pcx + dx, ty = pcy + dy;
if (PathPlanner.CanPlacePlatformAt(tx, ty))
tiles.Add((tx, ty, new Microsoft.Xna.Framework.Color(0, 255, 180, 160)));
}
PathVisSystem.SetTiles(tiles, ttlFrames: 300);
body = $"{{\"ok\":true,\"count\":{tiles.Count}}}";
}
}
else if (path == "/debug_jump_edges")
{
string reqBody;
using (var sr = new System.IO.StreamReader(ctx.Request.InputStream))
reqBody = sr.ReadToEnd();
var rb = reqBody.Replace(" ", "");
int dbgCx = int.Parse(System.Text.RegularExpressions.Regex.Match(rb, "\"cx\":(-?\\d+)").Groups[1].Value);
int dbgCy = int.Parse(System.Text.RegularExpressions.Regex.Match(rb, "\"cy\":(-?\\d+)").Groups[1].Value);
int dbgSign = System.Text.RegularExpressions.Regex.Match(rb, "\"sign\":(-?1)").Success ? int.Parse(System.Text.RegularExpressions.Regex.Match(rb, "\"sign\":(-?1)").Groups[1].Value) : 1;
var p2 = Main.LocalPlayer;
var edges = PathPlanner.DebugJumpEdges(p2, dbgCx, dbgCy, dbgSign);
var sb3 = new System.Text.StringBuilder();
sb3.Append("[");
for (int ei = 0; ei < edges.Count; ei++)
{
if (ei > 0) sb3.Append(',');
sb3.Append($"{{\"lx\":{edges[ei].lx},\"ly\":{edges[ei].ly},\"hold\":{edges[ei].hold}}}");
}
sb3.Append("]");
body = sb3.ToString();
}