Dimension.cpp 14 KB

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