Game.cpp 15 KB

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