Game.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. #include "Game.h"
  2. #include "Zeit.h"
  3. #include "Player.h"
  4. #include "OverworldDimension.h"
  5. #include "NoBlock.h"
  6. #include "AsynchronCall.h"
  7. #include "Entity.h"
  8. #include "AddEntityUpdate.h"
  9. #include "EntityRemovedUpdate.h"
  10. #include "NetworkMessage.h"
  11. using namespace Framework;
  12. GameClient::GameClient(Player* zPlayer, FCKlient* client)
  13. : ReferenceCounter(),
  14. zPlayer(zPlayer),
  15. client(client),
  16. viewDistance(DEFAULT_VIEW_DISTANCE),
  17. first(1),
  18. online(1),
  19. finished(0)
  20. {
  21. new AsynchronCall("Game Client", [this]()
  22. {
  23. while (online)
  24. {
  25. other.lock();
  26. if (updateQueue.hat(0))
  27. {
  28. WorldUpdate* update = updateQueue.get(0);
  29. updateQueue.remove(0);
  30. other.unlock();
  31. background.lock();
  32. this->client->zBackgroundWriter()->schreibe((char*)&Message::WORLD_UPDATE, 1);
  33. update->writeAndCheck(this->client->zBackgroundWriter());
  34. background.unlock();
  35. update->release();
  36. }
  37. else
  38. {
  39. other.unlock();
  40. updateSync.wait();
  41. }
  42. }
  43. finished = 1;
  44. });
  45. }
  46. GameClient::~GameClient()
  47. {
  48. online = 0;
  49. updateSync.notify();
  50. while (!finished)
  51. Sleep(100);
  52. client->release();
  53. }
  54. void GameClient::sendWorldUpdate(WorldUpdate* update)
  55. {
  56. bool add = 0;
  57. if (zPlayer->getCurrentDimensionId() == update->getAffectedDimension())
  58. {
  59. auto pos = (Vec3<int>)zPlayer->getPosition();
  60. int dist = update->distanceTo(pos.x, pos.y);
  61. if (dist < viewDistance * CHUNK_SIZE)
  62. {
  63. other.lock();
  64. int index = 0;
  65. for (auto update2 : updateQueue)
  66. {
  67. int dist2 = update2->distanceTo(pos.x, pos.y);
  68. if (dist2 > dist)
  69. break;
  70. index++;
  71. }
  72. updateQueue.add(update, index);
  73. other.unlock();
  74. updateSync.notify();
  75. add = 1;
  76. }
  77. }
  78. if (!add)
  79. update->release();
  80. }
  81. void GameClient::reply()
  82. {
  83. other.lock();
  84. for (auto req : requests)
  85. Game::INSTANCE->api(req, this);
  86. requests.leeren();
  87. other.unlock();
  88. if (first)
  89. {
  90. foreground.lock();
  91. int id = zPlayer->getId();
  92. client->zForegroundWriter()->schreibe((char*)&Message::POSITION_UPDATE, 1);
  93. client->zForegroundWriter()->schreibe((char*)&id, 4);
  94. foreground.unlock();
  95. first = 0;
  96. }
  97. }
  98. void GameClient::logout()
  99. {
  100. online = 0;
  101. }
  102. void GameClient::addMessage(StreamReader* reader)
  103. {
  104. short len = 0;
  105. reader->lese((char*)&len, 2);
  106. InMemoryBuffer* buffer = new InMemoryBuffer();
  107. char* tmp = new char[len];
  108. reader->lese(tmp, len);
  109. buffer->schreibe(tmp, len);
  110. delete[]tmp;
  111. other.lock();
  112. requests.add(buffer);
  113. other.unlock();
  114. }
  115. bool GameClient::isOnline() const
  116. {
  117. return online;
  118. }
  119. void GameClient::sendResponse(NetworkMessage* zResponse)
  120. {
  121. if (zResponse->isUseBackground())
  122. {
  123. background.lock();
  124. zResponse->writeTo(client->zBackgroundWriter());
  125. background.unlock();
  126. }
  127. else
  128. {
  129. foreground.lock();
  130. zResponse->writeTo(client->zForegroundWriter());
  131. foreground.unlock();
  132. }
  133. }
  134. Player* GameClient::zEntity() const
  135. {
  136. return zPlayer;
  137. }
  138. void GameClient::sendTypes()
  139. {
  140. foreground.lock();
  141. int count = StaticRegistry<BlockType>::INSTANCE.getCount();
  142. client->zForegroundWriter()->schreibe((char*)&count, 4);
  143. for (int i = 0; i < count; i++)
  144. {
  145. BlockType* t = StaticRegistry<BlockType>::INSTANCE.zElement(i);
  146. int id = t->getId();
  147. client->zForegroundWriter()->schreibe((char*)&id, 4);
  148. bool inst = t->doesNeedClientInstance();
  149. client->zForegroundWriter()->schreibe((char*)&inst, 1);
  150. int maxHp = t->getInitialMaxHP();
  151. client->zForegroundWriter()->schreibe((char*)&maxHp, 4);
  152. t->getModel().writeTo(client->zForegroundWriter());
  153. }
  154. count = StaticRegistry<ItemType>::INSTANCE.getCount();
  155. client->zForegroundWriter()->schreibe((char*)&count, 4);
  156. for (int i = 0; i < count; i++)
  157. {
  158. ItemType* t = StaticRegistry<ItemType>::INSTANCE.zElement(i);
  159. int id = t->getId();
  160. client->zForegroundWriter()->schreibe((char*)&id, 4);
  161. t->getModel().writeTo(client->zForegroundWriter());
  162. }
  163. count = StaticRegistry<EntityType>::INSTANCE.getCount();
  164. client->zForegroundWriter()->schreibe((char*)&count, 4);
  165. for (int i = 0; i < count; i++)
  166. {
  167. EntityType* t = StaticRegistry<EntityType>::INSTANCE.zElement(i);
  168. int id = t->getId();
  169. client->zForegroundWriter()->schreibe((char*)&id, 4);
  170. t->getModel().writeTo(client->zForegroundWriter());
  171. }
  172. foreground.unlock();
  173. }
  174. Game::Game(Framework::Text name, Framework::Text worldsDir)
  175. : Thread(),
  176. name(name),
  177. dimensions(new RCArray<Dimension>()),
  178. updates(new RCArray<WorldUpdate>()),
  179. clients(new RCArray<GameClient>()),
  180. ticker(new TickOrganizer()),
  181. path((const char*)(worldsDir + "/" + name)),
  182. stop(0),
  183. tickId(0),
  184. nextEntityId(0),
  185. generator(0),
  186. loader(0),
  187. totalTickTime(0),
  188. tickCounter(0)
  189. {
  190. if (!DateiExistiert(worldsDir + "/" + name))
  191. DateiPfadErstellen(worldsDir + "/" + name + "/");
  192. Datei d;
  193. d.setDatei(path + "/eid");
  194. if (d.existiert())
  195. {
  196. d.open(Datei::Style::lesen);
  197. d.lese((char*)&nextEntityId, 4);
  198. d.close();
  199. }
  200. start();
  201. }
  202. Game::~Game()
  203. {
  204. dimensions->release();
  205. updates->release();
  206. clients->release();
  207. generator->release();
  208. loader->release();
  209. }
  210. void Game::initialize()
  211. {
  212. int seed = 0;
  213. int index = 0;
  214. for (char* n = name; *n; n++)
  215. seed += (int)pow((float)*n * 31, (float)++index);
  216. generator = new WorldGenerator(seed);
  217. loader = new WorldLoader();
  218. recipies.loadRecipies("data/recipies");
  219. }
  220. void Game::thread()
  221. {
  222. ZeitMesser m;
  223. while (!stop)
  224. {
  225. m.messungStart();
  226. ticker->nextTick();
  227. Array<int> removed;
  228. cs.lock();
  229. int index = 0;
  230. for (auto player : *clients)
  231. {
  232. if (!player->isOnline())
  233. {
  234. std::cout << "player " << player->zEntity()->getName() << " disconnected.\n";
  235. Datei pFile;
  236. pFile.setDatei(path + "/player/" + player->zEntity()->getName());
  237. pFile.erstellen();
  238. if (pFile.open(Datei::Style::schreiben))
  239. PlayerEntityType::INSTANCE->saveEntity(player->zEntity(), &pFile);
  240. pFile.close();
  241. removed.add(index, 0);
  242. Dimension* dim = zDimension(player->zEntity()->getCurrentDimensionId());
  243. dim->removeSubscriptions(player->zEntity());
  244. this->requestWorldUpdate(new EntityRemovedUpdate(player->zEntity()->getId(), player->zEntity()->getCurrentDimensionId(), player->zEntity()->getPosition()));
  245. }
  246. index++;
  247. }
  248. for (auto i : removed)
  249. clients->remove(i);
  250. cs.unlock();
  251. for (auto dim : *dimensions)
  252. dim->tickEntities();
  253. cs.lock();
  254. while (updates->hat(0))
  255. {
  256. WorldUpdate* update = updates->z(0);
  257. for (auto client : *clients)
  258. client->sendWorldUpdate(dynamic_cast<WorldUpdate*>(update->getThis()));
  259. if (!zDimension(update->getAffectedDimension()))
  260. addDimension(new Dimension(update->getAffectedDimension()));
  261. update->onUpdate(zDimension(update->getAffectedDimension()));
  262. updates->remove(0);
  263. }
  264. cs.unlock();
  265. for (auto client : *clients)
  266. client->reply();
  267. cs.lock();
  268. for (auto dim : *dimensions)
  269. dim->removeOldChunks();
  270. cs.unlock();
  271. m.messungEnde();
  272. double sec = m.getSekunden();
  273. tickCounter++;
  274. totalTickTime += sec;
  275. if (tickCounter >= 1000)
  276. {
  277. std::cout << "Average Tick time: " << (totalTickTime / 1000) << "\n";
  278. if ((totalTickTime / 1000) * 20 > 1)
  279. {
  280. std::cout << "The game runns slower than normal.\n";
  281. }
  282. else
  283. {
  284. std::cout << "No performance issues detected.\n";
  285. }
  286. totalTickTime = 0;
  287. tickCounter = 0;
  288. }
  289. if (sec < 0.05)
  290. Sleep((int)((0.05 - sec) * 1000));
  291. else
  292. {
  293. std::cout << "WARNING: tick needed " << sec << " seconds. The game will run sower then normal.\n";
  294. }
  295. }
  296. save();
  297. }
  298. void Game::api(Framework::InMemoryBuffer* zRequest, GameClient* zOrigin)
  299. {
  300. char type;
  301. zRequest->lese(&type, 1);
  302. NetworkMessage response;
  303. switch (type)
  304. {
  305. case 1: // world
  306. {
  307. Dimension* dim = zDimension(zOrigin->zEntity()->getCurrentDimensionId());
  308. if (!dim)
  309. {
  310. dim = new Dimension(zOrigin->zEntity()->getCurrentDimensionId());
  311. addDimension(dim);
  312. }
  313. dim->api(zRequest, &response, zOrigin->zEntity());
  314. break;
  315. }
  316. case 2: // player
  317. zOrigin->zEntity()->playerApi(zRequest, &response);
  318. break;
  319. case 3: // entity
  320. {
  321. int id;
  322. zRequest->lese((char*)&id, 4);
  323. for (Dimension* dim : *dimensions)
  324. {
  325. Entity* entity = dim->zEntity(id);
  326. if (entity)
  327. {
  328. entity->api(zRequest, &response);
  329. break;
  330. }
  331. }
  332. break;
  333. }
  334. case 4:
  335. { // inventory
  336. bool isEntity;
  337. zRequest->lese((char*)&isEntity, 1);
  338. Inventory* target;
  339. if (isEntity)
  340. {
  341. int id;
  342. zRequest->lese((char*)&id, 4);
  343. target = zEntity(id);
  344. }
  345. else
  346. {
  347. int dim;
  348. Vec3<int> pos;
  349. zRequest->lese((char*)&dim, 4);
  350. zRequest->lese((char*)&pos.x, 4);
  351. zRequest->lese((char*)&pos.y, 4);
  352. zRequest->lese((char*)&pos.z, 4);
  353. target = zBlockAt(pos, dim);
  354. }
  355. if (target)
  356. target->inventoryApi(zRequest, &response, zOrigin->zEntity());
  357. break;
  358. }
  359. default:
  360. std::cout << "received unknown api request in game with type " << (int)type << "\n";
  361. }
  362. if (!response.isEmpty())
  363. {
  364. if (response.isBroadcast())
  365. broadcastMessage(&response);
  366. else
  367. zOrigin->sendResponse(&response);
  368. }
  369. }
  370. void Game::updateLightning(int dimensionId, Vec3<int> location)
  371. {
  372. Dimension* zDim = zDimension(dimensionId);
  373. if (zDim)
  374. zDim->updateLightning(location);
  375. }
  376. void Game::broadcastMessage(NetworkMessage* zResponse)
  377. {
  378. for (auto client : *clients)
  379. client->sendResponse(zResponse);
  380. }
  381. void Game::sendMessage(NetworkMessage* zResponse, Entity* zTargetPlayer)
  382. {
  383. for (auto client : *clients)
  384. {
  385. if (client->zEntity()->getId() == zTargetPlayer->getId())
  386. {
  387. client->sendResponse(zResponse);
  388. break;
  389. }
  390. }
  391. }
  392. bool Game::requestWorldUpdate(WorldUpdate* update)
  393. {
  394. cs.lock();
  395. for (WorldUpdate* u : *updates)
  396. {
  397. if (u->getMaxAffectedPoint().x >= update->getMinAffectedPoint().x && u->getMinAffectedPoint().x <= update->getMaxAffectedPoint().x &&
  398. u->getMaxAffectedPoint().y >= update->getMinAffectedPoint().y && u->getMinAffectedPoint().y <= update->getMaxAffectedPoint().y &&
  399. u->getMaxAffectedPoint().z >= update->getMinAffectedPoint().z && u->getMinAffectedPoint().z <= update->getMaxAffectedPoint().z && u->getType() == update->getType())
  400. {
  401. cs.unlock();
  402. update->release();
  403. return 0;
  404. }
  405. }
  406. updates->add(update);
  407. cs.unlock();
  408. return 1;
  409. }
  410. GameClient* Game::addPlayer(FCKlient* client, Framework::Text name)
  411. {
  412. cs.lock();
  413. Datei pFile;
  414. pFile.setDatei(path + "/player/" + name);
  415. std::cout << "player " << name.getText() << " connected.\n";
  416. Player* player;
  417. bool isNew = 0;
  418. if (!pFile.existiert() || !pFile.open(Datei::Style::lesen))
  419. {
  420. player = (Player*)PlayerEntityType::INSTANCE->createEntityAt(Vec3<float>(0.5, 0.5, 0), OverworldDimension::ID);
  421. player->setName(name);
  422. isNew = 1;
  423. }
  424. else
  425. {
  426. player = (Player*)PlayerEntityType::INSTANCE->loadEntity(&pFile);
  427. pFile.close();
  428. }
  429. GameClient* gameClient = new GameClient(player, client);
  430. gameClient->sendTypes();
  431. clients->add(gameClient);
  432. if (!zDimension(player->getCurrentDimensionId()))
  433. {
  434. this->addDimension(new Dimension(player->getCurrentDimensionId()));
  435. }
  436. // subscribe the new player as an observer of the new chunk
  437. Dimension* dim = zDimension(player->getCurrentDimensionId());
  438. InMemoryBuffer* buffer = new InMemoryBuffer();
  439. buffer->schreibe("\0", 1);
  440. Punkt center = getChunkCenter((int)player->getPosition().x, (int)player->getPosition().y);
  441. buffer->schreibe((char*)&center.x, 4);
  442. buffer->schreibe((char*)&center.y, 4);
  443. buffer->schreibe("\0", 1);
  444. dim->api(buffer, 0, player);
  445. buffer->release();
  446. while (isNew && !dim->zChunk(getChunkCenter((int)player->getPosition().x, (int)player->getPosition().y)))
  447. {
  448. cs.unlock();
  449. Sleep(1000);
  450. cs.lock();
  451. }
  452. if (isNew)
  453. {
  454. Either<Block*, int> b = AirBlockBlockType::ID;
  455. int h = WORLD_HEIGHT;
  456. while (((b.isA() && (!(Block*)b || ((Block*)b)->isPassable())) || (b.isB() && StaticRegistry<BlockType>::INSTANCE.zElement(b)->zDefault()->isPassable())) && h > 0)
  457. b = zBlockAt({ (int)player->getPosition().x, (int)player->getPosition().y, --h }, player->getCurrentDimensionId());
  458. player->setPosition({ player->getPosition().x, player->getPosition().y, (float)h + 1.f });
  459. }
  460. requestWorldUpdate(new AddEntityUpdate(player, player->getCurrentDimensionId()));
  461. cs.unlock();
  462. return dynamic_cast<GameClient*>(gameClient->getThis());
  463. }
  464. bool Game::isChunkLoaded(int x, int y, int dimension) const
  465. {
  466. Dimension* dim = zDimension(dimension);
  467. return (dim && dim->hasChunck(x, y));
  468. }
  469. bool Game::doesChunkExist(int x, int y, int dimension)
  470. {
  471. cs.lock();
  472. bool result = isChunkLoaded(x, y, dimension) || loader->existsChunk(x, y, dimension);
  473. cs.unlock();
  474. return result;
  475. }
  476. Framework::Either<Block*, int> Game::zBlockAt(Framework::Vec3<int> location, int dimension) const
  477. {
  478. Dimension* dim = zDimension(dimension);
  479. if (dim)
  480. return dim->zBlock(location);
  481. return 0;
  482. }
  483. Block* Game::zRealBlockInstance(Framework::Vec3<int> location, int dimension)
  484. {
  485. Dimension* dim = zDimension(dimension);
  486. if (dim)
  487. return dim->zRealBlockInstance(location);
  488. return 0;
  489. }
  490. Dimension* Game::zDimension(int id) const
  491. {
  492. for (auto dim : *dimensions)
  493. {
  494. if (dim->getDimensionId() == id)
  495. return dim;
  496. }
  497. return 0;
  498. }
  499. Framework::Punkt Game::getChunkCenter(int x, int y)
  500. {
  501. return Punkt(((x < 0 ? x + 1 : x) / CHUNK_SIZE) * CHUNK_SIZE + (x < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2, ((y < 0 ? y + 1 : y) / CHUNK_SIZE) * CHUNK_SIZE + (y < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2);
  502. }
  503. Area Game::getChunckArea(Punkt center) const
  504. {
  505. return { center.x - CHUNK_SIZE / 2, center.y - CHUNK_SIZE / 2, center.x + CHUNK_SIZE / 2 - 1, center.y + CHUNK_SIZE / 2 - 1, 0 };
  506. }
  507. Framework::Text Game::getWorldDirectory() const
  508. {
  509. return path;
  510. }
  511. void Game::requestArea(Area area)
  512. {
  513. generator->requestGeneration(area);
  514. loader->requestLoading(area);
  515. }
  516. void Game::save() const
  517. {
  518. Datei d;
  519. d.setDatei(path + "/eid");
  520. d.open(Datei::Style::schreiben);
  521. d.schreibe((char*)&nextEntityId, 4);
  522. d.close();
  523. for (auto dim : *dimensions)
  524. dim->save(path);
  525. }
  526. void Game::requestStop()
  527. {
  528. stop = 1;
  529. warteAufThread(1000000);
  530. }
  531. void Game::addDimension(Dimension* d)
  532. {
  533. dimensions->add(d);
  534. }
  535. int Game::getNextEntityId()
  536. {
  537. cs.lock();
  538. int result = nextEntityId++;
  539. cs.unlock();
  540. return result;
  541. }
  542. WorldGenerator* Game::zGenerator() const
  543. {
  544. return generator;
  545. }
  546. Game* Game::INSTANCE = 0;
  547. void Game::initialize(Framework::Text name, Framework::Text worldsDir)
  548. {
  549. if (!Game::INSTANCE)
  550. {
  551. Game::INSTANCE = new Game(name, worldsDir);
  552. Game::INSTANCE->initialize();
  553. }
  554. }
  555. Entity* Game::zEntity(int id, int dimensionId) const
  556. {
  557. Dimension* d = zDimension(dimensionId);
  558. if (d)
  559. return d->zEntity(id);
  560. return 0;
  561. }
  562. Entity* Game::zEntity(int id) const
  563. {
  564. for (Dimension* d : *dimensions)
  565. {
  566. Entity* e = d->zEntity(id);
  567. if (e)
  568. return e;
  569. }
  570. // for new players that are currently loading
  571. for (GameClient* client : *clients)
  572. {
  573. if (client->zEntity()->getId() == id)
  574. {
  575. return client->zEntity();
  576. }
  577. }
  578. return 0;
  579. }
  580. Entity* Game::zNearestEntity(int dimensionId, Framework::Vec3<float> pos, std::function<bool(Entity*)> filter)
  581. {
  582. Dimension* d = zDimension(dimensionId);
  583. if (!d)
  584. return 0;
  585. return d->zNearestEntity(pos, filter);
  586. }
  587. const RecipieLoader& Game::getRecipies() const
  588. {
  589. return recipies;
  590. }