Game.cpp 30 KB

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