Game.cpp 14 KB

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