| 1 | // This file is part of Dust Racing 2D. |
| 2 | // Copyright (C) 2015 Jussi Lind <[email protected]> |
| 3 | // |
| 4 | // Dust Racing 2D is free software: you can redistribute it and/or modify |
| 5 | // it under the terms of the GNU General Public License as published by |
| 6 | // the Free Software Foundation, either version 3 of the License, or |
| 7 | // (at your option) any later version. |
| 8 | // Dust Racing 2D is distributed in the hope that it will be useful, |
| 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 11 | // GNU General Public License for more details. |
| 12 | // |
| 13 | // You should have received a copy of the GNU General Public License |
| 14 | // along with Dust Racing 2D. If not, see <http://www.gnu.org/licenses/>. |
| 15 | |
| 16 | #include "race.hpp" |
| 17 | |
| 18 | #include "car.hpp" |
| 19 | #include "carsoundeffectmanager.hpp" |
| 20 | #include "database.hpp" |
| 21 | #include "game.hpp" |
| 22 | #include "offtrackdetector.hpp" |
| 23 | #include "track.hpp" |
| 24 | #include "trackdata.hpp" |
| 25 | #include "tracktile.hpp" |
| 26 | |
| 27 | #include "../common/config.hpp" |
| 28 | #include "../common/targetnodebase.hpp" |
| 29 | |
| 30 | #include <algorithm> |
| 31 | #include <cassert> |
| 32 | #include <random> |
| 33 | |
| 34 | #include <MCAssetManager> |
| 35 | #include <MCObjectFactory> |
| 36 | #include <MCPhysicsComponent> |
| 37 | #include <MCShape> |
| 38 | #include <MCShapeView> |
| 39 | #include <MCSurfaceManager> |
| 40 | |
| 41 | #include "simple_logger.hpp" |
| 42 | |
| 43 | Race::Race(Game & game, size_t numCars) |
| 44 | : m_humanPlayerIndex1 { 0 } |
| 45 | , m_humanPlayerIndex2 { 1 } |
| 46 | , m_numCars { numCars } |
| 47 | , m_lapCount { 5 } |
| 48 | , m_timing { std::make_shared<Timing>(numCars) } |
| 49 | , m_game { game } |
| 50 | { |
| 51 | createStartGridObjects(); |
| 52 | |
| 53 | m_offTrackMessageTimer.setSingleShot(true); |
| 54 | m_offTrackMessageTimer.setInterval(30000ms); |
| 55 | |
| 56 | connect(m_timing.get(), &Timing::lapRecordAchieved, this, [this](int msecs) { |
| 57 | Database::instance().saveLapRecord(*m_track, msecs); |
| 58 | emit messageRequested(QObject::tr("New lap record!")); |
| 59 | emit lapRecordAchieved(msecs); |
| 60 | }); |
| 61 | |
| 62 | connect(m_timing.get(), &Timing::raceRecordAchieved, this, [this](int msecs) { |
| 63 | if (m_game.hasComputerPlayers()) |
| 64 | { |
| 65 | Database::instance().saveRaceRecord(*m_track, msecs, static_cast<int>(m_lapCount), m_game.difficultyProfile().difficulty()); |
| 66 | emit messageRequested(QObject::tr("New race record!")); |
| 67 | emit raceRecordAchieved(msecs); |
| 68 | } |
| 69 | }); |
| 70 | |
| 71 | connect(m_timing.get(), &Timing::lapCompleted, this, [this](size_t, int msecs) { |
| 72 | emit messageRequested(QString::fromWCharArray(Timing::msecsToString(msecs).c_str())); |
| 73 | }); |
| 74 | } |
| 75 | |
| 76 | void Race::createStartGridObjects() |
| 77 | { |
| 78 | static MCObjectFactory objectFactory { MCAssetManager::instance() }; |
| 79 | for (size_t i = 0; i < m_numCars; i++) |
| 80 | { |
| 81 | const auto grid = "grid"; |
| 82 | MCSurfaceObjectData data { grid }; |
| 83 | data.setIsStationary(true); |
| 84 | data.setSurfaceId(grid); |
| 85 | |
| 86 | const auto object = objectFactory.build(data); |
| 87 | object->shape()->view()->setHasShadow(false); |
| 88 | object->setIsPhysicsObject(false); |
| 89 | |
| 90 | m_startGridObjects.push_back(object); |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | void Race::initialize(TrackS track, size_t lapCount) |
| 95 | { |
| 96 | setTrack(track, lapCount); |
| 97 | |
| 98 | clearPositions(); |
| 99 | clearRaceFlags(); |
| 100 | |
| 101 | initTiming(); |
| 102 | initCars(); |
| 103 | } |
| 104 | |
| 105 | void Race::initTiming() |
| 106 | { |
| 107 | const auto lapRecord = Database::instance().loadLapRecord(*m_track); |
| 108 | m_timing->setLapRecord(lapRecord.second ? lapRecord.first : -1); |
| 109 | const auto raceRecord = Database::instance().loadRaceRecord(*m_track, static_cast<int>(m_lapCount), m_game.difficultyProfile().difficulty()); |
| 110 | m_timing->setRaceRecord(raceRecord.second ? raceRecord.first : -1); |
| 111 | m_timing->reset(); |
| 112 | } |
| 113 | |
| 114 | void Race::initCars() |
| 115 | { |
| 116 | translateCarsToStartPositions(); |
| 117 | |
| 118 | m_statusHash.clear(); |
| 119 | |
| 120 | for (auto && car : m_cars) |
| 121 | { |
| 122 | car->resetDamage(); |
| 123 | car->resetTireWear(); |
| 124 | |
| 125 | m_stuckHash[car->index()] = StuckTileCounter(nullptr, 0); |
| 126 | m_statusHash[car->index()] = CarStatus {}; |
| 127 | |
| 128 | if (car->soundEffectManager()) |
| 129 | { |
| 130 | car->soundEffectManager()->startEngineSound(); |
| 131 | } |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | void Race::clearPositions() |
| 136 | { |
| 137 | m_progression.clear(); |
| 138 | } |
| 139 | |
| 140 | void Race::clearRaceFlags() |
| 141 | { |
| 142 | m_checkeredFlagEnabled = false; |
| 143 | m_winnerFinished = false; |
| 144 | m_isfinishedSignalSent = false; |
| 145 | m_started = false; |
| 146 | } |
| 147 | |
| 148 | void placeCar(Car & car, float x, float y, int angle) |
| 149 | { |
| 150 | car.translate({ x, y }); |
| 151 | car.rotate(static_cast<float>(angle)); |
| 152 | |
| 153 | juzzlin::L().debug() << "Car " << car.index() << " location: " << car.location(); |
| 154 | juzzlin::L().debug() << "Car " << car.index() << " rotation: " << car.angle(); |
| 155 | } |
| 156 | |
| 157 | void placeStartGrid(MCObject & grid, float x, float y, int angle) |
| 158 | { |
| 159 | grid.translate({ x, y }); |
| 160 | grid.rotate(static_cast<float>(angle)); |
| 161 | grid.addToWorld(); |
| 162 | |
| 163 | juzzlin::L().debug() << "Start grid location: " << grid.location(); |
| 164 | juzzlin::L().debug() << "Start grid rotation: " << grid.angle(); |
| 165 | } |
| 166 | |
| 167 | void Race::translateCarsToStartPositions() |
| 168 | { |
| 169 | assert(m_track); |
| 170 | |
| 171 | if (const auto finishLine = m_track->finishLine()) |
| 172 | { |
| 173 | auto order = m_cars; |
| 174 | std::reverse(order.begin(), order.end()); |
| 175 | |
| 176 | // Move the human player to a starting place that equals the best position |
| 177 | // of the current race track. |
| 178 | if (m_game.hasComputerPlayers() && !m_game.hasTwoHumanPlayers()) |
| 179 | { |
| 180 | const auto bestPos = Database::instance().loadBestPos(*m_track, static_cast<int>(m_lapCount), m_game.difficultyProfile().difficulty()); |
| 181 | if (bestPos.second) |
| 182 | { |
| 183 | order.insert(order.begin() + bestPos.first - 1, *m_cars.begin()); |
| 184 | order.pop_back(); |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | // Position the cars into two queues. |
| 189 | const float oddOffset = static_cast<float>(TrackTile::width() / 8); |
| 190 | const float gridOffset = static_cast<float>(TrackTile::width() / 12); |
| 191 | const float tileWidth = static_cast<float>(TrackTile::width()); |
| 192 | const float tileHeight = static_cast<float>(TrackTile::height()); |
| 193 | const float spacing = 0.75f * static_cast<float>(TrackTile::width()); |
| 194 | const float startTileX = static_cast<float>(finishLine->location().x()); |
| 195 | const float startTileY = static_cast<float>(finishLine->location().y()); |
| 196 | |
| 197 | const int routeDirection = finishLine->rotation() % 360; |
| 198 | juzzlin::L().debug() << "Route direction: " << routeDirection; |
| 199 | |
| 200 | switch (routeDirection) |
| 201 | { |
| 202 | case 90: |
| 203 | case -270: |
| 204 | { |
| 205 | float moveDueToBridge = 0; |
| 206 | for (size_t i = 0; i < order.size(); i++) |
| 207 | { |
| 208 | const float y = startTileY + (i % 2) * tileHeight / 3 - tileHeight / 6; |
| 209 | float x = startTileX + (static_cast<float>(i / 2) * spacing) + (i % 2) * oddOffset + moveDueToBridge; |
| 210 | while (m_track->trackTileAtLocation(x, y)->tileTypeEnum() == TrackTile::TileType::Bridge) |
| 211 | { |
| 212 | moveDueToBridge += tileWidth; |
| 213 | x += moveDueToBridge; |
| 214 | } |
| 215 | placeCar(*order.at(i), x, y, 180); |
| 216 | placeStartGrid(*m_startGridObjects.at(i), x - gridOffset, y, 180); |
| 217 | } |
| 218 | break; |
| 219 | } |
| 220 | default: |
| 221 | case 270: |
| 222 | case -90: |
| 223 | { |
| 224 | float moveDueToBridge = 0; |
| 225 | for (size_t i = 0; i < order.size(); i++) |
| 226 | { |
| 227 | const float y = startTileY + (i % 2) * tileHeight / 3 - tileHeight / 6; |
| 228 | float x = startTileX - static_cast<float>(i / 2) * spacing + (i % 2) * oddOffset - moveDueToBridge; |
| 229 | while (m_track->trackTileAtLocation(x, y)->tileTypeEnum() == TrackTile::TileType::Bridge) |
| 230 | { |
| 231 | moveDueToBridge += tileWidth; |
| 232 | x -= moveDueToBridge; |
| 233 | } |
| 234 | placeCar(*order.at(i), x, y, 0); |
| 235 | placeStartGrid(*m_startGridObjects.at(i), x + gridOffset, y, 0); |
| 236 | } |
| 237 | break; |
| 238 | } |
| 239 | case 0: |
| 240 | { |
| 241 | float moveDueToBridge = 0; |
| 242 | for (size_t i = 0; i < order.size(); i++) |
| 243 | { |
| 244 | const float x = startTileX + (i % 2) * tileWidth / 3 - tileWidth / 6; |
| 245 | float y = startTileY - static_cast<float>(i / 2) * spacing + (i % 2) * oddOffset - moveDueToBridge; |
| 246 | while (m_track->trackTileAtLocation(x, y)->tileTypeEnum() == TrackTile::TileType::Bridge) |
| 247 | { |
| 248 | moveDueToBridge += tileHeight; |
| 249 | y -= moveDueToBridge; |
| 250 | } |
| 251 | placeCar(*order.at(i), x, y, 90); |
| 252 | placeStartGrid(*m_startGridObjects.at(i), x, y + gridOffset, 90); |
| 253 | } |
| 254 | break; |
| 255 | } |
| 256 | case 180: |
| 257 | case -180: |
| 258 | { |
| 259 | float moveDueToBridge = 0; |
| 260 | for (size_t i = 0; i < order.size(); i++) |
| 261 | { |
| 262 | const float x = startTileX + (i % 2) * tileWidth / 3 - tileWidth / 6; |
| 263 | float y = startTileY + static_cast<float>(i / 2) * spacing + (i % 2) * oddOffset + moveDueToBridge; |
| 264 | while (m_track->trackTileAtLocation(x, y)->tileTypeEnum() == TrackTile::TileType::Bridge) |
| 265 | { |
| 266 | moveDueToBridge += tileHeight; |
| 267 | y += moveDueToBridge; |
| 268 | } |
| 269 | placeCar(*order.at(i), x, y, 270); |
| 270 | placeStartGrid(*m_startGridObjects.at(i), x, y - gridOffset, 270); |
| 271 | } |
| 272 | break; |
| 273 | } |
| 274 | } |
| 275 | } |
| 276 | else |
| 277 | { |
| 278 | juzzlin::L().error() << "Finish line tile not found in track '" << m_track->trackData().name().toStdString() << "'"; |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | void Race::start() |
| 283 | { |
| 284 | if (!m_started) |
| 285 | { |
| 286 | m_timing->start(); |
| 287 | m_started = true; |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | void Race::stopEngineSounds() |
| 292 | { |
| 293 | for (auto && car : m_cars) |
| 294 | { |
| 295 | if (car->soundEffectManager()) |
| 296 | { |
| 297 | car->soundEffectManager()->stopEngineSound(); |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | bool Race::started() const |
| 303 | { |
| 304 | return m_started; |
| 305 | } |
| 306 | |
| 307 | void Race::update(std::chrono::milliseconds timeStep) |
| 308 | { |
| 309 | for (auto && car : m_cars) |
| 310 | { |
| 311 | updateRouteProgress(*car); |
| 312 | } |
| 313 | |
| 314 | // Enable the checkered flag if leader has done at least 95% of the last lap. |
| 315 | if (m_timing->leadersLap() + 1 == m_lapCount) |
| 316 | { |
| 317 | auto && route = m_track->trackData().route(); |
| 318 | auto && targetNode = route.get(m_statusHash[getLeader().index()].currentTargetNodeIndex); |
| 319 | if (targetNode->index() >= static_cast<int>(9 * route.numNodes() / 10)) |
| 320 | { |
| 321 | if (!m_checkeredFlagEnabled) |
| 322 | { |
| 323 | const QString bellSoundHandle("bell"); |
| 324 | emit playRequested(bellSoundHandle, false); |
| 325 | |
| 326 | m_checkeredFlagEnabled = true; |
| 327 | } |
| 328 | } |
| 329 | } |
| 330 | // Check if winner has finished |
| 331 | else if (m_timing->leadersLap() == m_lapCount) |
| 332 | { |
| 333 | if (!m_winnerFinished) |
| 334 | { |
| 335 | m_winnerFinished = true; |
| 336 | |
| 337 | auto && leader = getLeader(); |
| 338 | m_timing->setRaceCompleted(leader.index(), true, leader.isHuman()); |
| 339 | |
| 340 | if (m_game.mode() == Game::Mode::TimeTrial) |
| 341 | { |
| 342 | emit messageRequested(QObject::tr("The Time Trial has ended!")); |
| 343 | } |
| 344 | else |
| 345 | { |
| 346 | emit messageRequested(QObject::tr("The winner has finished!")); |
| 347 | emit playRequested("cheering", false); |
| 348 | } |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | for (auto && otd : m_offTrackDetectors) |
| 353 | { |
| 354 | otd->update(); |
| 355 | } |
| 356 | |
| 357 | if (isRaceFinished() && !m_isfinishedSignalSent) |
| 358 | { |
| 359 | emit finished(); |
| 360 | m_isfinishedSignalSent = true; |
| 361 | } |
| 362 | |
| 363 | m_timing->tick(timeStep); |
| 364 | } |
| 365 | |
| 366 | void Race::pitStop(Car & car) |
| 367 | { |
| 368 | if (m_timing->lap(car.index()) > 0) |
| 369 | { |
| 370 | emit messageRequested(QObject::tr("Pit stop!")); |
| 371 | |
| 372 | const QString pitSoundHandle { "pit" }; |
| 373 | emit locationChanged(pitSoundHandle, car.location().i(), car.location().j()); |
| 374 | emit playRequested(pitSoundHandle, false); |
| 375 | |
| 376 | emit tiresChanged(car); |
| 377 | |
| 378 | car.resetDamage(); |
| 379 | car.resetTireWear(); |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | bool isInsideCheckPoint(Car & car, TargetNodeBasePtr targetNode, float tolerance) |
| 384 | { |
| 385 | const float halfWidth = static_cast<float>(targetNode->size().width() / 2); |
| 386 | const float halfHeight = static_cast<float>(targetNode->size().height() / 2); |
| 387 | |
| 388 | if (car.location().i() < static_cast<float>(targetNode->location().x()) - halfWidth - tolerance) |
| 389 | { |
| 390 | return false; |
| 391 | } |
| 392 | else if (car.location().i() > static_cast<float>(targetNode->location().x()) + halfWidth + tolerance) |
| 393 | { |
| 394 | return false; |
| 395 | } |
| 396 | else if (car.location().j() < static_cast<float>(targetNode->location().y()) - halfHeight - tolerance) |
| 397 | { |
| 398 | return false; |
| 399 | } |
| 400 | else if (car.location().j() > static_cast<float>(targetNode->location().y()) + halfHeight + tolerance) |
| 401 | { |
| 402 | return false; |
| 403 | } |
| 404 | |
| 405 | return true; |
| 406 | } |
| 407 | |
| 408 | void Race::updateRouteProgress(Car & car) |
| 409 | { |
| 410 | auto && route = m_track->trackData().route(); |
| 411 | size_t currentTargetNodeIndex = m_statusHash[car.index()].currentTargetNodeIndex; |
| 412 | size_t nextTargetNodeIndex = m_statusHash[car.index()].nextTargetNodeIndex; |
| 413 | const auto targetNode = route.get(currentTargetNodeIndex); |
| 414 | |
| 415 | // Give a bit more tolerance for other than the finishing check point. |
| 416 | const float tolerance = (!currentTargetNodeIndex ? 0 : static_cast<float>(TrackTile::height()) / 20); |
| 417 | |
| 418 | // Car still racing |
| 419 | if (m_timing->isActive(car.index())) |
| 420 | { |
| 421 | if (!m_timing->raceCompleted(car.index())) |
| 422 | { |
| 423 | // Check is car is stuck and if so, move onto nearest asphalt tile. |
| 424 | if (!car.isHuman()) |
| 425 | { |
| 426 | checkIfCarIsStuck(car); |
| 427 | } |
| 428 | |
| 429 | // Check is car is off track and display a message. |
| 430 | if (car.isHuman()) |
| 431 | { |
| 432 | checkIfCarIsOffTrack(car); |
| 433 | } |
| 434 | |
| 435 | if (isInsideCheckPoint(car, targetNode, tolerance)) |
| 436 | { |
| 437 | updatePositions(); |
| 438 | |
| 439 | checkIfLapIsCompleted(car, route, currentTargetNodeIndex); |
| 440 | |
| 441 | // Increase progress and update the positions hash |
| 442 | m_progression[++m_statusHash[car.index()].routeProgression].push_back(car.index()); |
| 443 | |
| 444 | // Switch to next check point |
| 445 | m_statusHash[car.index()].prevTargetNodeIndex = currentTargetNodeIndex; |
| 446 | if (++currentTargetNodeIndex >= route.numNodes()) |
| 447 | { |
| 448 | currentTargetNodeIndex = 0; |
| 449 | } |
| 450 | |
| 451 | nextTargetNodeIndex = currentTargetNodeIndex; |
| 452 | if (++nextTargetNodeIndex >= route.numNodes()) |
| 453 | { |
| 454 | nextTargetNodeIndex = 0; |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | m_statusHash[car.index()].currentTargetNodeIndex = currentTargetNodeIndex; |
| 459 | m_statusHash[car.index()].nextTargetNodeIndex = nextTargetNodeIndex; |
| 460 | } |
| 461 | else |
| 462 | { |
| 463 | checkForNewBestPosition(car); |
| 464 | |
| 465 | m_timing->setIsActive(car.index(), false); |
| 466 | } |
| 467 | } |
| 468 | // Car has finished: cooldown laps |
| 469 | else |
| 470 | { |
| 471 | if (isInsideCheckPoint(car, targetNode, tolerance)) |
| 472 | { |
| 473 | // Switch to next check point |
| 474 | m_statusHash[car.index()].prevTargetNodeIndex = currentTargetNodeIndex; |
| 475 | if (++currentTargetNodeIndex >= route.numNodes()) |
| 476 | { |
| 477 | currentTargetNodeIndex = 0; |
| 478 | } |
| 479 | |
| 480 | nextTargetNodeIndex = currentTargetNodeIndex; |
| 481 | if (++nextTargetNodeIndex >= route.numNodes()) |
| 482 | { |
| 483 | nextTargetNodeIndex = 0; |
| 484 | } |
| 485 | } |
| 486 | |
| 487 | m_statusHash[car.index()].currentTargetNodeIndex = currentTargetNodeIndex; |
| 488 | m_statusHash[car.index()].nextTargetNodeIndex = nextTargetNodeIndex; |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | void Race::updatePositions() |
| 493 | { |
| 494 | auto positions = m_cars; |
| 495 | std::sort(positions.begin(), positions.end(), [this](auto lhs, auto rhs) -> bool { |
| 496 | // Easy comparison: cars have reached different checkpoints |
| 497 | if (m_statusHash[lhs->index()].routeProgression > m_statusHash[rhs->index()].routeProgression) |
| 498 | { |
| 499 | return true; |
| 500 | } |
| 501 | else if (m_statusHash[lhs->index()].routeProgression < m_statusHash[rhs->index()].routeProgression) |
| 502 | { |
| 503 | return false; |
| 504 | } |
| 505 | // For cars that have reached the same checkpoint do comparison |
| 506 | // by the position inside that checkpoint |
| 507 | else |
| 508 | { |
| 509 | int lhsPos = 0; |
| 510 | int rhsPos = 0; |
| 511 | int pos = 0; |
| 512 | auto && progression = m_progression[m_statusHash[lhs->index()].routeProgression]; |
| 513 | for (size_t index : progression) |
| 514 | { |
| 515 | if (m_cars[index] == lhs) |
| 516 | { |
| 517 | lhsPos = pos; |
| 518 | } |
| 519 | else if (m_cars[index] == rhs) |
| 520 | { |
| 521 | rhsPos = pos; |
| 522 | } |
| 523 | |
| 524 | pos++; |
| 525 | } |
| 526 | |
| 527 | return lhsPos < rhsPos; |
| 528 | } |
| 529 | }); |
| 530 | |
| 531 | // Store current position to car objects for fast access |
| 532 | size_t position = 1; |
| 533 | for (auto && car : positions) |
| 534 | { |
| 535 | m_statusHash[car->index()].position = position; |
| 536 | position++; |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | void Race::checkIfLapIsCompleted(Car & car, const Route & route, size_t currentTargetNodeIndex) |
| 541 | { |
| 542 | if (currentTargetNodeIndex == 0 && m_statusHash[car.index()].prevTargetNodeIndex + 1 == route.numNodes()) |
| 543 | { |
| 544 | m_timing->setLapCompleted(car.index(), car.isHuman()); |
| 545 | |
| 546 | // Finish the race if winner has already finished. |
| 547 | if (m_winnerFinished) |
| 548 | { |
| 549 | m_timing->setRaceCompleted(car.index(), true, car.isHuman()); |
| 550 | } |
| 551 | } |
| 552 | } |
| 553 | |
| 554 | void Race::checkForNewBestPosition(const Car & car) |
| 555 | { |
| 556 | // Check if the race is completed for a human player and if so, |
| 557 | // check if new best pos achieved and save it. |
| 558 | if (m_game.mode() == Game::Mode::OnePlayerRace || m_game.mode() == Game::Mode::TwoPlayerRace) |
| 559 | { |
| 560 | if (car.isHuman()) |
| 561 | { |
| 562 | const size_t position = m_statusHash[car.index()].position; |
| 563 | if (!m_bestPos.has_value() || static_cast<int>(position) < m_bestPos) |
| 564 | { |
| 565 | Database::instance().saveBestPos(*m_track, static_cast<int>(position), static_cast<int>(m_lapCount), m_game.difficultyProfile().difficulty()); |
| 566 | emit messageRequested(QObject::tr("A new best pos!")); |
| 567 | } |
| 568 | |
| 569 | auto && next = m_track->next().lock(); |
| 570 | if (next && next->trackData().isLocked()) |
| 571 | { |
| 572 | if (position <= m_unlockLimit) |
| 573 | { |
| 574 | next->trackData().setIsLocked(false); |
| 575 | Database::instance().saveTrackUnlockStatus(*next, static_cast<int>(m_lapCount), m_game.difficultyProfile().difficulty()); |
| 576 | emit messageRequested(QObject::tr("A new track unlocked!")); |
| 577 | } |
| 578 | else |
| 579 | { |
| 580 | emit messageRequested(QObject::tr("Better luck next time..")); |
| 581 | } |
| 582 | } |
| 583 | } |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | void Race::checkIfCarIsStuck(Car & car) |
| 588 | { |
| 589 | if (started()) |
| 590 | { |
| 591 | static const int STUCK_LIMIT = 60 * 5; // 5 secs. |
| 592 | |
| 593 | const auto currentTile = m_track->trackTileAtLocation(car.location().i(), car.location().j()); |
| 594 | auto && counter = m_stuckHash[car.index()]; |
| 595 | if (counter.first == nullptr || counter.first != currentTile) |
| 596 | { |
| 597 | counter.first = currentTile; |
| 598 | counter.second = 0; |
| 599 | } |
| 600 | else if (counter.first == currentTile) |
| 601 | { |
| 602 | if (++counter.second >= STUCK_LIMIT) |
| 603 | { |
| 604 | moveCarOntoPreviousCheckPoint(car); |
| 605 | counter.first = nullptr; |
| 606 | counter.second = 0; |
| 607 | } |
| 608 | } |
| 609 | } |
| 610 | } |
| 611 | |
| 612 | void Race::checkIfCarIsOffTrack(Car & car) |
| 613 | { |
| 614 | if (car.isOffTrack() && !m_offTrackMessageTimer.isActive()) |
| 615 | { |
| 616 | static const int OFF_TRACK_LIMIT = 60; // 1 sec |
| 617 | |
| 618 | m_offTrackCounter++; |
| 619 | if (m_offTrackCounter > OFF_TRACK_LIMIT) |
| 620 | { |
| 621 | if (rand() % 2) |
| 622 | { |
| 623 | emit messageRequested(QObject::tr("You must stay on track!")); |
| 624 | } |
| 625 | else |
| 626 | { |
| 627 | emit messageRequested(QObject::tr("Watch your tires!")); |
| 628 | } |
| 629 | m_offTrackMessageTimer.start(); |
| 630 | } |
| 631 | } |
| 632 | else |
| 633 | { |
| 634 | m_offTrackCounter = 0; |
| 635 | } |
| 636 | } |
| 637 | |
| 638 | void Race::moveCarOntoPreviousCheckPoint(Car & car) |
| 639 | { |
| 640 | // Randomize the target location a bit, because otherwise multiple |
| 641 | // stuck cars could be sent to the exactly same location and that would |
| 642 | // result in really bad things. |
| 643 | const auto targetNode = m_track->trackData().route().get(m_statusHash[car.index()].prevTargetNodeIndex); |
| 644 | const auto randRadius = static_cast<double>(TrackTile::width()) / 4; |
| 645 | std::mt19937 engine; |
| 646 | std::uniform_real_distribution<double> dist { -randRadius, randRadius }; |
| 647 | const float x = static_cast<float>(targetNode->location().x() + dist(engine)); |
| 648 | const float y = static_cast<float>(targetNode->location().y() + dist(engine)); |
| 649 | car.translate({ x, y }); |
| 650 | car.physicsComponent().reset(); |
| 651 | juzzlin::L().debug() << "Moved stuck car " << car.index() << " to (" << x << ", " << y << ")"; |
| 652 | } |
| 653 | |
| 654 | size_t Race::getCurrentTargetNodeIndex(size_t carIndex) const |
| 655 | { |
| 656 | return m_statusHash.at(carIndex).currentTargetNodeIndex; |
| 657 | } |
| 658 | |
| 659 | Car & Race::getLeader() const |
| 660 | { |
| 661 | const auto it = std::min_element( |
| 662 | m_cars.begin(), m_cars.end(), |
| 663 | [&](const auto & a, const auto & b) { |
| 664 | const auto posA = m_statusHash.at(a->index()).position; |
| 665 | const auto posB = m_statusHash.at(b->index()).position; |
| 666 | |
| 667 | if (posA <= 0) |
| 668 | { |
| 669 | return false; |
| 670 | } |
| 671 | |
| 672 | if (posB <= 0) |
| 673 | { |
| 674 | return true; |
| 675 | } |
| 676 | |
| 677 | return posA < posB; |
| 678 | }); |
| 679 | |
| 680 | if (it == m_cars.end()) |
| 681 | { |
| 682 | throw std::runtime_error("No leader found"); |
| 683 | } |
| 684 | |
| 685 | return **it; // because m_cars holds Car* |
| 686 | } |
| 687 | |
| 688 | Car & Race::getLoser() const |
| 689 | { |
| 690 | const auto it = std::max_element( |
| 691 | m_cars.begin(), m_cars.end(), |
| 692 | [&](const auto & a, const auto & b) { |
| 693 | auto posA = m_statusHash.at(a->index()).position; |
| 694 | auto posB = m_statusHash.at(b->index()).position; |
| 695 | return posA < posB; |
| 696 | }); |
| 697 | |
| 698 | if (it == m_cars.end()) |
| 699 | { |
| 700 | throw std::runtime_error("No loser found"); |
| 701 | } |
| 702 | |
| 703 | return **it; |
| 704 | } |
| 705 | |
| 706 | size_t Race::position(size_t carIndex) const |
| 707 | { |
| 708 | return m_statusHash.at(carIndex).position; |
| 709 | } |
| 710 | |
| 711 | void Race::setTrack(TrackS track, size_t lapCount) |
| 712 | { |
| 713 | m_lapCount = lapCount; |
| 714 | |
| 715 | m_track = track; |
| 716 | |
| 717 | const auto bestPos = Database::instance().loadBestPos(*m_track, static_cast<int>(m_lapCount), m_game.difficultyProfile().difficulty()); |
| 718 | m_bestPos = bestPos.second ? std::optional { bestPos.first } : std::nullopt; |
| 719 | |
| 720 | for (auto && offTrackDetector : m_offTrackDetectors) |
| 721 | { |
| 722 | offTrackDetector->setTrack(track); |
| 723 | } |
| 724 | } |
| 725 | |
| 726 | size_t Race::lapCount() const |
| 727 | { |
| 728 | return m_lapCount; |
| 729 | } |
| 730 | |
| 731 | void Race::addCar(Car & car) |
| 732 | { |
| 733 | if (find(m_cars.begin(), m_cars.end(), &car) == m_cars.end()) |
| 734 | { |
| 735 | m_cars.push_back(&car); |
| 736 | m_offTrackDetectors.push_back(std::make_shared<OffTrackDetector>(car)); |
| 737 | } |
| 738 | } |
| 739 | |
| 740 | void Race::removeCars() |
| 741 | { |
| 742 | m_cars.clear(); |
| 743 | m_offTrackDetectors.clear(); |
| 744 | } |
| 745 | |
| 746 | Race::TimingW Race::timing() const |
| 747 | { |
| 748 | return m_timing; |
| 749 | } |
| 750 | |
| 751 | bool Race::checkeredFlagEnabled() const |
| 752 | { |
| 753 | return m_checkeredFlagEnabled; |
| 754 | } |
| 755 | |
| 756 | bool Race::isRaceFinished() const |
| 757 | { |
| 758 | if (m_game.hasTwoHumanPlayers()) |
| 759 | { |
| 760 | return m_timing->raceCompleted(m_humanPlayerIndex1) && m_timing->raceCompleted(m_humanPlayerIndex2); |
| 761 | } |
| 762 | |
| 763 | return m_timing->raceCompleted(m_humanPlayerIndex1); |
| 764 | } |
| 765 | |
| 766 | Race::~Race() = default; |