Game.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  1. #include "Game.h"
  2. #include <Logging.h>
  3. #include "AsynchronCall.h"
  4. #include "Chat.h"
  5. #include "Dimension.h"
  6. #include "Entity.h"
  7. #include "ItemEntity.h"
  8. #include "JsonUtils.h"
  9. #include "MultiblockTree.h"
  10. #include "NetworkMessage.h"
  11. #include "NoBlock.h"
  12. #include "Player.h"
  13. #include "PlayerHand.h"
  14. #include "PlayerRegister.h"
  15. #include "Quest.h"
  16. #include "RecipieLoader.h"
  17. #include "Server.h"
  18. #include "TickOrganizer.h"
  19. #include "UIController.h"
  20. #include "WorldGenerator.h"
  21. #include "WorldLoader.h"
  22. #include "Zeit.h"
  23. using namespace Framework;
  24. Framework::ConsoleHandler* Game::consoleHandler = 0;
  25. Framework::InputLine* Game::consoleInput = 0;
  26. Game::Game(Framework::Text name, Framework::Text worldsDir)
  27. : Thread(),
  28. name(name),
  29. typeRegistry(new TypeRegistry()),
  30. blockTypeNameFactory(new BlockTypeNameFactory()),
  31. itemTypeNameFactory(new ItemTypeNameFactory()),
  32. dimensions(new RCArray<Dimension>()),
  33. clients(new RCArray<GameClient>()),
  34. questManager(new QuestManager()),
  35. ticker(new TickOrganizer()),
  36. path((const char*)(worldsDir + "/" + name)),
  37. stop(0),
  38. tickId(0),
  39. nextEntityId(0),
  40. generator(0),
  41. loader(0),
  42. recipies(new RecipieLoader()),
  43. chat(0),
  44. playerRegister(new PlayerRegister(path)),
  45. uiController(new UIController()),
  46. totalTickTime(0),
  47. tickCounter(0),
  48. averageTickTime(0),
  49. ticksPerSecond(0),
  50. totalTime(0),
  51. blockTypes(0),
  52. blockTypeCount(0),
  53. itemTypes(0),
  54. itemTypeCount(0),
  55. entityTypes(0),
  56. entityTypeCount(0),
  57. multiblockStructureTypes(0),
  58. multiblockStructureTypeCount(0)
  59. {
  60. typeRegistry->registerType(
  61. BlockTypeNameFactory::TYPE_ID, blockTypeNameFactory);
  62. typeRegistry->registerType(
  63. ItemTypeNameFactory::TYPE_ID, itemTypeNameFactory);
  64. if (!DateiExistiert(path)) DateiPfadErstellen(path + "/");
  65. Datei d;
  66. d.setDatei(path + "/eid");
  67. if (d.existiert())
  68. {
  69. d.open(Datei::Style::lesen);
  70. d.lese((char*)&nextEntityId, 4);
  71. d.close();
  72. }
  73. start();
  74. }
  75. Game::~Game()
  76. {
  77. dimensions->release();
  78. clients->release();
  79. generator->release();
  80. loader->release();
  81. chat->release();
  82. playerRegister->release();
  83. typeRegistry->release();
  84. uiController->release();
  85. recipies->release();
  86. for (int i = 0; i < blockTypeCount; i++)
  87. {
  88. if (blockTypes[i]) blockTypes[i]->release();
  89. }
  90. delete[] blockTypes;
  91. for (int i = 0; i < itemTypeCount; i++)
  92. {
  93. if (itemTypes[i]) itemTypes[i]->release();
  94. }
  95. delete[] itemTypes;
  96. for (int i = 0; i < entityTypeCount; i++)
  97. {
  98. if (entityTypes[i]) entityTypes[i]->release();
  99. }
  100. delete[] entityTypes;
  101. for (int i = 0; i < multiblockStructureTypeCount; i++)
  102. {
  103. if (multiblockStructureTypes[i]) multiblockStructureTypes[i]->release();
  104. }
  105. delete[] multiblockStructureTypes;
  106. }
  107. void Game::initialize()
  108. {
  109. // TODO load mods libraries
  110. // load block types
  111. Framework::Logging::info() << "Loading block types";
  112. Framework::Array<BlockType*> blockTypeArray;
  113. Framework::Validator::DataValidator* validator
  114. = Framework::Validator::DataValidator::buildForArray()
  115. ->addAcceptedTypeInArray(typeRegistry->getValidator<BlockType>())
  116. ->removeInvalidEntries()
  117. ->finishArray();
  118. loadAllJsonsFromDirectory("data/blocks",
  119. [this, &blockTypeArray, validator](
  120. Framework::JSON::JSONValue* zValue, Framework::Text path) {
  121. Framework::RCArray<Framework::Validator::ValidationResult>
  122. validationResults;
  123. Framework::JSON::JSONValue* validParts
  124. = validator->getValidParts(zValue, &validationResults);
  125. for (Framework::Validator::ValidationResult* result :
  126. validationResults)
  127. {
  128. Framework::Logging::error() << result->getInvalidInfo();
  129. }
  130. if (validParts)
  131. {
  132. for (Framework::JSON::JSONValue* value : *validParts->asArray())
  133. {
  134. BlockType* blockType
  135. = typeRegistry->fromJson<BlockType>(value);
  136. if (blockType)
  137. {
  138. blockTypeArray.add(blockType);
  139. }
  140. }
  141. validParts->release();
  142. }
  143. });
  144. validator->release();
  145. Framework::Logging::info() << "Loaded " << blockTypeArray.getEintragAnzahl()
  146. << " block types from data/blocks";
  147. blockTypes = new BlockType*[2 + blockTypeArray.getEintragAnzahl()];
  148. blockTypes[0] = new NoBlockBlockType(
  149. dynamic_cast<Block*>(NoBlock::INSTANCE.getThis()),
  150. "__not_yet_generated");
  151. blockTypes[1] = new NoBlockBlockType(
  152. dynamic_cast<Block*>(AirBlock::INSTANCE.getThis()), "Air");
  153. blockTypeCount = 2;
  154. for (BlockType* blockType : blockTypeArray)
  155. {
  156. blockTypes[blockTypeCount++] = blockType;
  157. }
  158. Framework::RCArray<Framework::Text>* blockTypeNames
  159. = new Framework::RCArray<Framework::Text>();
  160. for (int i = 0; i < blockTypeCount; i++)
  161. {
  162. blockTypeNames->add(new Framework::Text(blockTypes[i]->getName()));
  163. blockTypes[i]->setTypeId(i);
  164. }
  165. blockTypeNameFactory->setBlockTypeNames(blockTypeNames);
  166. Framework::Logging::info() << "Loading item types";
  167. Framework::Array<ItemType*> itemTypeArray;
  168. validator
  169. = Framework::Validator::DataValidator::buildForArray()
  170. ->addAcceptedTypeInArray(typeRegistry->getValidator<ItemType>())
  171. ->removeInvalidEntries()
  172. ->finishArray();
  173. loadAllJsonsFromDirectory("data/items",
  174. [this, &itemTypeArray, validator](
  175. Framework::JSON::JSONValue* zValue, Framework::Text path) {
  176. Framework::RCArray<Framework::Validator::ValidationResult>
  177. validationResults;
  178. Framework::JSON::JSONValue* validParts
  179. = validator->getValidParts(zValue, &validationResults);
  180. for (Framework::Validator::ValidationResult* result :
  181. validationResults)
  182. {
  183. Framework::Logging::error() << result->getInvalidInfo();
  184. }
  185. if (validParts)
  186. {
  187. for (Framework::JSON::JSONValue* value : *validParts->asArray())
  188. {
  189. ItemType* itemType
  190. = typeRegistry->fromJson<ItemType>(value);
  191. if (itemType)
  192. {
  193. itemTypeArray.add(itemType);
  194. }
  195. }
  196. validParts->release();
  197. }
  198. });
  199. validator->release();
  200. Framework::Logging::info() << "Loaded " << itemTypeArray.getEintragAnzahl()
  201. << " item types from data/items";
  202. itemTypes
  203. = new ItemType*[blockTypeCount + itemTypeArray.getEintragAnzahl()];
  204. itemTypes[0] = new PlayerHandItemType();
  205. itemTypeCount = 1;
  206. for (int i = 0; i < blockTypeCount; i++)
  207. {
  208. ItemType* itemType = blockTypes[i]->createItemType();
  209. if (itemType)
  210. {
  211. itemTypes[itemTypeCount++] = itemType;
  212. }
  213. }
  214. for (ItemType* itemType : itemTypeArray)
  215. {
  216. itemTypes[itemTypeCount++] = itemType;
  217. }
  218. Framework::RCArray<Framework::Text>* itemTypeNames
  219. = new Framework::RCArray<Framework::Text>();
  220. for (int i = 0; i < itemTypeCount; i++)
  221. {
  222. itemTypes[i]->setTypeId(i);
  223. itemTypeNames->add(new Framework::Text(itemTypes[i]->getName()));
  224. }
  225. itemTypeNameFactory->setItemTypeNames(itemTypeNames);
  226. Framework::Logging::info() << "Loading entity types";
  227. Framework::Array<EntityType*> entityTypeArray;
  228. /*validator
  229. = Framework::JSON::Validator::JSONValidator::buildForArray()
  230. ->addAcceptedTypeInArray(typeRegistry->getValidator<EntityType>())
  231. ->removeInvalidEntries()
  232. ->finishArray();
  233. loadAllJsonsFromDirectory("data/entities",
  234. [this, &entityTypeArray, validator](
  235. Framework::JSON::JSONValue* zValue, Framework::Text path) {
  236. Framework::RCArray<Framework::JSON::Validator::JSONValidationResult>
  237. validationResults;
  238. Framework::JSON::JSONValue* validParts
  239. = validator->getValidParts(zValue, &validationResults);
  240. for (Framework::JSON::Validator::JSONValidationResult* result :
  241. validationResults)
  242. {
  243. result->printInvalidInfo();
  244. }
  245. if (validParts)
  246. {
  247. for (Framework::JSON::JSONValue* value : *validParts->asArray())
  248. {
  249. EntityType* entityType
  250. = typeRegistry->fromJson<EntityType>(value);
  251. if (entityType)
  252. {
  253. entityTypeArray.add(entityType);
  254. }
  255. }
  256. validParts->release();
  257. }
  258. });
  259. validator->release();*/
  260. Framework::Logging::info()
  261. << "Loaded " << entityTypeArray.getEintragAnzahl()
  262. << " entity types from data/entities";
  263. entityTypes = new EntityType*[2 + entityTypeArray.getEintragAnzahl()];
  264. entityTypes[0] = new PlayerEntityType();
  265. entityTypes[1] = new ItemEntityType();
  266. entityTypeCount = 2;
  267. for (EntityType* entityType : entityTypeArray)
  268. {
  269. entityTypes[entityTypeCount++] = entityType;
  270. }
  271. for (int i = 0; i < entityTypeCount; i++)
  272. {
  273. entityTypes[i]->setTypeId(i);
  274. }
  275. // initialize loaded types
  276. bool allInitialized = false;
  277. while (!allInitialized)
  278. {
  279. allInitialized = true;
  280. for (int i = 0; i < blockTypeCount; i++)
  281. {
  282. if (blockTypes[i] && !blockTypes[i]->initialize(this))
  283. {
  284. Framework::Logging::error()
  285. << "Could not initialize Block Type '"
  286. << blockTypes[i]->getName() << "'.";
  287. blockTypes[i]->release();
  288. blockTypes[i] = 0;
  289. allInitialized = false;
  290. }
  291. }
  292. }
  293. allInitialized = false;
  294. while (!allInitialized)
  295. {
  296. allInitialized = true;
  297. for (int i = 0; i < itemTypeCount; i++)
  298. {
  299. if (itemTypes[i] && !itemTypes[i]->initialize(this))
  300. {
  301. Framework::Logging::error()
  302. << "Could not initialize Item Type '"
  303. << itemTypes[i]->getName() << "'.";
  304. itemTypes[i]->release();
  305. itemTypes[i] = 0;
  306. allInitialized = false;
  307. }
  308. }
  309. }
  310. allInitialized = false;
  311. while (!allInitialized)
  312. {
  313. allInitialized = true;
  314. for (int i = 0; i < entityTypeCount; i++)
  315. {
  316. if (entityTypes[i] && !entityTypes[i]->initialize(this))
  317. {
  318. Framework::Logging::error()
  319. << "Could not initialize Entity Type '"
  320. << entityTypes[i]->getName() << "'.";
  321. entityTypes[i]->release();
  322. entityTypes[i] = 0;
  323. allInitialized = false;
  324. }
  325. }
  326. }
  327. for (int i = 0; i < blockTypeCount; i++)
  328. {
  329. if (blockTypes[i])
  330. {
  331. blockTypes[i]->initializeDefault();
  332. }
  333. }
  334. multiblockStructureTypes = new MultiblockStructureType*[1];
  335. multiblockStructureTypes[0] = new MultiblockTreeStructureType();
  336. multiblockStructureTypeCount = 1;
  337. // save syntax info
  338. Framework::DateiRemove("data/syntax");
  339. // typeRegistry->writeSyntaxInfo("data/syntax");
  340. validator
  341. = Framework::Validator::DataValidator::buildForArray()
  342. ->addAcceptedTypeInArray(typeRegistry->getValidator<BlockType>())
  343. ->finishArray();
  344. Framework::JSON::JSONObject* schema = validator->getJsonSchema();
  345. Framework::Datei syntaxFile;
  346. syntaxFile.setDatei("data/syntax/schema/blocks.json");
  347. syntaxFile.erstellen();
  348. syntaxFile.open(Framework::Datei::Style::schreiben);
  349. syntaxFile.schreibe(schema->toString(), schema->toString().getLength());
  350. syntaxFile.close();
  351. schema->release();
  352. validator->release();
  353. validator
  354. = Framework::Validator::DataValidator::buildForArray()
  355. ->addAcceptedTypeInArray(typeRegistry->getValidator<ItemType>())
  356. ->finishArray();
  357. schema = validator->getJsonSchema();
  358. syntaxFile.setDatei("data/syntax/schema/items.json");
  359. syntaxFile.erstellen();
  360. syntaxFile.open(Framework::Datei::Style::schreiben);
  361. syntaxFile.schreibe(schema->toString(), schema->toString().getLength());
  362. syntaxFile.close();
  363. schema->release();
  364. validator->release();
  365. validator
  366. = Framework::Validator::DataValidator::buildForArray()
  367. ->addAcceptedTypeInArray(typeRegistry->getValidator<EntityType>())
  368. ->finishArray();
  369. schema = validator->getJsonSchema();
  370. syntaxFile.setDatei("data/syntax/schema/entities.json");
  371. syntaxFile.erstellen();
  372. syntaxFile.open(Framework::Datei::Style::schreiben);
  373. syntaxFile.schreibe(schema->toString(), schema->toString().getLength());
  374. syntaxFile.close();
  375. schema->release();
  376. validator->release();
  377. // initialize world generator and world loader
  378. int seed = 0;
  379. int index = 0;
  380. for (const char* n = name; *n; n++)
  381. seed += (int)pow((float)*n * 31, (float)++index);
  382. generator = new WorldGenerator(seed);
  383. loader = new WorldLoader();
  384. // load recipies
  385. recipies->loadRecipies("data");
  386. // initialize chat
  387. chat = new Chat();
  388. // load quests
  389. questManager->loadQuests();
  390. }
  391. void Game::thread()
  392. {
  393. ZeitMesser waitForLock;
  394. ZeitMesser removeOldClients;
  395. ZeitMesser tickEntities;
  396. ZeitMesser worldUpdates;
  397. ZeitMesser clientReply;
  398. ZeitMesser removeOldChunks;
  399. ZeitMesser m;
  400. ZeitMesser total;
  401. total.messungStart();
  402. double tickTime = 0;
  403. double sleepTime = 0;
  404. int nextTimeSync = MAX_TICKS_PER_SECOND;
  405. while (!stop)
  406. {
  407. m.messungStart();
  408. ticker->nextTick();
  409. actionsCs.lock();
  410. while (actions.getEintragAnzahl() > 0)
  411. {
  412. actions.get(0)();
  413. actions.remove(0);
  414. }
  415. actionsCs.unlock();
  416. Array<int> removed;
  417. double waitTotal = 0;
  418. waitForLock.messungStart();
  419. cs.lock();
  420. waitForLock.messungEnde();
  421. waitTotal += waitForLock.getSekunden();
  422. removeOldClients.messungStart();
  423. int index = 0;
  424. nextTimeSync--;
  425. for (auto player : *clients)
  426. {
  427. if (!player->isOnline())
  428. {
  429. uiController->removePlayerDialogs(player->zEntity()->getId());
  430. chat->removeObserver(player->zEntity()->getId());
  431. chat->broadcastMessage(
  432. Framework::Text(player->zEntity()->getName())
  433. + " left the game.",
  434. Chat::CHANNEL_INFO);
  435. Datei pFile;
  436. pFile.setDatei(path + "/player/"
  437. + getPlayerId(player->zEntity()->getName()));
  438. pFile.erstellen();
  439. if (pFile.open(Datei::Style::schreiben))
  440. {
  441. zEntityType(EntityTypeEnum::PLAYER)
  442. ->saveEntity(player->zEntity(), &pFile);
  443. }
  444. pFile.close();
  445. Dimension* dim
  446. = zDimension(player->zEntity()->getDimensionId());
  447. Chunk* chunk = dim->zChunk(
  448. getChunkCenter((int)player->zEntity()->getLocation().x,
  449. (int)player->zEntity()->getLocation().y));
  450. if (chunk)
  451. {
  452. chunk->onEntityLeaves(player->zEntity(), 0);
  453. }
  454. dim->removeEntity(player->zEntity()->getId());
  455. removed.add(index, 0);
  456. dim->removeSubscriptions(player->zEntity());
  457. }
  458. else
  459. {
  460. if (nextTimeSync <= 0 && player->zEntity())
  461. {
  462. Dimension* zDim
  463. = zDimension(player->zEntity()->getDimensionId());
  464. if (zDim)
  465. {
  466. NetworkMessage* msg = new NetworkMessage();
  467. msg->syncTime(zDim->getCurrentDayTime(),
  468. zDim->getNightDuration(),
  469. zDim->getNightTransitionDuration(),
  470. zDim->getDayDuration());
  471. player->sendResponse(msg);
  472. }
  473. }
  474. }
  475. index++;
  476. }
  477. if (nextTimeSync <= 0)
  478. {
  479. consoleHandler->print();
  480. nextTimeSync = MAX_TICKS_PER_SECOND;
  481. }
  482. for (auto i : removed)
  483. clients->remove(i);
  484. removeOldClients.messungEnde();
  485. cs.unlock();
  486. tickEntities.messungStart();
  487. for (auto dim : *dimensions)
  488. dim->tickEntities();
  489. tickEntities.messungEnde();
  490. waitForLock.messungStart();
  491. cs.lock();
  492. waitForLock.messungEnde();
  493. waitTotal += waitForLock.getSekunden();
  494. worldUpdates.messungStart();
  495. worldUpdates.messungEnde();
  496. cs.unlock();
  497. clientReply.messungStart();
  498. for (auto client : *clients)
  499. client->reply();
  500. clientReply.messungEnde();
  501. waitForLock.messungStart();
  502. cs.lock();
  503. waitForLock.messungEnde();
  504. waitTotal += waitForLock.getSekunden();
  505. removeOldChunks.messungStart();
  506. for (auto dim : *dimensions)
  507. dim->removeOldChunks();
  508. removeOldChunks.messungEnde();
  509. cs.unlock();
  510. m.messungEnde();
  511. double sec = m.getSekunden();
  512. tickCounter++;
  513. totalTickTime += sec;
  514. sleepTime += 1.0 / MAX_TICKS_PER_SECOND - tickTime;
  515. if (sleepTime > 0)
  516. {
  517. Sleep((int)(sleepTime * 1000));
  518. }
  519. total.messungEnde();
  520. total.messungStart();
  521. tickTime = total.getSekunden();
  522. totalTime += tickTime;
  523. if (totalTime >= 1)
  524. {
  525. averageTickTime = totalTickTime / tickCounter;
  526. ticksPerSecond = tickCounter;
  527. totalTickTime = 0;
  528. tickCounter = 0;
  529. totalTime = 0;
  530. }
  531. else if (sec > 1)
  532. {
  533. Framework::Logging::warning()
  534. << "tick needed " << sec
  535. << " seconds. The game will run sower then normal.\n";
  536. Framework::Logging::trace()
  537. << "waiting: " << waitTotal
  538. << "\nremoveOldClients: " << removeOldClients.getSekunden()
  539. << "\ntickEntities:" << tickEntities.getSekunden()
  540. << "\nworldUpdates: " << worldUpdates.getSekunden()
  541. << "\nclientReply: " << clientReply.getSekunden()
  542. << "\nremoveOldChunks:" << removeOldChunks.getSekunden();
  543. }
  544. }
  545. save();
  546. generator->exitAndWait();
  547. loader->exitAndWait();
  548. ticker->exitAndWait();
  549. for (Dimension* dim : *dimensions)
  550. dim->requestStopAndWait();
  551. Framework::Logging::info() << "Game thread exited";
  552. }
  553. void Game::api(Framework::InMemoryBuffer* zRequest, GameClient* zOrigin)
  554. {
  555. char type;
  556. zRequest->lese(&type, 1);
  557. NetworkMessage* response = new NetworkMessage();
  558. switch (type)
  559. {
  560. case 1: // world
  561. {
  562. Dimension* dim = zDimension(zOrigin->zEntity()->getDimensionId());
  563. if (!dim)
  564. {
  565. dim = generator->createDimension(
  566. zOrigin->zEntity()->getDimensionId());
  567. if (!dim)
  568. {
  569. Framework::Logging::error()
  570. << "could not create dimension "
  571. << zOrigin->zEntity()->getDimensionId()
  572. << ". No Factory was provided.";
  573. return;
  574. }
  575. addDimension(dim);
  576. }
  577. dim->api(zRequest, response, zOrigin->zEntity());
  578. break;
  579. }
  580. case 2: // player
  581. zOrigin->zEntity()->playerApi(zRequest, response);
  582. break;
  583. case 3: // entity
  584. {
  585. int id;
  586. zRequest->lese((char*)&id, 4);
  587. for (Dimension* dim : *dimensions)
  588. {
  589. Entity* entity = dim->zEntity(id);
  590. if (entity)
  591. {
  592. entity->api(zRequest, response, zOrigin->zEntity());
  593. break;
  594. }
  595. }
  596. break;
  597. }
  598. case 4:
  599. { // inventory
  600. bool isEntity;
  601. zRequest->lese((char*)&isEntity, 1);
  602. Inventory* target;
  603. if (isEntity)
  604. {
  605. int id;
  606. zRequest->lese((char*)&id, 4);
  607. target = zEntity(id);
  608. }
  609. else
  610. {
  611. int dim;
  612. Vec3<int> pos;
  613. zRequest->lese((char*)&dim, 4);
  614. zRequest->lese((char*)&pos.x, 4);
  615. zRequest->lese((char*)&pos.y, 4);
  616. zRequest->lese((char*)&pos.z, 4);
  617. target = zBlockAt(pos, dim, 0);
  618. }
  619. if (target)
  620. target->inventoryApi(zRequest, response, zOrigin->zEntity());
  621. break;
  622. }
  623. case 5:
  624. { // crafting uiml request
  625. int id;
  626. zRequest->lese((char*)&id, 4);
  627. Text uiml = recipies->getCrafingUIML(id);
  628. Text dialogId = "crafting_";
  629. dialogId += id;
  630. uiController->addDialog(new UIDialog(dialogId,
  631. zOrigin->zEntity()->getId(),
  632. new Framework::XML::Element(uiml)));
  633. break;
  634. }
  635. case 6:
  636. { // chat message
  637. chat->chatApi(zRequest, zOrigin->zEntity(), response);
  638. break;
  639. }
  640. case 7: // other dimension
  641. {
  642. int dimensionId;
  643. zRequest->lese((char*)&dimensionId, 4);
  644. Dimension* dim = zDimension(dimensionId);
  645. if (dim)
  646. {
  647. dim->api(zRequest, response, zOrigin->zEntity());
  648. }
  649. break;
  650. }
  651. case 8: // ui message
  652. {
  653. uiController->api(zRequest, response, zOrigin->zEntity());
  654. break;
  655. }
  656. default:
  657. Framework::Logging::warning()
  658. << "received unknown api request in game with type " << (int)type;
  659. }
  660. if (!response->isEmpty())
  661. {
  662. if (response->isBroadcast())
  663. broadcastMessage(response);
  664. else
  665. zOrigin->sendResponse(response);
  666. }
  667. else
  668. {
  669. response->release();
  670. }
  671. }
  672. void Game::updateLightning(int dimensionId, Vec3<int> location)
  673. {
  674. Dimension* zDim = zDimension(dimensionId);
  675. if (zDim) zDim->updateLightning(location);
  676. }
  677. void Game::updateLightningWithoutWait(int dimensionId, Vec3<int> location)
  678. {
  679. Dimension* zDim = zDimension(dimensionId);
  680. if (zDim) zDim->updateLightningWithoutWait(location);
  681. }
  682. void Game::broadcastMessage(NetworkMessage* response)
  683. {
  684. for (auto client : *clients)
  685. client->sendResponse(
  686. dynamic_cast<NetworkMessage*>(response->getThis()));
  687. response->release();
  688. }
  689. void Game::sendMessage(NetworkMessage* response, Entity* zTargetPlayer)
  690. {
  691. for (auto client : *clients)
  692. {
  693. if (client->zEntity()->getId() == zTargetPlayer->getId())
  694. {
  695. client->sendResponse(response);
  696. return;
  697. }
  698. }
  699. response->release();
  700. }
  701. bool Game::checkPlayer(Framework::Text name, Framework::Text secret)
  702. {
  703. if (playerRegister->checkSecret(name, secret))
  704. return 1;
  705. else
  706. {
  707. Framework::Logging::warning()
  708. << "player " << name.getText()
  709. << " tryed to connect with an invalid secret.";
  710. return 0;
  711. }
  712. }
  713. bool Game::existsPlayer(Framework::Text name)
  714. {
  715. return playerRegister->hasPlayer(name);
  716. }
  717. Framework::Text Game::createPlayer(Framework::Text name)
  718. {
  719. return playerRegister->addPlayer(name);
  720. }
  721. GameClient* Game::addPlayer(FCKlient* client, Framework::Text name)
  722. {
  723. cs.lock();
  724. int id = playerRegister->getPlayerId(name);
  725. Datei pFile;
  726. pFile.setDatei(path + "/player/" + id);
  727. Player* player;
  728. bool isNew = 0;
  729. if (!pFile.existiert() || !pFile.open(Datei::Style::lesen))
  730. {
  731. player = (Player*)zEntityType(EntityTypeEnum::PLAYER)
  732. ->createEntityAt(
  733. Vec3<float>(0.5, 0.5, 0), DimensionEnum::OVERWORLD);
  734. player->setName(name);
  735. isNew = 1;
  736. }
  737. else
  738. {
  739. player
  740. = (Player*)zEntityType(EntityTypeEnum::PLAYER)->loadEntity(&pFile);
  741. pFile.close();
  742. }
  743. if (player->getId() >= nextEntityId)
  744. {
  745. nextEntityId = player->getId() + 1;
  746. }
  747. GameClient* gameClient = new GameClient(player, client);
  748. gameClient->sendTypes();
  749. clients->add(gameClient);
  750. if (!zDimension(player->getDimensionId()))
  751. {
  752. Dimension* dim = generator->createDimension(player->getDimensionId());
  753. if (!dim)
  754. {
  755. Framework::Logging::error() << "could not create dimension "
  756. << (int)player->getDimensionId()
  757. << ". No Factory was provided.";
  758. return 0;
  759. }
  760. NetworkMessage* msg = new NetworkMessage();
  761. msg->syncTime(dim->getCurrentDayTime(),
  762. dim->getNightDuration(),
  763. dim->getNightTransitionDuration(),
  764. dim->getDayDuration());
  765. gameClient->sendResponse(msg);
  766. this->addDimension(dim);
  767. }
  768. // subscribe the new player as an observer of the new chunk
  769. Dimension* dim = zDimension(player->getDimensionId());
  770. InMemoryBuffer* buffer = new InMemoryBuffer();
  771. buffer->schreibe("\0", 1);
  772. Punkt center = getChunkCenter(
  773. (int)player->getPosition().x, (int)player->getPosition().y);
  774. buffer->schreibe((char*)&center.x, 4);
  775. buffer->schreibe((char*)&center.y, 4);
  776. buffer->schreibe("\0", 1);
  777. dim->api(buffer, 0, player);
  778. buffer->release();
  779. while (isNew
  780. && !dim->zChunk(getChunkCenter(
  781. (int)player->getPosition().x, (int)player->getPosition().y)))
  782. {
  783. cs.unlock();
  784. Sleep(1000);
  785. cs.lock();
  786. }
  787. if (isNew)
  788. {
  789. Either<Block*, int> b = BlockTypeEnum::AIR;
  790. int h = WORLD_HEIGHT;
  791. while (((b.isA() && (!(Block*)b || ((Block*)b)->isPassable()))
  792. || (b.isB() && zBlockType(b)->zDefault()->isPassable()))
  793. && h > 0)
  794. b = zBlockAt({(int)player->getPosition().x,
  795. (int)player->getPosition().y,
  796. --h},
  797. player->getDimensionId(),
  798. 0);
  799. player->setPosition(
  800. {player->getPosition().x, player->getPosition().y, (float)h + 2.f});
  801. }
  802. Dimension* zDim = zDimension(player->getDimensionId());
  803. if (zDim)
  804. {
  805. zDim->addEntity(player);
  806. }
  807. else
  808. {
  809. Framework::Logging::error()
  810. << "could not add player to dimension "
  811. << (int)player->getDimensionId() << ". Dimension not loaded.";
  812. player->release();
  813. }
  814. chat->addObserver(gameClient->zEntity()->getId());
  815. chat->broadcastMessage(name + " joined the game.", Chat::CHANNEL_INFO);
  816. cs.unlock();
  817. return dynamic_cast<GameClient*>(gameClient->getThis());
  818. }
  819. bool Game::isChunkLoaded(int x, int y, int dimension) const
  820. {
  821. Dimension* dim = zDimension(dimension);
  822. return (dim && dim->hasChunck(x, y));
  823. }
  824. bool Game::doesChunkExist(int x, int y, int dimension)
  825. {
  826. cs.lock();
  827. bool result = isChunkLoaded(x, y, dimension)
  828. || loader->existsChunk(x, y, dimension);
  829. cs.unlock();
  830. return result;
  831. }
  832. void Game::blockTargetChanged(Block* zBlock)
  833. {
  834. for (GameClient* client : *this->clients)
  835. {
  836. if (client->zEntity()->zTarget()
  837. && client->zEntity()->zTarget()->isBlock(
  838. zBlock->getPos(), NO_DIRECTION))
  839. {
  840. client->zEntity()->onTargetChange();
  841. }
  842. }
  843. }
  844. void Game::entityTargetChanged(Entity* zEntity)
  845. {
  846. for (GameClient* client : *this->clients)
  847. {
  848. if (client->zEntity()->zTarget()
  849. && client->zEntity()->zTarget()->isEntity(zEntity->getId()))
  850. {
  851. client->zEntity()->onTargetChange();
  852. }
  853. }
  854. }
  855. void Game::spawnItem(
  856. Framework::Vec3<float> location, int dimensionId, Item* stack)
  857. {
  858. spawnItem(location, dimensionId, new ItemStack(stack, 1));
  859. }
  860. void Game::spawnItem(
  861. Framework::Vec3<float> location, int dimensionId, ItemStack* stack)
  862. {
  863. ItemEntity* itemEntity
  864. = (ItemEntity*)zEntityType(EntityTypeEnum::ITEM)
  865. ->createEntity(
  866. location, dimensionId, Game::INSTANCE->getNextEntityId());
  867. itemEntity->unsaveAddItem(stack, NO_DIRECTION, 0);
  868. stack->release();
  869. Dimension* dim = zDimension(dimensionId);
  870. if (dim)
  871. {
  872. dim->addEntity(itemEntity);
  873. }
  874. else
  875. {
  876. Framework::Logging::error()
  877. << "could not spawn item entity in dimension " << dimensionId
  878. << ". Dimension not loaded.";
  879. itemEntity->release();
  880. return;
  881. }
  882. }
  883. Framework::Either<Block*, int> Game::zBlockAt(
  884. Framework::Vec3<int> location, int dimension, OUT Chunk** zChunk) const
  885. {
  886. Dimension* dim = zDimension(dimension);
  887. if (dim) return dim->zBlock(location, zChunk);
  888. return 0;
  889. }
  890. Block* Game::zRealBlockInstance(Framework::Vec3<int> location, int dimension)
  891. {
  892. Dimension* dim = zDimension(dimension);
  893. if (dim) return dim->zRealBlockInstance(location);
  894. return 0;
  895. }
  896. const Block* Game::zConstBlock(Framework::Vec3<int> location, int dimension)
  897. {
  898. Dimension* dim = zDimension(dimension);
  899. if (dim) return dim->zBlockOrDefault(location);
  900. return 0;
  901. }
  902. int Game::getBlockType(Framework::Vec3<int> location, int dimension)
  903. {
  904. Dimension* dim = zDimension(dimension);
  905. if (dim) return dim->getBlockType(location);
  906. return 0;
  907. }
  908. Dimension* Game::zDimension(int id) const
  909. {
  910. for (auto dim : *dimensions)
  911. {
  912. if (dim->getDimensionId() == id) return dim;
  913. }
  914. return 0;
  915. }
  916. Framework::Punkt Game::getChunkCenter(int x, int y)
  917. {
  918. return Punkt(((x < 0 ? x + 1 : x) / CHUNK_SIZE) * CHUNK_SIZE
  919. + (x < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2,
  920. ((y < 0 ? y + 1 : y) / CHUNK_SIZE) * CHUNK_SIZE
  921. + (y < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2);
  922. }
  923. Area Game::getChunckArea(Punkt center) const
  924. {
  925. return {center.x - CHUNK_SIZE / 2,
  926. center.y - CHUNK_SIZE / 2,
  927. center.x + CHUNK_SIZE / 2 - 1,
  928. center.y + CHUNK_SIZE / 2 - 1,
  929. 0};
  930. }
  931. Framework::Text Game::getWorldDirectory() const
  932. {
  933. return path;
  934. }
  935. void Game::requestArea(Area area)
  936. {
  937. generator->requestGeneration(area);
  938. loader->requestLoading(area);
  939. }
  940. void Game::save() const
  941. {
  942. questManager->saveQuests();
  943. Datei d;
  944. d.setDatei(path + "/eid");
  945. d.open(Datei::Style::schreiben);
  946. d.schreibe((char*)&nextEntityId, 4);
  947. d.close();
  948. playerRegister->save();
  949. for (auto dim : *dimensions)
  950. dim->save(path);
  951. chat->save();
  952. Framework::Logging::info() << "Game was saved";
  953. }
  954. void Game::requestStop()
  955. {
  956. stop = 1;
  957. warteAufThread(1000000);
  958. }
  959. void Game::addDimension(Dimension* d)
  960. {
  961. dimensions->add(d);
  962. }
  963. int Game::getNextEntityId()
  964. {
  965. cs.lock();
  966. int result = nextEntityId++;
  967. cs.unlock();
  968. return result;
  969. }
  970. WorldGenerator* Game::zGenerator() const
  971. {
  972. return generator;
  973. }
  974. Game* Game::INSTANCE = 0;
  975. void Game::initialize(Framework::Text name, Framework::Text worldsDir)
  976. {
  977. if (!Game::INSTANCE)
  978. {
  979. Game::INSTANCE = new Game(name, worldsDir);
  980. Game::INSTANCE->initialize();
  981. }
  982. }
  983. Entity* Game::zEntity(int id, int dimensionId) const
  984. {
  985. Dimension* d = zDimension(dimensionId);
  986. if (d) return d->zEntity(id);
  987. return 0;
  988. }
  989. Entity* Game::zEntity(int id) const
  990. {
  991. for (Dimension* d : *dimensions)
  992. {
  993. Entity* e = d->zEntity(id);
  994. if (e) return e;
  995. }
  996. // for new players that are currently loading
  997. for (GameClient* client : *clients)
  998. {
  999. if (client->zEntity()->getId() == id)
  1000. {
  1001. return client->zEntity();
  1002. }
  1003. }
  1004. return 0;
  1005. }
  1006. Entity* Game::zNearestEntity(int dimensionId,
  1007. Framework::Vec3<float> pos,
  1008. std::function<bool(Entity*)> filter)
  1009. {
  1010. Dimension* d = zDimension(dimensionId);
  1011. if (!d) return 0;
  1012. return d->zNearestEntity(pos, filter);
  1013. }
  1014. RecipieLoader* Game::zRecipies() const
  1015. {
  1016. return recipies;
  1017. }
  1018. void Game::doLater(std::function<void()> action)
  1019. {
  1020. actionsCs.lock();
  1021. actions.add(action);
  1022. actionsCs.unlock();
  1023. }
  1024. TickOrganizer* Game::zTickOrganizer() const
  1025. {
  1026. return ticker;
  1027. }
  1028. Chat* Game::zChat() const
  1029. {
  1030. return chat;
  1031. }
  1032. Player* Game::zPlayerByName(const char* name) const
  1033. {
  1034. for (GameClient* client : *clients)
  1035. {
  1036. if (strcmp(client->zEntity()->getName(), name) == 0)
  1037. {
  1038. return client->zEntity();
  1039. }
  1040. }
  1041. return 0;
  1042. }
  1043. void Game::listPlayerNames(Framework::RCArray<Framework::Text>& names)
  1044. {
  1045. for (GameClient* client : *clients)
  1046. {
  1047. names.add(new Framework::Text(client->zEntity()->getName()));
  1048. }
  1049. }
  1050. TypeRegistry* Game::zTypeRegistry() const
  1051. {
  1052. return typeRegistry;
  1053. }
  1054. int Game::getPlayerId(const char* name) const
  1055. {
  1056. return playerRegister->getPlayerId(name);
  1057. }
  1058. QuestManager* Game::zQuestManager() const
  1059. {
  1060. return questManager;
  1061. }
  1062. UIController* Game::zUIController() const
  1063. {
  1064. return uiController;
  1065. }
  1066. double Game::getAverageTickTime() const
  1067. {
  1068. return averageTickTime;
  1069. }
  1070. int Game::getTicksPerSecond() const
  1071. {
  1072. return ticksPerSecond;
  1073. }
  1074. int Game::getPlayerCount() const
  1075. {
  1076. return clients->getEintragAnzahl();
  1077. }
  1078. int Game::getChunkCount() const
  1079. {
  1080. int result = 0;
  1081. for (Dimension* dim : *dimensions)
  1082. {
  1083. result += dim->getChunkCount();
  1084. }
  1085. return result;
  1086. }
  1087. const BlockType* Game::zBlockType(int id) const
  1088. {
  1089. return blockTypes[id];
  1090. }
  1091. const ItemType* Game::zItemType(int id) const
  1092. {
  1093. return itemTypes[id];
  1094. }
  1095. const EntityType* Game::zEntityType(int id) const
  1096. {
  1097. return entityTypes[id];
  1098. }
  1099. int Game::getEntityTypeId(const char* name) const
  1100. {
  1101. for (int i = 0; i < entityTypeCount; i++)
  1102. {
  1103. if (entityTypes[i]
  1104. && Framework::Text(entityTypes[i]->getName()).istGleich(name))
  1105. {
  1106. return i;
  1107. }
  1108. }
  1109. Framework::Logging::warning()
  1110. << "no entity type with name '" << name << "' found.";
  1111. return -1;
  1112. }
  1113. int Game::getBlockTypeId(const char* name) const
  1114. {
  1115. for (int i = 0; i < blockTypeCount; i++)
  1116. {
  1117. if (blockTypes[i]
  1118. && Framework::Text(blockTypes[i]->getName()).istGleich(name))
  1119. {
  1120. return i;
  1121. }
  1122. }
  1123. Framework::Logging::warning()
  1124. << "no block type with name '" << name << "' found.";
  1125. return -1;
  1126. }
  1127. int Game::getItemTypeId(const char* name) const
  1128. {
  1129. for (int i = 0; i < itemTypeCount; i++)
  1130. {
  1131. if (itemTypes[i]
  1132. && Framework::Text(itemTypes[i]->getName()).istGleich(name))
  1133. {
  1134. return i;
  1135. }
  1136. }
  1137. Framework::Logging::warning()
  1138. << "no item type with name '" << name << "' found.";
  1139. return -1;
  1140. }
  1141. int Game::getBlockTypeCount() const
  1142. {
  1143. return blockTypeCount;
  1144. }
  1145. int Game::getItemTypeCount() const
  1146. {
  1147. return itemTypeCount;
  1148. }
  1149. int Game::getEntityTypeCount() const
  1150. {
  1151. return entityTypeCount;
  1152. }
  1153. const MultiblockStructureType* Game::zMultiblockStructureType(int id) const
  1154. {
  1155. return multiblockStructureTypes[id];
  1156. }
  1157. int Game::getMultiblockStructureTypeCount() const
  1158. {
  1159. return multiblockStructureTypeCount;
  1160. }