Game.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229
  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. zEntityType(EntityTypeEnum::PLAYER)
  441. ->saveEntity(player->zEntity(), &pFile);
  442. pFile.close();
  443. removed.add(index, 0);
  444. Dimension* dim
  445. = zDimension(player->zEntity()->getDimensionId());
  446. dim->removeSubscriptions(player->zEntity());
  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. }
  456. else
  457. {
  458. if (nextTimeSync <= 0 && player->zEntity())
  459. {
  460. Dimension* zDim
  461. = zDimension(player->zEntity()->getDimensionId());
  462. if (zDim)
  463. {
  464. NetworkMessage* msg = new NetworkMessage();
  465. msg->syncTime(zDim->getCurrentDayTime(),
  466. zDim->getNightDuration(),
  467. zDim->getNightTransitionDuration(),
  468. zDim->getDayDuration());
  469. player->sendResponse(msg);
  470. }
  471. }
  472. }
  473. index++;
  474. }
  475. if (nextTimeSync <= 0)
  476. {
  477. consoleHandler->print();
  478. nextTimeSync = MAX_TICKS_PER_SECOND;
  479. }
  480. for (auto i : removed)
  481. clients->remove(i);
  482. removeOldClients.messungEnde();
  483. cs.unlock();
  484. tickEntities.messungStart();
  485. for (auto dim : *dimensions)
  486. dim->tickEntities();
  487. tickEntities.messungEnde();
  488. waitForLock.messungStart();
  489. cs.lock();
  490. waitForLock.messungEnde();
  491. waitTotal += waitForLock.getSekunden();
  492. worldUpdates.messungStart();
  493. worldUpdates.messungEnde();
  494. cs.unlock();
  495. clientReply.messungStart();
  496. for (auto client : *clients)
  497. client->reply();
  498. clientReply.messungEnde();
  499. waitForLock.messungStart();
  500. cs.lock();
  501. waitForLock.messungEnde();
  502. waitTotal += waitForLock.getSekunden();
  503. removeOldChunks.messungStart();
  504. for (auto dim : *dimensions)
  505. dim->removeOldChunks();
  506. removeOldChunks.messungEnde();
  507. cs.unlock();
  508. m.messungEnde();
  509. double sec = m.getSekunden();
  510. tickCounter++;
  511. totalTickTime += sec;
  512. sleepTime += 1.0 / MAX_TICKS_PER_SECOND - tickTime;
  513. if (sleepTime > 0)
  514. {
  515. Sleep((int)(sleepTime * 1000));
  516. }
  517. total.messungEnde();
  518. total.messungStart();
  519. tickTime = total.getSekunden();
  520. totalTime += tickTime;
  521. if (totalTime >= 1)
  522. {
  523. averageTickTime = totalTickTime / tickCounter;
  524. ticksPerSecond = tickCounter;
  525. totalTickTime = 0;
  526. tickCounter = 0;
  527. totalTime = 0;
  528. }
  529. else if (sec > 1)
  530. {
  531. Framework::Logging::warning()
  532. << "tick needed " << sec
  533. << " seconds. The game will run sower then normal.\n";
  534. Framework::Logging::trace()
  535. << "waiting: " << waitTotal
  536. << "\nremoveOldClients: " << removeOldClients.getSekunden()
  537. << "\ntickEntities:" << tickEntities.getSekunden()
  538. << "\nworldUpdates: " << worldUpdates.getSekunden()
  539. << "\nclientReply: " << clientReply.getSekunden()
  540. << "\nremoveOldChunks:" << removeOldChunks.getSekunden();
  541. }
  542. }
  543. save();
  544. generator->exitAndWait();
  545. loader->exitAndWait();
  546. ticker->exitAndWait();
  547. for (Dimension* dim : *dimensions)
  548. dim->requestStopAndWait();
  549. Framework::Logging::info() << "Game thread exited";
  550. }
  551. void Game::api(Framework::InMemoryBuffer* zRequest, GameClient* zOrigin)
  552. {
  553. char type;
  554. zRequest->lese(&type, 1);
  555. NetworkMessage* response = new NetworkMessage();
  556. switch (type)
  557. {
  558. case 1: // world
  559. {
  560. Dimension* dim = zDimension(zOrigin->zEntity()->getDimensionId());
  561. if (!dim)
  562. {
  563. dim = generator->createDimension(
  564. zOrigin->zEntity()->getDimensionId());
  565. if (!dim)
  566. {
  567. Framework::Logging::error()
  568. << "could not create dimension "
  569. << zOrigin->zEntity()->getDimensionId()
  570. << ". No Factory was provided.";
  571. return;
  572. }
  573. addDimension(dim);
  574. }
  575. dim->api(zRequest, response, zOrigin->zEntity());
  576. break;
  577. }
  578. case 2: // player
  579. zOrigin->zEntity()->playerApi(zRequest, response);
  580. break;
  581. case 3: // entity
  582. {
  583. int id;
  584. zRequest->lese((char*)&id, 4);
  585. for (Dimension* dim : *dimensions)
  586. {
  587. Entity* entity = dim->zEntity(id);
  588. if (entity)
  589. {
  590. entity->api(zRequest, response, zOrigin->zEntity());
  591. break;
  592. }
  593. }
  594. break;
  595. }
  596. case 4:
  597. { // inventory
  598. bool isEntity;
  599. zRequest->lese((char*)&isEntity, 1);
  600. Inventory* target;
  601. if (isEntity)
  602. {
  603. int id;
  604. zRequest->lese((char*)&id, 4);
  605. target = zEntity(id);
  606. }
  607. else
  608. {
  609. int dim;
  610. Vec3<int> pos;
  611. zRequest->lese((char*)&dim, 4);
  612. zRequest->lese((char*)&pos.x, 4);
  613. zRequest->lese((char*)&pos.y, 4);
  614. zRequest->lese((char*)&pos.z, 4);
  615. target = zBlockAt(pos, dim, 0);
  616. }
  617. if (target)
  618. target->inventoryApi(zRequest, response, zOrigin->zEntity());
  619. break;
  620. }
  621. case 5:
  622. { // crafting uiml request
  623. int id;
  624. zRequest->lese((char*)&id, 4);
  625. Text uiml = recipies->getCrafingUIML(id);
  626. Text dialogId = "crafting_";
  627. dialogId += id;
  628. uiController->addDialog(new UIDialog(dialogId,
  629. zOrigin->zEntity()->getId(),
  630. new Framework::XML::Element(uiml)));
  631. break;
  632. }
  633. case 6:
  634. { // chat message
  635. chat->chatApi(zRequest, zOrigin->zEntity(), response);
  636. break;
  637. }
  638. case 7: // other dimension
  639. {
  640. int dimensionId;
  641. zRequest->lese((char*)&dimensionId, 4);
  642. Dimension* dim = zDimension(dimensionId);
  643. if (dim)
  644. {
  645. dim->api(zRequest, response, zOrigin->zEntity());
  646. }
  647. break;
  648. }
  649. case 8: // ui message
  650. {
  651. uiController->api(zRequest, response, zOrigin->zEntity());
  652. break;
  653. }
  654. default:
  655. Framework::Logging::warning()
  656. << "received unknown api request in game with type " << (int)type;
  657. }
  658. if (!response->isEmpty())
  659. {
  660. if (response->isBroadcast())
  661. broadcastMessage(response);
  662. else
  663. zOrigin->sendResponse(response);
  664. }
  665. else
  666. {
  667. response->release();
  668. }
  669. }
  670. void Game::updateLightning(int dimensionId, Vec3<int> location)
  671. {
  672. Dimension* zDim = zDimension(dimensionId);
  673. if (zDim) zDim->updateLightning(location);
  674. }
  675. void Game::updateLightningWithoutWait(int dimensionId, Vec3<int> location)
  676. {
  677. Dimension* zDim = zDimension(dimensionId);
  678. if (zDim) zDim->updateLightningWithoutWait(location);
  679. }
  680. void Game::broadcastMessage(NetworkMessage* response)
  681. {
  682. for (auto client : *clients)
  683. client->sendResponse(
  684. dynamic_cast<NetworkMessage*>(response->getThis()));
  685. response->release();
  686. }
  687. void Game::sendMessage(NetworkMessage* response, Entity* zTargetPlayer)
  688. {
  689. for (auto client : *clients)
  690. {
  691. if (client->zEntity()->getId() == zTargetPlayer->getId())
  692. {
  693. client->sendResponse(response);
  694. return;
  695. }
  696. }
  697. response->release();
  698. }
  699. bool Game::checkPlayer(Framework::Text name, Framework::Text secret)
  700. {
  701. if (playerRegister->checkSecret(name, secret))
  702. return 1;
  703. else
  704. {
  705. Framework::Logging::warning()
  706. << "player " << name.getText()
  707. << " tryed to connect with an invalid secret.";
  708. return 0;
  709. }
  710. }
  711. bool Game::existsPlayer(Framework::Text name)
  712. {
  713. return playerRegister->hasPlayer(name);
  714. }
  715. Framework::Text Game::createPlayer(Framework::Text name)
  716. {
  717. return playerRegister->addPlayer(name);
  718. }
  719. GameClient* Game::addPlayer(FCKlient* client, Framework::Text name)
  720. {
  721. cs.lock();
  722. int id = playerRegister->getPlayerId(name);
  723. Datei pFile;
  724. pFile.setDatei(path + "/player/" + id);
  725. Player* player;
  726. bool isNew = 0;
  727. if (!pFile.existiert() || !pFile.open(Datei::Style::lesen))
  728. {
  729. player = (Player*)zEntityType(EntityTypeEnum::PLAYER)
  730. ->createEntityAt(
  731. Vec3<float>(0.5, 0.5, 0), DimensionEnum::OVERWORLD);
  732. player->setName(name);
  733. isNew = 1;
  734. }
  735. else
  736. {
  737. player
  738. = (Player*)zEntityType(EntityTypeEnum::PLAYER)->loadEntity(&pFile);
  739. pFile.close();
  740. }
  741. if (player->getId() >= nextEntityId)
  742. {
  743. nextEntityId = player->getId() + 1;
  744. }
  745. GameClient* gameClient = new GameClient(player, client);
  746. gameClient->sendTypes();
  747. clients->add(gameClient);
  748. if (!zDimension(player->getDimensionId()))
  749. {
  750. Dimension* dim = generator->createDimension(player->getDimensionId());
  751. if (!dim)
  752. {
  753. Framework::Logging::error() << "could not create dimension "
  754. << (int)player->getDimensionId()
  755. << ". No Factory was provided.";
  756. return 0;
  757. }
  758. NetworkMessage* msg = new NetworkMessage();
  759. msg->syncTime(dim->getCurrentDayTime(),
  760. dim->getNightDuration(),
  761. dim->getNightTransitionDuration(),
  762. dim->getDayDuration());
  763. gameClient->sendResponse(msg);
  764. this->addDimension(dim);
  765. }
  766. // subscribe the new player as an observer of the new chunk
  767. Dimension* dim = zDimension(player->getDimensionId());
  768. InMemoryBuffer* buffer = new InMemoryBuffer();
  769. buffer->schreibe("\0", 1);
  770. Punkt center = getChunkCenter(
  771. (int)player->getPosition().x, (int)player->getPosition().y);
  772. buffer->schreibe((char*)&center.x, 4);
  773. buffer->schreibe((char*)&center.y, 4);
  774. buffer->schreibe("\0", 1);
  775. dim->api(buffer, 0, player);
  776. buffer->release();
  777. while (isNew
  778. && !dim->zChunk(getChunkCenter(
  779. (int)player->getPosition().x, (int)player->getPosition().y)))
  780. {
  781. cs.unlock();
  782. Sleep(1000);
  783. cs.lock();
  784. }
  785. if (isNew)
  786. {
  787. Either<Block*, int> b = BlockTypeEnum::AIR;
  788. int h = WORLD_HEIGHT;
  789. while (((b.isA() && (!(Block*)b || ((Block*)b)->isPassable()))
  790. || (b.isB() && zBlockType(b)->zDefault()->isPassable()))
  791. && h > 0)
  792. b = zBlockAt({(int)player->getPosition().x,
  793. (int)player->getPosition().y,
  794. --h},
  795. player->getDimensionId(),
  796. 0);
  797. player->setPosition(
  798. {player->getPosition().x, player->getPosition().y, (float)h + 2.f});
  799. }
  800. Dimension* zDim = zDimension(player->getDimensionId());
  801. if (zDim)
  802. {
  803. zDim->addEntity(player);
  804. }
  805. else
  806. {
  807. Framework::Logging::error()
  808. << "could not add player to dimension "
  809. << (int)player->getDimensionId() << ". Dimension not loaded.";
  810. player->release();
  811. }
  812. chat->addObserver(gameClient->zEntity()->getId());
  813. chat->broadcastMessage(name + " joined the game.", Chat::CHANNEL_INFO);
  814. cs.unlock();
  815. return dynamic_cast<GameClient*>(gameClient->getThis());
  816. }
  817. bool Game::isChunkLoaded(int x, int y, int dimension) const
  818. {
  819. Dimension* dim = zDimension(dimension);
  820. return (dim && dim->hasChunck(x, y));
  821. }
  822. bool Game::doesChunkExist(int x, int y, int dimension)
  823. {
  824. cs.lock();
  825. bool result = isChunkLoaded(x, y, dimension)
  826. || loader->existsChunk(x, y, dimension);
  827. cs.unlock();
  828. return result;
  829. }
  830. void Game::blockTargetChanged(Block* zBlock)
  831. {
  832. for (GameClient* client : *this->clients)
  833. {
  834. if (client->zEntity()->zTarget()
  835. && client->zEntity()->zTarget()->isBlock(
  836. zBlock->getPos(), NO_DIRECTION))
  837. {
  838. client->zEntity()->onTargetChange();
  839. }
  840. }
  841. }
  842. void Game::entityTargetChanged(Entity* zEntity)
  843. {
  844. for (GameClient* client : *this->clients)
  845. {
  846. if (client->zEntity()->zTarget()
  847. && client->zEntity()->zTarget()->isEntity(zEntity->getId()))
  848. {
  849. client->zEntity()->onTargetChange();
  850. }
  851. }
  852. }
  853. void Game::spawnItem(
  854. Framework::Vec3<float> location, int dimensionId, Item* stack)
  855. {
  856. spawnItem(location, dimensionId, new ItemStack(stack, 1));
  857. }
  858. void Game::spawnItem(
  859. Framework::Vec3<float> location, int dimensionId, ItemStack* stack)
  860. {
  861. ItemEntity* itemEntity
  862. = (ItemEntity*)zEntityType(EntityTypeEnum::ITEM)
  863. ->createEntity(
  864. location, dimensionId, Game::INSTANCE->getNextEntityId());
  865. itemEntity->unsaveAddItem(stack, NO_DIRECTION, 0);
  866. stack->release();
  867. Dimension* dim = zDimension(dimensionId);
  868. if (dim)
  869. {
  870. dim->addEntity(itemEntity);
  871. }
  872. else
  873. {
  874. Framework::Logging::error()
  875. << "could not spawn item entity in dimension " << dimensionId
  876. << ". Dimension not loaded.";
  877. itemEntity->release();
  878. return;
  879. }
  880. }
  881. Framework::Either<Block*, int> Game::zBlockAt(
  882. Framework::Vec3<int> location, int dimension, OUT Chunk** zChunk) const
  883. {
  884. Dimension* dim = zDimension(dimension);
  885. if (dim) return dim->zBlock(location, zChunk);
  886. return 0;
  887. }
  888. Block* Game::zRealBlockInstance(Framework::Vec3<int> location, int dimension)
  889. {
  890. Dimension* dim = zDimension(dimension);
  891. if (dim) return dim->zRealBlockInstance(location);
  892. return 0;
  893. }
  894. const Block* Game::zConstBlock(Framework::Vec3<int> location, int dimension)
  895. {
  896. Dimension* dim = zDimension(dimension);
  897. if (dim) return dim->zBlockOrDefault(location);
  898. return 0;
  899. }
  900. int Game::getBlockType(Framework::Vec3<int> location, int dimension)
  901. {
  902. Dimension* dim = zDimension(dimension);
  903. if (dim) return dim->getBlockType(location);
  904. return 0;
  905. }
  906. Dimension* Game::zDimension(int id) const
  907. {
  908. for (auto dim : *dimensions)
  909. {
  910. if (dim->getDimensionId() == id) return dim;
  911. }
  912. return 0;
  913. }
  914. Framework::Punkt Game::getChunkCenter(int x, int y)
  915. {
  916. return Punkt(((x < 0 ? x + 1 : x) / CHUNK_SIZE) * CHUNK_SIZE
  917. + (x < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2,
  918. ((y < 0 ? y + 1 : y) / CHUNK_SIZE) * CHUNK_SIZE
  919. + (y < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2);
  920. }
  921. Area Game::getChunckArea(Punkt center) const
  922. {
  923. return {center.x - CHUNK_SIZE / 2,
  924. center.y - CHUNK_SIZE / 2,
  925. center.x + CHUNK_SIZE / 2 - 1,
  926. center.y + CHUNK_SIZE / 2 - 1,
  927. 0};
  928. }
  929. Framework::Text Game::getWorldDirectory() const
  930. {
  931. return path;
  932. }
  933. void Game::requestArea(Area area)
  934. {
  935. generator->requestGeneration(area);
  936. loader->requestLoading(area);
  937. }
  938. void Game::save() const
  939. {
  940. questManager->saveQuests();
  941. Datei d;
  942. d.setDatei(path + "/eid");
  943. d.open(Datei::Style::schreiben);
  944. d.schreibe((char*)&nextEntityId, 4);
  945. d.close();
  946. playerRegister->save();
  947. for (auto dim : *dimensions)
  948. dim->save(path);
  949. chat->save();
  950. Framework::Logging::info() << "Game was saved";
  951. }
  952. void Game::requestStop()
  953. {
  954. stop = 1;
  955. warteAufThread(1000000);
  956. }
  957. void Game::addDimension(Dimension* d)
  958. {
  959. dimensions->add(d);
  960. }
  961. int Game::getNextEntityId()
  962. {
  963. cs.lock();
  964. int result = nextEntityId++;
  965. cs.unlock();
  966. return result;
  967. }
  968. WorldGenerator* Game::zGenerator() const
  969. {
  970. return generator;
  971. }
  972. Game* Game::INSTANCE = 0;
  973. void Game::initialize(Framework::Text name, Framework::Text worldsDir)
  974. {
  975. if (!Game::INSTANCE)
  976. {
  977. Game::INSTANCE = new Game(name, worldsDir);
  978. Game::INSTANCE->initialize();
  979. }
  980. }
  981. Entity* Game::zEntity(int id, int dimensionId) const
  982. {
  983. Dimension* d = zDimension(dimensionId);
  984. if (d) return d->zEntity(id);
  985. return 0;
  986. }
  987. Entity* Game::zEntity(int id) const
  988. {
  989. for (Dimension* d : *dimensions)
  990. {
  991. Entity* e = d->zEntity(id);
  992. if (e) return e;
  993. }
  994. // for new players that are currently loading
  995. for (GameClient* client : *clients)
  996. {
  997. if (client->zEntity()->getId() == id)
  998. {
  999. return client->zEntity();
  1000. }
  1001. }
  1002. return 0;
  1003. }
  1004. Entity* Game::zNearestEntity(int dimensionId,
  1005. Framework::Vec3<float> pos,
  1006. std::function<bool(Entity*)> filter)
  1007. {
  1008. Dimension* d = zDimension(dimensionId);
  1009. if (!d) return 0;
  1010. return d->zNearestEntity(pos, filter);
  1011. }
  1012. RecipieLoader* Game::zRecipies() const
  1013. {
  1014. return recipies;
  1015. }
  1016. void Game::doLater(std::function<void()> action)
  1017. {
  1018. actionsCs.lock();
  1019. actions.add(action);
  1020. actionsCs.unlock();
  1021. }
  1022. TickOrganizer* Game::zTickOrganizer() const
  1023. {
  1024. return ticker;
  1025. }
  1026. Chat* Game::zChat() const
  1027. {
  1028. return chat;
  1029. }
  1030. Player* Game::zPlayerByName(const char* name) const
  1031. {
  1032. for (GameClient* client : *clients)
  1033. {
  1034. if (strcmp(client->zEntity()->getName(), name) == 0)
  1035. {
  1036. return client->zEntity();
  1037. }
  1038. }
  1039. return 0;
  1040. }
  1041. void Game::listPlayerNames(Framework::RCArray<Framework::Text>& names)
  1042. {
  1043. for (GameClient* client : *clients)
  1044. {
  1045. names.add(new Framework::Text(client->zEntity()->getName()));
  1046. }
  1047. }
  1048. TypeRegistry* Game::zTypeRegistry() const
  1049. {
  1050. return typeRegistry;
  1051. }
  1052. int Game::getPlayerId(const char* name) const
  1053. {
  1054. return playerRegister->getPlayerId(name);
  1055. }
  1056. QuestManager* Game::zQuestManager() const
  1057. {
  1058. return questManager;
  1059. }
  1060. UIController* Game::zUIController() const
  1061. {
  1062. return uiController;
  1063. }
  1064. double Game::getAverageTickTime() const
  1065. {
  1066. return averageTickTime;
  1067. }
  1068. int Game::getTicksPerSecond() const
  1069. {
  1070. return ticksPerSecond;
  1071. }
  1072. int Game::getPlayerCount() const
  1073. {
  1074. return clients->getEintragAnzahl();
  1075. }
  1076. int Game::getChunkCount() const
  1077. {
  1078. int result = 0;
  1079. for (Dimension* dim : *dimensions)
  1080. {
  1081. result += dim->getChunkCount();
  1082. }
  1083. return result;
  1084. }
  1085. const BlockType* Game::zBlockType(int id) const
  1086. {
  1087. return blockTypes[id];
  1088. }
  1089. const ItemType* Game::zItemType(int id) const
  1090. {
  1091. return itemTypes[id];
  1092. }
  1093. const EntityType* Game::zEntityType(int id) const
  1094. {
  1095. return entityTypes[id];
  1096. }
  1097. int Game::getEntityTypeId(const char* name) const
  1098. {
  1099. for (int i = 0; i < entityTypeCount; i++)
  1100. {
  1101. if (entityTypes[i]
  1102. && Framework::Text(entityTypes[i]->getName()).istGleich(name))
  1103. {
  1104. return i;
  1105. }
  1106. }
  1107. Framework::Logging::warning()
  1108. << "no entity type with name '" << name << "' found.";
  1109. return -1;
  1110. }
  1111. int Game::getBlockTypeId(const char* name) const
  1112. {
  1113. for (int i = 0; i < blockTypeCount; i++)
  1114. {
  1115. if (blockTypes[i]
  1116. && Framework::Text(blockTypes[i]->getName()).istGleich(name))
  1117. {
  1118. return i;
  1119. }
  1120. }
  1121. Framework::Logging::warning()
  1122. << "no block type with name '" << name << "' found.";
  1123. return -1;
  1124. }
  1125. int Game::getItemTypeId(const char* name) const
  1126. {
  1127. for (int i = 0; i < itemTypeCount; i++)
  1128. {
  1129. if (itemTypes[i]
  1130. && Framework::Text(itemTypes[i]->getName()).istGleich(name))
  1131. {
  1132. return i;
  1133. }
  1134. }
  1135. Framework::Logging::warning()
  1136. << "no item type with name '" << name << "' found.";
  1137. return -1;
  1138. }
  1139. int Game::getBlockTypeCount() const
  1140. {
  1141. return blockTypeCount;
  1142. }
  1143. int Game::getItemTypeCount() const
  1144. {
  1145. return itemTypeCount;
  1146. }
  1147. int Game::getEntityTypeCount() const
  1148. {
  1149. return entityTypeCount;
  1150. }
  1151. const MultiblockStructureType* Game::zMultiblockStructureType(int id) const
  1152. {
  1153. return multiblockStructureTypes[id];
  1154. }
  1155. int Game::getMultiblockStructureTypeCount() const
  1156. {
  1157. return multiblockStructureTypeCount;
  1158. }