Dimension.cpp 13 KB

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