Game.cpp 19 KB

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