Game.cpp 30 KB

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