Game.cpp 31 KB

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