Game.cpp 15 KB

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