Game.cpp 25 KB

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