Game.cpp 27 KB

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