Dimension.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. #include "Dimension.h"
  2. #include "Constants.h"
  3. #include "Datei.h"
  4. #include "Game.h"
  5. #include "NoBlock.h"
  6. using namespace Framework;
  7. Dimension::Dimension(int id)
  8. : Thread(),
  9. nextStructureId(0),
  10. dimensionId(id),
  11. gravity(9.8f),
  12. chunks(new Trie<Chunk>()),
  13. entities(new RCArray<Entity>())
  14. {
  15. Datei d;
  16. d.setDatei(Game::INSTANCE->getWorldDirectory() + "/dim/" + Text(id) + "/nst.id");
  17. if (d.existiert())
  18. {
  19. d.open(Datei::Style::lesen);
  20. d.lese((char*)&nextStructureId, 8);
  21. d.close();
  22. }
  23. start();
  24. }
  25. Dimension::~Dimension()
  26. {
  27. entities->release();
  28. chunks->release();
  29. }
  30. void Dimension::api(Framework::InMemoryBuffer* zRequest, NetworkMessage* zResponse, Entity* zSource)
  31. {
  32. DoLaterHandler laterHandler;
  33. char type;
  34. zRequest->lese(&type, 1);
  35. switch (type)
  36. {
  37. case 0: // chunk message
  38. {
  39. Punkt center;
  40. zRequest->lese((char*)&center.x, 4);
  41. zRequest->lese((char*)&center.y, 4);
  42. cs.lock();
  43. Chunk* cC = zChunk(center);
  44. if (!cC)
  45. {
  46. // TODO: have a max amount of waiting requests per player
  47. waitingRequests.add({ dynamic_cast<InMemoryBuffer*>(zRequest->getThis()), center, zSource->getId() });
  48. Game::INSTANCE->requestArea({ center.x - CHUNK_SIZE / 2, center.y - CHUNK_SIZE / 2, center.x + CHUNK_SIZE / 2 - 1, center.y + CHUNK_SIZE / 2 - 1, dimensionId });
  49. }
  50. else
  51. {
  52. cC->api(zRequest, zSource, laterHandler);
  53. }
  54. cs.unlock();
  55. break;
  56. }
  57. }
  58. }
  59. void Dimension::tickEntities()
  60. {
  61. for (auto entity : *entities)
  62. {
  63. if (!entity->isRemoved() && (entity->isMoving() || zChunk(Punkt((int)entity->getPosition().x, (int)entity->getPosition().y))))
  64. entity->prepareTick(this);
  65. }
  66. int index = 0;
  67. for (auto entity : *entities)
  68. {
  69. if (!entity->isRemoved() && (entity->isMoving() || zChunk(Punkt((int)entity->getPosition().x, (int)entity->getPosition().y))))
  70. entity->tick(this);
  71. index++;
  72. }
  73. }
  74. void Dimension::thread()
  75. {
  76. // light calculation
  77. int index = 0;
  78. ZeitMesser messer;
  79. messer.messungStart();
  80. double time = 0;
  81. bool isForeground = 0;
  82. Framework::Array<Framework::Vec3<int>> internalLightUpdateQueue;
  83. while (true)
  84. {
  85. Vec3<int> position;
  86. if (internalLightUpdateQueue.getEintragAnzahl())
  87. {
  88. position = internalLightUpdateQueue.get(0);
  89. internalLightUpdateQueue.remove(0);
  90. }
  91. else
  92. {
  93. removedChunksCs.lock();
  94. if (removedChunks.getEintragAnzahl() > 0)
  95. {
  96. Chunk* removedChunk = removedChunks.z(0);
  97. removedChunksCs.unlock();
  98. Text filePath = Game::INSTANCE->getWorldDirectory() + "/dim/" + getDimensionId() + "/";
  99. filePath.appendHex(removedChunk->getCenter().x);
  100. filePath += "_";
  101. filePath.appendHex(removedChunk->getCenter().y);
  102. filePath += ".chunk";
  103. Datei d;
  104. d.setDatei(filePath);
  105. d.erstellen();
  106. d.open(Datei::Style::schreiben);
  107. removedChunk->save(&d);
  108. d.close();
  109. removedChunksCs.lock();
  110. removedChunks.remove(0);
  111. }
  112. removedChunksCs.unlock();
  113. if (priorizedLightUpdateQueue.getEintragAnzahl())
  114. {
  115. prioLightCs.lock();
  116. position = priorizedLightUpdateQueue.get(0);
  117. priorizedLightUpdateQueue.remove(0);
  118. prioLightCs.unlock();
  119. isForeground = 1;
  120. }
  121. else
  122. {
  123. if (!lightUpdateQueue.getEintragAnzahl())
  124. {
  125. messer.messungEnde();
  126. time += messer.getSekunden();
  127. Sleep(500);
  128. messer.messungStart();
  129. continue;
  130. }
  131. lightCs.lock();
  132. position = lightUpdateQueue.get(0);
  133. lightUpdateQueue.remove(0);
  134. lightCs.unlock();
  135. isForeground = 0;
  136. }
  137. }
  138. Chunk* chunk = zChunk(Game::INSTANCE->getChunkCenter(position.x, position.y));
  139. if (position.z >= 0 && position.z < WORLD_HEIGHT)
  140. {
  141. if (chunk)
  142. {
  143. int x = position.x % CHUNK_SIZE;
  144. int y = position.y % CHUNK_SIZE;
  145. if (x < 0)
  146. x += CHUNK_SIZE;
  147. if (y < 0)
  148. y += CHUNK_SIZE;
  149. unsigned char* light = chunk->getLightData(Vec3<int>(x, y, position.z));
  150. unsigned char dayLight[6] = { 255, 255, 255, 0, 0, 0 };
  151. unsigned char noLight[6] = { 0, 0, 0, 0, 0, 0 };
  152. unsigned char newLight[6] = { 0, 0, 0, 0, 0, 0 };
  153. // add neighbor light emission
  154. for (int i = 0; i < 6; i++)
  155. {
  156. unsigned char* neighborLeight;
  157. Vec3<int> neighborPos = position + getDirection(getDirectionFromIndex(i));
  158. if (neighborPos.z < 0)
  159. {
  160. neighborLeight = noLight;
  161. }
  162. else if (neighborPos.z >= WORLD_HEIGHT)
  163. {
  164. neighborLeight = dayLight;
  165. }
  166. else
  167. {
  168. Chunk* neighborChunk = zChunk(Game::INSTANCE->getChunkCenter(neighborPos.x, neighborPos.y));
  169. int x = neighborPos.x % CHUNK_SIZE;
  170. int y = neighborPos.y % CHUNK_SIZE;
  171. if (x < 0)
  172. x += CHUNK_SIZE;
  173. if (y < 0)
  174. y += CHUNK_SIZE;
  175. if (neighborChunk)
  176. neighborLeight = neighborChunk->getLightData(Vec3<int>(x, y, neighborPos.z));
  177. else
  178. neighborLeight = noLight;
  179. }
  180. for (int j = 0; j < 3; j++)
  181. newLight[j] = (unsigned char)MAX(newLight[j], i == getDirectionIndex(TOP) ? neighborLeight[j] : (unsigned char)((float)neighborLeight[j] * 0.8f));
  182. for (int j = 3; j < 6; j++)
  183. newLight[j] = (unsigned char)MAX(newLight[j], (unsigned char)((float)neighborLeight[j] * 0.85f));
  184. }
  185. const Block* current = zBlockOrDefault(position);
  186. if (!current)
  187. current = &NoBlock::INSTANCE;
  188. // add own light emission
  189. for (int j = 3; j < 6; j++)
  190. newLight[j] = (unsigned char)MAX(newLight[j], current->getLightEmisionColor()[j - 3]);
  191. current->filterPassingLight(newLight);
  192. current->filterPassingLight(newLight + 3);
  193. for (int i = 0; i < 6; i++)
  194. {
  195. if (newLight[i] != light[i])
  196. {
  197. chunk->setLightData(Vec3<int>(x, y, position.z), newLight, isForeground);
  198. for (int j = 0; j < 6; j++)
  199. internalLightUpdateQueue.add(position + getDirection(getDirectionFromIndex(j)), 0);
  200. break;
  201. }
  202. }
  203. }
  204. }
  205. index++;
  206. if (index > 100000)
  207. {
  208. messer.messungEnde();
  209. time += messer.getSekunden();
  210. std::cout << "100000 light updates needed " << time << " seconds\n";
  211. time = 0;
  212. index = 0;
  213. Sleep(250);
  214. messer.messungStart();
  215. }
  216. }
  217. }
  218. void Dimension::getAddrOf(Punkt cPos, char* addr) const
  219. {
  220. *(int*)addr = cPos.x;
  221. *((int*)addr + 1) = cPos.y;
  222. }
  223. void Dimension::getAddrOfWorld(Punkt wPos, char* addr) const
  224. {
  225. if (wPos.x < 0)
  226. wPos.x -= CHUNK_SIZE;
  227. if (wPos.y < 0) // needed because otherwise would (-8, -8) have the same adress as (8, 8)
  228. wPos.y -= CHUNK_SIZE;
  229. wPos /= CHUNK_SIZE;
  230. getAddrOf(wPos, addr);
  231. }
  232. Chunk* Dimension::zChunk(Punkt wPos) const
  233. {
  234. char addr[8];
  235. getAddrOfWorld(wPos, addr);
  236. return chunks->z(addr, 8);
  237. }
  238. Framework::Either<Block*, int> Dimension::zBlock(Vec3<int> location)
  239. {
  240. Chunk* c = zChunk(Game::INSTANCE->getChunkCenter(location.x, location.y));
  241. if (c)
  242. {
  243. int x = location.x % CHUNK_SIZE;
  244. int y = location.y % CHUNK_SIZE;
  245. if (x < 0)
  246. x += CHUNK_SIZE;
  247. if (y < 0)
  248. y += CHUNK_SIZE;
  249. return c->zBlockAt(Vec3<int>(x, y, location.z));
  250. }
  251. return 0;
  252. }
  253. Block* Dimension::zRealBlockInstance(Framework::Vec3<int> location)
  254. {
  255. Chunk* c = zChunk(Game::INSTANCE->getChunkCenter(location.x, location.y));
  256. if (c)
  257. {
  258. int x = location.x % CHUNK_SIZE;
  259. int y = location.y % CHUNK_SIZE;
  260. if (x < 0)
  261. x += CHUNK_SIZE;
  262. if (y < 0)
  263. y += CHUNK_SIZE;
  264. c->instantiateBlock(Vec3<int>(x, y, location.z));
  265. auto result = c->zBlockAt(Vec3<int>(x, y, location.z));
  266. return result.isA() ? result.getA() : 0;
  267. }
  268. return 0;
  269. }
  270. const Block* Dimension::zBlockOrDefault(Framework::Vec3<int> location)
  271. {
  272. Chunk* c = zChunk(Game::INSTANCE->getChunkCenter(location.x, location.y));
  273. if (c)
  274. {
  275. int x = location.x % CHUNK_SIZE;
  276. int y = location.y % CHUNK_SIZE;
  277. if (x < 0)
  278. x += CHUNK_SIZE;
  279. if (y < 0)
  280. y += CHUNK_SIZE;
  281. return c->zBlockConst(Vec3<int>(x, y, location.z));
  282. }
  283. return 0;
  284. }
  285. void Dimension::placeBlock(Framework::Vec3<int> location, Framework::Either<Block*, int> block)
  286. {
  287. Chunk* c = zChunk(Game::getChunkCenter(location.x, location.y));
  288. if (c)
  289. {
  290. int x = location.x % CHUNK_SIZE;
  291. int y = location.y % CHUNK_SIZE;
  292. if (x < 0)
  293. x += CHUNK_SIZE;
  294. if (y < 0)
  295. y += CHUNK_SIZE;
  296. if (block.isA())
  297. c->putBlockAt(Vec3<int>(x, y, location.z), block);
  298. else
  299. {
  300. c->putBlockAt(Vec3<int>(x, y, location.z), 0);
  301. c->putBlockTypeAt(Vec3<int>(x, y, location.z), block);
  302. }
  303. }
  304. else if (block.isA())
  305. block.getA()->release();
  306. }
  307. void Dimension::addEntity(Entity* entity)
  308. {
  309. entities->add(entity);
  310. }
  311. void Dimension::setChunk(Chunk* chunk, Punkt center)
  312. {
  313. chunkCs.lock();
  314. char addr[8];
  315. getAddrOfWorld(center, addr);
  316. Chunk* old = chunks->get(addr, 8);
  317. if (old)
  318. {
  319. old->prepareRemove();
  320. for (int i = 0; i < chunkList.getEintragAnzahl(); i++)
  321. {
  322. if (chunkList.get(i) == old)
  323. {
  324. chunkList.remove(i);
  325. break;
  326. }
  327. }
  328. }
  329. chunks->set(addr, 8, chunk);
  330. if (chunk)
  331. {
  332. chunkList.add(chunk);
  333. chunk->setAdded();
  334. }
  335. getAddrOfWorld(center + Punkt(CHUNK_SIZE, 0), addr);
  336. Chunk* zChunk = chunks->z(addr, 8);
  337. if (zChunk)
  338. {
  339. zChunk->setNeighbor(WEST, chunk);
  340. if (chunk)
  341. {
  342. chunk->setNeighbor(EAST, zChunk);
  343. }
  344. }
  345. getAddrOfWorld(center + Punkt(-CHUNK_SIZE, 0), addr);
  346. zChunk = chunks->z(addr, 8);
  347. if (zChunk)
  348. {
  349. zChunk->setNeighbor(EAST, chunk);
  350. if (chunk)
  351. chunk->setNeighbor(WEST, zChunk);
  352. }
  353. getAddrOfWorld(center + Punkt(0, CHUNK_SIZE), addr);
  354. zChunk = chunks->z(addr, 8);
  355. if (zChunk)
  356. {
  357. zChunk->setNeighbor(NORTH, chunk);
  358. if (chunk)
  359. chunk->setNeighbor(SOUTH, zChunk);
  360. }
  361. getAddrOfWorld(center + Punkt(0, -CHUNK_SIZE), addr);
  362. zChunk = chunks->z(addr, 8);
  363. if (zChunk)
  364. {
  365. zChunk->setNeighbor(SOUTH, chunk);
  366. if (chunk)
  367. chunk->setNeighbor(NORTH, zChunk);
  368. }
  369. DoLaterHandler laterHandler;
  370. if (chunk)
  371. {
  372. cs.lock();
  373. int index = 0;
  374. for (Iterator<RequestQueue> iterator = waitingRequests.begin(); iterator; )
  375. {
  376. Entity* zE = Game::INSTANCE->zEntity(iterator.val().sourceId);
  377. if (zE)
  378. {
  379. if (iterator.val().chunkCenter == chunk->getCenter())
  380. {
  381. chunk->api(iterator.val().request, zE, laterHandler);
  382. iterator.val().request->release();
  383. iterator.remove();
  384. continue;
  385. }
  386. }
  387. else
  388. {
  389. iterator.val().request->release();
  390. iterator.remove();
  391. continue;
  392. }
  393. iterator++;
  394. index++;
  395. }
  396. cs.unlock();
  397. }
  398. chunkCs.unlock();
  399. if (old)
  400. {
  401. old->onUnloaded();
  402. removedChunksCs.lock();
  403. removedChunks.add(old);
  404. removedChunksCs.unlock();
  405. }
  406. if (chunk)
  407. chunk->onLoaded();
  408. updateLightAtChunkBorders(center);
  409. }
  410. void Dimension::save(Text worldDir) const
  411. {
  412. Datei d;
  413. d.setDatei(Game::INSTANCE->getWorldDirectory() + "/dim/" + Text(dimensionId) + "/nst.id");
  414. d.erstellen();
  415. d.open(Datei::Style::schreiben);
  416. d.schreibe((char*)&nextStructureId, 8);
  417. d.close();
  418. for (auto chunk = chunks->getIterator(); chunk; chunk++)
  419. {
  420. if (!chunk._)
  421. continue;
  422. Datei* file = new Datei();
  423. Text filePath = worldDir + "/dim/" + dimensionId + "/";
  424. filePath.appendHex(chunk->getCenter().x);
  425. filePath += "_";
  426. filePath.appendHex(chunk->getCenter().y);
  427. filePath += ".chunk";
  428. file->setDatei(filePath);
  429. if (file->open(Datei::Style::schreiben))
  430. chunk->save(file);
  431. file->close();
  432. file->release();
  433. }
  434. Text filePath = worldDir + "/dim/" + dimensionId + "/entities";
  435. Datei* file = new Datei();
  436. file->setDatei(filePath);
  437. if (file->open(Datei::Style::schreiben))
  438. {
  439. for (Entity* entity : *entities)
  440. {
  441. if (entity->zType()->getId() != PlayerEntityType::ID)
  442. {
  443. if (!entity->isRemoved())
  444. {
  445. int type = entity->zType()->getId();
  446. file->schreibe((char*)&type, 4);
  447. StaticRegistry<EntityType>::INSTANCE.zElement(type)->saveEntity(entity, file);
  448. }
  449. }
  450. else
  451. {
  452. Datei pFile;
  453. pFile.setDatei(worldDir + "/player/" + ((Player*)entity)->getName());
  454. if (pFile.open(Datei::Style::schreiben))
  455. PlayerEntityType::INSTANCE->saveEntity(entity, &pFile);
  456. }
  457. }
  458. file->close();
  459. }
  460. }
  461. int Dimension::getDimensionId() const
  462. {
  463. return dimensionId;
  464. }
  465. bool Dimension::hasChunck(int x, int y)
  466. {
  467. if (zChunk(Punkt(x, y)))
  468. return 1;
  469. removedChunksCs.lock();
  470. for (Chunk* c : removedChunks)
  471. {
  472. if (c->getCenter().x == x && c->getCenter().y == y)
  473. {
  474. removedChunksCs.unlock();
  475. return 1;
  476. }
  477. }
  478. removedChunksCs.unlock();
  479. return 0;
  480. }
  481. bool Dimension::reviveChunk(int x, int y)
  482. {
  483. chunkCs.lock();
  484. if (zChunk(Punkt(x, y)))
  485. {
  486. chunkCs.unlock();
  487. return 1;
  488. }
  489. removedChunksCs.lock();
  490. int index = 0;
  491. for (Iterator<Chunk*> i = removedChunks.begin(); i; i++)
  492. {
  493. if (i->getCenter().x == x && i->getCenter().y == y)
  494. {
  495. setChunk(dynamic_cast<Chunk*>(i->getThis()), Punkt(x, y));
  496. if (index > 0)
  497. i.remove();
  498. removedChunksCs.unlock();
  499. chunkCs.unlock();
  500. return 1;
  501. }
  502. index++;
  503. }
  504. removedChunksCs.unlock();
  505. chunkCs.unlock();
  506. return 0;
  507. }
  508. float Dimension::getGravity() const
  509. {
  510. return gravity;
  511. }
  512. void Dimension::removeOldChunks()
  513. {
  514. chunkCs.lock();
  515. int index = 0;
  516. for (Chunk* chunk : chunkList)
  517. {
  518. if (!chunk->hasObservers())
  519. setChunk(0, chunk->getCenter());
  520. index++;
  521. }
  522. chunkCs.unlock();
  523. }
  524. Entity* Dimension::zEntity(int id)
  525. {
  526. for (auto entity : *entities)
  527. {
  528. if (!entity->isRemoved() && entity->getId() == id)
  529. return entity;
  530. }
  531. return 0;
  532. }
  533. Entity* Dimension::zNearestEntity(Framework::Vec3<float> pos, std::function<bool(Entity*)> filter)
  534. {
  535. Entity* result = 0;
  536. float sqDist = 0;
  537. for (auto entity : *entities)
  538. {
  539. if (!entity->isRemoved() && filter(entity))
  540. {
  541. float d = pos.abstandSq(entity->getPosition());
  542. if (!result || d < sqDist)
  543. {
  544. result = entity;
  545. sqDist = d;
  546. }
  547. }
  548. }
  549. return result;
  550. }
  551. void Dimension::removeEntity(int id)
  552. {
  553. int index = 0;
  554. for (auto entity : *entities)
  555. {
  556. if (entity->getId() == id)
  557. {
  558. entities->remove(index);
  559. return;
  560. }
  561. index++;
  562. }
  563. }
  564. void Dimension::removeSubscriptions(Entity* zEntity)
  565. {
  566. for (Chunk* chunk : chunkList)
  567. chunk->removeObserver(zEntity);
  568. }
  569. void Dimension::updateLightning(Vec3<int> location)
  570. {
  571. lightCs.lock();
  572. lightUpdateQueue.add(location, 0);
  573. lightCs.unlock();
  574. }
  575. void Dimension::updateLightningWithoutWait(Framework::Vec3<int> location)
  576. {
  577. prioLightCs.lock();
  578. priorizedLightUpdateQueue.add(location, 0);
  579. prioLightCs.unlock();
  580. }
  581. void Dimension::updateLightAtChunkBorders(Punkt chunkCenter)
  582. {
  583. if (lightUpdateQueue.getEintragAnzahl() > 300000)
  584. {
  585. std::cout << "warning: light calculation queue is over 300000 blocks long";
  586. }
  587. for (int i = WORLD_HEIGHT - 1; i >= 0; i--)
  588. {
  589. for (int j = 0; j < CHUNK_SIZE; j++)
  590. {
  591. updateLightning(Vec3<int>(chunkCenter.x - CHUNK_SIZE / 8 - 1, chunkCenter.y - CHUNK_SIZE / 8 + j, i));
  592. updateLightning(Vec3<int>(chunkCenter.x - CHUNK_SIZE / 8, chunkCenter.y - CHUNK_SIZE / 8 + j, i));
  593. updateLightning(Vec3<int>(chunkCenter.x + CHUNK_SIZE / 8 - 1, chunkCenter.y - CHUNK_SIZE / 8 + j, i));
  594. updateLightning(Vec3<int>(chunkCenter.x + CHUNK_SIZE / 8, chunkCenter.y - CHUNK_SIZE / 8 + j, i));
  595. updateLightning(Vec3<int>(chunkCenter.x - CHUNK_SIZE / 8 + j, chunkCenter.y - CHUNK_SIZE / 8 - 1, i));
  596. updateLightning(Vec3<int>(chunkCenter.x - CHUNK_SIZE / 8 + j, chunkCenter.y - CHUNK_SIZE / 8, i));
  597. updateLightning(Vec3<int>(chunkCenter.x - CHUNK_SIZE / 8 + j, chunkCenter.y + CHUNK_SIZE / 8 - 1, i));
  598. updateLightning(Vec3<int>(chunkCenter.x - CHUNK_SIZE / 8 + j, chunkCenter.y + CHUNK_SIZE / 8, i));
  599. }
  600. }
  601. }
  602. __int64 Dimension::getNextStructureId()
  603. {
  604. return nextStructureId++;
  605. }
  606. void Dimension::addStructure(MultiblockStructure* structure)
  607. {
  608. structures.add(structure);
  609. }
  610. MultiblockStructure* Dimension::zStructureByPosition(Framework::Vec3<int> uniquePosition)
  611. {
  612. for (MultiblockStructure* str : structures)
  613. {
  614. if (str->getUniquePosition() == uniquePosition)
  615. return str;
  616. }
  617. return 0;
  618. }