Game.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. #include "Game.h"
  2. #include "Zeit.h"
  3. #include "Player.h"
  4. #include "OverworldDimension.h"
  5. #include "NoBlock.h"
  6. #include "AsynchronCall.h"
  7. #include "Entity.h"
  8. #include "AddEntityUpdate.h"
  9. #include "EntityRemovedUpdate.h"
  10. #include "NetworkMessage.h"
  11. using namespace Framework;
  12. GameClient::GameClient(Player* zPlayer, FCKlient* client)
  13. : Thread(),
  14. zPlayer(zPlayer),
  15. client(client),
  16. viewDistance(DEFAULT_VIEW_DISTANCE),
  17. first(1),
  18. online(1),
  19. finished(0),
  20. backgroundFinished(0),
  21. foregroundFinished(0)
  22. {
  23. new AsynchronCall("Game Client Updates", [this]()
  24. {
  25. while (online)
  26. {
  27. other.lock();
  28. if (updateQueue.hat(0))
  29. {
  30. WorldUpdate* update = updateQueue.get(0);
  31. updateQueue.remove(0);
  32. other.unlock();
  33. background.lock();
  34. this->client->zBackgroundWriter()->schreibe((char*)&Message::WORLD_UPDATE, 1);
  35. update->writeAndCheck(this->client->zBackgroundWriter());
  36. background.unlock();
  37. update->release();
  38. }
  39. else
  40. {
  41. other.unlock();
  42. updateSync.wait();
  43. }
  44. }
  45. finished = 1;
  46. });
  47. start();
  48. }
  49. GameClient::~GameClient()
  50. {
  51. online = 0;
  52. updateSync.notify();
  53. emptyForegroundQueueSync.notifyAll();
  54. emptyBackgroundQueueSync.notifyAll();
  55. foregroundQueueSync.notify();
  56. backgroundQueueSync.notify();
  57. while (!finished || !foregroundFinished || !backgroundFinished)
  58. Sleep(100);
  59. client->release();
  60. }
  61. void GameClient::thread()
  62. {
  63. new AsynchronCall("Game Client Background", [this]()
  64. {
  65. while (online)
  66. {
  67. queueCs.lock();
  68. if (backgroundQueue.hat(0))
  69. {
  70. NetworkMessage* message = backgroundQueue.get(0);
  71. backgroundQueue.remove(0);
  72. queueCs.unlock();
  73. background.lock();
  74. message->writeTo(client->zBackgroundWriter());
  75. background.unlock();
  76. message->release();
  77. }
  78. else
  79. {
  80. queueCs.unlock();
  81. emptyBackgroundQueueSync.notifyAll();
  82. backgroundQueueSync.wait();
  83. }
  84. }
  85. backgroundFinished = 1;
  86. });
  87. while (online)
  88. {
  89. queueCs.lock();
  90. if (foregroundQueue.hat(0))
  91. {
  92. NetworkMessage* message = foregroundQueue.get(0);
  93. foregroundQueue.remove(0);
  94. queueCs.unlock();
  95. foreground.lock();
  96. message->writeTo(client->zForegroundWriter());
  97. foreground.unlock();
  98. message->release();
  99. }
  100. else
  101. {
  102. queueCs.unlock();
  103. emptyForegroundQueueSync.notifyAll();
  104. foregroundQueueSync.wait();
  105. }
  106. }
  107. foregroundFinished = 1;
  108. }
  109. void GameClient::sendWorldUpdate(WorldUpdate* update)
  110. {
  111. bool add = 0;
  112. if (zPlayer->getCurrentDimensionId() == update->getAffectedDimension())
  113. {
  114. auto pos = (Vec3<int>)zPlayer->getPosition();
  115. int dist = update->distanceTo(pos.x, pos.y);
  116. if (dist < viewDistance * CHUNK_SIZE)
  117. {
  118. other.lock();
  119. int index = 0;
  120. for (auto update2 : updateQueue)
  121. {
  122. int dist2 = update2->distanceTo(pos.x, pos.y);
  123. if (dist2 > dist)
  124. break;
  125. index++;
  126. }
  127. updateQueue.add(update, index);
  128. other.unlock();
  129. updateSync.notify();
  130. add = 1;
  131. }
  132. }
  133. if (!add)
  134. update->release();
  135. }
  136. void GameClient::reply()
  137. {
  138. other.lock();
  139. for (auto req : requests)
  140. Game::INSTANCE->api(req, this);
  141. requests.leeren();
  142. other.unlock();
  143. if (first)
  144. {
  145. foreground.lock();
  146. int id = zPlayer->getId();
  147. client->zForegroundWriter()->schreibe((char*)&Message::POSITION_UPDATE, 1);
  148. client->zForegroundWriter()->schreibe((char*)&id, 4);
  149. foreground.unlock();
  150. first = 0;
  151. }
  152. }
  153. void GameClient::logout()
  154. {
  155. online = 0;
  156. }
  157. void GameClient::addMessage(StreamReader* reader)
  158. {
  159. short len = 0;
  160. reader->lese((char*)&len, 2);
  161. InMemoryBuffer* buffer = new InMemoryBuffer();
  162. char* tmp = new char[len];
  163. reader->lese(tmp, len);
  164. buffer->schreibe(tmp, len);
  165. delete[]tmp;
  166. other.lock();
  167. requests.add(buffer);
  168. other.unlock();
  169. }
  170. bool GameClient::isOnline() const
  171. {
  172. return online;
  173. }
  174. void GameClient::sendResponse(NetworkMessage* response)
  175. {
  176. queueCs.lock();
  177. if (response->isUseBackground())
  178. {
  179. if (backgroundQueue.getEintragAnzahl() > 20)
  180. {
  181. queueCs.unlock();
  182. emptyBackgroundQueueSync.wait();
  183. queueCs.lock();
  184. }
  185. backgroundQueue.add(response);
  186. queueCs.unlock();
  187. backgroundQueueSync.notify();
  188. }
  189. else
  190. {
  191. if (foregroundQueue.getEintragAnzahl() > 100)
  192. {
  193. queueCs.unlock();
  194. std::cout << "WARNING: Game paused because nework connection to " << zPlayer->getName() << " is to slow.\n";
  195. ZeitMesser m;
  196. m.messungStart();
  197. emptyForegroundQueueSync.wait();
  198. m.messungEnde();
  199. std::cout << "WARNING: Game resumed after " << m.getSekunden() << " seconds.\n";
  200. queueCs.lock();
  201. }
  202. foregroundQueue.add(response);
  203. queueCs.unlock();
  204. foregroundQueueSync.notify();
  205. }
  206. }
  207. Player* GameClient::zEntity() const
  208. {
  209. return zPlayer;
  210. }
  211. void GameClient::sendTypes()
  212. {
  213. foreground.lock();
  214. int count = StaticRegistry<BlockType>::INSTANCE.getCount();
  215. client->zForegroundWriter()->schreibe((char*)&count, 4);
  216. for (int i = 0; i < count; i++)
  217. {
  218. BlockType* t = StaticRegistry<BlockType>::INSTANCE.zElement(i);
  219. int id = t->getId();
  220. client->zForegroundWriter()->schreibe((char*)&id, 4);
  221. bool inst = t->doesNeedClientInstance();
  222. client->zForegroundWriter()->schreibe((char*)&inst, 1);
  223. int maxHp = t->getInitialMaxHP();
  224. client->zForegroundWriter()->schreibe((char*)&maxHp, 4);
  225. t->getModel().writeTo(client->zForegroundWriter());
  226. }
  227. count = StaticRegistry<ItemType>::INSTANCE.getCount();
  228. client->zForegroundWriter()->schreibe((char*)&count, 4);
  229. for (int i = 0; i < count; i++)
  230. {
  231. ItemType* t = StaticRegistry<ItemType>::INSTANCE.zElement(i);
  232. int id = t->getId();
  233. client->zForegroundWriter()->schreibe((char*)&id, 4);
  234. t->getModel().writeTo(client->zForegroundWriter());
  235. }
  236. count = StaticRegistry<EntityType>::INSTANCE.getCount();
  237. client->zForegroundWriter()->schreibe((char*)&count, 4);
  238. for (int i = 0; i < count; i++)
  239. {
  240. EntityType* t = StaticRegistry<EntityType>::INSTANCE.zElement(i);
  241. int id = t->getId();
  242. client->zForegroundWriter()->schreibe((char*)&id, 4);
  243. t->getModel().writeTo(client->zForegroundWriter());
  244. }
  245. foreground.unlock();
  246. }
  247. Game::Game(Framework::Text name, Framework::Text worldsDir)
  248. : Thread(),
  249. name(name),
  250. dimensions(new RCArray<Dimension>()),
  251. updates(new RCArray<WorldUpdate>()),
  252. clients(new RCArray<GameClient>()),
  253. ticker(new TickOrganizer()),
  254. path((const char*)(worldsDir + "/" + name)),
  255. stop(0),
  256. tickId(0),
  257. nextEntityId(0),
  258. generator(0),
  259. loader(0),
  260. totalTickTime(0),
  261. tickCounter(0)
  262. {
  263. if (!DateiExistiert(worldsDir + "/" + name))
  264. DateiPfadErstellen(worldsDir + "/" + name + "/");
  265. Datei d;
  266. d.setDatei(path + "/eid");
  267. if (d.existiert())
  268. {
  269. d.open(Datei::Style::lesen);
  270. d.lese((char*)&nextEntityId, 4);
  271. d.close();
  272. }
  273. start();
  274. }
  275. Game::~Game()
  276. {
  277. dimensions->release();
  278. updates->release();
  279. clients->release();
  280. generator->release();
  281. loader->release();
  282. }
  283. void Game::initialize()
  284. {
  285. int seed = 0;
  286. int index = 0;
  287. for (char* n = name; *n; n++)
  288. seed += (int)pow((float)*n * 31, (float)++index);
  289. generator = new WorldGenerator(seed);
  290. loader = new WorldLoader();
  291. recipies.loadRecipies("data/recipies");
  292. }
  293. void Game::thread()
  294. {
  295. ZeitMesser waitForLock;
  296. ZeitMesser removeOldClients;
  297. ZeitMesser tickEntities;
  298. ZeitMesser worldUpdates;
  299. ZeitMesser clientReply;
  300. ZeitMesser removeOldChunks;
  301. ZeitMesser m;
  302. while (!stop)
  303. {
  304. m.messungStart();
  305. ticker->nextTick();
  306. Array<int> removed;
  307. double waitTotal = 0;
  308. waitForLock.messungStart();
  309. cs.lock();
  310. waitForLock.messungEnde();
  311. waitTotal += waitForLock.getSekunden();
  312. removeOldClients.messungStart();
  313. int index = 0;
  314. for (auto player : *clients)
  315. {
  316. if (!player->isOnline())
  317. {
  318. std::cout << "player " << player->zEntity()->getName() << " disconnected.\n";
  319. Datei pFile;
  320. pFile.setDatei(path + "/player/" + player->zEntity()->getName());
  321. pFile.erstellen();
  322. if (pFile.open(Datei::Style::schreiben))
  323. PlayerEntityType::INSTANCE->saveEntity(player->zEntity(), &pFile);
  324. pFile.close();
  325. removed.add(index, 0);
  326. Dimension* dim = zDimension(player->zEntity()->getCurrentDimensionId());
  327. dim->removeSubscriptions(player->zEntity());
  328. this->requestWorldUpdate(new EntityRemovedUpdate(player->zEntity()->getId(), player->zEntity()->getCurrentDimensionId(), player->zEntity()->getPosition()));
  329. }
  330. index++;
  331. }
  332. for (auto i : removed)
  333. clients->remove(i);
  334. removeOldClients.messungEnde();
  335. cs.unlock();
  336. tickEntities.messungStart();
  337. for (auto dim : *dimensions)
  338. dim->tickEntities();
  339. tickEntities.messungEnde();
  340. waitForLock.messungStart();
  341. cs.lock();
  342. waitForLock.messungEnde();
  343. waitTotal += waitForLock.getSekunden();
  344. worldUpdates.messungStart();
  345. while (updates->hat(0))
  346. {
  347. WorldUpdate* update = updates->z(0);
  348. for (auto client : *clients)
  349. client->sendWorldUpdate(dynamic_cast<WorldUpdate*>(update->getThis()));
  350. if (!zDimension(update->getAffectedDimension()))
  351. addDimension(new Dimension(update->getAffectedDimension()));
  352. update->onUpdate(zDimension(update->getAffectedDimension()));
  353. updates->remove(0);
  354. }
  355. worldUpdates.messungEnde();
  356. cs.unlock();
  357. clientReply.messungStart();
  358. for (auto client : *clients)
  359. client->reply();
  360. clientReply.messungEnde();
  361. waitForLock.messungStart();
  362. cs.lock();
  363. waitForLock.messungEnde();
  364. waitTotal += waitForLock.getSekunden();
  365. removeOldChunks.messungStart();
  366. for (auto dim : *dimensions)
  367. dim->removeOldChunks();
  368. removeOldChunks.messungEnde();
  369. cs.unlock();
  370. m.messungEnde();
  371. double sec = m.getSekunden();
  372. tickCounter++;
  373. totalTickTime += sec;
  374. if (tickCounter >= 1000)
  375. {
  376. std::cout << "Average Tick time: " << (totalTickTime / 1000) << "\n";
  377. if ((totalTickTime / 1000) * 20 > 1)
  378. {
  379. std::cout << "The game runns slower than normal.\n";
  380. }
  381. else
  382. {
  383. std::cout << "No performance issues detected.\n";
  384. }
  385. totalTickTime = 0;
  386. tickCounter = 0;
  387. }
  388. if (sec < 0.05)
  389. Sleep((int)((0.05 - sec) * 1000));
  390. else if (sec > 1)
  391. {
  392. std::cout << "WARNING: tick needed " << sec << " seconds. The game will run sower then normal.\n";
  393. std::cout << "waiting: " << waitTotal << "\nremoveOldClients: " << removeOldClients.getSekunden() << "\ntickEntities:" << tickEntities.getSekunden() << "\nworldUpdates: " << worldUpdates.getSekunden() << "\nclientReply: " << clientReply.getSekunden() << "\nremoveOldChunks:" << removeOldChunks.getSekunden() << "\n";
  394. }
  395. }
  396. save();
  397. }
  398. void Game::api(Framework::InMemoryBuffer* zRequest, GameClient* zOrigin)
  399. {
  400. char type;
  401. zRequest->lese(&type, 1);
  402. NetworkMessage* response = new NetworkMessage();
  403. switch (type)
  404. {
  405. case 1: // world
  406. {
  407. Dimension* dim = zDimension(zOrigin->zEntity()->getCurrentDimensionId());
  408. if (!dim)
  409. {
  410. dim = new Dimension(zOrigin->zEntity()->getCurrentDimensionId());
  411. addDimension(dim);
  412. }
  413. dim->api(zRequest, response, zOrigin->zEntity());
  414. break;
  415. }
  416. case 2: // player
  417. zOrigin->zEntity()->playerApi(zRequest, response);
  418. break;
  419. case 3: // entity
  420. {
  421. int id;
  422. zRequest->lese((char*)&id, 4);
  423. for (Dimension* dim : *dimensions)
  424. {
  425. Entity* entity = dim->zEntity(id);
  426. if (entity)
  427. {
  428. entity->api(zRequest, response);
  429. break;
  430. }
  431. }
  432. break;
  433. }
  434. case 4:
  435. { // inventory
  436. bool isEntity;
  437. zRequest->lese((char*)&isEntity, 1);
  438. Inventory* target;
  439. if (isEntity)
  440. {
  441. int id;
  442. zRequest->lese((char*)&id, 4);
  443. target = zEntity(id);
  444. }
  445. else
  446. {
  447. int dim;
  448. Vec3<int> pos;
  449. zRequest->lese((char*)&dim, 4);
  450. zRequest->lese((char*)&pos.x, 4);
  451. zRequest->lese((char*)&pos.y, 4);
  452. zRequest->lese((char*)&pos.z, 4);
  453. target = zBlockAt(pos, dim);
  454. }
  455. if (target)
  456. target->inventoryApi(zRequest, response, zOrigin->zEntity());
  457. break;
  458. }
  459. default:
  460. std::cout << "received unknown api request in game with type " << (int)type << "\n";
  461. }
  462. if (!response->isEmpty())
  463. {
  464. if (response->isBroadcast())
  465. broadcastMessage(response);
  466. else
  467. zOrigin->sendResponse(response);
  468. }
  469. else
  470. {
  471. response->release();
  472. }
  473. }
  474. void Game::updateLightning(int dimensionId, Vec3<int> location)
  475. {
  476. Dimension* zDim = zDimension(dimensionId);
  477. if (zDim)
  478. zDim->updateLightning(location);
  479. }
  480. void Game::updateLightningWithoutWait(int dimensionId, Vec3<int> location)
  481. {
  482. Dimension* zDim = zDimension(dimensionId);
  483. if (zDim)
  484. zDim->updateLightningWithoutWait(location);
  485. }
  486. void Game::broadcastMessage(NetworkMessage* response)
  487. {
  488. for (auto client : *clients)
  489. client->sendResponse(dynamic_cast<NetworkMessage*>(response->getThis()));
  490. }
  491. void Game::sendMessage(NetworkMessage* response, Entity* zTargetPlayer)
  492. {
  493. for (auto client : *clients)
  494. {
  495. if (client->zEntity()->getId() == zTargetPlayer->getId())
  496. {
  497. client->sendResponse(response);
  498. return;
  499. }
  500. }
  501. response->release();
  502. }
  503. bool Game::requestWorldUpdate(WorldUpdate* update)
  504. {
  505. cs.lock();
  506. for (WorldUpdate* u : *updates)
  507. {
  508. if (u->getMaxAffectedPoint().x >= update->getMinAffectedPoint().x && u->getMinAffectedPoint().x <= update->getMaxAffectedPoint().x &&
  509. u->getMaxAffectedPoint().y >= update->getMinAffectedPoint().y && u->getMinAffectedPoint().y <= update->getMaxAffectedPoint().y &&
  510. u->getMaxAffectedPoint().z >= update->getMinAffectedPoint().z && u->getMinAffectedPoint().z <= update->getMaxAffectedPoint().z && u->getType() == update->getType())
  511. {
  512. cs.unlock();
  513. update->release();
  514. return 0;
  515. }
  516. }
  517. updates->add(update);
  518. cs.unlock();
  519. return 1;
  520. }
  521. GameClient* Game::addPlayer(FCKlient* client, Framework::Text name)
  522. {
  523. cs.lock();
  524. Datei pFile;
  525. pFile.setDatei(path + "/player/" + name);
  526. std::cout << "player " << name.getText() << " connected.\n";
  527. Player* player;
  528. bool isNew = 0;
  529. if (!pFile.existiert() || !pFile.open(Datei::Style::lesen))
  530. {
  531. player = (Player*)PlayerEntityType::INSTANCE->createEntityAt(Vec3<float>(0.5, 0.5, 0), OverworldDimension::ID);
  532. player->setName(name);
  533. isNew = 1;
  534. }
  535. else
  536. {
  537. player = (Player*)PlayerEntityType::INSTANCE->loadEntity(&pFile);
  538. pFile.close();
  539. }
  540. if (player->getId() >= nextEntityId)
  541. {
  542. nextEntityId = player->getId() + 1;
  543. }
  544. GameClient* gameClient = new GameClient(player, client);
  545. gameClient->sendTypes();
  546. clients->add(gameClient);
  547. if (!zDimension(player->getCurrentDimensionId()))
  548. {
  549. this->addDimension(new Dimension(player->getCurrentDimensionId()));
  550. }
  551. // subscribe the new player as an observer of the new chunk
  552. Dimension* dim = zDimension(player->getCurrentDimensionId());
  553. InMemoryBuffer* buffer = new InMemoryBuffer();
  554. buffer->schreibe("\0", 1);
  555. Punkt center = getChunkCenter((int)player->getPosition().x, (int)player->getPosition().y);
  556. buffer->schreibe((char*)&center.x, 4);
  557. buffer->schreibe((char*)&center.y, 4);
  558. buffer->schreibe("\0", 1);
  559. dim->api(buffer, 0, player);
  560. buffer->release();
  561. while (isNew && !dim->zChunk(getChunkCenter((int)player->getPosition().x, (int)player->getPosition().y)))
  562. {
  563. cs.unlock();
  564. Sleep(1000);
  565. cs.lock();
  566. }
  567. if (isNew)
  568. {
  569. Either<Block*, int> b = AirBlockBlockType::ID;
  570. int h = WORLD_HEIGHT;
  571. while (((b.isA() && (!(Block*)b || ((Block*)b)->isPassable())) || (b.isB() && StaticRegistry<BlockType>::INSTANCE.zElement(b)->zDefault()->isPassable())) && h > 0)
  572. b = zBlockAt({ (int)player->getPosition().x, (int)player->getPosition().y, --h }, player->getCurrentDimensionId());
  573. player->setPosition({ player->getPosition().x, player->getPosition().y, (float)h + 1.f });
  574. }
  575. requestWorldUpdate(new AddEntityUpdate(player, player->getCurrentDimensionId()));
  576. cs.unlock();
  577. return dynamic_cast<GameClient*>(gameClient->getThis());
  578. }
  579. bool Game::isChunkLoaded(int x, int y, int dimension) const
  580. {
  581. Dimension* dim = zDimension(dimension);
  582. return (dim && dim->hasChunck(x, y));
  583. }
  584. bool Game::doesChunkExist(int x, int y, int dimension)
  585. {
  586. cs.lock();
  587. bool result = isChunkLoaded(x, y, dimension) || loader->existsChunk(x, y, dimension);
  588. cs.unlock();
  589. return result;
  590. }
  591. Framework::Either<Block*, int> Game::zBlockAt(Framework::Vec3<int> location, int dimension) const
  592. {
  593. Dimension* dim = zDimension(dimension);
  594. if (dim)
  595. return dim->zBlock(location);
  596. return 0;
  597. }
  598. Block* Game::zRealBlockInstance(Framework::Vec3<int> location, int dimension)
  599. {
  600. Dimension* dim = zDimension(dimension);
  601. if (dim)
  602. return dim->zRealBlockInstance(location);
  603. return 0;
  604. }
  605. Dimension* Game::zDimension(int id) const
  606. {
  607. for (auto dim : *dimensions)
  608. {
  609. if (dim->getDimensionId() == id)
  610. return dim;
  611. }
  612. return 0;
  613. }
  614. Framework::Punkt Game::getChunkCenter(int x, int y)
  615. {
  616. return Punkt(((x < 0 ? x + 1 : x) / CHUNK_SIZE) * CHUNK_SIZE + (x < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2, ((y < 0 ? y + 1 : y) / CHUNK_SIZE) * CHUNK_SIZE + (y < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2);
  617. }
  618. Area Game::getChunckArea(Punkt center) const
  619. {
  620. return { center.x - CHUNK_SIZE / 2, center.y - CHUNK_SIZE / 2, center.x + CHUNK_SIZE / 2 - 1, center.y + CHUNK_SIZE / 2 - 1, 0 };
  621. }
  622. Framework::Text Game::getWorldDirectory() const
  623. {
  624. return path;
  625. }
  626. void Game::requestArea(Area area)
  627. {
  628. generator->requestGeneration(area);
  629. loader->requestLoading(area);
  630. }
  631. void Game::save() const
  632. {
  633. Datei d;
  634. d.setDatei(path + "/eid");
  635. d.open(Datei::Style::schreiben);
  636. d.schreibe((char*)&nextEntityId, 4);
  637. d.close();
  638. for (auto dim : *dimensions)
  639. dim->save(path);
  640. }
  641. void Game::requestStop()
  642. {
  643. stop = 1;
  644. warteAufThread(1000000);
  645. }
  646. void Game::addDimension(Dimension* d)
  647. {
  648. dimensions->add(d);
  649. }
  650. int Game::getNextEntityId()
  651. {
  652. cs.lock();
  653. int result = nextEntityId++;
  654. cs.unlock();
  655. return result;
  656. }
  657. WorldGenerator* Game::zGenerator() const
  658. {
  659. return generator;
  660. }
  661. Game* Game::INSTANCE = 0;
  662. void Game::initialize(Framework::Text name, Framework::Text worldsDir)
  663. {
  664. if (!Game::INSTANCE)
  665. {
  666. Game::INSTANCE = new Game(name, worldsDir);
  667. Game::INSTANCE->initialize();
  668. }
  669. }
  670. Entity* Game::zEntity(int id, int dimensionId) const
  671. {
  672. Dimension* d = zDimension(dimensionId);
  673. if (d)
  674. return d->zEntity(id);
  675. return 0;
  676. }
  677. Entity* Game::zEntity(int id) const
  678. {
  679. for (Dimension* d : *dimensions)
  680. {
  681. Entity* e = d->zEntity(id);
  682. if (e)
  683. return e;
  684. }
  685. // for new players that are currently loading
  686. for (GameClient* client : *clients)
  687. {
  688. if (client->zEntity()->getId() == id)
  689. {
  690. return client->zEntity();
  691. }
  692. }
  693. return 0;
  694. }
  695. Entity* Game::zNearestEntity(int dimensionId, Framework::Vec3<float> pos, std::function<bool(Entity*)> filter)
  696. {
  697. Dimension* d = zDimension(dimensionId);
  698. if (!d)
  699. return 0;
  700. return d->zNearestEntity(pos, filter);
  701. }
  702. const RecipieLoader& Game::getRecipies() const
  703. {
  704. return recipies;
  705. }