Game.cpp 13 KB

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