-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.cpp
613 lines (533 loc) · 15.4 KB
/
worker.cpp
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
#include "worker.h"
#include <QDateTime>
#include <QDebug>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QEventLoop>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QImageWriter>
#include <QThread>
#include <QFile>
#include <QFileInfoList>
#include <QDir>
#include <QSettings>
#include "classes/replay.h"
#include <chrono>
#include <iostream>
#include <QMessageBox>
bool Worker::havePOIBeenDrawn = false;
QString Worker::DATA_URL = "http://localhost:8111/map_obj.json";
QString Worker::MAP_URL = "http://localhost:8111/map.img";
QString Worker::MAP_INFO = "http://localhost:8111/map_info.json";
Worker::Worker(SceneImageViewer* imageViewer, QObject* parent)
: QObject(parent),
m_timer(new QTimer(this)),
matchStartTime(0),
networkManager(new QNetworkAccessManager(this))
{
connect(m_timer, &QTimer::timeout, this, &Worker::onTimeout);
}
Worker::~Worker()
{
stopTimer();
}
void Worker::startTimer()
{
if (QThread::currentThread() != this->thread()) {
QMetaObject::invokeMethod(this, "startTimer", Qt::QueuedConnection);
return;
}
m_timer->start(1000);
}
void Worker::stopTimer()
{
if (QThread::currentThread() != this->thread()) {
QMetaObject::invokeMethod(this, "stopTimer", Qt::QueuedConnection);
return;
}
if (m_timer->isActive()) {
m_timer->stop();
qDebug() << "Timer stopped.";
}
}
void Worker::performTask()
{
startTimer();
}
void Worker::onTimeout()
{
try
{
if (shouldLoadMap())
{
fetchAndDisplayMap();
emit changeStackedWidget(2);
emit updateStatusLabel(QString("Map loaded..."));
}
else if (shouldUpdateMarkers())
{
if (matchStartTime == 0)
{
matchStartTime = QDateTime::currentMSecsSinceEpoch();
updatePOI();
emit updateStatusLabel(QString("Match started..."));
}
updateMarkers();
}
else if (shouldEndMatch())
{
matchStartTime = 0;
emit updateStatusLabel(QString("Match ended..."));
QPixmap drawedMapImage = getOriginalMapImage();
drawSpecialMarkers(drawedMapImage);
drawMarkers(drawedMapImage);
this->drawedMapImage = drawedMapImage;
emit changeStackedWidget(1);
emit updatePixmap(drawedMapImage);
endMatch();
restartScheduler();
}
else {
emit updateStatusLabel(QString("Awaiting match start..."));
}
}
catch (const std::exception& e)
{
qDebug() << "An error occurred during scheduled task execution:" << e.what();
}
}
void Worker::updatePOI() {
try {
QJsonArray objectArray = fetchJsonArray(DATA_URL);
for (const QJsonValue& value : objectArray) {
QJsonObject element = value.toObject();
if (element.contains("x") && element.contains("y")
&& element["x"].toDouble() > 0
&& element["x"].toDouble() < 1
&& element["y"].toDouble() > 0
&& element["y"].toDouble() < 1) {
Position position = getPositionFromJsonElement(element);
if (!position.isValid()) continue;
if (position.isCaptureZone() || position.isRespawnBaseTank()) {
addPOI(position);
}
}
}
}
catch (const std::exception& e) {
qDebug() << "Exception while fetching map objects:" << e.what();
throw std::runtime_error(e.what());
}
}
bool Worker::shouldLoadMap()
{
return getOriginalMapImage().isNull() && isMatchRunning();
}
bool Worker::shouldUpdateMarkers()
{
return !getOriginalMapImage().isNull() && isMatchRunning();
}
void Worker::updateMarkers()
{
//TODO: Check if player is spectating
if (isPlayerOnTank())
{
fetchMapObjects();
}
}
bool Worker::shouldEndMatch()
{
return !getOriginalMapImage().isNull() && !isMatchRunning();
}
void Worker::endMatch()
{
QString currEpoch = QString::number(QDateTime::currentMSecsSinceEpoch());
try {
QSettings settings("sgambe33", "wtplotter");
QString replayDir = settings.value("replayFolderPath", "").toString();
QString plotDir = settings.value("plotSavePath", "").toString();
bool autosave = settings.value("autosave", false).toBool();
QFile latestReplay;
int retries = 60;
if (autosave) {
saveImage();
}
do {
latestReplay.setFileName(getLatestReplay(QDir(replayDir)).fileName());
if (!latestReplay.exists()) {
QThread::sleep(1);
}
} while (!latestReplay.exists() && retries-- > 0);
if (latestReplay.exists()) {
qInfo() << "Latest replay file:" << latestReplay.fileName();
Replay replayData = Replay::fromFile(latestReplay.fileName());
QString uploader = replayData.getAuthorId();
if (!uploader.isEmpty()) {
uploadReplay(replayData, uploader);
}
else {
qWarning() << "Failed to get user UID. Data will not be validated against replay.";
}
}
else {
qWarning() << "No replay file found after match end. Data will not be validated against replay.";
}
qInfo() << "Position cache exported and plot saved to disk with timestamp:" << currEpoch;
}
catch (const std::exception& e) {
throw std::runtime_error(e.what());
}
clearMarkers();
setOriginalMapImage(QPixmap());
this->drawedMapImage = QPixmap();
qDebug() << "Match ended, markers cleared.";
}
void Worker::saveImage() {
QPixmap drawedMapImage = getDrawedMapImage();
QString savePath = QSettings("sgambe33", "wtplotter").value("plotSavePath", "").toString();
if (drawedMapImage.isNull()) {
qDebug() << "Error: drawedMapImage is null.";
return;
}
if (savePath.trimmed().isEmpty()) {
qDebug() << "Error: savePath is not set.";
QMessageBox msgBox;
msgBox.critical(nullptr, "Error", "You have not set the save folder in the preferences!");
return;
}
QDir savePathDir(savePath);
if (!savePathDir.exists()) {
qDebug() << "Error: savePath directory does not exist:" << savePath;
return;
}
QString fileName = savePathDir.absoluteFilePath(QString::number(QDateTime::currentSecsSinceEpoch()) + ".png");
qDebug() << "Saving to file:" << fileName;
QImageWriter writer;
writer.setFormat("png");
writer.setFileName(fileName);
if (!writer.write(drawedMapImage.toImage())) {
qDebug() << "Error saving image:" << writer.errorString();
}
else {
qDebug() << "Image saved successfully.";
}
}
QJsonArray Worker::exportPositionsToJson(Replay& replayData) {
QJsonArray positions;
for (const Position& position : this->positionCache) {
QJsonObject obj;
obj["x"] = position.x();
obj["y"] = position.y();
obj["type"] = position.type();
obj["icon"] = position.icon();
obj["timestamp"] = position.timestamp();
obj["sessionId"] = replayData.getSessionId();
positions.append(obj);
}
for (const Position& position : this->poi) {
QJsonObject obj;
obj["x"] = position.x();
obj["y"] = position.y();
obj["type"] = position.type();
obj["icon"] = position.icon();
obj["timestamp"] = position.timestamp();
obj["sessionId"] = replayData.getSessionId();
positions.append(obj);
}
return positions;
}
void Worker::uploadReplay(Replay& replayData, const QString& uploader)
{
QNetworkRequest request(QUrl("http://warthunder-heatmaps.crabdance.com/uploadPositions"));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
QJsonObject headerMap;
headerMap["sessionId"] = replayData.getSessionId();
headerMap["uploader"] = uploader;
headerMap["startTime"] = replayData.getStartTime();
headerMap["map"] = replayData.getLevel();
headerMap["gameMode"] = replayData.getBattleType();
QJsonObject data;
data["replayHeader"] = headerMap;
data["positions"] = exportPositionsToJson(replayData);
QJsonDocument doc(data);
QByteArray jsonData = doc.toJson();
QNetworkReply* reply = networkManager->post(request, jsonData);
QEventLoop loop;
connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
if (reply->error() != QNetworkReply::NoError)
{
qWarning() << "Failed to upload replay:" << reply->errorString();
}
else
{
qInfo() << "Replay uploaded successfully.";
}
reply->deleteLater();
}
void Worker::restartScheduler()
{
stopTimer();
startTimer();
}
QFile Worker::getLatestReplay(const QDir& replayDirectory)
{
QFileInfoList files = replayDirectory.entryInfoList(QDir::Files, QDir::Time);
if (files.isEmpty())
{
return QFile();
}
qint64 sixtySecondsAgo = QDateTime::currentMSecsSinceEpoch() - 120000;
for (const QFileInfo& fileInfo : files)
{
if (fileInfo.suffix() == "wrpl" && fileInfo.lastModified().toMSecsSinceEpoch() >= sixtySecondsAgo)
{
return QFile(fileInfo.filePath());
}
}
return QFile();
}
void Worker::setMatchStartTime(long matchStartTime)
{
this->matchStartTime = matchStartTime;
}
bool Worker::isMatchRunning()
{
try {
QJsonObject mapInfo = fetchJsonElement(MAP_INFO);
if (!mapInfo.isEmpty()) {
return mapInfo.contains("valid") && mapInfo["valid"].toBool();
}
return false;
}
catch (const std::exception& e) {
qDebug() << "Exception while fetching map info:" << e.what();
return false;
}
}
bool Worker::isPlayerOnTank()
{
try {
QJsonObject response = fetchJsonElement("http://localhost:8111/indicators");
if (!response.isEmpty()) {
bool result = response.contains("valid") && response["valid"].toBool();
result = result && (response.contains("army") && response["army"].toString().compare("tank", Qt::CaseInsensitive) == 0);
return result;
}
return false;
}
catch (const std::exception& e) {
qDebug() << "Exception while fetching indicators:" << e.what();
return false;
}
}
void Worker::fetchAndDisplayMap()
{
if (!isMatchRunning())
return;
QPixmap mapImage = fetchMapImage();
if (!mapImage.isNull()) {
setOriginalMapImage(mapImage);
}
}
void Worker::fetchMapObjects()
{
try {
QJsonArray objectArray = fetchJsonArray(DATA_URL);
for (const QJsonValue& value : objectArray) {
QJsonObject element = value.toObject();
if (element.contains("x") && element.contains("y")
&& element["x"].toDouble() > 0
&& element["x"].toDouble() < 1
&& element["y"].toDouble() > 0
&& element["y"].toDouble() < 1) {
Position position = getPositionFromJsonElement(element);
if (!position.isValid()) continue;
if (position.isCaptureZone() || position.isRespawnBaseTank()) {
continue;
}
else {
addPosition(position);
}
}
}
}
catch (const std::exception& e) {
qDebug() << "Exception while fetching map objects:" << e.what();
throw std::runtime_error(e.what());
}
}
QPixmap Worker::getDrawedMapImage()
{
return drawedMapImage;
}
QPixmap Worker::getOriginalMapImage() const
{
return originalMapImage;
}
void Worker::setOriginalMapImage(const QPixmap& originalMapImage)
{
this->originalMapImage = originalMapImage;
}
void Worker::clearMarkers()
{
positionCache.clear();
poi.clear();
havePOIBeenDrawn = false;
}
void Worker::addPosition(const Position& position)
{
positionCache.append(position);
}
void Worker::addPOI(const Position& position)
{
if (!havePOIBeenDrawn) {
poi.append(position);
}
}
bool Worker::havePOIBeenDrawnFunc() const
{
return havePOIBeenDrawn;
}
void Worker::drawMarkers(QPixmap& displayImage)
{
if (displayImage.isNull()) {
qDebug() << "Error: displayImage is null.";
return;
}
QPainter painter(&displayImage);
painter.setPen(Qt::NoPen);
painter.setRenderHint(QPainter::Antialiasing, false);
painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
drawMarkers(displayImage, painter, positionCache);
}
void Worker::drawMarkers(QPixmap& displayImage, QPainter& painter, const QList<Position>& positionCache)
{
for (const Position& pos : positionCache) {
double x = pos.x();
double y = pos.y();
QString color = pos.color();
QString type = pos.type();
QColor markerColor(color);
painter.setBrush(markerColor);
if (type != "aircraft" && type != "airfield" && type != "respawn_base_tank" && type != "respawn_base_ship" && type != "respawn_base_aircraft" && type != "capture_zone") {
int markerSize = 2;
int px = static_cast<int>(x * displayImage.width());
int py = static_cast<int>(y * displayImage.height());
painter.drawRect(px - markerSize / 2, py - markerSize / 2, markerSize, markerSize);
}
}
}
void Worker::drawSpecialMarkers(QPixmap& displayImage)
{
if (displayImage.isNull()) {
qDebug() << "Error: displayImage is null.";
return;
}
QPainter painter(&displayImage);
painter.setPen(Qt::NoPen);
painter.setRenderHint(QPainter::Antialiasing, false);
painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
QMap<QString, QList<Position>> respawnBaseTankGroups;
for (const Position& pos : poi) {
if (pos.type() == "capture_zone") {
drawCaptureZoneMarker(displayImage, painter, pos);
}
else if (pos.type() == "respawn_base_tank") {
respawnBaseTankGroups[pos.color()].append(pos);
}
}
if (!poi.isEmpty() && !respawnBaseTankGroups.isEmpty()) {
havePOIBeenDrawn = true;
}
for (const QList<Position>& group : respawnBaseTankGroups) {
if (group.size() >= 5) {
drawRespawnBaseTank(displayImage, painter, group);
}
}
}
void Worker::drawCaptureZoneMarker(QPixmap& displayImage, QPainter& painter, const Position& pos)
{
double x = pos.x();
double y = pos.y();
int px = static_cast<int>(x * displayImage.width());
int py = static_cast<int>(y * displayImage.height());
painter.setPen(Qt::yellow);
painter.setBrush(Qt::NoBrush);
painter.drawRect(px - 10, py - 10, 20, 20);
}
void Worker::drawRespawnBaseTank(QPixmap& displayImage, QPainter& painter, const QList<Position>& group)
{
for (const Position& pos : group) {
QColor markerColor("#ff00ff");
painter.setPen(markerColor);
painter.setBrush(Qt::NoBrush);
int markerSize = 4;
int px1 = static_cast<int>(pos.x() * displayImage.width());
int py1 = static_cast<int>(pos.y() * displayImage.height());
painter.drawRect(px1 - markerSize / 2, py1 - markerSize / 2, markerSize, markerSize);
}
}
QJsonObject Worker::fetchJsonElement(QString url)
{
QNetworkReply* reply = networkManager->get(QNetworkRequest(QUrl(url)));
QEventLoop loop;
QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
QJsonObject jsonObject;
if (reply->error() == QNetworkReply::NoError) {
QJsonDocument doc = QJsonDocument::fromJson(reply->readAll());
jsonObject = doc.object();
}
else {
qDebug() << "Network error:" << reply->errorString();
}
reply->deleteLater();
return jsonObject;
}
QJsonArray Worker::fetchJsonArray(QString url)
{
QNetworkReply* reply = networkManager->get(QNetworkRequest(QUrl(url)));
QEventLoop loop;
QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
if (reply->error() != QNetworkReply::NoError) {
qDebug() << "Network error:" << reply->errorString();
throw std::runtime_error(reply->errorString().toStdString());
}
QByteArray responseData = reply->readAll();
QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);
if (!jsonDoc.isArray()) {
qDebug() << "Error: JSON response is not an array.";
throw std::runtime_error("JSON response is not an array.");
}
return jsonDoc.array();
}
QPixmap Worker::fetchMapImage()
{
QNetworkReply* reply = networkManager->get(QNetworkRequest(QUrl(MAP_URL)));
QEventLoop loop;
QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
loop.exec();
QPixmap pixmap;
if (reply->error() == QNetworkReply::NoError) {
pixmap.loadFromData(reply->readAll());
}
else {
qDebug() << "Network error:" << reply->errorString();
}
reply->deleteLater();
return pixmap;
}
Position Worker::getPositionFromJsonElement(QJsonObject element)
{
double x = element["x"].toDouble();
double y = element["y"].toDouble();
QString color = element["color"].toString();
QString type = element["type"].toString();
QString icon = element["icon"].toString();
qint64 timeSinceBeginning = (QDateTime::currentMSecsSinceEpoch() - this->matchStartTime) / 1000;
return Position(x, y, color, type, icon, timeSinceBeginning);
}