Game.cpp 15 KB

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