Game.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  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. averageTickTime(0),
  283. ticksPerSecond(0),
  284. totalTime(0)
  285. {
  286. if (!DateiExistiert(worldsDir + "/" + name))
  287. DateiPfadErstellen(worldsDir + "/" + name + "/");
  288. Datei d;
  289. d.setDatei(path + "/eid");
  290. if (d.existiert())
  291. {
  292. d.open(Datei::Style::lesen);
  293. d.lese((char*)&nextEntityId, 4);
  294. d.close();
  295. }
  296. start();
  297. }
  298. Game::~Game()
  299. {
  300. dimensions->release();
  301. updates->release();
  302. clients->release();
  303. generator->release();
  304. loader->release();
  305. chat->release();
  306. playerRegister->release();
  307. }
  308. void Game::initialize()
  309. {
  310. int seed = 0;
  311. int index = 0;
  312. for (const char* n = name; *n; n++)
  313. seed += (int)pow((float)*n * 31, (float)++index);
  314. generator = new WorldGenerator(seed);
  315. loader = new WorldLoader();
  316. recipies.loadRecipies("data/recipies");
  317. chat = new Chat();
  318. }
  319. void Game::thread()
  320. {
  321. ZeitMesser waitForLock;
  322. ZeitMesser removeOldClients;
  323. ZeitMesser tickEntities;
  324. ZeitMesser worldUpdates;
  325. ZeitMesser clientReply;
  326. ZeitMesser removeOldChunks;
  327. ZeitMesser m;
  328. ZeitMesser total;
  329. total.messungStart();
  330. double tickTime = 0;
  331. double sleepTime = 0;
  332. while (!stop)
  333. {
  334. m.messungStart();
  335. ticker->nextTick();
  336. actionsCs.lock();
  337. while (actions.getEintragAnzahl() > 0)
  338. {
  339. actions.get(0)();
  340. actions.remove(0);
  341. }
  342. actionsCs.unlock();
  343. Array<int> removed;
  344. double waitTotal = 0;
  345. waitForLock.messungStart();
  346. cs.lock();
  347. waitForLock.messungEnde();
  348. waitTotal += waitForLock.getSekunden();
  349. removeOldClients.messungStart();
  350. int index = 0;
  351. for (auto player : *clients)
  352. {
  353. if (!player->isOnline())
  354. {
  355. chat->removeObserver(player->zEntity()->getId());
  356. chat->broadcastMessage(
  357. Framework::Text(player->zEntity()->getName())
  358. + " left the game.",
  359. Chat::CHANNEL_INFO);
  360. Datei pFile;
  361. pFile.setDatei(
  362. path + "/player/" + getPlayerId(player->zEntity()->getName()));
  363. pFile.erstellen();
  364. if (pFile.open(Datei::Style::schreiben))
  365. StaticRegistry<EntityType>::INSTANCE
  366. .zElement(EntityTypeEnum::PLAYER)
  367. ->saveEntity(player->zEntity(), &pFile);
  368. pFile.close();
  369. removed.add(index, 0);
  370. Dimension* dim
  371. = zDimension(player->zEntity()->getCurrentDimensionId());
  372. dim->removeSubscriptions(player->zEntity());
  373. this->requestWorldUpdate(
  374. new EntityRemovedUpdate(player->zEntity()->getId(),
  375. player->zEntity()->getCurrentDimensionId(),
  376. player->zEntity()->getPosition()));
  377. }
  378. index++;
  379. }
  380. for (auto i : removed)
  381. clients->remove(i);
  382. removeOldClients.messungEnde();
  383. cs.unlock();
  384. tickEntities.messungStart();
  385. for (auto dim : *dimensions)
  386. dim->tickEntities();
  387. tickEntities.messungEnde();
  388. waitForLock.messungStart();
  389. cs.lock();
  390. waitForLock.messungEnde();
  391. waitTotal += waitForLock.getSekunden();
  392. worldUpdates.messungStart();
  393. while (updates->hat(0))
  394. {
  395. WorldUpdate* update = updates->z(0);
  396. for (auto client : *clients)
  397. client->sendWorldUpdate(
  398. dynamic_cast<WorldUpdate*>(update->getThis()));
  399. if (!zDimension(update->getAffectedDimension()))
  400. addDimension(new Dimension(update->getAffectedDimension()));
  401. update->onUpdate(zDimension(update->getAffectedDimension()));
  402. updates->remove(0);
  403. }
  404. worldUpdates.messungEnde();
  405. cs.unlock();
  406. clientReply.messungStart();
  407. for (auto client : *clients)
  408. client->reply();
  409. clientReply.messungEnde();
  410. waitForLock.messungStart();
  411. cs.lock();
  412. waitForLock.messungEnde();
  413. waitTotal += waitForLock.getSekunden();
  414. removeOldChunks.messungStart();
  415. for (auto dim : *dimensions)
  416. dim->removeOldChunks();
  417. removeOldChunks.messungEnde();
  418. cs.unlock();
  419. m.messungEnde();
  420. double sec = m.getSekunden();
  421. tickCounter++;
  422. totalTickTime += sec;
  423. sleepTime += 1.0 / 20 - tickTime;
  424. if (sleepTime > 0)
  425. {
  426. Sleep((int)(sleepTime * 1000));
  427. }
  428. total.messungEnde();
  429. total.messungStart();
  430. tickTime = total.getSekunden();
  431. totalTime += tickTime;
  432. if (totalTime >= 1)
  433. {
  434. averageTickTime = totalTickTime / tickCounter;
  435. ticksPerSecond = tickCounter;
  436. totalTickTime = 0;
  437. tickCounter = 0;
  438. totalTime = 0;
  439. std::cout << std::flush; // update info in console
  440. }
  441. else if (sec > 1)
  442. {
  443. std::cout << "WARNING: tick needed " << sec
  444. << " seconds. The game will run sower then normal.\n";
  445. std::cout << "waiting: " << waitTotal << "\nremoveOldClients: "
  446. << removeOldClients.getSekunden()
  447. << "\ntickEntities:" << tickEntities.getSekunden()
  448. << "\nworldUpdates: " << worldUpdates.getSekunden()
  449. << "\nclientReply: " << clientReply.getSekunden()
  450. << "\nremoveOldChunks:" << removeOldChunks.getSekunden()
  451. << "\n";
  452. }
  453. }
  454. save();
  455. generator->exitAndWait();
  456. loader->exitAndWait();
  457. ticker->exitAndWait();
  458. for (Dimension* dim : *dimensions)
  459. dim->requestStopAndWait();
  460. std::cout << "Game thread exited\n";
  461. getThis();
  462. }
  463. void Game::api(Framework::InMemoryBuffer* zRequest, GameClient* zOrigin)
  464. {
  465. char type;
  466. zRequest->lese(&type, 1);
  467. NetworkMessage* response = new NetworkMessage();
  468. switch (type)
  469. {
  470. case 1: // world
  471. {
  472. Dimension* dim
  473. = zDimension(zOrigin->zEntity()->getCurrentDimensionId());
  474. if (!dim)
  475. {
  476. dim = new Dimension(
  477. zOrigin->zEntity()->getCurrentDimensionId());
  478. addDimension(dim);
  479. }
  480. dim->api(zRequest, response, zOrigin->zEntity());
  481. break;
  482. }
  483. case 2: // player
  484. zOrigin->zEntity()->playerApi(zRequest, response);
  485. break;
  486. case 3: // entity
  487. {
  488. int id;
  489. zRequest->lese((char*)&id, 4);
  490. for (Dimension* dim : *dimensions)
  491. {
  492. Entity* entity = dim->zEntity(id);
  493. if (entity)
  494. {
  495. entity->api(zRequest, response, zOrigin->zEntity());
  496. break;
  497. }
  498. }
  499. break;
  500. }
  501. case 4:
  502. { // inventory
  503. bool isEntity;
  504. zRequest->lese((char*)&isEntity, 1);
  505. Inventory* target;
  506. if (isEntity)
  507. {
  508. int id;
  509. zRequest->lese((char*)&id, 4);
  510. target = zEntity(id);
  511. }
  512. else
  513. {
  514. int dim;
  515. Vec3<int> pos;
  516. zRequest->lese((char*)&dim, 4);
  517. zRequest->lese((char*)&pos.x, 4);
  518. zRequest->lese((char*)&pos.y, 4);
  519. zRequest->lese((char*)&pos.z, 4);
  520. target = zBlockAt(pos, dim);
  521. }
  522. if (target)
  523. target->inventoryApi(zRequest, response, zOrigin->zEntity());
  524. break;
  525. }
  526. case 5:
  527. { // crafting uiml request
  528. int id;
  529. zRequest->lese((char*)&id, 4);
  530. Text uiml = recipies.getCrafingUIML(
  531. StaticRegistry<ItemType>::INSTANCE.zElement(id));
  532. Text dialogId = "crafting_";
  533. dialogId += id;
  534. response->openDialog(dialogId);
  535. int msgSize = 4 + uiml.getLength();
  536. char* msg = new char[msgSize];
  537. *(int*)msg = uiml.getLength();
  538. memcpy(msg + 4, uiml.getText(), uiml.getLength());
  539. response->setMessage(msg, msgSize);
  540. break;
  541. }
  542. case 6:
  543. { // chat message
  544. chat->chatApi(zRequest, zOrigin->zEntity(), response);
  545. break;
  546. }
  547. default:
  548. std::cout << "received unknown api request in game with type "
  549. << (int)type << "\n";
  550. }
  551. if (!response->isEmpty())
  552. {
  553. if (response->isBroadcast())
  554. broadcastMessage(response);
  555. else
  556. zOrigin->sendResponse(response);
  557. }
  558. else
  559. {
  560. response->release();
  561. }
  562. }
  563. void Game::updateLightning(int dimensionId, Vec3<int> location)
  564. {
  565. Dimension* zDim = zDimension(dimensionId);
  566. if (zDim) zDim->updateLightning(location);
  567. }
  568. void Game::updateLightningWithoutWait(int dimensionId, Vec3<int> location)
  569. {
  570. Dimension* zDim = zDimension(dimensionId);
  571. if (zDim) zDim->updateLightningWithoutWait(location);
  572. }
  573. void Game::broadcastMessage(NetworkMessage* response)
  574. {
  575. for (auto client : *clients)
  576. client->sendResponse(
  577. dynamic_cast<NetworkMessage*>(response->getThis()));
  578. }
  579. void Game::sendMessage(NetworkMessage* response, Entity* zTargetPlayer)
  580. {
  581. for (auto client : *clients)
  582. {
  583. if (client->zEntity()->getId() == zTargetPlayer->getId())
  584. {
  585. client->sendResponse(response);
  586. return;
  587. }
  588. }
  589. response->release();
  590. }
  591. bool Game::requestWorldUpdate(WorldUpdate* update)
  592. {
  593. cs.lock();
  594. for (WorldUpdate* u : *updates)
  595. {
  596. if (u->getMaxAffectedPoint().x >= update->getMinAffectedPoint().x
  597. && u->getMinAffectedPoint().x <= update->getMaxAffectedPoint().x
  598. && u->getMaxAffectedPoint().y >= update->getMinAffectedPoint().y
  599. && u->getMinAffectedPoint().y <= update->getMaxAffectedPoint().y
  600. && u->getMaxAffectedPoint().z >= update->getMinAffectedPoint().z
  601. && u->getMinAffectedPoint().z <= update->getMaxAffectedPoint().z
  602. && u->getType() == update->getType())
  603. {
  604. cs.unlock();
  605. update->release();
  606. return 0;
  607. }
  608. }
  609. updates->add(update);
  610. cs.unlock();
  611. return 1;
  612. }
  613. bool Game::checkPlayer(Framework::Text name, Framework::Text secret)
  614. {
  615. if (playerRegister->checkSecret(name, secret))
  616. return 1;
  617. else
  618. {
  619. std::cout << "player " << name.getText()
  620. << " tryed to connect with an invalid secret.\n";
  621. return 0;
  622. }
  623. }
  624. bool Game::existsPlayer(Framework::Text name)
  625. {
  626. return playerRegister->hasPlayer(name);
  627. }
  628. Framework::Text Game::createPlayer(Framework::Text name)
  629. {
  630. return playerRegister->addPlayer(name);
  631. }
  632. GameClient* Game::addPlayer(FCKlient* client, Framework::Text name)
  633. {
  634. cs.lock();
  635. int id = playerRegister->getPlayerId(name);
  636. Datei pFile;
  637. pFile.setDatei(path + "/player/" + id);
  638. Player* player;
  639. bool isNew = 0;
  640. if (!pFile.existiert() || !pFile.open(Datei::Style::lesen))
  641. {
  642. player = (Player*)StaticRegistry<EntityType>::INSTANCE
  643. .zElement(EntityTypeEnum::PLAYER)
  644. ->createEntityAt(
  645. Vec3<float>(0.5, 0.5, 0), DimensionEnum::OVERWORLD);
  646. player->setName(name);
  647. isNew = 1;
  648. }
  649. else
  650. {
  651. player = (Player*)StaticRegistry<EntityType>::INSTANCE
  652. .zElement(EntityTypeEnum::PLAYER)
  653. ->loadEntity(&pFile);
  654. pFile.close();
  655. }
  656. if (player->getId() >= nextEntityId)
  657. {
  658. nextEntityId = player->getId() + 1;
  659. }
  660. GameClient* gameClient = new GameClient(player, client);
  661. gameClient->sendTypes();
  662. clients->add(gameClient);
  663. if (!zDimension(player->getCurrentDimensionId()))
  664. {
  665. this->addDimension(new Dimension(player->getCurrentDimensionId()));
  666. }
  667. // subscribe the new player as an observer of the new chunk
  668. Dimension* dim = zDimension(player->getCurrentDimensionId());
  669. InMemoryBuffer* buffer = new InMemoryBuffer();
  670. buffer->schreibe("\0", 1);
  671. Punkt center = getChunkCenter(
  672. (int)player->getPosition().x, (int)player->getPosition().y);
  673. buffer->schreibe((char*)&center.x, 4);
  674. buffer->schreibe((char*)&center.y, 4);
  675. buffer->schreibe("\0", 1);
  676. dim->api(buffer, 0, player);
  677. buffer->release();
  678. while (isNew
  679. && !dim->zChunk(getChunkCenter(
  680. (int)player->getPosition().x, (int)player->getPosition().y)))
  681. {
  682. cs.unlock();
  683. Sleep(1000);
  684. cs.lock();
  685. }
  686. if (isNew)
  687. {
  688. Either<Block*, int> b = BlockTypeEnum::AIR;
  689. int h = WORLD_HEIGHT;
  690. while (((b.isA() && (!(Block*)b || ((Block*)b)->isPassable()))
  691. || (b.isB()
  692. && StaticRegistry<BlockType>::INSTANCE.zElement(b)
  693. ->zDefault()
  694. ->isPassable()))
  695. && h > 0)
  696. b = zBlockAt({(int)player->getPosition().x,
  697. (int)player->getPosition().y,
  698. --h},
  699. player->getCurrentDimensionId());
  700. player->setPosition(
  701. {player->getPosition().x, player->getPosition().y, (float)h + 1.f});
  702. }
  703. requestWorldUpdate(
  704. new AddEntityUpdate(player, player->getCurrentDimensionId()));
  705. chat->addObserver(gameClient->zEntity()->getId());
  706. chat->broadcastMessage(name + " joined the game.", Chat::CHANNEL_INFO);
  707. cs.unlock();
  708. return dynamic_cast<GameClient*>(gameClient->getThis());
  709. }
  710. bool Game::isChunkLoaded(int x, int y, int dimension) const
  711. {
  712. Dimension* dim = zDimension(dimension);
  713. return (dim && dim->hasChunck(x, y));
  714. }
  715. bool Game::doesChunkExist(int x, int y, int dimension)
  716. {
  717. cs.lock();
  718. bool result = isChunkLoaded(x, y, dimension)
  719. || loader->existsChunk(x, y, dimension);
  720. cs.unlock();
  721. return result;
  722. }
  723. void Game::blockTargetChanged(Block* zBlock)
  724. {
  725. for (GameClient* client : *this->clients)
  726. {
  727. if (client->zEntity()->zTarget()
  728. && client->zEntity()->zTarget()->isBlock(
  729. zBlock->getPos(), NO_DIRECTION))
  730. {
  731. client->zEntity()->onTargetChange();
  732. }
  733. }
  734. }
  735. void Game::entityTargetChanged(Entity* zEntity)
  736. {
  737. for (GameClient* client : *this->clients)
  738. {
  739. if (client->zEntity()->zTarget()
  740. && client->zEntity()->zTarget()->isEntity(zEntity->getId()))
  741. {
  742. client->zEntity()->onTargetChange();
  743. }
  744. }
  745. }
  746. Framework::Either<Block*, int> Game::zBlockAt(
  747. Framework::Vec3<int> location, int dimension) const
  748. {
  749. Dimension* dim = zDimension(dimension);
  750. if (dim) return dim->zBlock(location);
  751. return 0;
  752. }
  753. Block* Game::zRealBlockInstance(Framework::Vec3<int> location, int dimension)
  754. {
  755. Dimension* dim = zDimension(dimension);
  756. if (dim) return dim->zRealBlockInstance(location);
  757. return 0;
  758. }
  759. Dimension* Game::zDimension(int id) const
  760. {
  761. for (auto dim : *dimensions)
  762. {
  763. if (dim->getDimensionId() == id) return dim;
  764. }
  765. return 0;
  766. }
  767. Framework::Punkt Game::getChunkCenter(int x, int y)
  768. {
  769. return Punkt(((x < 0 ? x + 1 : x) / CHUNK_SIZE) * CHUNK_SIZE
  770. + (x < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2,
  771. ((y < 0 ? y + 1 : y) / CHUNK_SIZE) * CHUNK_SIZE
  772. + (y < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2);
  773. }
  774. Area Game::getChunckArea(Punkt center) const
  775. {
  776. return {center.x - CHUNK_SIZE / 2,
  777. center.y - CHUNK_SIZE / 2,
  778. center.x + CHUNK_SIZE / 2 - 1,
  779. center.y + CHUNK_SIZE / 2 - 1,
  780. 0};
  781. }
  782. Framework::Text Game::getWorldDirectory() const
  783. {
  784. return path;
  785. }
  786. void Game::requestArea(Area area)
  787. {
  788. generator->requestGeneration(area);
  789. loader->requestLoading(area);
  790. }
  791. void Game::save() const
  792. {
  793. Datei d;
  794. d.setDatei(path + "/eid");
  795. d.open(Datei::Style::schreiben);
  796. d.schreibe((char*)&nextEntityId, 4);
  797. d.close();
  798. playerRegister->save();
  799. for (auto dim : *dimensions)
  800. dim->save(path);
  801. chat->save();
  802. std::cout << "Game was saved\n";
  803. }
  804. void Game::requestStop()
  805. {
  806. stop = 1;
  807. warteAufThread(1000000);
  808. }
  809. void Game::addDimension(Dimension* d)
  810. {
  811. dimensions->add(d);
  812. }
  813. int Game::getNextEntityId()
  814. {
  815. cs.lock();
  816. int result = nextEntityId++;
  817. cs.unlock();
  818. return result;
  819. }
  820. WorldGenerator* Game::zGenerator() const
  821. {
  822. return generator;
  823. }
  824. Game* Game::INSTANCE = 0;
  825. void Game::initialize(Framework::Text name, Framework::Text worldsDir)
  826. {
  827. if (!Game::INSTANCE)
  828. {
  829. Game::INSTANCE = new Game(name, worldsDir);
  830. Game::INSTANCE->initialize();
  831. }
  832. }
  833. Entity* Game::zEntity(int id, int dimensionId) const
  834. {
  835. Dimension* d = zDimension(dimensionId);
  836. if (d) return d->zEntity(id);
  837. return 0;
  838. }
  839. Entity* Game::zEntity(int id) const
  840. {
  841. for (Dimension* d : *dimensions)
  842. {
  843. Entity* e = d->zEntity(id);
  844. if (e) return e;
  845. }
  846. // for new players that are currently loading
  847. for (GameClient* client : *clients)
  848. {
  849. if (client->zEntity()->getId() == id)
  850. {
  851. return client->zEntity();
  852. }
  853. }
  854. return 0;
  855. }
  856. Entity* Game::zNearestEntity(int dimensionId,
  857. Framework::Vec3<float> pos,
  858. std::function<bool(Entity*)> filter)
  859. {
  860. Dimension* d = zDimension(dimensionId);
  861. if (!d) return 0;
  862. return d->zNearestEntity(pos, filter);
  863. }
  864. const RecipieLoader& Game::getRecipies() const
  865. {
  866. return recipies;
  867. }
  868. void Game::doLater(std::function<void()> action)
  869. {
  870. actionsCs.lock();
  871. actions.add(action);
  872. actionsCs.unlock();
  873. }
  874. TickOrganizer* Game::zTickOrganizer() const
  875. {
  876. return ticker;
  877. }
  878. Chat* Game::zChat() const
  879. {
  880. return chat;
  881. }
  882. Player* Game::zPlayerByName(const char* name) const
  883. {
  884. for (GameClient* client : *clients)
  885. {
  886. if (strcmp(client->zEntity()->getName(), name) == 0)
  887. {
  888. return client->zEntity();
  889. }
  890. }
  891. return 0;
  892. }
  893. int Game::getPlayerId(const char* name) const
  894. {
  895. return playerRegister->getPlayerId(name);
  896. }
  897. double Game::getAverageTickTime() const
  898. {
  899. return averageTickTime;
  900. }
  901. int Game::getTicksPerSecond() const
  902. {
  903. return ticksPerSecond;
  904. }
  905. int Game::getPlayerCount() const
  906. {
  907. return clients->getEintragAnzahl();
  908. }
  909. int Game::getChunkCount() const
  910. {
  911. int result = 0;
  912. for (Dimension* dim : *dimensions)
  913. {
  914. result += dim->getChunkCount();
  915. }
  916. return result;
  917. }