Game.cpp 26 KB

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