-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgui.cpp
More file actions
1849 lines (1537 loc) · 69.6 KB
/
Copy pathgui.cpp
File metadata and controls
1849 lines (1537 loc) · 69.6 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
// gui.cpp : ImGui + GLFW + OpenGL3 - Clean GUI Only
#define _CRT_SECURE_NO_WARNINGS
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <string>
#include <vector>
#include <ctime>
#include <thread>
#include <chrono>
#include <atomic>
#include <random>
#include <cstring>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <algorithm>
#include <filesystem>
#ifdef _WIN32
#include <Windows.h>
#include <Shellapi.h> // For ShellExecute
#include <commdlg.h> // For file dialog
#pragma comment(lib, "comdlg32.lib")
#endif
#define IMGUI_IMPL_OPENGL_LOADER_GLAD
#include "glad/glad.h"
#define GLFW_DLL
#include <GLFW/glfw3.h>
#include "backends/imgui_impl_glfw.h"
#include "backends/imgui_impl_opengl3.h"
#include "imgui.h"
#include "capture screen.h"
#include "Discord.h"
void OpenURL(const char* url) {
#ifdef _WIN32
ShellExecuteA(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
#endif
}
std::chrono::steady_clock::time_point g_LastAdTime;
bool g_IsFirstRun = true;
std::string g_AdbPath = "C:\\Program Files\\Microvirt\\MEmu\\adb.exe";
std::string g_MEmuPath = "C:\\Program Files\\Microvirt\\MEmu\\MEmu.exe";
extern int g_SleepAfterScreenshot;
// Template thresholds
struct TemplateThresholds {
float soilThreshold = 0.70f;
float grownThreshold = 0.7f;
float wheatThreshold = 0.70f;
float sickleThreshold = 0.70f;
float nmsThreshold = 0.3f;
float shopThreshold = 0.80f;
float crateThreshold = 0.80f;
float arrowsThreshold = 0.85f;
float plusThreshold = 0.80f;
float crossThreshold = 0.80f;
float advertiseThreshold = 0.72f;
float createSaleThreshold = 0.80f;
// --- CORN THRESHOLDS ---
float cornThreshold = 0.70f;
float grownCornThreshold = 0.70f;
};
TemplateThresholds g_Thresholds;
// Template paths
std::string f_templatePath = "templates\\field.png";
std::string w_templatePath = "templates\\wheat.png";
std::string s_templatePath = "templates\\sickle.png";
std::string g_templatePath = "templates\\grown.png";
std::string shop_templatePath = "templates\\shop.png";
std::string wheatshop_templatePath = "templates\\wheat_shop.png";
std::string soldcrate_templatePath = "templates\\sold_crate.png";
std::string crate_templatePath = "templates\\shop_crate.png";
std::string arrows_templatePath = "templates\\arrows.png";
std::string plus_templatePath = "templates\\plus.png";
std::string cross_templatePath = "templates\\cross.png";
std::string advertise_templatePath = "templates\\advertise.png";
std::string create_sale_templatePath = "templates\\create_sale.png";
std::string c_templatePath = "templates\\corn.png";
std::string gc_templatePath = "templates\\grown_corn.png"; // gc stands for grown corn
std::string cornshop_templatePath = "templates\\corn_shop.png";
std::string barn_market_templatePath = "templates\\barn_market.png";
std::string silo_market_templatePath = "templates\\silo_market.png";
// Template path buffers for ImGui input
char g_fieldPathBuf[260] = "templates\\field.png";
char g_wheatPathBuf[260] = "templates\\wheat.png";
char g_sicklePathBuf[260] = "templates\\sickle.png";
char g_grownPathBuf[260] = "templates\\grown.png";
char g_shopPathBuf[260] = "templates\\shop.png";
char g_wheatshopPathBuf[260] = "templates\\wheat_shop.png";
char g_soldcratePathBuf[260] = "templates\\sold_crate.png";
char g_cratePathBuf[260] = "templates\\shop_crate.png";
char g_arrowsPathBuf[260] = "templates\\arrows.png";
char g_plusPathBuf[260] = "templates\\plus.png";
char g_crossPathBuf[260] = "templates\\cross.png";
char g_advertisePathBuf[260] = "templates\\advertise.png";
char g_createSalePathBuf[260] = "templates\\create_sale.png";
char g_cornPathBuf[260] = "templates\\corn.png";
char g_grownCornPathBuf[260] = "templates\\grown_corn.png";
char g_cornShopPathBuf[260] = "templates\\corn_shop.png";
char g_barnMarketBuf[260] = "templates\\barn_market.png";
char g_siloMarketBuf[260] = "templates\\silo_market.png";
// Selected Crop
int g_SelectedCropMode = 0;
const char* g_CropModes[] = { "Wheat (2 min)", "Corn (5 min)" };
double GetDistance(cv::Point p1, cv::Point p2) {
return std::sqrt(std::pow(p1.x - p2.x, 2) + std::pow(p1.y - p2.y, 2));
}
std::vector<cv::Point> FilterUniqueMatches(const std::vector<cv::Point>& rawMatches, int minDist) {
std::vector<cv::Point> uniqueMatches;
for (const auto& pt : rawMatches) {
bool isTooClose = false;
for (const auto& existing : uniqueMatches) {
if (GetDistance(pt, existing) < minDist) {
isTooClose = true;
break;
}
}
if (!isTooClose) {
uniqueMatches.push_back(pt);
}
}
return uniqueMatches;
}
int f_konumX = 0;
int f_konumY = 0;
int w_konumX = 0;
int w_konumY = 0;
int s_konumX = 0;
int s_konumY = 0;
int g_konumX = 0;
int g_konumY = 0;
bool g_EnableDiscordRPC = true; // On by default, can be toggled off in settings
std::atomic<bool> g_BotRunning{ false };
//webhook stuff
// --- WEBHOOK & CYCLE VARIABLES ---
int g_CycleCount = 0; // Cycle counter
// Webhook Settings
bool g_EnableWebhook = false;
bool g_EnableDiscord = false;
bool g_EnableTelegram = false;
char g_DiscordWebhookBuf[512] = "";
char g_TelegramTokenBuf[128] = "";
char g_TelegramChatIdBuf[128] = "";
// ============================================================================
// FILE DIALOG HELPER
// ============================================================================
#ifdef _WIN32
std::string OpenFileDialog(const char* filter = "PNG Files\0*.png\0All Files\0*.*\0") { // Default filter for PNG files when loading a template.
OPENFILENAMEA ofn;
char fileName[MAX_PATH] = "";
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(OPENFILENAMEA);
ofn.hwndOwner = NULL;
ofn.lpstrFilter = filter;
ofn.lpstrFile = fileName;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
ofn.lpstrDefExt = "png";
if (GetOpenFileNameA(&ofn)) {
return std::string(fileName);
}
return "";
}
#endif
// ============================================================================
// Start, Stop bot button management helper function.
// ============================================================================
bool SmartSleep(int milliseconds) {
int step = 100; // Check every 100ms
for (int i = 0; i < milliseconds; i += step) {
if (!g_BotRunning) return false; // Stop signal received
std::this_thread::sleep_for(std::chrono::milliseconds(step));
}
return true;
}
// ============================================================================
// LOG SYSTEM
// ============================================================================
std::string GetTimeStr() {
time_t rawtime;
struct tm* timeinfo;
char buffer[80];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, sizeof(buffer), "%H:%M:%S", timeinfo);
return std::string(buffer);
}
struct LogEntry {
std::string timestamp;
std::string message;
ImVec4 color;
};
std::vector<LogEntry> g_Logs;
void AddLog(std::string message, ImVec4 color = ImVec4(0.7f, 0.7f, 0.7f, 1.0f)) {
LogEntry newLog;
newLog.timestamp = GetTimeStr();
newLog.message = message;
newLog.color = color;
g_Logs.push_back(newLog);
if (g_Logs.size() > 500) {
g_Logs.erase(g_Logs.begin(), g_Logs.begin() + 100);
}
}
// Check helper
bool IsBotStopped() {
if (!g_BotRunning) {
AddLog("Stopping...", ImVec4(1, 0.2f, 0.2f, 1));
return true;
}
return false;
}
// ============================================================================
// PROCESS HELPERS
// ============================================================================
bool RunCmdHidden(const std::string& command)
{
STARTUPINFOA si{};
PROCESS_INFORMATION pi{};
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
std::string finalCmd = "cmd /S /C \"" + command + "\"";
BOOL ok = CreateProcessA(
nullptr,
(LPSTR)finalCmd.c_str(), // Yeni komut yapısı
nullptr,
nullptr,
FALSE,
CREATE_NO_WINDOW,
nullptr,
nullptr,
&si,
&pi
);
if (!ok) return false;
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return true;
}
// Helper: Send Image via Curl (Background Thread)
void SendWebhookImage(std::string imagePath, std::string caption) {
std::string cmd = "";
// Discord Sending
if (g_EnableDiscord && strlen(g_DiscordWebhookBuf) > 5) {
// Discord multipart upload
cmd = "curl -i -H \"Content-Type: multipart/form-data\" -X POST -F \"file1=@" + imagePath + "\" \"" + std::string(g_DiscordWebhookBuf) + "\"";
RunCmdHidden(cmd);
}
// Telegram Sending
if (g_EnableTelegram && strlen(g_TelegramTokenBuf) > 5 && strlen(g_TelegramChatIdBuf) > 1) {
// Telegram sendPhoto API
std::string token = g_TelegramTokenBuf;
std::string chat_id = g_TelegramChatIdBuf;
cmd = "curl -F photo=@" + imagePath + " -F caption=\"" + caption + "\" https://api.telegram.org/bot" + token + "/sendPhoto?chat_id=" + chat_id;
RunCmdHidden(cmd);
}
}
void SendWebhookMessage(std::string message, bool force = false) {
std::string cmd = "";
if ((g_EnableDiscord || force) && strlen(g_DiscordWebhookBuf) > 5) {
std::string json = "{\"content\":\"" + message + "\"}";
cmd = "curl -H \"Content-Type: application/json\" -X POST -d \"" + json + "\" \"" + std::string(g_DiscordWebhookBuf) + "\"";
RunCmdHidden(cmd);
}
// Telegram Message
if ((g_EnableTelegram || force) && strlen(g_TelegramTokenBuf) > 5 && strlen(g_TelegramChatIdBuf) > 1) {
std::string token = g_TelegramTokenBuf;
std::string chat_id = g_TelegramChatIdBuf;
std::replace(message.begin(), message.end(), ' ', '+');
cmd = "curl -s -X POST https://api.telegram.org/bot" + token + "/sendMessage -d chat_id=" + chat_id + " -d text=\"" + message + "\"";
RunCmdHidden(cmd);
}
}
bool StartProcessDetached(const std::string& exePath)
{
STARTUPINFOA si{};
PROCESS_INFORMATION pi{};
si.cb = sizeof(si);
std::string cmd = "\"" + exePath + "\"";
BOOL ok = CreateProcessA(
nullptr,
cmd.data(),
nullptr,
nullptr,
FALSE,
DETACHED_PROCESS,
nullptr,
nullptr,
&si,
&pi
);
if (!ok) return false;
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return true;
}
bool RunAdbCommandHidden(const std::string& args) // this runs adb commands on background without opening a cmd window every time. It uses the kAdbPath constant to locate adb.exe and runs the provided arguments. Returns true if the command executed successfully, false otherwise.
{
std::string fullCmd = std::string("\"") + g_AdbPath + "\" " + args;
return RunCmdHidden(fullCmd);
}
void AdbTap(int x, int y) // this function helps tapping on (x,y) position on the screen.
{
RunAdbCommandHidden("shell input tap " + std::to_string(x) + " " + std::to_string(y));
}
std::string g_InputDevice = "/dev/input/event1";
char g_InputDeviceBuf[128] = "/dev/input/event1";
// THIS FUNCTION WILL HELP YOU TO FIND CORRECT INPUT DEVICE FOR THE EMULATOR YOUR USING.
void AutoDetectTouchDevice() {
AddLog("Detecting Touch Device...", ImVec4(1, 1, 0, 1));
std::string tempFile = "tempfile\\devicelist.txt";
remove(tempFile.c_str());
// 'getevent -pl' command lists the all devices.
// ABS_MT_POSITION_X (Multi-touch X ekseni) device is our main target to find.
std::string cmd = "cmd /c \"\"" + std::string(g_AdbPath) + "\" shell getevent -pl > \"" + tempFile + "\"\"";
RunCmdHidden(cmd);
std::this_thread::sleep_for(std::chrono::milliseconds(500)); // Wait for output to be written
std::ifstream file(tempFile);
if (!file.is_open()) {
AddLog("Error: Could not read device list.", ImVec4(1, 0, 0, 1));
return;
}
std::string line;
std::string currentDevice = "";
bool found = false;
while (std::getline(file, line)) {
// catch "add device X: /dev/input/eventX"
if (line.find("add device") != std::string::npos && line.find("/dev/input/") != std::string::npos) {
size_t startPos = line.find("/dev/input/");
currentDevice = line.substr(startPos);
// Clear spaces in the line if theres any
currentDevice.erase(std::remove(currentDevice.begin(), currentDevice.end(), '\r'), currentDevice.end());
currentDevice.erase(std::remove(currentDevice.begin(), currentDevice.end(), '\n'), currentDevice.end());
}
// Checks if theres "ABS_MT_POSITION_X" or "0035" (Hex code) on the cmd output.
if (!currentDevice.empty()) {
if (line.find("ABS_MT_POSITION_X") != std::string::npos || line.find("0035") != std::string::npos) {
g_InputDevice = currentDevice;
strncpy(g_InputDeviceBuf, g_InputDevice.c_str(), sizeof(g_InputDeviceBuf));
AddLog("Touch Device Found: " + g_InputDevice, ImVec4(0, 1, 0, 1));
found = true;
break; // Bulduk, çıkabiliriz.
}
}
}
file.close();
if (!found) {
AddLog("Could not auto-detect. Using default: " + g_InputDevice, ImVec4(1, 0.5f, 0, 1));
}
}
// ===========================================================
// SALES SECTION
// ===========================================================
void RunSalesCycle() {
AddLog("--- Entering Sales Mode ---", ImVec4(0, 1, 1, 1));
int shopX = -1, shopY = -1;
bool shopFound = false;
int maxRetries = 3;
for (int i = 0; i < maxRetries; i++) {
cv::Mat shopFrame = shopscan(shop_templatePath, shopX, shopY);
if (shopX != -1) {
AddLog("Shop Found.", ImVec4(0, 1, 0, 1));
AdbTap(shopX, shopY);
SmartSleep(1500);
shopFound = true;
break;
}
else {
AddLog("Shop not found. Retrying...", ImVec4(1, 0.5f, 0, 1));
SmartSleep(2000);
}
}
if (!shopFound) {
AddLog("ABORTING SALES: Shop could not be opened.", ImVec4(1, 0, 0, 1));
return;
}
// --- WEBHOOK LOGIC (Every 2 Cycles: 1, 3, 5...) ---
bool doWebhook = g_EnableWebhook && (g_CycleCount % 2 != 0);
if (doWebhook) {
// Find a crate to click (Empty or Sold) to enter the shop menu
std::vector<cv::Point> matches;
cv::Point bestMatch;
cv::Size size;
double score = 0;
// Try finding an empty crate first
FindTemplateMatches(crate_templatePath, 0.80f, matches, bestMatch, size, &score);
// If no empty crate, try finding a sold crate
if (matches.empty()) {
FindTemplateMatches(soldcrate_templatePath, 0.80f, matches, bestMatch, size, &score);
}
if (!matches.empty()) {
int crateX = matches[0].x + size.width / 2;
int crateY = matches[0].y + size.height / 2;
AdbTap(crateX, crateY); // Open Menu
SmartSleep(1000);
// Now look for BARN icon to switch tabs
int barnX = -1, barnY = -1;
shopscan(barn_market_templatePath, barnX, barnY);
if (barnX != -1) {
// Barn Found -> Click and capture
AdbTap(barnX, barnY);
SmartSleep(1500); // Wait for tab switch animation
// Capture Screenshot
cv::Mat fullScreen = CaptureAdbScreen(false);
if (!fullScreen.empty()) {
// ROI Crop (Center of the screen for the menu)
int w = fullScreen.cols;
int h = fullScreen.rows;
int roiW = (int)(w * 0.70); // 70% width
int roiH = (int)(h * 0.60); // 60% height
int roiX = (w - roiW) / 2;
int roiY = (h - roiH) / 2;
// Safety check for ROI
if (roiX >= 0 && roiY >= 0 && roiX + roiW <= w && roiY + roiH <= h) {
cv::Rect roi(roiX, roiY, roiW, roiH);
cv::Mat cropped = fullScreen(roi);
std::string webhookImgPath = "webhook_capture.png";
cv::imwrite(webhookImgPath, cropped);
// Send Image via Webhook
std::string msg = "NXRTH Bot - Cycle #" + std::to_string(g_CycleCount) + " Status";
std::thread([=]() { SendWebhookImage(webhookImgPath, msg); }).detach();
AddLog("Webhook sent!", ImVec4(0, 1, 0, 1));
}
}
// Switch back to Silo to continue sales
int siloX = -1, siloY = -1;
shopscan(silo_market_templatePath, siloX, siloY);
if (siloX != -1) {
AdbTap(siloX, siloY);
SmartSleep(1000);
}
}
else {
// --- BARN NOT FOUND ERROR HANDLING ---
std::string err = "Barn_market template not found so cannot send screenshot!";
AddLog(err, ImVec4(1, 0, 0, 1)); // Log to GUI
// Send text message to Discord/Telegram
std::thread([=]() { SendWebhookMessage(err); }).detach();
}
// Close menu to reset state for the sales loop below
int crossX = -1, crossY = -1;
shopscan(cross_templatePath, crossX, crossY);
if (crossX != -1) {
AdbTap(crossX, crossY);
SmartSleep(1000);
}
}
}
// ------------------------------------------------------
bool moreWheat = true;
int salesCount = 0;
while (moreWheat && salesCount < 10) {
if (!g_BotRunning) break;
std::vector<cv::Point> matches;
cv::Point bestMatch;
cv::Size size;
double score = 0;
FindTemplateMatches(crate_templatePath, 0.80f, matches, bestMatch, size, &score);
if (matches.empty()) {
std::vector<cv::Point> soldMatches;
FindTemplateMatches(soldcrate_templatePath, 0.80f, soldMatches, bestMatch, size, &score);
if (!soldMatches.empty()) {
std::vector<cv::Point> uniqueSoldCrates = FilterUniqueMatches(soldMatches, 60);
AddLog("Collecting " + std::to_string(uniqueSoldCrates.size()) + " crates...", ImVec4(0, 1, 0, 1));
for (const auto& pt : uniqueSoldCrates) {
int cx = pt.x + size.width / 2;
int cy = pt.y + size.height / 2;
AdbTap(cx, cy);
SmartSleep(300);
}
AddLog("Coins collected. Re-scanning...", ImVec4(0, 1, 1, 1));
SmartSleep(1000);
continue;
}
else {
AddLog("Shop is FULL (No empty or sold crates).", ImVec4(1, 0.5f, 0, 1));
break;
}
}
int crateX = matches[0].x + size.width / 2;
int crateY = matches[0].y + size.height / 2;
AdbTap(crateX, crateY);
SmartSleep(800);
std::string currentProductTemplate;
if (g_SelectedCropMode == 0) {
currentProductTemplate = wheatshop_templatePath;
}
else {
currentProductTemplate = cornshop_templatePath;
}
matches.clear();
FindTemplateMatches(currentProductTemplate, 0.80f, matches, bestMatch, size, &score);
if (matches.empty()) {
AddLog("No crop left. Closing sub-menu...", ImVec4(1, 0.5f, 0, 1));
int subCrossX = -1, subCrossY = -1;
shopscan(cross_templatePath, subCrossX, subCrossY);
if (subCrossX != -1) {
AdbTap(subCrossX, subCrossY);
SmartSleep(1000);
}
moreWheat = false;
break;
}
int prodX = matches[0].x + size.width / 2;
int prodY = matches[0].y + size.height / 2;
AdbTap(prodX, prodY);
SmartSleep(300);
matches.clear();
FindTemplateMatches(arrows_templatePath, 0.85f, matches, bestMatch, size, &score);
if (!matches.empty()) {
AdbTap(matches[0].x + size.width / 2, matches[0].y + size.height / 2);
SmartSleep(200);
}
matches.clear();
FindTemplateMatches(plus_templatePath, 0.8f, matches, bestMatch, size, &score);
std::string debugMsg = "Plus Search: Best Score=" + std::to_string(score);
if (score > 0.1) {
debugMsg += " at X=" + std::to_string(bestMatch.x) + " Y=" + std::to_string(bestMatch.y);
}
AddLog(debugMsg, score >= 0.70f ? ImVec4(0, 1, 0, 1) : ImVec4(1, 0.5f, 0, 1));
if (!matches.empty()) {
std::sort(matches.begin(), matches.end(), [](const cv::Point& a, const cv::Point& b) {
return a.y < b.y;
});
int pX = matches[0].x + size.width / 2;
int pY = matches[0].y + size.height / 2;
AddLog("Clicking Top Plus at Y=" + std::to_string(pY), ImVec4(0, 1, 0, 1));
for (int k = 0; k < 5; k++) {
AdbTap(pX, pY);
SmartSleep(150);
}
}
else {
AddLog("Plus button NOT found. Check Score in log.", ImVec4(1, 0, 0, 1));
}
auto now = std::chrono::steady_clock::now();
auto elapsedMinutes = std::chrono::duration_cast<std::chrono::minutes>(now - g_LastAdTime).count();
if (g_IsFirstRun || elapsedMinutes >= 5) {
matches.clear();
FindTemplateMatches(advertise_templatePath, 0.72f, matches, bestMatch, size, &score);
if (!matches.empty()) {
AddLog("Placing ADVERTISEMENT...", ImVec4(0, 1, 0, 1));
AdbTap(matches[0].x + size.width / 2, matches[0].y + size.height / 2);
g_LastAdTime = std::chrono::steady_clock::now();
g_IsFirstRun = false;
SmartSleep(300);
}
else {
AddLog("Advertise button not found.", ImVec4(1, 0.5f, 0, 1));
}
}
matches.clear();
FindTemplateMatches(create_sale_templatePath, 0.80f, matches, bestMatch, size, &score);
if (!matches.empty()) {
AdbTap(matches[0].x + size.width / 2, matches[0].y + size.height / 2);
AddLog("Item sold.", ImVec4(0, 1, 0, 1));
salesCount++;
SmartSleep(1200);
}
else {
AddLog("Create Sale Button not found!", ImVec4(1, 0, 0, 1));
break;
}
}
int crossX = -1, crossY = -1;
shopscan(cross_templatePath, crossX, crossY);
if (crossX != -1) {
AdbTap(crossX, crossY);
AddLog("Shop closed.", ImVec4(0.7f, 0.7f, 0.7f, 1));
}
else {
AddLog("Cross button not found.", ImVec4(1, 0.5f, 0, 1));
}
}
// ============================================================================
// COMPLEX GESTURE HELPER
// ============================================================================
void ExecuteComplexGesture(int startX, int startY, int screenW, int screenH) {
std::string scriptPath = "C:\\Users\\Public\\gesture.sh";
std::ofstream script(scriptPath);
if (!script.is_open()) {
AddLog("ERROR: Cannot create gesture.sh script!", ImVec4(1, 0, 0, 1));
return;
}
// not stable to event1 anymore, will change after auto detect:
std::string inputDev = g_InputDevice;
// ------------------------------------------
int margin = 80;
auto writeEvent = [&](int type, int code, int value) {
script << "sendevent " << inputDev << " " << type << " " << code << " " << value << "\n";
};
auto writeSync = [&]() {
writeEvent(0, 0, 0);
};
// --- Start point ---
int startY_Plus = (startY + 1 >= screenH) ? screenH - 1 : startY + 1;
// Click 1
writeEvent(1, 330, 1);
writeEvent(3, 47, 0);
writeEvent(3, 57, 100);
writeEvent(3, 53, startX);
writeEvent(3, 54, startY);
writeEvent(3, 48, 5);
writeEvent(3, 50, 5);
writeEvent(3, 58, 15);
// Click 2 (Multi-touch gerekliyse)
writeEvent(3, 47, 1);
writeEvent(3, 57, 101);
writeEvent(3, 53, startX);
writeEvent(3, 54, startY_Plus);
writeEvent(3, 48, 5);
writeEvent(3, 50, 5);
writeEvent(3, 58, 15);
writeSync();
// --- Swipe Action ---
int steps = 28;
int leftX = margin;
int rightX = screenW - margin;
int bottomY = screenH - margin;
for (int i = 0; i <= steps; ++i) {
float t = (float)i / steps;
int curX1 = startX + (leftX - startX) * t;
int curY1 = startY + (bottomY - startY) * t;
int curX2 = startX + (rightX - startX) * t;
int curY2 = startY_Plus + (bottomY - startY_Plus) * t;
writeEvent(3, 47, 0);
writeEvent(3, 53, curX1);
writeEvent(3, 54, curY1);
writeEvent(3, 47, 1);
writeEvent(3, 53, curX2);
writeEvent(3, 54, curY2);
writeSync();
}
// Swipe up
int topY = margin;
for (int i = 0; i <= steps; ++i) {
float t = (float)i / steps;
int curY_Up = bottomY + (topY - bottomY) * t;
writeEvent(3, 47, 0);
writeEvent(3, 53, leftX);
writeEvent(3, 54, curY_Up);
writeEvent(3, 47, 1);
writeEvent(3, 53, rightX);
writeEvent(3, 54, curY_Up);
writeSync();
}
// IF corn is selected, swipe down once more
if (g_SelectedCropMode == 1) {
for (int i = 0; i <= steps; ++i) {
float t = (float)i / steps;
int curY_Down = topY + (bottomY - topY) * t;
writeEvent(3, 47, 0);
writeEvent(3, 53, leftX);
writeEvent(3, 54, curY_Down);
writeEvent(3, 47, 1);
writeEvent(3, 53, rightX);
writeEvent(3, 54, curY_Down);
writeSync();
}
}
// --- Release ---
writeEvent(3, 47, 0);
writeEvent(3, 57, -1);
writeEvent(3, 47, 1);
writeEvent(3, 57, -1);
writeEvent(1, 330, 0);
writeSync();
script.close();
RunAdbCommandHidden("push C:\\Users\\Public\\gesture.sh /data/local/tmp/");
RunAdbCommandHidden("shell sh /data/local/tmp/gesture.sh");
}
// ============================================================================
// BOT LOGIC
// ============================================================================
bool RunPlantHarvestCycle() {
// Initial check before doing anything
if (!g_BotRunning) return false;
// --- CYCLE COUNT INCREMENT ---
g_CycleCount++;
std::string cycleLog = "--- Starting Cycle #" + std::to_string(g_CycleCount) + " ---";
AddLog(cycleLog, ImVec4(0, 1, 1, 1));
// -----------------------------
std::string seedTemplate;
std::string grownTemplate;
int growthTimeSeconds = 120; // 120 by default because default plant is wheat. will be set to 300 if user selects corn.
if (g_SelectedCropMode == 0) {
seedTemplate = w_templatePath;
grownTemplate = g_templatePath;
growthTimeSeconds = 120;
AddLog("Mode: WHEAT (2 min)", ImVec4(1, 1, 0, 1));
}
else {
seedTemplate = c_templatePath;
grownTemplate = gc_templatePath;
growthTimeSeconds = 300;
AddLog("Mode: CORN (5 min)", ImVec4(1, 0.8f, 0.2f, 1));
}
int fieldX = -1, fieldY = -1;
cv::Mat fieldFrame = screenscan(f_templatePath, fieldX, fieldY); // Finds Fields on the screen using screenscan().
if (fieldFrame.empty()) return false; // adds field not found log if screenscan returns empty frame, this means it couldnt find any field on the screen.
if (fieldX == -1 || fieldY == -1) {
AddLog("Field not found. Retrying...", ImVec4(1, 0.4f, 0.4f, 1));
return false;
}
// Check stop before waiting
if (!g_BotRunning) return false;
AdbTap(fieldX, fieldY); // taps on the found field positions and waits 1500 ms (1.5 seconds) for menu animation.
if (!SmartSleep(1500)) return false;
int seedX = -1, seedY = -1;
bool seedFound = false;
int maxRetries = 10;
for (int i = 0; i < maxRetries; ++i) { // this function helps to retry 10 times, sometimes bot cant find objects on first run.
if (!g_BotRunning) return false;
wheatscan(seedTemplate, seedX, seedY); // Function name is wheatscan but its also scanning for corn seeds based on the template passed
if (seedX != -1 && seedY != -1) {
seedFound = true;
break;
}
if (!SmartSleep(500)) return false;
}
if (!seedFound) {
AddLog("Seed icon NOT found!", ImVec4(1, 0.2f, 0.2f, 1));
return false;
}
if (!g_BotRunning) return false;
AddLog("Planting...", ImVec4(0, 1, 1, 1));
ExecuteComplexGesture(seedX, seedY, fieldFrame.cols, fieldFrame.rows); // starts planting gesture.
if (!SmartSleep(500)) return false;
auto plantTime = std::chrono::steady_clock::now();
AddLog("Growth timer started (" + std::to_string(growthTimeSeconds) + "). Going to Sales...", ImVec4(0, 1, 0, 1));
// enters sales mode and sells crops.
if (g_BotRunning) {
RunSalesCycle();
}
while (g_BotRunning) {
auto now = std::chrono::steady_clock::now();
auto elapsedSec = std::chrono::duration_cast<std::chrono::seconds>(now - plantTime).count(); // calculates elapsed time since planting in seconds.
if (elapsedSec >= growthTimeSeconds) {
AddLog("Growth time over. Ready to harvest.", ImVec4(0, 1, 0, 1));
break;
}
// Using SmartSleep(1000) instead of sleep_for to allow immediate stop
if (!SmartSleep(1000)) return false;
}
if (!g_BotRunning) return false;
int grownX = -1, grownY = -1;
bool grownFound = false;
for (int i = 0; i < 10; ++i) { // as you can tell by reading AddLog function this scans for grown crops, if cant find retries for 10 times with 1 second intervals.
if (!g_BotRunning) return false;
AddLog("Checking grown crop... (" + std::to_string(i + 1) + ")", ImVec4(1, 1, 0, 1));
grownscan(grownTemplate, grownX, grownY);
if (grownX != -1 && grownY != -1) {
grownFound = true;
break;
}
if (!SmartSleep(1000)) return false;
}
// --- FALLBACK MECHANISM (tries to harvest even if can't find template) ---
if (!grownFound) { // if you have grown crops and get this message, this is also going to break your bot because it can't find empty fields anymore because all are planted.
if (!g_BotRunning) return false;
AddLog("No grown crop found. Tapping the field position before planting. Please Try Grown Tests on status tab and make sure bot detects them.", ImVec4(1, 0.6f, 0.2f, 1));
AdbTap(fieldX, fieldY); // first clicked field position, if user swipes a bit from the screen, it will tap wrong places.
if (!SmartSleep(1500)) return false; // Waiting for menu animation
int sickleX = -1, sickleY = -1;
bool sickleFound = false;
for (int i = 0; i < 5; ++i) {
if (!g_BotRunning) return false;
sicklescan(s_templatePath, sickleX, sickleY);
if (sickleX != -1 && sickleY != -1) {
sickleFound = true;
break;
}
if (!SmartSleep(1000)) return false;
}
if (sickleFound) {
AddLog("Harvesting...", ImVec4(0, 1, 1, 1));
ExecuteComplexGesture(sickleX, sickleY, fieldFrame.cols, fieldFrame.rows);
if (!SmartSleep(1500)) return false;
}
else {
AddLog("Sickle NOT found.", ImVec4(1, 0.4f, 0.4f, 1));
return false;
}
AddLog("Cycle Complete (via Fallback).", ImVec4(0, 1, 1, 1));
return true;
}
// --------------------------------------------------------------------------
// Keep usual harvesting process
if (!g_BotRunning) return false;
AdbTap(fieldX, fieldY); // clicks on the found position
if (!SmartSleep(1500)) return false;
int sickleX = -1, sickleY = -1;
bool sickleFound = false;
for (int i = 0; i < 5; ++i) { // scans for sickle 5 times.
if (!g_BotRunning) return false;
sicklescan(s_templatePath, sickleX, sickleY);
if (sickleX != -1 && sickleY != -1) {
sickleFound = true;
break;
}
if (!SmartSleep(1000)) return false;
}
if (sickleFound) { // harvests using same gesture when planted.
AddLog("Harvesting...", ImVec4(0, 1, 1, 1));
ExecuteComplexGesture(sickleX, sickleY, fieldFrame.cols, fieldFrame.rows);
if (!SmartSleep(1500)) return false;
}
else {
AddLog("Sickle NOT found.", ImVec4(1, 0.4f, 0.4f, 1));
return false;
}
AddLog("Cycle Complete.", ImVec4(0, 1, 1, 1)); // Loops.
return true;
}
void StartBotLoop()
{
if (g_BotRunning) {
AddLog("Bot already running.", ImVec4(1, 0.6f, 0.2f, 1));
return;
}
g_BotRunning = true;
g_CycleCount = 0;
std::thread([]() {
AddLog("Bot started.", ImVec4(0, 1, 0, 1));
while (g_BotRunning) {
// If RunPlantHarvestCycle returns false (stopped or error), loop continues
// but checks g_BotRunning again immediately.
bool result = RunPlantHarvestCycle();
if (!g_BotRunning) break; // Exit immediately if stopped
// Small delay between cycles using SmartSleep
SmartSleep(2000);
}
AddLog("Bot stopped.", ImVec4(1, 0.2f, 0.2f, 1));
}).detach();
}
void StopBotLoop()
{
if (!g_BotRunning) {
AddLog("Bot is not running.", ImVec4(1, 0.6f, 0.2f, 1));
return;
}
g_BotRunning = false; // This triggers SmartSleep to return false immediately
AddLog("Stopping bot...", ImVec4(1, 1, 0, 1));
}