Game.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  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. }
  462. void Game::api(Framework::InMemoryBuffer* zRequest, GameClient* zOrigin)
  463. {
  464. char type;
  465. zRequest->lese(&type, 1);
  466. NetworkMessage* response = new NetworkMessage();
  467. switch (type)
  468. {
  469. case 1: // world
  470. {
  471. Dimension* dim
  472. = zDimension(zOrigin->zEntity()->getCurrentDimensionId());
  473. if (!dim)
  474. {
  475. dim = new Dimension(
  476. zOrigin->zEntity()->getCurrentDimensionId());
  477. addDimension(dim);
  478. }
  479. dim->api(zRequest, response, zOrigin->zEntity());
  480. break;
  481. }
  482. case 2: // player
  483. zOrigin->zEntity()->playerApi(zRequest, response);
  484. break;
  485. case 3: // entity
  486. {
  487. int id;
  488. zRequest->lese((char*)&id, 4);
  489. for (Dimension* dim : *dimensions)
  490. {
  491. Entity* entity = dim->zEntity(id);
  492. if (entity)
  493. {
  494. entity->api(zRequest, response, zOrigin->zEntity());
  495. break;
  496. }
  497. }
  498. break;
  499. }
  500. case 4:
  501. { // inventory
  502. bool isEntity;
  503. zRequest->lese((char*)&isEntity, 1);
  504. Inventory* target;
  505. if (isEntity)
  506. {
  507. int id;
  508. zRequest->lese((char*)&id, 4);
  509. target = zEntity(id);
  510. }
  511. else
  512. {
  513. int dim;
  514. Vec3<int> pos;
  515. zRequest->lese((char*)&dim, 4);
  516. zRequest->lese((char*)&pos.x, 4);
  517. zRequest->lese((char*)&pos.y, 4);
  518. zRequest->lese((char*)&pos.z, 4);
  519. target = zBlockAt(pos, dim);
  520. }
  521. if (target)
  522. target->inventoryApi(zRequest, response, zOrigin->zEntity());
  523. break;
  524. }
  525. case 5:
  526. { // crafting uiml request
  527. int id;
  528. zRequest->lese((char*)&id, 4);
  529. Text uiml = recipies.getCrafingUIML(
  530. StaticRegistry<ItemType>::INSTANCE.zElement(id));
  531. Text dialogId = "crafting_";
  532. dialogId += id;
  533. response->openDialog(dialogId);
  534. int msgSize = 4 + uiml.getLength();
  535. char* msg = new char[msgSize];
  536. *(int*)msg = uiml.getLength();
  537. memcpy(msg + 4, uiml.getText(), uiml.getLength());
  538. response->setMessage(msg, msgSize);
  539. break;
  540. }
  541. case 6:
  542. { // chat message
  543. chat->chatApi(zRequest, zOrigin->zEntity(), response);
  544. break;
  545. }
  546. default:
  547. std::cout << "received unknown api request in game with type "
  548. << (int)type << "\n";
  549. }
  550. if (!response->isEmpty())
  551. {
  552. if (response->isBroadcast())
  553. broadcastMessage(response);
  554. else
  555. zOrigin->sendResponse(response);
  556. }
  557. else
  558. {
  559. response->release();
  560. }
  561. }
  562. void Game::updateLightning(int dimensionId, Vec3<int> location)
  563. {
  564. Dimension* zDim = zDimension(dimensionId);
  565. if (zDim) zDim->updateLightning(location);
  566. }
  567. void Game::updateLightningWithoutWait(int dimensionId, Vec3<int> location)
  568. {
  569. Dimension* zDim = zDimension(dimensionId);
  570. if (zDim) zDim->updateLightningWithoutWait(location);
  571. }
  572. void Game::broadcastMessage(NetworkMessage* response)
  573. {
  574. for (auto client : *clients)
  575. client->sendResponse(
  576. dynamic_cast<NetworkMessage*>(response->getThis()));
  577. }
  578. void Game::sendMessage(NetworkMessage* response, Entity* zTargetPlayer)
  579. {
  580. for (auto client : *clients)
  581. {
  582. if (client->zEntity()->getId() == zTargetPlayer->getId())
  583. {
  584. client->sendResponse(response);
  585. return;
  586. }
  587. }
  588. response->release();
  589. }
  590. bool Game::requestWorldUpdate(WorldUpdate* update)
  591. {
  592. cs.lock();
  593. for (WorldUpdate* u : *updates)
  594. {
  595. if (u->getMaxAffectedPoint().x >= update->getMinAffectedPoint().x
  596. && u->getMinAffectedPoint().x <= update->getMaxAffectedPoint().x
  597. && u->getMaxAffectedPoint().y >= update->getMinAffectedPoint().y
  598. && u->getMinAffectedPoint().y <= update->getMaxAffectedPoint().y
  599. && u->getMaxAffectedPoint().z >= update->getMinAffectedPoint().z
  600. && u->getMinAffectedPoint().z <= update->getMaxAffectedPoint().z
  601. && u->getType() == update->getType())
  602. {
  603. cs.unlock();
  604. update->release();
  605. return 0;
  606. }
  607. }
  608. updates->add(update);
  609. cs.unlock();
  610. return 1;
  611. }
  612. bool Game::checkPlayer(Framework::Text name, Framework::Text secret)
  613. {
  614. if (playerRegister->checkSecret(name, secret))
  615. return 1;
  616. else
  617. {
  618. std::cout << "player " << name.getText()
  619. << " tryed to connect with an invalid secret.\n";
  620. return 0;
  621. }
  622. }
  623. bool Game::existsPlayer(Framework::Text name)
  624. {
  625. return playerRegister->hasPlayer(name);
  626. }
  627. Framework::Text Game::createPlayer(Framework::Text name)
  628. {
  629. return playerRegister->addPlayer(name);
  630. }
  631. GameClient* Game::addPlayer(FCKlient* client, Framework::Text name)
  632. {
  633. cs.lock();
  634. int id = playerRegister->getPlayerId(name);
  635. Datei pFile;
  636. pFile.setDatei(path + "/player/" + id);
  637. Player* player;
  638. bool isNew = 0;
  639. if (!pFile.existiert() || !pFile.open(Datei::Style::lesen))
  640. {
  641. player = (Player*)StaticRegistry<EntityType>::INSTANCE
  642. .zElement(EntityTypeEnum::PLAYER)
  643. ->createEntityAt(
  644. Vec3<float>(0.5, 0.5, 0), DimensionEnum::OVERWORLD);
  645. player->setName(name);
  646. isNew = 1;
  647. }
  648. else
  649. {
  650. player = (Player*)StaticRegistry<EntityType>::INSTANCE
  651. .zElement(EntityTypeEnum::PLAYER)
  652. ->loadEntity(&pFile);
  653. pFile.close();
  654. }
  655. if (player->getId() >= nextEntityId)
  656. {
  657. nextEntityId = player->getId() + 1;
  658. }
  659. GameClient* gameClient = new GameClient(player, client);
  660. gameClient->sendTypes();
  661. clients->add(gameClient);
  662. if (!zDimension(player->getCurrentDimensionId()))
  663. {
  664. this->addDimension(new Dimension(player->getCurrentDimensionId()));
  665. }
  666. // subscribe the new player as an observer of the new chunk
  667. Dimension* dim = zDimension(player->getCurrentDimensionId());
  668. InMemoryBuffer* buffer = new InMemoryBuffer();
  669. buffer->schreibe("\0", 1);
  670. Punkt center = getChunkCenter(
  671. (int)player->getPosition().x, (int)player->getPosition().y);
  672. buffer->schreibe((char*)&center.x, 4);
  673. buffer->schreibe((char*)&center.y, 4);
  674. buffer->schreibe("\0", 1);
  675. dim->api(buffer, 0, player);
  676. buffer->release();
  677. while (isNew
  678. && !dim->zChunk(getChunkCenter(
  679. (int)player->getPosition().x, (int)player->getPosition().y)))
  680. {
  681. cs.unlock();
  682. Sleep(1000);
  683. cs.lock();
  684. }
  685. if (isNew)
  686. {
  687. Either<Block*, int> b = BlockTypeEnum::AIR;
  688. int h = WORLD_HEIGHT;
  689. while (((b.isA() && (!(Block*)b || ((Block*)b)->isPassable()))
  690. || (b.isB()
  691. && StaticRegistry<BlockType>::INSTANCE.zElement(b)
  692. ->zDefault()
  693. ->isPassable()))
  694. && h > 0)
  695. b = zBlockAt({(int)player->getPosition().x,
  696. (int)player->getPosition().y,
  697. --h},
  698. player->getCurrentDimensionId());
  699. player->setPosition(
  700. {player->getPosition().x, player->getPosition().y, (float)h + 1.f});
  701. }
  702. requestWorldUpdate(
  703. new AddEntityUpdate(player, player->getCurrentDimensionId()));
  704. chat->addObserver(gameClient->zEntity()->getId());
  705. chat->broadcastMessage(name + " joined the game.", Chat::CHANNEL_INFO);
  706. cs.unlock();
  707. return dynamic_cast<GameClient*>(gameClient->getThis());
  708. }
  709. bool Game::isChunkLoaded(int x, int y, int dimension) const
  710. {
  711. Dimension* dim = zDimension(dimension);
  712. return (dim && dim->hasChunck(x, y));
  713. }
  714. bool Game::doesChunkExist(int x, int y, int dimension)
  715. {
  716. cs.lock();
  717. bool result = isChunkLoaded(x, y, dimension)
  718. || loader->existsChunk(x, y, dimension);
  719. cs.unlock();
  720. return result;
  721. }
  722. void Game::blockTargetChanged(Block* zBlock)
  723. {
  724. for (GameClient* client : *this->clients)
  725. {
  726. if (client->zEntity()->zTarget()
  727. && client->zEntity()->zTarget()->isBlock(
  728. zBlock->getPos(), NO_DIRECTION))
  729. {
  730. client->zEntity()->onTargetChange();
  731. }
  732. }
  733. }
  734. void Game::entityTargetChanged(Entity* zEntity)
  735. {
  736. for (GameClient* client : *this->clients)
  737. {
  738. if (client->zEntity()->zTarget()
  739. && client->zEntity()->zTarget()->isEntity(zEntity->getId()))
  740. {
  741. client->zEntity()->onTargetChange();
  742. }
  743. }
  744. }
  745. Framework::Either<Block*, int> Game::zBlockAt(
  746. Framework::Vec3<int> location, int dimension) const
  747. {
  748. Dimension* dim = zDimension(dimension);
  749. if (dim) return dim->zBlock(location);
  750. return 0;
  751. }
  752. Block* Game::zRealBlockInstance(Framework::Vec3<int> location, int dimension)
  753. {
  754. Dimension* dim = zDimension(dimension);
  755. if (dim) return dim->zRealBlockInstance(location);
  756. return 0;
  757. }
  758. Dimension* Game::zDimension(int id) const
  759. {
  760. for (auto dim : *dimensions)
  761. {
  762. if (dim->getDimensionId() == id) return dim;
  763. }
  764. return 0;
  765. }
  766. Framework::Punkt Game::getChunkCenter(int x, int y)
  767. {
  768. return Punkt(((x < 0 ? x + 1 : x) / CHUNK_SIZE) * CHUNK_SIZE
  769. + (x < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2,
  770. ((y < 0 ? y + 1 : y) / CHUNK_SIZE) * CHUNK_SIZE
  771. + (y < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2);
  772. }
  773. Area Game::getChunckArea(Punkt center) const
  774. {
  775. return {center.x - CHUNK_SIZE / 2,
  776. center.y - CHUNK_SIZE / 2,
  777. center.x + CHUNK_SIZE / 2 - 1,
  778. center.y + CHUNK_SIZE / 2 - 1,
  779. 0};
  780. }
  781. Framework::Text Game::getWorldDirectory() const
  782. {
  783. return path;
  784. }
  785. void Game::requestArea(Area area)
  786. {
  787. generator->requestGeneration(area);
  788. loader->requestLoading(area);
  789. }
  790. void Game::save() const
  791. {
  792. Datei d;
  793. d.setDatei(path + "/eid");
  794. d.open(Datei::Style::schreiben);
  795. d.schreibe((char*)&nextEntityId, 4);
  796. d.close();
  797. playerRegister->save();
  798. for (auto dim : *dimensions)
  799. dim->save(path);
  800. chat->save();
  801. std::cout << "Game was saved\n";
  802. }
  803. void Game::requestStop()
  804. {
  805. stop = 1;
  806. warteAufThread(1000000);
  807. }
  808. void Game::addDimension(Dimension* d)
  809. {
  810. dimensions->add(d);
  811. }
  812. int Game::getNextEntityId()
  813. {
  814. cs.lock();
  815. int result = nextEntityId++;
  816. cs.unlock();
  817. return result;
  818. }
  819. WorldGenerator* Game::zGenerator() const
  820. {
  821. return generator;
  822. }
  823. Game* Game::INSTANCE = 0;
  824. void Game::initialize(Framework::Text name, Framework::Text worldsDir)
  825. {
  826. if (!Game::INSTANCE)
  827. {
  828. Game::INSTANCE = new Game(name, worldsDir);
  829. Game::INSTANCE->initialize();
  830. }
  831. }
  832. Entity* Game::zEntity(int id, int dimensionId) const
  833. {
  834. Dimension* d = zDimension(dimensionId);
  835. if (d) return d->zEntity(id);
  836. return 0;
  837. }
  838. Entity* Game::zEntity(int id) const
  839. {
  840. for (Dimension* d : *dimensions)
  841. {
  842. Entity* e = d->zEntity(id);
  843. if (e) return e;
  844. }
  845. // for new players that are currently loading
  846. for (GameClient* client : *clients)
  847. {
  848. if (client->zEntity()->getId() == id)
  849. {
  850. return client->zEntity();
  851. }
  852. }
  853. return 0;
  854. }
  855. Entity* Game::zNearestEntity(int dimensionId,
  856. Framework::Vec3<float> pos,
  857. std::function<bool(Entity*)> filter)
  858. {
  859. Dimension* d = zDimension(dimensionId);
  860. if (!d) return 0;
  861. return d->zNearestEntity(pos, filter);
  862. }
  863. const RecipieLoader& Game::getRecipies() const
  864. {
  865. return recipies;
  866. }
  867. void Game::doLater(std::function<void()> action)
  868. {
  869. actionsCs.lock();
  870. actions.add(action);
  871. actionsCs.unlock();
  872. }
  873. TickOrganizer* Game::zTickOrganizer() const
  874. {
  875. return ticker;
  876. }
  877. Chat* Game::zChat() const
  878. {
  879. return chat;
  880. }
  881. Player* Game::zPlayerByName(const char* name) const
  882. {
  883. for (GameClient* client : *clients)
  884. {
  885. if (strcmp(client->zEntity()->getName(), name) == 0)
  886. {
  887. return client->zEntity();
  888. }
  889. }
  890. return 0;
  891. }
  892. int Game::getPlayerId(const char* name) const
  893. {
  894. return playerRegister->getPlayerId(name);
  895. }
  896. double Game::getAverageTickTime() const
  897. {
  898. return averageTickTime;
  899. }
  900. int Game::getTicksPerSecond() const
  901. {
  902. return ticksPerSecond;
  903. }
  904. int Game::getPlayerCount() const
  905. {
  906. return clients->getEintragAnzahl();
  907. }
  908. int Game::getChunkCount() const
  909. {
  910. int result = 0;
  911. for (Dimension* dim : *dimensions)
  912. {
  913. result += dim->getChunkCount();
  914. }
  915. return result;
  916. }