Game.cpp 27 KB

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